[PATCH] D111760: [clang] Support __float128 on DragonFlyBSD.

2021-10-20 Thread Michał Górny via Phabricator via cfe-commits
mgorny accepted this revision.
mgorny added a comment.
This revision is now accepted and ready to land.

Ok then.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111760

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


[PATCH] D112102: [RISCV] Reduce the number of RISCV vector builtins by an order of magnitude.

2021-10-20 Thread Hsiangkai Wang via Phabricator via cfe-commits
HsiangKai added inline comments.



Comment at: llvm/test/CodeGen/RISCV/rvv/vmerge-rv32.ll:1358
+; CHECK-NEXT:vsetvli zero, a0, e16, mf4, ta, mu
+; CHECK-NEXT:vmerge.vvm v8, v8, v9, v0
+; CHECK-NEXT:ret

vmerge.vvm is for integer vectors, doesn't it? Why does it work for floating 
point vector types?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112102

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


[clang] 5e96912 - [clang-format] git-clang-format throws an assertion when removing files as part of the commit

2021-10-20 Thread via cfe-commits

Author: mydeveloperday
Date: 2021-10-20T09:07:12+01:00
New Revision: 5e969125c6094b909493bcd8360497adcdf8f6f5

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

LOG: [clang-format] git-clang-format throws an assertion when removing files as 
part of the commit

Following a change {D111273} to allow git-clang-format to see single lines 
being removed,
we introduced a regression such that if you are removing a whole file it will
assert in clang-format as its given the -lines=0:0  (lines are 1 based)

Reviewed By: HazardyKnusperkeks

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

Added: 


Modified: 
clang/tools/clang-format/git-clang-format

Removed: 




diff  --git a/clang/tools/clang-format/git-clang-format 
b/clang/tools/clang-format/git-clang-format
index 40e848d55a8c..c7e15eb7b483 100755
--- a/clang/tools/clang-format/git-clang-format
+++ b/clang/tools/clang-format/git-clang-format
@@ -327,6 +327,8 @@ def extract_lines(patch_file):
 line_count = int(match.group(3))
   if line_count == 0:
 line_count = 1
+  if start_line == 0:
+continue
   matches.setdefault(filename, []).append(Range(start_line, line_count))
   return matches
 



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


[PATCH] D112056: [clang-format] git-clang-format throws an assertion when removing files as part of the commit

2021-10-20 Thread MyDeveloperDay via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5e969125c609: [clang-format] git-clang-format throws an 
assertion when removing files as part… (authored by MyDeveloperDay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112056

Files:
  clang/tools/clang-format/git-clang-format


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -327,6 +327,8 @@
 line_count = int(match.group(3))
   if line_count == 0:
 line_count = 1
+  if start_line == 0:
+continue
   matches.setdefault(filename, []).append(Range(start_line, line_count))
   return matches
 


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -327,6 +327,8 @@
 line_count = int(match.group(3))
   if line_count == 0:
 line_count = 1
+  if start_line == 0:
+continue
   matches.setdefault(filename, []).append(Range(start_line, line_count))
   return matches
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D112020: [RISCV] Use clang_builtin_alias for all RISCV vector intrinsics.

2021-10-20 Thread Hsiangkai Wang via Phabricator via cfe-commits
HsiangKai added a comment.

After preprocessing, macro definitions will disappear, but function 
declarations will not. This is the benefit of using macro.

After applying D112102 , we could still use

  #define vadd_vv_i8m1(op0, op1, op2) \
  __builtin_rvv_vadd_vv((vint8m1_t)(op0), (vint8m1_t)(op1), (size_t)(op2))


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112020

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


[clang] 57e0081 - [clang-format] [PR52015] clang-format should put __attribute__((foo)) on its own line before @interface / @implementation / @protocol

2021-10-20 Thread via cfe-commits

Author: mydeveloperday
Date: 2021-10-20T09:09:31+01:00
New Revision: 57e00810edd7c4359e3de9242bcbd8874d58dc64

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

LOG: [clang-format] [PR52015] clang-format should put __attribute__((foo)) on 
its own line before @interface / @implementation / @protocol

https://bugs.llvm.org/show_bug.cgi?id=52015

A newline should be place between attribute and @ for objectivec

Reviewed By: benhamilton, HazardyKnusperkeks

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestObjC.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 29580ebe5ebf..e6be3a918034 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3832,6 +3832,10 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
   Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
 return true;
 
+  // Ensure wrapping after __attribute__((XX)) and @interface etc.
+  if (Left.is(TT_AttributeParen) && Right.is(TT_ObjCDecl))
+return true;
+
   if (Left.is(TT_LambdaLBrace)) {
 if (IsFunctionArgument(Left) &&
 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline)

diff  --git a/clang/unittests/Format/FormatTestObjC.cpp 
b/clang/unittests/Format/FormatTestObjC.cpp
index 78be44e7a3f2..e421082796c5 100644
--- a/clang/unittests/Format/FormatTestObjC.cpp
+++ b/clang/unittests/Format/FormatTestObjC.cpp
@@ -1526,6 +1526,18 @@ TEST_F(FormatTestObjC, IfNotUnlikely) {
"  [obj func:arg2];");
 }
 
+TEST_F(FormatTestObjC, Attributes) {
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@interface Foo\n"
+   "@end");
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@protocol Foo\n"
+   "@end");
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@implementation Foo\n"
+   "@end");
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang



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


[PATCH] D111975: [clang-format] [PR52015] clang-format should put __attribute__((foo)) on its own line before @interface / @implementation / @protocol

2021-10-20 Thread MyDeveloperDay via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG57e00810edd7: [clang-format] [PR52015] clang-format should 
put __attribute__((foo)) on its… (authored by MyDeveloperDay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111975

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


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -1526,6 +1526,18 @@
"  [obj func:arg2];");
 }
 
+TEST_F(FormatTestObjC, Attributes) {
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@interface Foo\n"
+   "@end");
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@protocol Foo\n"
+   "@end");
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@implementation Foo\n"
+   "@end");
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3832,6 +3832,10 @@
   Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
 return true;
 
+  // Ensure wrapping after __attribute__((XX)) and @interface etc.
+  if (Left.is(TT_AttributeParen) && Right.is(TT_ObjCDecl))
+return true;
+
   if (Left.is(TT_LambdaLBrace)) {
 if (IsFunctionArgument(Left) &&
 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline)


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -1526,6 +1526,18 @@
"  [obj func:arg2];");
 }
 
+TEST_F(FormatTestObjC, Attributes) {
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@interface Foo\n"
+   "@end");
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@protocol Foo\n"
+   "@end");
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@implementation Foo\n"
+   "@end");
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3832,6 +3832,10 @@
   Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
 return true;
 
+  // Ensure wrapping after __attribute__((XX)) and @interface etc.
+  if (Left.is(TT_AttributeParen) && Right.is(TT_ObjCDecl))
+return true;
+
   if (Left.is(TT_LambdaLBrace)) {
 if (IsFunctionArgument(Left) &&
 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D110257: [CFE][Codegen] Make sure to maintain the contiguity of all the static allocas

2021-10-20 Thread Mahesha S via Phabricator via cfe-commits
hsmhsm updated this revision to Diff 380871.
hsmhsm added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110257

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/test/CodeGenCUDA/builtins-amdgcn.cu
  clang/test/CodeGenCXX/amdgcn-automatic-variable.cpp
  clang/test/CodeGenCXX/amdgcn-func-arg.cpp
  clang/test/CodeGenCXX/builtin-amdgcn-atomic-inc-dec.cpp
  clang/test/CodeGenCXX/vla.cpp
  clang/test/CodeGenSYCL/address-space-deduction.cpp
  clang/test/OpenMP/amdgcn_target_init_temp_alloca.cpp

Index: clang/test/OpenMP/amdgcn_target_init_temp_alloca.cpp
===
--- clang/test/OpenMP/amdgcn_target_init_temp_alloca.cpp
+++ clang/test/OpenMP/amdgcn_target_init_temp_alloca.cpp
@@ -12,7 +12,9 @@
   int arr[N];
 
   // CHECK:  [[VAR_ADDR:%.+]] = alloca [100 x i32]*, align 8, addrspace(5)
+  // CHECK-NEXT: [[VAR2_ADDR:%.+]] = alloca i32, align 4, addrspace(5)
   // CHECK-NEXT: [[VAR_ADDR_CAST:%.+]] = addrspacecast [100 x i32]* addrspace(5)* [[VAR_ADDR]] to [100 x i32]**
+  // CHECK-NEXT: [[VAR2_ADDR_CAST:%.+]] = addrspacecast i32 addrspace(5)* [[VAR2_ADDR]] to i32*
   // CHECK:  store [100 x i32]* [[VAR:%.+]], [100 x i32]** [[VAR_ADDR_CAST]], align 8
 
 #pragma omp target
Index: clang/test/CodeGenSYCL/address-space-deduction.cpp
===
--- clang/test/CodeGenSYCL/address-space-deduction.cpp
+++ clang/test/CodeGenSYCL/address-space-deduction.cpp
@@ -1,34 +1,33 @@
 // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
 // RUN: %clang_cc1 -triple spir64 -fsycl-is-device -disable-llvm-passes -emit-llvm %s -o - | FileCheck %s
 
-
 // CHECK-LABEL: @_Z4testv(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[I:%.*]] = alloca i32, align 4
-// CHECK-NEXT:[[I_ASCAST:%.*]] = addrspacecast i32* [[I]] to i32 addrspace(4)*
 // CHECK-NEXT:[[PPTR:%.*]] = alloca i32 addrspace(4)*, align 8
-// CHECK-NEXT:[[PPTR_ASCAST:%.*]] = addrspacecast i32 addrspace(4)** [[PPTR]] to i32 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[IS_I_PTR:%.*]] = alloca i8, align 1
-// CHECK-NEXT:[[IS_I_PTR_ASCAST:%.*]] = addrspacecast i8* [[IS_I_PTR]] to i8 addrspace(4)*
 // CHECK-NEXT:[[VAR23:%.*]] = alloca i32, align 4
-// CHECK-NEXT:[[VAR23_ASCAST:%.*]] = addrspacecast i32* [[VAR23]] to i32 addrspace(4)*
 // CHECK-NEXT:[[CP:%.*]] = alloca i8 addrspace(4)*, align 8
-// CHECK-NEXT:[[CP_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[CP]] to i8 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[ARR:%.*]] = alloca [42 x i32], align 4
-// CHECK-NEXT:[[ARR_ASCAST:%.*]] = addrspacecast [42 x i32]* [[ARR]] to [42 x i32] addrspace(4)*
 // CHECK-NEXT:[[CPP:%.*]] = alloca i8 addrspace(4)*, align 8
-// CHECK-NEXT:[[CPP_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[CPP]] to i8 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[APTR:%.*]] = alloca i32 addrspace(4)*, align 8
-// CHECK-NEXT:[[APTR_ASCAST:%.*]] = addrspacecast i32 addrspace(4)** [[APTR]] to i32 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[STR:%.*]] = alloca i8 addrspace(4)*, align 8
-// CHECK-NEXT:[[STR_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[STR]] to i8 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[PHI_STR:%.*]] = alloca i8 addrspace(4)*, align 8
-// CHECK-NEXT:[[PHI_STR_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[PHI_STR]] to i8 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[SELECT_NULL:%.*]] = alloca i8 addrspace(4)*, align 8
-// CHECK-NEXT:[[SELECT_NULL_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[SELECT_NULL]] to i8 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[SELECT_STR_TRIVIAL1:%.*]] = alloca i8 addrspace(4)*, align 8
-// CHECK-NEXT:[[SELECT_STR_TRIVIAL1_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[SELECT_STR_TRIVIAL1]] to i8 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[SELECT_STR_TRIVIAL2:%.*]] = alloca i8 addrspace(4)*, align 8
+// CHECK-NEXT:[[I_ASCAST:%.*]] = addrspacecast i32* [[I]] to i32 addrspace(4)*
+// CHECK-NEXT:[[PPTR_ASCAST:%.*]] = addrspacecast i32 addrspace(4)** [[PPTR]] to i32 addrspace(4)* addrspace(4)*
+// CHECK-NEXT:[[IS_I_PTR_ASCAST:%.*]] = addrspacecast i8* [[IS_I_PTR]] to i8 addrspace(4)*
+// CHECK-NEXT:[[VAR23_ASCAST:%.*]] = addrspacecast i32* [[VAR23]] to i32 addrspace(4)*
+// CHECK-NEXT:[[CP_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[CP]] to i8 addrspace(4)* addrspace(4)*
+// CHECK-NEXT:[[ARR_ASCAST:%.*]] = addrspacecast [42 x i32]* [[ARR]] to [42 x i32] addrspace(4)*
+// CHECK-NEXT:[[CPP_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[CPP]] to i8 addrspace(4)* addrspace(4)*
+// CHECK-NEXT:[[APTR_ASCAST:%.*]] = addrspacecast i32 addrspace(4)** [[APTR]] to i32 addrspace(4)* addrspace(4)*
+// CHECK-NEXT:[[STR_ASCAS

[PATCH] D112020: [RISCV] Use clang_builtin_alias for all RISCV vector intrinsics.

2021-10-20 Thread Hsiangkai Wang via Phabricator via cfe-commits
HsiangKai added a comment.

In D112020#3074557 , @HsiangKai wrote:

> After preprocessing, macro definitions will disappear, but function 
> declarations will not. This is the benefit of using macro.
>
> After applying D112102 , we could still use
>
>   #define vadd_vv_i8m1(op0, op1, op2) \
>   __builtin_rvv_vadd_vv((vint8m1_t)(op0), (vint8m1_t)(op1), (size_t)(op2))

Sorry for the disturbing. After removing type string in the builtin 
definitions, we need a function declaration in the header. Macro doesn't work.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112020

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


[clang] 6d0c7bc - [WebAssembly] Implementation of table.get/set for reftypes in LLVM IR

2021-10-20 Thread Paulo Matos via cfe-commits

Author: Paulo Matos
Date: 2021-10-20T10:31:31+02:00
New Revision: 6d0c7bc17de85807c286f78571235b6658999faf

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

LOG: [WebAssembly] Implementation of table.get/set for reftypes in LLVM IR

This change implements new DAG nodes TABLE_GET/TABLE_SET, and lowering
methods for load and stores of reference types from IR arrays. These
global LLVM IR arrays represent tables at the Wasm level.

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

Added: 
llvm/test/CodeGen/WebAssembly/externref-tableget.ll
llvm/test/CodeGen/WebAssembly/externref-tableset.ll
llvm/test/CodeGen/WebAssembly/funcref-table_call.ll
llvm/test/CodeGen/WebAssembly/funcref-tableget.ll
llvm/test/CodeGen/WebAssembly/funcref-tableset.ll

Modified: 
clang/lib/Basic/Targets/WebAssembly.h
clang/test/CodeGen/target-data.c
lld/test/wasm/lto/Inputs/archive.ll
lld/test/wasm/lto/Inputs/cache.ll
lld/test/wasm/lto/Inputs/libcall-archive.ll
lld/test/wasm/lto/Inputs/libcall-truncsfhf2.ll
lld/test/wasm/lto/Inputs/save-temps.ll
lld/test/wasm/lto/Inputs/thinlto.ll
lld/test/wasm/lto/Inputs/used.ll
lld/test/wasm/lto/archive.ll
lld/test/wasm/lto/atomics.ll
lld/test/wasm/lto/cache.ll
lld/test/wasm/lto/comdat.ll
lld/test/wasm/lto/diagnostics.ll
lld/test/wasm/lto/export.ll
lld/test/wasm/lto/import-attributes.ll
lld/test/wasm/lto/internalize-basic.ll
lld/test/wasm/lto/libcall-archive.ll
lld/test/wasm/lto/libcall-truncsfhf2.ll
lld/test/wasm/lto/lto-start.ll
lld/test/wasm/lto/new-pass-manager.ll
lld/test/wasm/lto/opt-level.ll
lld/test/wasm/lto/parallel.ll
lld/test/wasm/lto/relocatable-undefined.ll
lld/test/wasm/lto/relocatable.ll
lld/test/wasm/lto/save-temps.ll
lld/test/wasm/lto/thinlto.ll
lld/test/wasm/lto/tls.ll
lld/test/wasm/lto/undef.ll
lld/test/wasm/lto/used.ll
lld/test/wasm/lto/verify-invalid.ll
lld/test/wasm/lto/weak-undefined.ll
lld/test/wasm/lto/weak.ll
llvm/lib/Target/WebAssembly/WebAssemblyISD.def
llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.h
llvm/lib/Target/WebAssembly/WebAssemblyInstrTable.td
llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp
llvm/lib/Target/WebAssembly/WebAssemblyRegStackify.cpp
llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp

Removed: 




diff  --git a/clang/lib/Basic/Targets/WebAssembly.h 
b/clang/lib/Basic/Targets/WebAssembly.h
index 27b6576e4b7a..16534d3ef99b 100644
--- a/clang/lib/Basic/Targets/WebAssembly.h
+++ b/clang/lib/Basic/Targets/WebAssembly.h
@@ -151,9 +151,11 @@ class LLVM_LIBRARY_VISIBILITY WebAssembly32TargetInfo
const TargetOptions &Opts)
   : WebAssemblyTargetInfo(T, Opts) {
 if (T.isOSEmscripten())
-  resetDataLayout("e-m:e-p:32:32-i64:64-f128:64-n32:64-S128-ni:1:10:20");
+  resetDataLayout("e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-f128:64-n32:64-"
+  "S128-ni:1:10:20");
 else
-  resetDataLayout("e-m:e-p:32:32-i64:64-n32:64-S128-ni:1:10:20");
+  resetDataLayout(
+  "e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-n32:64-S128-ni:1:10:20");
   }
 
 protected:
@@ -173,9 +175,11 @@ class LLVM_LIBRARY_VISIBILITY WebAssembly64TargetInfo
 PtrDiffType = SignedLong;
 IntPtrType = SignedLong;
 if (T.isOSEmscripten())
-  resetDataLayout("e-m:e-p:64:64-i64:64-f128:64-n32:64-S128-ni:1:10:20");
+  resetDataLayout("e-m:e-p:64:64-p10:8:8-p20:8:8-i64:64-f128:64-n32:64-"
+  "S128-ni:1:10:20");
 else
-  resetDataLayout("e-m:e-p:64:64-i64:64-n32:64-S128-ni:1:10:20");
+  resetDataLayout(
+  "e-m:e-p:64:64-p10:8:8-p20:8:8-i64:64-n32:64-S128-ni:1:10:20");
   }
 
 protected:

diff  --git a/clang/test/CodeGen/target-data.c 
b/clang/test/CodeGen/target-data.c
index 0749493d788f..d702f845112b 100644
--- a/clang/test/CodeGen/target-data.c
+++ b/clang/test/CodeGen/target-data.c
@@ -108,11 +108,11 @@
 
 // RUN: %clang_cc1 -triple wasm32-unknown-unknown -o - -emit-llvm %s | \
 // RUN: FileCheck %s -check-prefix=WEBASSEMBLY32
-// WEBASSEMBLY32: target datalayout = 
"e-m:e-p:32:32-i64:64-n32:64-S128-ni:1:10:20"
+// WEBASSEMBLY32: target datalayout = 
"e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-n32:64-S128-ni:1:10:20"
 
 // RUN: %clang_cc1 -triple wasm64-unknown-unknown -o - -emit-llvm %s | \
 // RUN: FileCheck %s -check-prefix=WEBASSEMBLY64
-// WEBASSEMBLY64: target datalayout = 
"e-m:e-p:64:64-i64:64-n32:64-S128-ni:1:10:20"
+// WEBASSEMBLY64: target datalayout = 
"e-m:e-p:64:64-p10:8:8-p20:8:8-i64:64-n32:64-S128-ni:1:10:20"
 
 // RUN: %clang_cc1 -triple lanai-unknown-unknown -o - -emit-llvm %s | \
 // R

[PATCH] D111154: [WebAssembly] Implementation of table.get/set for reftypes in LLVM IR

2021-10-20 Thread Paulo Matos via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6d0c7bc17de8: [WebAssembly] Implementation of table.get/set 
for reftypes in LLVM IR (authored by pmatos).

Changed prior to commit:
  https://reviews.llvm.org/D54?vs=380337&id=380872#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54

Files:
  clang/lib/Basic/Targets/WebAssembly.h
  clang/test/CodeGen/target-data.c
  lld/test/wasm/lto/Inputs/archive.ll
  lld/test/wasm/lto/Inputs/cache.ll
  lld/test/wasm/lto/Inputs/libcall-archive.ll
  lld/test/wasm/lto/Inputs/libcall-truncsfhf2.ll
  lld/test/wasm/lto/Inputs/save-temps.ll
  lld/test/wasm/lto/Inputs/thinlto.ll
  lld/test/wasm/lto/Inputs/used.ll
  lld/test/wasm/lto/archive.ll
  lld/test/wasm/lto/atomics.ll
  lld/test/wasm/lto/cache.ll
  lld/test/wasm/lto/comdat.ll
  lld/test/wasm/lto/diagnostics.ll
  lld/test/wasm/lto/export.ll
  lld/test/wasm/lto/import-attributes.ll
  lld/test/wasm/lto/internalize-basic.ll
  lld/test/wasm/lto/libcall-archive.ll
  lld/test/wasm/lto/libcall-truncsfhf2.ll
  lld/test/wasm/lto/lto-start.ll
  lld/test/wasm/lto/new-pass-manager.ll
  lld/test/wasm/lto/opt-level.ll
  lld/test/wasm/lto/parallel.ll
  lld/test/wasm/lto/relocatable-undefined.ll
  lld/test/wasm/lto/relocatable.ll
  lld/test/wasm/lto/save-temps.ll
  lld/test/wasm/lto/thinlto.ll
  lld/test/wasm/lto/tls.ll
  lld/test/wasm/lto/undef.ll
  lld/test/wasm/lto/used.ll
  lld/test/wasm/lto/verify-invalid.ll
  lld/test/wasm/lto/weak-undefined.ll
  lld/test/wasm/lto/weak.ll
  llvm/lib/Target/WebAssembly/WebAssemblyISD.def
  llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.h
  llvm/lib/Target/WebAssembly/WebAssemblyInstrTable.td
  llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyRegStackify.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
  llvm/test/CodeGen/WebAssembly/externref-tableget.ll
  llvm/test/CodeGen/WebAssembly/externref-tableset.ll
  llvm/test/CodeGen/WebAssembly/funcref-table_call.ll
  llvm/test/CodeGen/WebAssembly/funcref-tableget.ll
  llvm/test/CodeGen/WebAssembly/funcref-tableset.ll

Index: llvm/test/CodeGen/WebAssembly/funcref-tableset.ll
===
--- /dev/null
+++ llvm/test/CodeGen/WebAssembly/funcref-tableset.ll
@@ -0,0 +1,82 @@
+; RUN: llc --mtriple=wasm32-unknown-unknown -asm-verbose=false -mattr=+reference-types < %s | FileCheck %s
+
+%func = type void ()
+%funcref = type %func addrspace(20)* ;; addrspace 20 is nonintegral
+
+@funcref_table = local_unnamed_addr addrspace(1) global [0 x %funcref] undef
+
+define void @set_funcref_table(%funcref %g, i32 %i) {
+; CHECK-LABEL: set_funcref_table:
+; CHECK-NEXT: .functype   set_funcref_table (funcref, i32) -> ()
+; CHECK-NEXT: local.get  1
+; CHECK-NEXT: local.get  0
+; CHECK-NEXT: table.set funcref_table
+; CHECK-NEXT: end_function
+
+;; this generates a table.set of @funcref_table
+  %p = getelementptr [0 x %funcref], [0 x %funcref] addrspace (1)* @funcref_table, i32 0, i32 %i
+  store %funcref %g, %funcref addrspace(1)* %p
+  ret void
+}
+
+define void @set_funcref_table_const(%funcref %g) {
+; CHECK-LABEL: set_funcref_table_const:
+; CHECK-NEXT:  .functype  set_funcref_table_const (funcref) -> ()
+; CHECK-NEXT:  i32.const  0
+; CHECK-NEXT:  local.get  0
+; CHECK-NEXT:  table.set  funcref_table
+; CHECK-NEXT:  end_function
+  %p = getelementptr [0 x %funcref], [0 x %funcref] addrspace (1)* @funcref_table, i32 0, i32 0
+  store %funcref %g, %funcref addrspace(1)* %p
+  ret void
+}
+
+define void @set_funcref_table_with_offset(%funcref %g, i32 %i) {
+; CHECK-LABEL: set_funcref_table_with_offset:
+; CHECK-NEXT:  .functype   set_funcref_table_with_offset (funcref, i32) -> ()
+; CHECK-NEXT:  local.get   1
+; CHECK-NEXT:  i32.const   2
+; CHECK-NEXT:  i32.add
+; CHECK-NEXT:  local.get   0
+; CHECK-NEXT:  table.set   funcref_table
+; CHECK-NEXT:  end_function
+  %off = add nsw i32 %i, 2
+  %p = getelementptr [0 x %funcref], [0 x %funcref] addrspace (1)* @funcref_table, i32 0, i32 %off
+  store %funcref %g, %funcref addrspace(1)* %p
+  ret void
+}
+
+define void @set_funcref_table_with_var_offset(%funcref %g, i32 %i, i32 %j) {
+; CHECK-LABEL: set_funcref_table_with_var_offset:
+; CHECK-NEXT:  .functype   set_funcref_table_with_var_offset (funcref, i32, i32) -> ()
+; CHECK-NEXT:  local.get   1
+; CHECK-NEXT:  local.get   2
+; CHECK-NEXT:  i32.add
+; CHECK-NEXT:  local.get   0
+; CHECK-NEXT:  table.set   funcref_table
+; CHECK-NEXT:  end_function
+  %off = add nsw i32 %i, %j
+  %p = getelementptr [0 x %funcref], [0 x %funcref] addrspace (1)* @funcref_table, i32 0, i32 %off
+  store %funcref %g, %funcref addrspace(1)* %p
+  ret void
+}
+
+declare i32 @set_offset()
+
+define void @set_funcre

[PATCH] D111154: [WebAssembly] Implementation of table.get/set for reftypes in LLVM IR

2021-10-20 Thread Paulo Matos via Phabricator via cfe-commits
pmatos added a comment.

In D54#3074221 , @tlively wrote:

> Nice! Just a couple nits but I think this is good to go.

Perfect, thanks for the comments. Fixed nits and landed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54

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


[PATCH] D106681: [analyzer][NFC] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

@steakhal
All your comments are fair in terms of NFC. I also tried to improve some 
places. I think I should requalificate the revision to non-NFC, that I can be 
more untied to bring some improvements.




Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1636
+
+  // Array should be immutable.
+  const VarDecl *VD = VR->getDecl();

steakhal wrote:
> Please preserve the original comment.
OK.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1650
+  // TODO: Support multidimensional array.
+  if (isa(CAT->getElementType())) // is multidimensional
+return None;

steakhal wrote:
> What if that is a typedef?
I'll add a test case.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1714
+  // Return a constant value, if it is presented.
+  // FIXME: Support other SVals.
+  const Expr *E = ILE->getInit(Offset);

steakhal wrote:
> What other values could appear in this context other than constants?
It's hard to say. I didn't do any investigation yet, but I think some symbolic 
or loc values.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106681

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


[PATCH] D106681: [analyzer][NFC] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1686-1689
+  // Array's declaration should have an initializer.
+  const Expr *Init = VD->getAnyInitializer();
+  if (!Init)
+return None;

steakhal wrote:
> This should have been checked at L1642 to preserve the original behavior.
> As of now, the code might return `UndefinedVal` at L1683 or `Unknown` at 
> L1659, which is probably different than the original behavior - unless you 
> prove otherwise.
`Unknown` at L1659 comes from 
`RegionStoreManager::getBindingForFieldOrElementCommon`. As you can see, there 
is a snippet in here:
```
if (hasSymbolicIndex)
  return UnknownVal();
```



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106681

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


[PATCH] D106681: [analyzer][NFC] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1686-1689
+  // Array's declaration should have an initializer.
+  const Expr *Init = VD->getAnyInitializer();
+  if (!Init)
+return None;

ASDenysPetrov wrote:
> steakhal wrote:
> > This should have been checked at L1642 to preserve the original behavior.
> > As of now, the code might return `UndefinedVal` at L1683 or `Unknown` at 
> > L1659, which is probably different than the original behavior - unless you 
> > prove otherwise.
> `Unknown` at L1659 comes from 
> `RegionStoreManager::getBindingForFieldOrElementCommon`. As you can see, 
> there is a snippet in here:
> ```
> if (hasSymbolicIndex)
>   return UnknownVal();
> ```
> 
UndefinedVal at L1683 preserves exactly the previous behaviour.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106681

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


[PATCH] D112020: [RISCV] Use clang_builtin_alias for all RISCV vector intrinsics.

2021-10-20 Thread Hsiangkai Wang via Phabricator via cfe-commits
HsiangKai accepted this revision.
HsiangKai added a comment.
This revision is now accepted and ready to land.

I ran tests under `clang/test/CodeGen/RISCV/rvv-intrinsics/`. It spent a little 
more time to run the tests. (previous: 84.01s; apply this patch: 96.43s in my 
local environment.) We could apply some technic similar to D111617 
 to reduce the header size. I think to reduce 
the number of RVV builtins is important in the long run.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112020

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


[PATCH] D112102: [RISCV] Reduce the number of RISCV vector builtins by an order of magnitude.

2021-10-20 Thread Fraser Cormack via Phabricator via cfe-commits
frasercrmck added inline comments.



Comment at: llvm/test/CodeGen/RISCV/rvv/vmerge-rv32.ll:1358
+; CHECK-NEXT:vsetvli zero, a0, e16, mf4, ta, mu
+; CHECK-NEXT:vmerge.vvm v8, v8, v9, v0
+; CHECK-NEXT:ret

HsiangKai wrote:
> vmerge.vvm is for integer vectors, doesn't it? Why does it work for floating 
> point vector types?
It's just a `vselect` in llvm terms, so doesn't care what its (vector) inputs 
are. The only reason we need `vfmerge` is when one operand is a scalar 
floating-point register.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112102

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


[clang] f45d740 - [docs] Fix hyperlink

2021-10-20 Thread Sven van Haastregt via cfe-commits

Author: Sven van Haastregt
Date: 2021-10-20T10:20:17+01:00
New Revision: f45d7407168d08c4d80216ca13feb1e1c21ad6bb

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

LOG: [docs] Fix hyperlink

Added: 


Modified: 
clang/docs/UsersManual.rst

Removed: 




diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index 30da581c6770..68c112c964f2 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -2863,7 +2863,7 @@ clang fully implements all of standard C++98 except for 
exported
 templates (which were removed in C++11), all of standard C++11,
 C++14, and C++17, and most of C++20.
 
-See the `C++ support in Clang ` page
+See the `C++ support in Clang `_ page
 for detailed information on C++ feature support across Clang versions.
 
 Controlling implementation limits



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


[PATCH] D112102: [RISCV] Reduce the number of RISCV vector builtins by an order of magnitude.

2021-10-20 Thread Fraser Cormack via Phabricator via cfe-commits
frasercrmck added a comment.

Minor typo in the description: `differnet`

Does this help with compile times, binary sizes, etc?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112102

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


[PATCH] D99797: [analyzer] Implemented RangeSet::Factory::unite function to handle intersections and adjacency

2021-10-20 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:149
+
+RangeSet RangeSet::Factory::unite(RangeSet Original, llvm::APSInt Point) {
+  return unite(Original, Range(ValueFactory.getValue(Point)));

ASDenysPetrov wrote:
> steakhal wrote:
> > Why do you take `APSInt`s by value? Generally, we take them by reference.
> I want to send a message to the caller that he can pass an arbitrary 
> **APSInt** without warrying about making it permanent (aka stored by the 
> Factory). But we can revise this contract and carry this responsibility to a 
> caller.
> Why do you take `APSInt`s by value? Generally, we take them by reference.

Actually, it is specific to `BasicValueFactory` to cache the `APSInt`s, 
however, it might not be the best practice. I doubt that somebody has ever 
measured the performance of passing APSInts by value, so my guess is the 
caching of `APSInt`s might be an early optimization that might be more harmful 
than advantageous. On top of all this, we do the caching inconsistently, just 
consider the member functions of `APSIntType`, they all return by value.

Perhaps (totally independently from this patch of course), it might be worth to 
have a measurement/comparison with removed cache and pass by value.



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

https://reviews.llvm.org/D99797

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


[PATCH] D106681: [analyzer][NFC] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

I think it's fine, maybe `NFCi` is would be slightly more accurate, while 
stating the minor behavior change and the reason for doing so in the patch 
summary could further improve the visibility of this issue.

That being said, since it actually changes some behavior, I'd like to request 
some tests covering the following (uncovered lines):
L1646, L1689, L1699


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106681

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


[PATCH] D112020: [RISCV] Use clang_builtin_alias for all RISCV vector intrinsics.

2021-10-20 Thread Zakk Chen via Phabricator via cfe-commits
khchen accepted this revision.
khchen added a comment.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112020

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


[PATCH] D111639: [Sema] check PseudoObject when rebuilding CXXOperatorCallExpr in template instantiation

2021-10-20 Thread Bruno De Fraine via Phabricator via cfe-commits
brunodf updated this revision to Diff 380885.
brunodf edited the summary of this revision.
brunodf added a reviewer: akyrtzi.
brunodf added a subscriber: akyrtzi.
brunodf added a comment.

@rnk raises the remark that TreeTransform::RebuildCXXOperatorCallExpr already 
contains code to handle ObjC pseudo objects (including checking pseudo object 
assignment) and that calling Build*Op will re-run a lot of redundant checks.

To address this, in this updated diff, I tried to generalize the code for ObjC 
pseudo object handling (which originates from @akyrtzi in commit 0f99537ecac40) 
to handle other pseudo object kinds in addition to ObjC. I think calling 
`checkPseudoObjectAssignment` and `checkPseudoObjectIncDec` is critical for the 
PR I'm trying to solve, not sure about `CheckPlaceholderExpr`, but I retained 
that from @akyrtzi his patch.

Adding @akyrtzi as reviewer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111639

Files:
  clang/lib/Sema/TreeTransform.h
  clang/test/SemaCXX/PR51855.cpp

Index: clang/test/SemaCXX/PR51855.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/PR51855.cpp
@@ -0,0 +1,71 @@
+// RUN: %clang_cc1 -S -triple %itanium_abi_triple -fms-extensions -emit-llvm %s -o - | FileCheck %s
+
+struct F {};
+
+F operator*=(F &lhs, int rhs);
+
+F operator++(F &lhs);
+
+struct S {
+  short _m;
+  S(short _m) : _m(_m) {}
+
+  void putM(short rhs) { _m = rhs; }
+  short getM() { return _m; }
+
+  __declspec(property(get = getM, put = putM)) short theData;
+};
+
+int test1a(int i) {
+  S tmp(i);
+  tmp.theData *= 2;
+  return tmp.theData;
+}
+
+// CHECK-LABEL: define {{.*}} i32 @_Z6test1ai(i32 %i)
+// CHECK: call void @_ZN1SC1Es
+// CHECK: call {{(signext )?i16}} @_ZN1S4getMEv
+// CHECK: call void @_ZN1S4putMEs
+// CHECK: call {{(signext )?i16}} @_ZN1S4getMEv
+
+template 
+int test1b(int i) {
+  T tmp(i);
+  tmp.theData *= 2;
+  return tmp.theData;
+}
+
+template int test1b(int);
+
+// CHECK-LABEL: define {{.*}} i32 @_Z6test1bI1SEii(i32 %i)
+// CHECK: call void @_ZN1SC1Es
+// CHECK: call {{(signext )?i16}} @_ZN1S4getMEv
+// CHECK: call void @_ZN1S4putMEs
+// CHECK: call {{(signext )?i16}} @_ZN1S4getMEv
+
+int test2a(int i) {
+  S tmp(i);
+  ++tmp.theData;
+  return tmp.theData;
+}
+
+// CHECK-LABEL: define {{.*}} i32 @_Z6test2ai(i32 %i)
+// CHECK: call void @_ZN1SC1Es
+// CHECK: call {{(signext )?i16}} @_ZN1S4getMEv
+// CHECK: call void @_ZN1S4putMEs
+// CHECK: call {{(signext )?i16}} @_ZN1S4getMEv
+
+template 
+int test2b(int i) {
+  T tmp(i);
+  ++tmp.theData;
+  return tmp.theData;
+}
+
+template int test2b(int);
+
+// CHECK-LABEL: define {{.*}} i32 @_Z6test2bI1SEii(i32 %i)
+// CHECK: call void @_ZN1SC1Es
+// CHECK: call {{(signext )?i16}} @_ZN1S4getMEv
+// CHECK: call void @_ZN1S4putMEs
+// CHECK: call {{(signext )?i16}} @_ZN1S4getMEv
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -14569,24 +14569,6 @@
   Expr *Callee = OrigCallee->IgnoreParenCasts();
   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
 
-  if (First->getObjectKind() == OK_ObjCProperty) {
-BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
-if (BinaryOperator::isAssignmentOp(Opc))
-  return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
- First, Second);
-ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
-if (Result.isInvalid())
-  return ExprError();
-First = Result.get();
-  }
-
-  if (Second && Second->getObjectKind() == OK_ObjCProperty) {
-ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
-if (Result.isInvalid())
-  return ExprError();
-Second = Result.get();
-  }
-
   // Determine whether this should be a builtin operation.
   if (Op == OO_Subscript) {
 if (!First->getType()->isOverloadableType() &&
@@ -14602,8 +14584,21 @@
   // The argument is not of overloadable type, or this is an expression
   // of the form &Class::member, so try to create a built-in unary
   // operation.
+  //
+  // But handle pseudo-objects in the LHS, and increment and decrement
+  // of pseudo-object l-value (see Sema::BuildUnaryOp).
   UnaryOperatorKind Opc
 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
+  if (const BuiltinType *pty = First->getType()->getAsPlaceholderType()) {
+if (pty->getKind() == BuiltinType::PseudoObject &&
+UnaryOperator::isIncrementDecrementOp(Opc))
+  return SemaRef.checkPseudoObjectIncDec(/*Scope=*/nullptr, OpLoc, Opc,
+ First);
+ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
+if (Result.isInvalid())
+  return ExprError();

[PATCH] D112102: [RISCV] Reduce the number of RISCV vector builtins by an order of magnitude.

2021-10-20 Thread Zakk Chen via Phabricator via cfe-commits
khchen added inline comments.



Comment at: clang/include/clang/Basic/riscv_vector.td:120
 // type transformer (say "vv") each of the types is separated with an
 // underscore as in "__builtin_rvv_foo_i32m1_i32m1".
 //

nit: we need to update this comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112102

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


[PATCH] D107339: [analyzer] Retrieve a character from StringLiteral as an initializer for constant arrays.

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

In D107339#3060812 , @martong wrote:

> I am close to accepting this. However, D111542 
>  should be its parent patch. I think 
> similar issues could arise here as well, so, redecl chain tests would be 
> really beneficial.

I apologize for the delay, I'm still working on changes. I'll update it soon.


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

https://reviews.llvm.org/D107339

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


[PATCH] D112130: [clangd] Fix use-after-free in HeaderIncluderCache

2021-10-20 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: sammccall.
Herald added subscribers: usaxena95, arphaman, javed.absar.
kadircet requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Includer cache could get into a bad state when a main file went bad and
added back afterwards. This fixes the issue by getting rid of the main file to
first pointer completely to make sure we don't try invalidating again.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112130

Files:
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp


Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1174,10 +1174,10 @@
  Unreliable = testPath("unreliable.h"),
  OK = testPath("ok.h"),
  NotIncluded = testPath("not_included.h");
-  class NoHeadersCDB : public GlobalCompilationDatabase {
+  struct NoHeadersCDB : public GlobalCompilationDatabase {
 llvm::Optional
 getCompileCommand(PathRef File) const override {
-  if (File == NoCmd || File == NotIncluded)
+  if (File == NoCmd || File == NotIncluded || FailAll)
 return llvm::None;
   auto Basic = getFallbackCommand(File);
   Basic.Heuristic.clear();
@@ -1192,6 +1192,8 @@
   }
   return Basic;
 }
+
+std::atomic FailAll{false};
   } CDB;
   TUScheduler S(CDB, optsForTest());
   auto GetFlags = [&](PathRef Header) {
@@ -1262,6 +1264,21 @@
   << "association invalidated but not reclaimed";
   EXPECT_THAT(GetFlags(NotIncluded), Contains("-DMAIN2"))
   << "association still valid";
+
+  // Delete the file from CDB, it should invalidate the associations.
+  CDB.FailAll = true;
+  EXPECT_THAT(GetFlags(NoCmd), Not(Contains("-DMAIN3")))
+  << "association should've been invalidated.";
+  // Also run update for Main3 to invalidate the preeamble to make sure next
+  // update populates include cache associations.
+  S.update(Main3, getInputs(Main3, SomeIncludes), WantDiagnostics::Yes);
+  EXPECT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  // Re-add the file and make sure nothing crashes.
+  CDB.FailAll = false;
+  S.update(Main3, getInputs(Main3, SomeIncludes), WantDiagnostics::Yes);
+  EXPECT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  EXPECT_THAT(GetFlags(NoCmd), Contains("-DMAIN3"))
+  << "association invalidated and then claimed by main3";
 }
 
 TEST_F(TUSchedulerTests, PreservesLastActiveFile) {
Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -285,9 +285,12 @@
   // will be eligible for association with other files that get update()d.
   void remove(PathRef MainFile) {
 std::lock_guard Lock(Mu);
-Association *&First = MainToFirst[MainFile];
-if (First)
-  invalidate(First);
+auto It = MainToFirst.find(MainFile);
+if (It == MainToFirst.end())
+  return;
+if (It->second)
+  invalidate(It->second);
+MainToFirst.erase(It);
   }
 
   /// Get the mainfile associated with Header, or the empty string if none.


Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1174,10 +1174,10 @@
  Unreliable = testPath("unreliable.h"),
  OK = testPath("ok.h"),
  NotIncluded = testPath("not_included.h");
-  class NoHeadersCDB : public GlobalCompilationDatabase {
+  struct NoHeadersCDB : public GlobalCompilationDatabase {
 llvm::Optional
 getCompileCommand(PathRef File) const override {
-  if (File == NoCmd || File == NotIncluded)
+  if (File == NoCmd || File == NotIncluded || FailAll)
 return llvm::None;
   auto Basic = getFallbackCommand(File);
   Basic.Heuristic.clear();
@@ -1192,6 +1192,8 @@
   }
   return Basic;
 }
+
+std::atomic FailAll{false};
   } CDB;
   TUScheduler S(CDB, optsForTest());
   auto GetFlags = [&](PathRef Header) {
@@ -1262,6 +1264,21 @@
   << "association invalidated but not reclaimed";
   EXPECT_THAT(GetFlags(NotIncluded), Contains("-DMAIN2"))
   << "association still valid";
+
+  // Delete the file from CDB, it should invalidate the associations.
+  CDB.FailAll = true;
+  EXPECT_THAT(GetFlags(NoCmd), Not(Contains("-DMAIN3")))
+  << "association should've been invalidated.";
+  // Also run update for Main3 to invalidate the preeamble to make sure next
+  // update populates include cache associa

[PATCH] D111992: [MLIR][OpenMP] Added omp.atomic.read and omp.atomic.write

2021-10-20 Thread Kiran Chandramohan via Phabricator via cfe-commits
kiranchandramohan added a comment.

The patch looks OK. I just wanted to discuss the syntax also. Would any of the 
following be better?

  %8 = omp.atomic.read %addr : memref -> i32 hint(speculative, contended) 
memory_order(seq_cst) 

  %8 = omp.atomic.read %addr hint(speculative, contended) memory_order(seq_cst) 
: memref -> i32 

  %8 = omp.atomic.read %addr {hint(speculative, contended) 
memory_order(seq_cst)} : memref -> i32


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111992

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


[PATCH] D111992: [MLIR][OpenMP] Added omp.atomic.read and omp.atomic.write

2021-10-20 Thread Shraiysh via Phabricator via cfe-commits
shraiysh added a comment.

Hi @kiranchandramohan. Thanks for the review.

>   %8 = omp.atomic.read %addr : memref -> i32 hint(speculative, 
> contended) memory_order(seq_cst)

This cannot be done because the statement ends at optional clauses. This is 
dangerous in the following situation where parser will try to match `return` as 
a clause instead of a new instruction. I had first actually tried it this way. 
Let me know if there is something that can be done to avoid this problem with 
this syntax.

  %8 = omp.atomic.read %addr : memref -> i32 memory_order(seq_cst)
  return

We can try one of remaining two. I do not have a preference between these three:

>   %8 = omp.atomic.read %addr hint(speculative, contended) 
> memory_order(seq_cst) : memref -> i32 
>
>   %8 = omp.atomic.read %addr {hint(speculative, contended) 
> memory_order(seq_cst)} : memref -> i32

  %8 = omp.atomic.read hint(speculative, contended) memory_order(seq_cst) %addr 
: memref -> i32 // current syntax


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111992

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


[PATCH] D106681: [analyzer][NFC] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

In D106681#3074678 , @steakhal wrote:

> I think it's fine, maybe `NFCi` is would be slightly more accurate, while 
> stating the minor behavior change and the reason for doing so in the patch 
> summary could further improve the visibility of this issue.
>
> That being said, since it actually changes some behavior, I'd like to request 
> some tests covering the following (uncovered lines):
> L1646, L1689, L1699

For **L1646** currently I'm not sure about the exact test, since it is a 
heritage of the old code, so it just jumped here from the past. If you could 
give an example I would appreciate this.
For **L1689** I'll add it.
For **L1699** I've added //TODO// cases in D104285 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106681

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


[PATCH] D112102: [RISCV] Reduce the number of RISCV vector builtins by an order of magnitude.

2021-10-20 Thread Hsiangkai Wang via Phabricator via cfe-commits
HsiangKai added inline comments.



Comment at: llvm/test/CodeGen/RISCV/rvv/vmerge-rv32.ll:1358
+; CHECK-NEXT:vsetvli zero, a0, e16, mf4, ta, mu
+; CHECK-NEXT:vmerge.vvm v8, v8, v9, v0
+; CHECK-NEXT:ret

frasercrmck wrote:
> HsiangKai wrote:
> > vmerge.vvm is for integer vectors, doesn't it? Why does it work for 
> > floating point vector types?
> It's just a `vselect` in llvm terms, so doesn't care what its (vector) inputs 
> are. The only reason we need `vfmerge` is when one operand is a scalar 
> floating-point register.
Got it. I think I am misled by the title "Vector Integer Merge Instructions" in 
the spec. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112102

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


[PATCH] D112102: [RISCV] Reduce the number of RISCV vector builtins by an order of magnitude.

2021-10-20 Thread Hsiangkai Wang via Phabricator via cfe-commits
HsiangKai added a comment.

In D112102#3074656 , @frasercrmck 
wrote:

> Minor typo in the description: `differnet`
>
> Does this help with compile times, binary sizes, etc?

After this patch, we may be able to consider removing all type ending C APIs. 
Otherwise, I don't think it is helpful with compile times or binary sizes, etc.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112102

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


[clang] ab2ca84 - consteval if does not form a discarded statement

2021-10-20 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-10-20T07:24:55-04:00
New Revision: ab2ca8496d54573de1c8bec204009567ba2b4086

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

LOG: consteval if does not form a discarded statement

When we added support for if consteval, we accidentally formed a discarded
statement evaluation context for the branch-not-taken. However, a discarded
statement is a property of an if constexpr statement, not an if consteval
statement (https://eel.is/c++draft/stmt.if#2.sentence-2). This turned out to
cause issues when deducing the return type from a function with a consteval if
statement -- we wouldn't consider the branch-not-taken when deducing the return
type.

This fixes PR52206.

Note, there is additional work left to be done. We need to track discarded
statement and immediate evaluation contexts separately rather than as being
mutually exclusive.

Added: 
clang/test/SemaCXX/cxx2b-consteval-if.cpp

Modified: 
clang/lib/Parse/ParseStmt.cpp

Removed: 




diff  --git a/clang/lib/Parse/ParseStmt.cpp b/clang/lib/Parse/ParseStmt.cpp
index 4d76dfe91052..bb8718671bb0 100644
--- a/clang/lib/Parse/ParseStmt.cpp
+++ b/clang/lib/Parse/ParseStmt.cpp
@@ -1441,12 +1441,13 @@ StmtResult Parser::ParseIfStatement(SourceLocation 
*TrailingElseLoc) {
   SourceLocation InnerStatementTrailingElseLoc;
   StmtResult ThenStmt;
   {
-bool ShouldEnter =
-(ConstexprCondition && !*ConstexprCondition) || IsConsteval;
+bool ShouldEnter = ConstexprCondition && !*ConstexprCondition;
 Sema::ExpressionEvaluationContext Context =
 Sema::ExpressionEvaluationContext::DiscardedStatement;
-if (NotLocation.isInvalid() && IsConsteval)
+if (NotLocation.isInvalid() && IsConsteval) {
   Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;
+  ShouldEnter = true;
+}
 
 EnterExpressionEvaluationContext PotentiallyDiscarded(
 Actions, Context, nullptr,
@@ -1485,12 +1486,13 @@ StmtResult Parser::ParseIfStatement(SourceLocation 
*TrailingElseLoc) {
   Tok.is(tok::l_brace));
 
 MisleadingIndentationChecker MIChecker(*this, MSK_else, ElseLoc);
-bool ShouldEnter =
-(ConstexprCondition && *ConstexprCondition) || IsConsteval;
+bool ShouldEnter = ConstexprCondition && *ConstexprCondition;
 Sema::ExpressionEvaluationContext Context =
 Sema::ExpressionEvaluationContext::DiscardedStatement;
-if (NotLocation.isValid() && IsConsteval)
+if (NotLocation.isValid() && IsConsteval) {
   Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;
+  ShouldEnter = true;
+}
 
 EnterExpressionEvaluationContext PotentiallyDiscarded(
 Actions, Context, nullptr,

diff  --git a/clang/test/SemaCXX/cxx2b-consteval-if.cpp 
b/clang/test/SemaCXX/cxx2b-consteval-if.cpp
new file mode 100644
index ..e60959e5988d
--- /dev/null
+++ b/clang/test/SemaCXX/cxx2b-consteval-if.cpp
@@ -0,0 +1,57 @@
+// RUN: %clang_cc1 -std=c++2b -verify %s
+
+namespace PR52206 {
+constexpr auto f() {
+  if consteval  { return 0;   }
+  if !consteval { return 0.0; } // expected-error {{'auto' in return type 
deduced as 'double' here but deduced as 'int' in earlier return statement}}
+}
+
+constexpr auto g() {
+  if !consteval { return 0;   }
+  if consteval  { return 0.0; } // expected-error {{'auto' in return type 
deduced as 'double' here but deduced as 'int' in earlier return statement}}
+}
+
+constexpr auto h() {
+  if consteval  { return 0; }
+  if !consteval { return 0; } // okay
+}
+
+constexpr auto i() {
+  if consteval {
+if consteval { // expected-warning {{consteval if is always true in an 
immediate context}}
+ return 1;
+   }
+   return 2;
+  } else {
+return 1.0; // expected-error {{'auto' in return type deduced as 'double' 
here but deduced as 'int' in earlier return statement}}
+  }
+}
+
+void test() {
+  auto x1 = f();
+  constexpr auto y1 = f();
+
+  auto x2 = g();
+  constexpr auto y2 = g();
+
+  auto x3 = h();
+  constexpr auto y3 = h();
+
+  auto x4 = i();
+  constexpr auto y4 = i();
+}
+} // namespace PR52206
+
+consteval int *make() { return new int; }
+auto f() {
+  if constexpr (false) {
+if consteval {
+  // Immediate function context, so call to `make()` is valid.
+  // Discarded statement context, so `return 0;` is valid too.
+  delete make();
+  return 0;
+}
+  }
+  // FIXME: this error should not happen.
+  return 0.0; // expected-error {{'auto' in return type deduced as 'double' 
here but deduced as 'int' in earlier return statement}}
+}



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


[PATCH] D112089: consteval if does not form a discarded statement

2021-10-20 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

I've commit in ab2ca8496d54573de1c8bec204009567ba2b4086 
 and filed 
https://bugs.llvm.org/show_bug.cgi?id=52231 as the bug for the remaining bits, 
thanks for the reviews and discussion!




Comment at: clang/lib/Parse/ParseStmt.cpp:1445-1450
 Sema::ExpressionEvaluationContext Context =
 Sema::ExpressionEvaluationContext::DiscardedStatement;
-if (NotLocation.isInvalid() && IsConsteval)
+if (NotLocation.isInvalid() && IsConsteval) {
   Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;
+  ShouldEnter = true;
+}

cor3ntin wrote:
> rsmith wrote:
> > rsmith wrote:
> > > It looks to me like this is still incorrectly updating the context in 
> > > some cases. We shouldn't enter an immediate function context if we're 
> > > already in a discarded statement context. For example, Clang currently 
> > > rejects this valid code:
> > > 
> > > ```
> > > auto f() {
> > > if constexpr (false) {
> > > if consteval {
> > > return 0;
> > > }
> > > }
> > > return 0.0;
> > > }
> > > ```
> > > 
> > > ... and it looks like it still will after this change. I think we should 
> > > not enter a new context here if the existing context is a discarded 
> > > statement context.
> > Hm, not updating the context also seems wrong; then we'd reject things like 
> > this:
> > ```
> > consteval int *make() { return new int; }
> > auto f() {
> >   if constexpr (false) {
> > if consteval {
> >   // Immediate function context, so call to `make()` is valid.
> >   // Discarded statement context, so `return 0;` is valid too.
> >   delete make();
> >   return 0;
> > }
> >   }
> >   return 0.0;
> > }
> > ```
> > Perhaps we need to track whether we're in a discarded statement and whether 
> > we're in an immediate function context separately rather than treating them 
> > as mutually exclusive. I think it makes sense to go ahead with this patch 
> > as-is and deal with the bug that we overwrite a discarded statement context 
> > with an immediate function context separately.
> Hum, I missed these scenarios entirely. 
> But I agree with you, not entering an immediate context would be equally bad.
> I think the solution in both cases if to test whether any of the parent 
> context is discarded or immediate, instead of just looking at the current 
> context
> Perhaps we need to track whether we're in a discarded statement and whether 
> we're in an immediate function context separately rather than treating them 
> as mutually exclusive. I think it makes sense to go ahead with this patch 
> as-is and deal with the bug that we overwrite a discarded statement context 
> with an immediate function context separately.

I think you may be correct here. I've added your example to the test case with 
a FIXME comment so it's clear we've still got some work left to do here.  
Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112089

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


[PATCH] D112130: [clangd] Fix use-after-free in HeaderIncluderCache

2021-10-20 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 380895.
kadircet added a comment.

- Rather than dropping the entry, perform an extra check during invalidate. As

the entry actually backs the data for main file strings in associations.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112130

Files:
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp


Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1174,10 +1174,10 @@
  Unreliable = testPath("unreliable.h"),
  OK = testPath("ok.h"),
  NotIncluded = testPath("not_included.h");
-  class NoHeadersCDB : public GlobalCompilationDatabase {
+  struct NoHeadersCDB : public GlobalCompilationDatabase {
 llvm::Optional
 getCompileCommand(PathRef File) const override {
-  if (File == NoCmd || File == NotIncluded)
+  if (File == NoCmd || File == NotIncluded || FailAll)
 return llvm::None;
   auto Basic = getFallbackCommand(File);
   Basic.Heuristic.clear();
@@ -1192,6 +1192,8 @@
   }
   return Basic;
 }
+
+std::atomic FailAll{false};
   } CDB;
   TUScheduler S(CDB, optsForTest());
   auto GetFlags = [&](PathRef Header) {
@@ -1262,6 +1264,21 @@
   << "association invalidated but not reclaimed";
   EXPECT_THAT(GetFlags(NotIncluded), Contains("-DMAIN2"))
   << "association still valid";
+
+  // Delete the file from CDB, it should invalidate the associations.
+  CDB.FailAll = true;
+  EXPECT_THAT(GetFlags(NoCmd), Not(Contains("-DMAIN3")))
+  << "association should've been invalidated.";
+  // Also run update for Main3 to invalidate the preeamble to make sure next
+  // update populates include cache associations.
+  S.update(Main3, getInputs(Main3, SomeIncludes), WantDiagnostics::Yes);
+  EXPECT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  // Re-add the file and make sure nothing crashes.
+  CDB.FailAll = false;
+  S.update(Main3, getInputs(Main3, SomeIncludes), WantDiagnostics::Yes);
+  EXPECT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  EXPECT_THAT(GetFlags(NoCmd), Contains("-DMAIN3"))
+  << "association invalidated and then claimed by main3";
 }
 
 TEST_F(TUSchedulerTests, PreservesLastActiveFile) {
Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -224,6 +224,9 @@
   mutable std::mutex Mu;
 
   void invalidate(Association *First) {
+// Association might've already been invalidated.
+if (!First->Next)
+  return;
 Association *Current = First;
 do {
   Association *Next = Current->Next;
@@ -288,6 +291,8 @@
 Association *&First = MainToFirst[MainFile];
 if (First)
   invalidate(First);
+// MainToFirst entry should stay alive, as Associations might be pointing 
at
+// its key.
   }
 
   /// Get the mainfile associated with Header, or the empty string if none.


Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1174,10 +1174,10 @@
  Unreliable = testPath("unreliable.h"),
  OK = testPath("ok.h"),
  NotIncluded = testPath("not_included.h");
-  class NoHeadersCDB : public GlobalCompilationDatabase {
+  struct NoHeadersCDB : public GlobalCompilationDatabase {
 llvm::Optional
 getCompileCommand(PathRef File) const override {
-  if (File == NoCmd || File == NotIncluded)
+  if (File == NoCmd || File == NotIncluded || FailAll)
 return llvm::None;
   auto Basic = getFallbackCommand(File);
   Basic.Heuristic.clear();
@@ -1192,6 +1192,8 @@
   }
   return Basic;
 }
+
+std::atomic FailAll{false};
   } CDB;
   TUScheduler S(CDB, optsForTest());
   auto GetFlags = [&](PathRef Header) {
@@ -1262,6 +1264,21 @@
   << "association invalidated but not reclaimed";
   EXPECT_THAT(GetFlags(NotIncluded), Contains("-DMAIN2"))
   << "association still valid";
+
+  // Delete the file from CDB, it should invalidate the associations.
+  CDB.FailAll = true;
+  EXPECT_THAT(GetFlags(NoCmd), Not(Contains("-DMAIN3")))
+  << "association should've been invalidated.";
+  // Also run update for Main3 to invalidate the preeamble to make sure next
+  // update populates include cache associations.
+  S.update(Main3, getInputs(Main3, SomeIncludes), WantDiagnostics::Yes);
+  EXPECT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  // Re-add the fil

[PATCH] D106681: [analyzer][NFC] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 380897.
ASDenysPetrov added a comment.

Make changes according to comments. Thanks to @steakhal


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

https://reviews.llvm.org/D106681

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/initialization.c
  clang/test/Analysis/initialization.cpp

Index: clang/test/Analysis/initialization.cpp
===
--- clang/test/Analysis/initialization.cpp
+++ clang/test/Analysis/initialization.cpp
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -std=c++14 -triple i386-apple-darwin10 -analyze -analyzer-config eagerly-assume=false -analyzer-checker=core.uninitialized.Assign,core.builtin,debug.ExprInspection,core.uninitialized.UndefReturn -verify %s
 
+template 
+void clang_analyzer_dump(T x);
 void clang_analyzer_eval(int);
 
 struct S {
@@ -32,6 +34,10 @@
   auto x = ptr[idx]; // expected-warning{{garbage or undefined}}
 }
 
+void glob_symbolic_index1(int idx) {
+  clang_analyzer_dump(glob_arr1[idx]); // expected-warning{{Unknown}}
+}
+
 int const glob_arr2[4] = {1, 2};
 void glob_ptr_index1() {
   int const *ptr = glob_arr2;
@@ -128,3 +134,15 @@
   // FIXME: Should warn {{garbage or undefined}}.
   auto x = ptr[idx]; // // no-warning
 }
+
+extern const int glob_arr_no_init[10];
+void glob_array_index4() {
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}
+
+struct S {
+  static const int arr_no_init[10];
+};
+void struct_arr_index1() {
+  clang_analyzer_eval(S::arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}
Index: clang/test/Analysis/initialization.c
===
--- clang/test/Analysis/initialization.c
+++ clang/test/Analysis/initialization.c
@@ -97,3 +97,8 @@
   // FIXME: Should warn {{garbage or undefined}}.
   int res = glob_arr2[x][y]; // no-warning
 }
+
+const int glob_arr_no_init[10];
+void glob_arr_index4() {
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -437,6 +437,10 @@
 
   RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B,
 const SubRegion *R);
+  Optional getConstantValFromConstArrayInitializer(
+  RegionBindingsConstRef B, const VarRegion *VR, const ElementRegion *R);
+  Optional getSValFromInitListExpr(const InitListExpr *ILE,
+ uint64_t Offset, QualType ElemT);
 
 public: // Part of public interface to class.
 
@@ -1625,6 +1629,94 @@
   return Result;
 }
 
+Optional RegionStoreManager::getConstantValFromConstArrayInitializer(
+RegionBindingsConstRef B, const VarRegion *VR, const ElementRegion *R) {
+  assert(R && VR && "Regions should not be null");
+
+  // Check if the containing array has an initialized value that we can trust.
+  // We can trust a const value or a value of a global initializer in main().
+  const VarDecl *VD = VR->getDecl();
+  if (!VD->getType().isConstQualified() &&
+  !R->getElementType().isConstQualified() &&
+  (!B.isMainAnalysis() || !VD->hasGlobalStorage()))
+return None;
+
+  // Array's declaration should have an initializer.
+  const Expr *Init = VD->getAnyInitializer();
+  if (!Init)
+return None;
+
+  // Array's declaration should have ConstantArrayType type.
+  const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(VD->getType());
+  if (!CAT)
+return None;
+
+  // Array should be one-dimensional.
+  // TODO: Support multidimensional array.
+  if (isa(CAT->getElementType())) // is multidimensional
+return None;
+
+  // Array's offset should be a concrete value.
+  // Return Unknown value if symbolic index presented.
+  // FIXME: We also need to take ElementRegions with symbolic
+  // indexes into account.
+  const auto OffsetVal = R->getIndex().getAs();
+  if (!OffsetVal.hasValue())
+return UnknownVal();
+
+  // Check offset for being out of bounds.
+  // C++20 [expr.add] 7.6.6.4 (excerpt):
+  //   If P points to an array element i of an array object x with n
+  //   elements, where i < 0 or i > n, the behavior is undefined.
+  //   Dereferencing is not allowed on the "one past the last
+  //   element", when i == n.
+  // Example:
+  //   const int arr[4] = {1, 2};
+  //   const int *ptr = arr;
+  //   int x0 = ptr[0];  // 1
+  //   int x1 = ptr[1];  // 2
+  //   int x2 = ptr[2];  // 0
+  //   int x3 = ptr[3];  // 0
+  //   int x4 = ptr[4];  // UB
+  //   int x5 = ptr[-1]; // UB
+  const llvm::APSInt &OffsetInt = OffsetVal->getValue();
+  const auto Offset = static_cast(OffsetInt.getExtValue());
+  // Use `getZExtValue` because array extent can not be negative.
+  const uint64_t Extent = CAT->getSize().getZExtValue();
+

[PATCH] D112081: Define __STDC_NO_THREADS__ when targeting windows-msvc (PR48704)

2021-10-20 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

In D112081#3073291 , @rjmccall wrote:

> The standard answer is that compilers are designed to work with a specific 
> set of system headers.  In the Clang-on-Windows case, that's complicated by 
> the fact that many people acquire Clang separately from the rest of the build 
> environment (although Microsoft does distribute Clang officially now, 
> right?), but I think the standard answer is still ultimately the correct one: 
> Clang is designed to support the MSVC system headers that are currently out 
> in the world, and whenever Microsoft releases new system headers, it's 
> possible that you will need a new version of Clang.
>
> As an aside, it's unfortunate that the name of this define makes it sound 
> like not defining it implies that the environment is not concurrent.   Oh 
> well; if the standard says it's tied to the header, then obviously it's right 
> to not define it.

Yeah... I wish it was this clean and clear cut. :-D

N2731 (the latest C2x working draft) says in 6.10.8.3p1:

  __STDC_NO_THREADS__ The integer constant 1, intended to indicate that the 
implementation does not support the  header.

Which seems pretty straight-forward, until you get to 7.26.1p2:

  Implementations that define the macro __STDC_NO_THREADS__ need not provide 
this header nor support any of its facilities.

and those facilities includes `thread_local` (the macro that expands to 
`_Thread_local`, the keyword), which got me wondering whether `_Thread_local` 
has any relationship with `__STDC_NO_THREADS__`. The standard did not claim 
there was, which supports the changes in this patch, but I remember this 
discussion happening in WG14. I dug around and found 
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2291.htm that deals with 
exactly this question, and there was no consensus to adopt this proposal in 
WG14, so I eventually convinced myself this implementation is valid.

LGTM. :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112081

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


[PATCH] D106681: [analyzer][NFC] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 380906.
ASDenysPetrov added a comment.

Minor comment update.


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

https://reviews.llvm.org/D106681

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/initialization.c
  clang/test/Analysis/initialization.cpp

Index: clang/test/Analysis/initialization.cpp
===
--- clang/test/Analysis/initialization.cpp
+++ clang/test/Analysis/initialization.cpp
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -std=c++14 -triple i386-apple-darwin10 -analyze -analyzer-config eagerly-assume=false -analyzer-checker=core.uninitialized.Assign,core.builtin,debug.ExprInspection,core.uninitialized.UndefReturn -verify %s
 
+template 
+void clang_analyzer_dump(T x);
 void clang_analyzer_eval(int);
 
 struct S {
@@ -32,6 +34,10 @@
   auto x = ptr[idx]; // expected-warning{{garbage or undefined}}
 }
 
+void glob_symbolic_index1(int idx) {
+  clang_analyzer_dump(glob_arr1[idx]); // expected-warning{{Unknown}}
+}
+
 int const glob_arr2[4] = {1, 2};
 void glob_ptr_index1() {
   int const *ptr = glob_arr2;
@@ -128,3 +134,15 @@
   // FIXME: Should warn {{garbage or undefined}}.
   auto x = ptr[idx]; // // no-warning
 }
+
+extern const int glob_arr_no_init[10];
+void glob_array_index4() {
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}
+
+struct S {
+  static const int arr_no_init[10];
+};
+void struct_arr_index1() {
+  clang_analyzer_eval(S::arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}
Index: clang/test/Analysis/initialization.c
===
--- clang/test/Analysis/initialization.c
+++ clang/test/Analysis/initialization.c
@@ -97,3 +97,8 @@
   // FIXME: Should warn {{garbage or undefined}}.
   int res = glob_arr2[x][y]; // no-warning
 }
+
+const int glob_arr_no_init[10];
+void glob_arr_index4() {
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -437,6 +437,10 @@
 
   RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B,
 const SubRegion *R);
+  Optional getConstantValFromConstArrayInitializer(
+  RegionBindingsConstRef B, const VarRegion *VR, const ElementRegion *R);
+  Optional getSValFromInitListExpr(const InitListExpr *ILE,
+ uint64_t Offset, QualType ElemT);
 
 public: // Part of public interface to class.
 
@@ -1625,6 +1629,95 @@
   return Result;
 }
 
+Optional RegionStoreManager::getConstantValFromConstArrayInitializer(
+RegionBindingsConstRef B, const VarRegion *VR, const ElementRegion *R) {
+  assert(R && VR && "Regions should not be null");
+
+  // Check if the containing array has an initialized value that we can trust.
+  // We can trust a const value or a value of a global initializer in main().
+  const VarDecl *VD = VR->getDecl();
+  if (!VD->getType().isConstQualified() &&
+  !R->getElementType().isConstQualified() &&
+  (!B.isMainAnalysis() || !VD->hasGlobalStorage()))
+return None;
+
+  // Array's declaration should have an initializer.
+  const Expr *Init = VD->getAnyInitializer();
+  if (!Init)
+return None;
+
+  // Array's declaration should have ConstantArrayType type, because only this
+  // type contains an array extent.
+  const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(VD->getType());
+  if (!CAT)
+return None;
+
+  // Array should be one-dimensional.
+  // TODO: Support multidimensional array.
+  if (isa(CAT->getElementType())) // is multidimensional
+return None;
+
+  // Array's offset should be a concrete value.
+  // Return Unknown value if symbolic index presented.
+  // FIXME: We also need to take ElementRegions with symbolic
+  // indexes into account.
+  const auto OffsetVal = R->getIndex().getAs();
+  if (!OffsetVal.hasValue())
+return UnknownVal();
+
+  // Check offset for being out of bounds.
+  // C++20 [expr.add] 7.6.6.4 (excerpt):
+  //   If P points to an array element i of an array object x with n
+  //   elements, where i < 0 or i > n, the behavior is undefined.
+  //   Dereferencing is not allowed on the "one past the last
+  //   element", when i == n.
+  // Example:
+  //   const int arr[4] = {1, 2};
+  //   const int *ptr = arr;
+  //   int x0 = ptr[0];  // 1
+  //   int x1 = ptr[1];  // 2
+  //   int x2 = ptr[2];  // 0
+  //   int x3 = ptr[3];  // 0
+  //   int x4 = ptr[4];  // UB
+  //   int x5 = ptr[-1]; // UB
+  const llvm::APSInt &OffsetInt = OffsetVal->getValue();
+  const auto Offset = static_cast(OffsetInt.getExtValue());
+  // Use `getZExtValue` because array extent can not be negative.
+  const uint64_t Extent = CAT->getSiz

[PATCH] D106681: [analyzer][NFCI] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1666
+  if (!OffsetVal.hasValue())
+return UnknownVal();
+

Item 2 from the Summary. This was borrowed from 
`RegionStoreManager::getBindingForFieldOrElementCommon` :
```
   if (hasSymbolicIndex)
  return UnknownVal();
```


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

https://reviews.llvm.org/D106681

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


[PATCH] D111542: [analyzer] Retrieve incomplete array extent from its redeclaration.

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 380910.
ASDenysPetrov added a comment.

Updated according to the latest suggestions.
@martong I think now this patch is way more simple and clear than before.


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

https://reviews.llvm.org/D111542

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/initialization.c


Index: clang/test/Analysis/initialization.c
===
--- clang/test/Analysis/initialization.c
+++ clang/test/Analysis/initialization.c
@@ -102,3 +102,42 @@
 void glob_arr_index4() {
   clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
 }
+
+const int glob_arr3[];  // IncompleteArrayType
+const int glob_arr3[4] = {1, 2, 3}; // ConstantArrayType
+void glob_arr_index4() {
+  clang_analyzer_eval(glob_arr3[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[2] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[3] == 0); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index5() {
+  int x = 42;
+  int res = glob_arr3[x]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index6() {
+  int x = -42;
+  int res = glob_arr3[x]; // expected-warning{{garbage or undefined}}
+}
+
+const int glob_arr4[];  // IncompleteArrayType
+const int glob_arr4[4] = {1, 2, 3}; // ConstantArrayType
+const int glob_arr4[];  // ConstantArrayType (according to AST)
+void glob_arr_index5() {
+  clang_analyzer_eval(glob_arr4[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[2] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[3] == 0); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index7() {
+  int x = 42;
+  int res = glob_arr4[x]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index8() {
+  int x = -42;
+  int res = glob_arr4[x]; // expected-warning{{garbage or undefined}}
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1641,8 +1641,14 @@
   (!B.isMainAnalysis() || !VD->hasGlobalStorage()))
 return None;
 
-  // Array's declaration should have an initializer.
-  const Expr *Init = VD->getAnyInitializer();
+  // Array's declaration should have `ConstantArrayType` type, because only 
this
+  // type contains an array extent. It may happen that array type can be of
+  // `IncompleteArrayType` type. To get the declaration of `ConstantArrayType`
+  // type, we should find the declaration in the redeclarations chain that has
+  // the initialization expression.
+  // NOTE: `VD` is always non-null if `Init` is non-null, so we can check for
+  // null only one of them.
+  const Expr *Init = VD->getAnyInitializer(VD);
   if (!Init)
 return None;
 


Index: clang/test/Analysis/initialization.c
===
--- clang/test/Analysis/initialization.c
+++ clang/test/Analysis/initialization.c
@@ -102,3 +102,42 @@
 void glob_arr_index4() {
   clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
 }
+
+const int glob_arr3[];  // IncompleteArrayType
+const int glob_arr3[4] = {1, 2, 3}; // ConstantArrayType
+void glob_arr_index4() {
+  clang_analyzer_eval(glob_arr3[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[2] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[3] == 0); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index5() {
+  int x = 42;
+  int res = glob_arr3[x]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index6() {
+  int x = -42;
+  int res = glob_arr3[x]; // expected-warning{{garbage or undefined}}
+}
+
+const int glob_arr4[];  // IncompleteArrayType
+const int glob_arr4[4] = {1, 2, 3}; // ConstantArrayType
+const int glob_arr4[];  // ConstantArrayType (according to AST)
+void glob_arr_index5() {
+  clang_analyzer_eval(glob_arr4[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[2] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[3] == 0); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index7() {
+  int x = 42;
+  int res = glob_arr4[x]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index8() {
+  int x = -42;
+  int res = glob_arr4[x]; // expected-warning{{garbage or undefined}}
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- cl

[PATCH] D111542: [analyzer] Retrieve incomplete array extent from its redeclaration.

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

In D111542#3073709 , @NoQ wrote:

> Amazing, thanks a lot!

Thank you, @NoQ, for the acceptance. I got some fresher update. And, of course 
in order to load it, we should accept a parent revision D106681 
 as well.


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

https://reviews.llvm.org/D111542

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


[libunwind] 5a8ad80 - [libunwind] Use the from-scratch testing configuration by default

2021-10-20 Thread Louis Dionne via cfe-commits

Author: Louis Dionne
Date: 2021-10-20T08:45:58-04:00
New Revision: 5a8ad80b6fa5cbad58b78384f534b78fca863e7f

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

LOG: [libunwind] Use the from-scratch testing configuration by default

This commit switches libunwind from using the complicated logic in
libc++'s testing configuration to a from-scratch configuration.
I tried to make sure that all cases that were handled in the old
config were handled by this one too, so hopefully this shouldn't
break anyone. However, if you encounter issues with this change,
please let me know and feel free to revert if I don't reply quickly.

This change was engineered to be easily revertable.

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

Added: 


Modified: 
libunwind/CMakeLists.txt

Removed: 




diff  --git a/libunwind/CMakeLists.txt b/libunwind/CMakeLists.txt
index 59d489b909e4..93fd722475c2 100644
--- a/libunwind/CMakeLists.txt
+++ b/libunwind/CMakeLists.txt
@@ -87,7 +87,13 @@ set(LIBUNWIND_TEST_LINKER_FLAGS "" CACHE STRING
 "Additional linker flags for test programs.")
 set(LIBUNWIND_TEST_COMPILER_FLAGS "" CACHE STRING
 "Additional compiler flags for test programs.")
-set(LIBUNWIND_TEST_CONFIG "${CMAKE_CURRENT_SOURCE_DIR}/test/lit.site.cfg.in" 
CACHE STRING
+
+if (LIBUNWIND_ENABLE_SHARED)
+  set(LIBUNWIND_DEFAULT_TEST_CONFIG "llvm-libunwind-shared.cfg.in")
+else()
+  set(LIBUNWIND_DEFAULT_TEST_CONFIG "llvm-libunwind-static.cfg.in")
+endif()
+set(LIBUNWIND_TEST_CONFIG "${LIBUNWIND_DEFAULT_TEST_CONFIG}" CACHE STRING
   "The path to the Lit testing configuration to use when running the tests.
If a relative path is provided, it is assumed to be relative to 
'/libunwind/test/configs'.")
 if (NOT IS_ABSOLUTE "${LIBUNWIND_TEST_CONFIG}")



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


[PATCH] D112135: [ARM] Fix inline assembly referencing floating point registers on soft-float targets

2021-10-20 Thread Pavel Kosov via Phabricator via cfe-commits
kpdev42 created this revision.
kpdev42 added reviewers: dmgreen, thakis, dcandler, nickdesaulniers, LukeGeeson.
kpdev42 added a project: LLVM.
Herald added a subscriber: kristof.beyls.
kpdev42 requested review of this revision.
Herald added a project: clang.

Fixes PR: https://bugs.llvm.org/show_bug.cgi?id=52230


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112135

Files:
  clang/lib/Basic/Targets/ARM.cpp
  clang/lib/Basic/Targets/ARM.h
  clang/test/Sema/arm_inline_asm_constraints_no_fp_regs.c


Index: clang/test/Sema/arm_inline_asm_constraints_no_fp_regs.c
===
--- /dev/null
+++ clang/test/Sema/arm_inline_asm_constraints_no_fp_regs.c
@@ -0,0 +1,29 @@
+// REQUIRES: arm-registered-target
+// RUN: %clang_cc1 -triple arm -target-feature -fpregs -verify=arm-nofp %s
+
+// w: A 32, 64, or 128-bit floating-point/SIMD register: s0-s31, d0-d31, or 
q0-q15.
+float test_w(float x) {
+  __asm__("vsqrt.f32 %0, %1"
+  : "=w"(x)
+  : "w"(x)); // No error expected.
+  // arm-nofp-error@7 {{invalid output constraint '=w' in asm}}
+  return x;
+}
+
+// x: A 32, 64, or 128-bit floating-point/SIMD register: s0-s15, d0-d7, or 
q0-q3.
+float test_x(float x) {
+  __asm__("vsqrt.f32 %0, %1"
+  : "=x"(x)
+  : "x"(x)); // No error expected.
+  // arm-nofp-error@16 {{invalid output constraint '=x' in asm}}
+  return x;
+}
+
+// t: A 32, 64, or 128-bit floating-point/SIMD register: s0-s31, d0-d15, or 
q0-q7.
+float test_t(float x) {
+  __asm__("vsqrt.f32 %0, %1"
+  : "=t"(x)
+  : "t"(x)); // No error expected.
+  // arm-nofp-error@25 {{invalid output constraint '=t' in asm}}
+  return x;
+}
Index: clang/lib/Basic/Targets/ARM.h
===
--- clang/lib/Basic/Targets/ARM.h
+++ clang/lib/Basic/Targets/ARM.h
@@ -78,6 +78,7 @@
   unsigned Unaligned : 1;
   unsigned DotProd : 1;
   unsigned HasMatMul : 1;
+  unsigned FPRegsDisabled : 1;
 
   enum {
 LDREX_B = (1 << 0), /// byte (8-bit)
Index: clang/lib/Basic/Targets/ARM.cpp
===
--- clang/lib/Basic/Targets/ARM.cpp
+++ clang/lib/Basic/Targets/ARM.cpp
@@ -440,6 +440,7 @@
   HasFloat16 = true;
   ARMCDECoprocMask = 0;
   HasBFloat16 = false;
+  FPRegsDisabled = false;
 
   // This does not diagnose illegal cases like having both
   // "+vfpv2" and "+vfpv3" or having "+neon" and "-fp64".
@@ -516,6 +517,8 @@
   ARMCDECoprocMask |= (1U << Coproc);
 } else if (Feature == "+bf16") {
   HasBFloat16 = true;
+} else if (Feature == "-fpregs") {
+  FPRegsDisabled = true;
 }
   }
 
@@ -968,6 +971,8 @@
   case 't': // s0-s31, d0-d31, or q0-q15
   case 'w': // s0-s15, d0-d7, or q0-q3
   case 'x': // s0-s31, d0-d15, or q0-q7
+if (FPRegsDisabled)
+  return false;
 Info.setAllowsRegister();
 return true;
   case 'j': // An immediate integer between 0 and 65535 (valid for MOVW)


Index: clang/test/Sema/arm_inline_asm_constraints_no_fp_regs.c
===
--- /dev/null
+++ clang/test/Sema/arm_inline_asm_constraints_no_fp_regs.c
@@ -0,0 +1,29 @@
+// REQUIRES: arm-registered-target
+// RUN: %clang_cc1 -triple arm -target-feature -fpregs -verify=arm-nofp %s
+
+// w: A 32, 64, or 128-bit floating-point/SIMD register: s0-s31, d0-d31, or q0-q15.
+float test_w(float x) {
+  __asm__("vsqrt.f32 %0, %1"
+  : "=w"(x)
+  : "w"(x)); // No error expected.
+  // arm-nofp-error@7 {{invalid output constraint '=w' in asm}}
+  return x;
+}
+
+// x: A 32, 64, or 128-bit floating-point/SIMD register: s0-s15, d0-d7, or q0-q3.
+float test_x(float x) {
+  __asm__("vsqrt.f32 %0, %1"
+  : "=x"(x)
+  : "x"(x)); // No error expected.
+  // arm-nofp-error@16 {{invalid output constraint '=x' in asm}}
+  return x;
+}
+
+// t: A 32, 64, or 128-bit floating-point/SIMD register: s0-s31, d0-d15, or q0-q7.
+float test_t(float x) {
+  __asm__("vsqrt.f32 %0, %1"
+  : "=t"(x)
+  : "t"(x)); // No error expected.
+  // arm-nofp-error@25 {{invalid output constraint '=t' in asm}}
+  return x;
+}
Index: clang/lib/Basic/Targets/ARM.h
===
--- clang/lib/Basic/Targets/ARM.h
+++ clang/lib/Basic/Targets/ARM.h
@@ -78,6 +78,7 @@
   unsigned Unaligned : 1;
   unsigned DotProd : 1;
   unsigned HasMatMul : 1;
+  unsigned FPRegsDisabled : 1;
 
   enum {
 LDREX_B = (1 << 0), /// byte (8-bit)
Index: clang/lib/Basic/Targets/ARM.cpp
===
--- clang/lib/Basic/Targets/ARM.cpp
+++ clang/lib/Basic/Targets/ARM.cpp
@@ -440,6 +440,7 @@
   HasFloat16 = true;
   ARMCDECoprocMask = 0;
   HasBFloat16 = false;
+  FPRegsDisabled = false;
 
   // This does not diagnose illegal cases like having both
   // "+vfpv2" and "+vfpv3" or having "+neon" and "-fp64".
@@ -51

[PATCH] D112137: [clangd] Only publish preamble after rebuilds

2021-10-20 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: sammccall.
Herald added subscribers: usaxena95, arphaman, javed.absar.
kadircet requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Don't invoke parsing callback for preamble if clangd is using a
previously built one.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112137

Files:
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp


Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1165,6 +1165,32 @@
   Ready.notify();
 }
 
+TEST_F(TUSchedulerTests, OnlyPublishWhenPreambleIsBuilt) {
+  struct PreamblePublishCounter : public ParsingCallbacks {
+PreamblePublishCounter(int &PreamblePublishCount)
+: PreamblePublishCount(PreamblePublishCount) {}
+void onPreamblePublished(PathRef File) override { ++PreamblePublishCount; }
+int &PreamblePublishCount;
+  };
+
+  int PreamblePublishCount = 0;
+  TUScheduler S(CDB, optsForTest(),
+
std::make_unique(PreamblePublishCount));
+
+  Path File = testPath("foo.cpp");
+  S.update(File, getInputs(File, ""), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 1);
+  // Same contents, no publish.
+  S.update(File, getInputs(File, ""), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 1);
+  // New contents, should publish.
+  S.update(File, getInputs(File, "#define FOO"), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 2);
+}
+
 // If a header file is missing from the CDB (or inferred using heuristics), and
 // it's included by another open file, then we parse it using that files flags.
 TEST_F(TUSchedulerTests, IncluderCache) {
Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -901,15 +901,17 @@
 void PreambleThread::build(Request Req) {
   assert(Req.CI && "Got preamble request with null compiler invocation");
   const ParseInputs &Inputs = Req.Inputs;
+  bool RebuiltPreamble = true;
 
   Status.update([&](TUStatus &Status) {
 Status.PreambleActivity = PreambleAction::Building;
   });
-  auto _ = llvm::make_scope_exit([this, &Req] {
+  auto _ = llvm::make_scope_exit([this, &Req, &RebuiltPreamble] {
 ASTPeer.updatePreamble(std::move(Req.CI), std::move(Req.Inputs),
LatestBuild, std::move(Req.CIDiags),
std::move(Req.WantDiags));
-Callbacks.onPreamblePublished(FileName);
+if (RebuiltPreamble)
+  Callbacks.onPreamblePublished(FileName);
   });
 
   if (!LatestBuild || Inputs.ForceRebuild) {
@@ -918,6 +920,7 @@
   } else if (isPreambleCompatible(*LatestBuild, Inputs, FileName, *Req.CI)) {
 vlog("Reusing preamble version {0} for version {1} of {2}",
  LatestBuild->Version, Inputs.Version, FileName);
+RebuiltPreamble = false;
 return;
   } else {
 vlog("Rebuilding invalidated preamble for {0} version {1} (previous was "


Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1165,6 +1165,32 @@
   Ready.notify();
 }
 
+TEST_F(TUSchedulerTests, OnlyPublishWhenPreambleIsBuilt) {
+  struct PreamblePublishCounter : public ParsingCallbacks {
+PreamblePublishCounter(int &PreamblePublishCount)
+: PreamblePublishCount(PreamblePublishCount) {}
+void onPreamblePublished(PathRef File) override { ++PreamblePublishCount; }
+int &PreamblePublishCount;
+  };
+
+  int PreamblePublishCount = 0;
+  TUScheduler S(CDB, optsForTest(),
+std::make_unique(PreamblePublishCount));
+
+  Path File = testPath("foo.cpp");
+  S.update(File, getInputs(File, ""), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 1);
+  // Same contents, no publish.
+  S.update(File, getInputs(File, ""), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 1);
+  // New contents, should publish.
+  S.update(File, getInputs(File, "#define FOO"), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 2);
+}
+
 // If a header file is missing from the CDB (or inferred using heuristics), and
 // it's included by another open file, then we parse it using that files flags.
 TEST_F(TUSchedulerTests, IncluderCache) {
Inde

[PATCH] D108003: [Clang] Extend -Wbool-operation to warn about bitwise and of bools with side effects

2021-10-20 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Thanks for this warning! I just finished turning it on in Chromium. Here's a 
short report on the things it fired on in case it's interesting to anyone. (I'm 
not suggesting any changes to the warning, I think it works very well as-is).

The warning fired in 21 different files. In 16 cases, using && instead of & and 
|| instead of | was possible, but the change was inconsequential [1]. In 6 
cases, & and | were used intentionally to prevent short-circuiting, but it 
wasn't always obvious that that was the case. I usually rewrote the code to 
make it more obvious [2]. In addition to these, there was of course the true 
positive that motivated this warning :)

Apparently we build a (small) subset of LLVM 10 as part of some dependency of 
chrome. The warning fired a few times there, so I turned it off for those files 
(in trunk LLVM it's fixed). I also found a quality-of-implementation bug with 
the warning which I reported as https://bugs.llvm.org/show_bug.cgi?id=52226

1:
https://chromium-review.googlesource.com/c/angle/angle/+/3212889/2/src/libANGLE/renderer/gl/VertexArrayGL.cpp
https://chromium-review.googlesource.com/c/angle/angle/+/3212889/2/src/tests/gl_tests/CopyTexImageTest.cpp
https://chromium-review.googlesource.com/c/chromium/src/+/3212300/2/content/browser/payments/payment_app_database.cc
https://chromium-review.googlesource.com/c/chromium/src/+/3212300/2/gin/v8_initializer.cc
https://chromium-review.googlesource.com/c/chromium/src/+/3212300/2/net/spdy/spdy_http_stream.cc
https://chromium-review.googlesource.com/c/chromium/src/+/3212300/2/services/network/url_loader.cc
https://chromium-review.googlesource.com/c/chromium/src/+/3212300/2/third_party/blink/renderer/core/intersection_observer/intersection_observation.cc
https://chromium-review.googlesource.com/c/chromium/src/+/3229610/2/chromecast/cast_core/url_rewrite_rules_adapter.cc
https://chromium-review.googlesource.com/c/v8/v8/+/3212891/2/src/objects/feedback-vector.cc
https://chromium-review.googlesource.com/c/v8/v8/+/3231077/2/src/codegen/arm64/assembler-arm64.cc
https://chromium.googlesource.com/external/github.com/google/distributed_point_functions/+/refs/heads/upstream/master%5E%21/#F0
https://dawn-review.googlesource.com/c/dawn/+/66200/2/src/tests/end2end/QueryTests.cpp
https://github.com/KhronosGroup/Vulkan-ValidationLayers/commit/51279399eaecf651d176544d8197f91f48637b2f
https://github.com/netwide-assembler/nasm/pull/17
https://skia-review.googlesource.com/c/skia/+/459456/3/src/core/SkColorFilter.cpp
https://webrtc-review.googlesource.com/c/src/+/234600/2/media/engine/simulcast_encoder_adapter.cc

2:
https://bugs.chromium.org/p/chromium/issues/detail?id=1261591 (still undecided)
https://chromium-review.googlesource.com/c/v8/v8/+/3212891/2/src/compiler/branch-elimination.cc
https://github.com/harfbuzz/harfbuzz/pull/3256
https://skia-review.googlesource.com/c/skia/+/459456/3/modules/skottie/src/animator/Vec2KeyframeAnimator.cpp
https://skia-review.googlesource.com/c/skia/+/459456/3/modules/skottie/src/animator/VectorKeyframeAnimator.cpp
https://skia-review.googlesource.com/c/skia/+/459456/3/src/core/SkPathEffect.cpp


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108003

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


[PATCH] D106681: [analyzer][NFCI] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 380934.
ASDenysPetrov added a comment.

Fixed redefinition in test file //initialization.cpp//.


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

https://reviews.llvm.org/D106681

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/initialization.c
  clang/test/Analysis/initialization.cpp

Index: clang/test/Analysis/initialization.cpp
===
--- clang/test/Analysis/initialization.cpp
+++ clang/test/Analysis/initialization.cpp
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -std=c++14 -triple i386-apple-darwin10 -analyze -analyzer-config eagerly-assume=false -analyzer-checker=core.uninitialized.Assign,core.builtin,debug.ExprInspection,core.uninitialized.UndefReturn -verify %s
 
+template 
+void clang_analyzer_dump(T x);
 void clang_analyzer_eval(int);
 
 struct S {
@@ -32,6 +34,10 @@
   auto x = ptr[idx]; // expected-warning{{garbage or undefined}}
 }
 
+void glob_symbolic_index1(int idx) {
+  clang_analyzer_dump(glob_arr1[idx]); // expected-warning{{Unknown}}
+}
+
 int const glob_arr2[4] = {1, 2};
 void glob_ptr_index1() {
   int const *ptr = glob_arr2;
@@ -128,3 +134,15 @@
   // FIXME: Should warn {{garbage or undefined}}.
   auto x = ptr[idx]; // // no-warning
 }
+
+extern const int glob_arr_no_init[10];
+void glob_array_index4() {
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}
+
+struct S2 {
+  static const int arr_no_init[10];
+};
+void struct_arr_index1() {
+  clang_analyzer_eval(S2::arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}
Index: clang/test/Analysis/initialization.c
===
--- clang/test/Analysis/initialization.c
+++ clang/test/Analysis/initialization.c
@@ -97,3 +97,8 @@
   // FIXME: Should warn {{garbage or undefined}}.
   int res = glob_arr2[x][y]; // no-warning
 }
+
+const int glob_arr_no_init[10];
+void glob_arr_index4() {
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -437,6 +437,10 @@
 
   RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B,
 const SubRegion *R);
+  Optional getConstantValFromConstArrayInitializer(
+  RegionBindingsConstRef B, const VarRegion *VR, const ElementRegion *R);
+  Optional getSValFromInitListExpr(const InitListExpr *ILE,
+ uint64_t Offset, QualType ElemT);
 
 public: // Part of public interface to class.
 
@@ -1625,6 +1629,95 @@
   return Result;
 }
 
+Optional RegionStoreManager::getConstantValFromConstArrayInitializer(
+RegionBindingsConstRef B, const VarRegion *VR, const ElementRegion *R) {
+  assert(R && VR && "Regions should not be null");
+
+  // Check if the containing array has an initialized value that we can trust.
+  // We can trust a const value or a value of a global initializer in main().
+  const VarDecl *VD = VR->getDecl();
+  if (!VD->getType().isConstQualified() &&
+  !R->getElementType().isConstQualified() &&
+  (!B.isMainAnalysis() || !VD->hasGlobalStorage()))
+return None;
+
+  // Array's declaration should have an initializer.
+  const Expr *Init = VD->getAnyInitializer();
+  if (!Init)
+return None;
+
+  // Array's declaration should have ConstantArrayType type, because only this
+  // type contains an array extent.
+  const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(VD->getType());
+  if (!CAT)
+return None;
+
+  // Array should be one-dimensional.
+  // TODO: Support multidimensional array.
+  if (isa(CAT->getElementType())) // is multidimensional
+return None;
+
+  // Array's offset should be a concrete value.
+  // Return Unknown value if symbolic index presented.
+  // FIXME: We also need to take ElementRegions with symbolic
+  // indexes into account.
+  const auto OffsetVal = R->getIndex().getAs();
+  if (!OffsetVal.hasValue())
+return UnknownVal();
+
+  // Check offset for being out of bounds.
+  // C++20 [expr.add] 7.6.6.4 (excerpt):
+  //   If P points to an array element i of an array object x with n
+  //   elements, where i < 0 or i > n, the behavior is undefined.
+  //   Dereferencing is not allowed on the "one past the last
+  //   element", when i == n.
+  // Example:
+  //   const int arr[4] = {1, 2};
+  //   const int *ptr = arr;
+  //   int x0 = ptr[0];  // 1
+  //   int x1 = ptr[1];  // 2
+  //   int x2 = ptr[2];  // 0
+  //   int x3 = ptr[3];  // 0
+  //   int x4 = ptr[4];  // UB
+  //   int x5 = ptr[-1]; // UB
+  const llvm::APSInt &OffsetInt = OffsetVal->getValue();
+  const auto Offset = static_cast(OffsetInt.getExtValue());
+  // Use `getZExtValue` because array extent can not be negative.
+ 

[PATCH] D112130: [clangd] Fix use-after-free in HeaderIncluderCache

2021-10-20 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/TUScheduler.cpp:294
   invalidate(First);
+// MainToFirst entry should stay alive, as Associations might be pointing 
at
+// its key.

Hmm, this leaves MainToFirst pointing to an invalidated entry.
Would it make more sense to just null out the value (i.e. First here)?

Then I think we need no code changes elsewhere, as update() already checks if 
First already exists before invalidating.

(This special case would occur on a rarer path, but the real reason for my 
preference is that I think the data structure is easier to interpret)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112130

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


[PATCH] D112137: [clangd] Only publish preamble after rebuilds

2021-10-20 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/TUScheduler.cpp:904
   const ParseInputs &Inputs = Req.Inputs;
+  bool RebuiltPreamble = true;
 

I think it would be clearer to invert the sense here (`ReusedPreamble=false`).

This avoids the "tension" of saying `RebuiltPreamble=true` when we haven't 
built one yet, and then having to ensure we satisfy that promise later.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112137

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


[PATCH] D111542: [analyzer] Retrieve incomplete array extent from its redeclaration.

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 380936.
ASDenysPetrov added a comment.

Fixed redefinition in test file initialization.cpp.


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

https://reviews.llvm.org/D111542

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/initialization.c


Index: clang/test/Analysis/initialization.c
===
--- clang/test/Analysis/initialization.c
+++ clang/test/Analysis/initialization.c
@@ -102,3 +102,42 @@
 void glob_arr_index4() {
   clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
 }
+
+const int glob_arr3[];  // IncompleteArrayType
+const int glob_arr3[4] = {1, 2, 3}; // ConstantArrayType
+void glob_arr_index5() {
+  clang_analyzer_eval(glob_arr3[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[2] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[3] == 0); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index5() {
+  int x = 42;
+  int res = glob_arr3[x]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index6() {
+  int x = -42;
+  int res = glob_arr3[x]; // expected-warning{{garbage or undefined}}
+}
+
+const int glob_arr4[];  // IncompleteArrayType
+const int glob_arr4[4] = {1, 2, 3}; // ConstantArrayType
+const int glob_arr4[];  // ConstantArrayType (according to AST)
+void glob_arr_index6() {
+  clang_analyzer_eval(glob_arr4[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[2] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[3] == 0); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index7() {
+  int x = 42;
+  int res = glob_arr4[x]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index8() {
+  int x = -42;
+  int res = glob_arr4[x]; // expected-warning{{garbage or undefined}}
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1641,8 +1641,14 @@
   (!B.isMainAnalysis() || !VD->hasGlobalStorage()))
 return None;
 
-  // Array's declaration should have an initializer.
-  const Expr *Init = VD->getAnyInitializer();
+  // Array's declaration should have `ConstantArrayType` type, because only 
this
+  // type contains an array extent. It may happen that array type can be of
+  // `IncompleteArrayType` type. To get the declaration of `ConstantArrayType`
+  // type, we should find the declaration in the redeclarations chain that has
+  // the initialization expression.
+  // NOTE: `VD` is always non-null if `Init` is non-null, so we can check for
+  // null only one of them.
+  const Expr *Init = VD->getAnyInitializer(VD);
   if (!Init)
 return None;
 


Index: clang/test/Analysis/initialization.c
===
--- clang/test/Analysis/initialization.c
+++ clang/test/Analysis/initialization.c
@@ -102,3 +102,42 @@
 void glob_arr_index4() {
   clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
 }
+
+const int glob_arr3[];  // IncompleteArrayType
+const int glob_arr3[4] = {1, 2, 3}; // ConstantArrayType
+void glob_arr_index5() {
+  clang_analyzer_eval(glob_arr3[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[2] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[3] == 0); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index5() {
+  int x = 42;
+  int res = glob_arr3[x]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index6() {
+  int x = -42;
+  int res = glob_arr3[x]; // expected-warning{{garbage or undefined}}
+}
+
+const int glob_arr4[];  // IncompleteArrayType
+const int glob_arr4[4] = {1, 2, 3}; // ConstantArrayType
+const int glob_arr4[];  // ConstantArrayType (according to AST)
+void glob_arr_index6() {
+  clang_analyzer_eval(glob_arr4[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[2] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[3] == 0); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index7() {
+  int x = 42;
+  int res = glob_arr4[x]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index8() {
+  int x = -42;
+  int res = glob_arr4[x]; // expected-warning{{garbage or undefined}}
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAna

[PATCH] D111985: [Clang] Add elementwise min/max builtins.

2021-10-20 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 380946.
fhahn added a comment.

Move type checking to helper function checkMathBuiltinElementType to be reused 
in D111986 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111985

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-elementwise-math.c
  clang/test/Sema/builtins-elementwise-math.c

Index: clang/test/Sema/builtins-elementwise-math.c
===
--- /dev/null
+++ clang/test/Sema/builtins-elementwise-math.c
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 %s -pedantic -verify -triple=x86_64-apple-darwin9
+
+typedef float float4 __attribute__((ext_vector_type(4)));
+typedef int int3 __attribute__((ext_vector_type(3)));
+
+struct Foo {
+  char *p;
+};
+
+void test_builtin_elementwise_max(int i, double d, float4 v, int3 iv) {
+  i = __builtin_elementwise_max(i, d);
+  // expected-error@-1 {{argument types do not match, 'int' != 'double'}}
+
+  struct Foo s = __builtin_elementwise_max(i, i);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_elementwise_max(i);
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 1}}
+
+  i = __builtin_elementwise_max();
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 0}}
+
+  i = __builtin_elementwise_max(v, iv);
+  // expected-error@-1 {{argument types do not match, 'float4' (vector of 4 'float' values) != 'int3' (vector of 3 'int' values)}}
+}
+
+void test_builtin_elementwise_min(int i, double d, float4 v, int3 iv) {
+  i = __builtin_elementwise_min(i, d);
+  // expected-error@-1 {{argument types do not match, 'int' != 'double'}}
+
+  struct Foo s = __builtin_elementwise_min(i, i);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_elementwise_min(i);
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 1}}
+
+  i = __builtin_elementwise_min();
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 0}}
+
+  i = __builtin_elementwise_min(v, iv);
+  // expected-error@-1 {{argument types do not match, 'float4' (vector of 4 'float' values) != 'int3' (vector of 3 'int' values)}}
+}
Index: clang/test/CodeGen/builtins-elementwise-math.c
===
--- /dev/null
+++ clang/test/CodeGen/builtins-elementwise-math.c
@@ -0,0 +1,88 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin %s -emit-llvm -disable-llvm-passes -o - | FileCheck %s
+
+typedef float float4 __attribute__((ext_vector_type(4)));
+typedef short int si8 __attribute__((ext_vector_type(8)));
+typedef unsigned int u4 __attribute__((ext_vector_type(4)));
+
+void test_builtin_elementwise_max(float f1, float f2, double d1, double d2,
+  float4 vf1, float4 vf2, long long int i1,
+  long long int i2, si8 vi1, si8 vi2,
+  unsigned u1, unsigned u2, u4 vu1, u4 vu2) {
+  // CHECK-LABEL: define void @test_builtin_elementwise_max(
+
+  // CHECK:  [[F1:%.+]] = load float, float* %f1.addr, align 4
+  // CHECK-NEXT: [[F2:%.+]] = load float, float* %f2.addr, align 4
+  // CHECK-NEXT:  call float @llvm.maxnum.f32(float %0, float %1)
+  f1 = __builtin_elementwise_max(f1, f2);
+
+  // CHECK:  [[D1:%.+]] = load double, double* %d1.addr, align 8
+  // CHECK-NEXT: [[D2:%.+]] = load double, double* %d2.addr, align 8
+  // CHECK-NEXT: call double @llvm.maxnum.f64(double [[D1]], double [[D2]])
+  d1 = __builtin_elementwise_max(d1, d2);
+
+  // CHECK:  [[VF1:%.+]] = load <4 x float>, <4 x float>* %vf1.addr, align 16
+  // CHECK-NEXT: [[VF2:%.+]] = load <4 x float>, <4 x float>* %vf2.addr, align 16
+  // CHECK-NEXT: call <4 x float> @llvm.maxnum.v4f32(<4 x float> [[VF1]], <4 x float> [[VF2]])
+  vf1 = __builtin_elementwise_max(vf1, vf2);
+
+  // CHECK:  [[I1:%.+]] = load i64, i64* %i1.addr, align 8
+  // CHECK-NEXT: [[I2:%.+]] = load i64, i64* %i2.addr, align 8
+  // CHECK-NEXT: call i64 @llvm.smax.i64(i64 [[I1]], i64 [[I2]])
+  i1 = __builtin_elementwise_max(i1, i2);
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: [[VI2:%.+]] = load <8 x i16>, <8 x i16>* %vi2.addr, align 16
+  // CHECK-NEXT: call <8 x i16> @llvm.smax.v8i16(<8 x i16> [[VI1]], <8 x i16> [[VI2]])
+  vi1 = __builtin_elementwise_max(vi1, vi2);
+
+  // CHECK:  [[U1:%.+]] = load i32, i32* %u1.addr, align 4
+  // CHECK-NEXT: [[U2:%.+]] = load i32, i32* %u2.addr, align 4
+  // CHECK-NEXT: call i32 @llvm.umax.i32(i32 [[U1]], i32 [[U2]])
+  u1 = __buil

[PATCH] D111986: [Clang] Add elementwise abs builtin.

2021-10-20 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 380947.
fhahn added a comment.

Use checkMathBuiltinElementType helper added in D111985 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111986

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-elementwise-math.c
  clang/test/Sema/builtins-elementwise-math.c

Index: clang/test/Sema/builtins-elementwise-math.c
===
--- clang/test/Sema/builtins-elementwise-math.c
+++ clang/test/Sema/builtins-elementwise-math.c
@@ -2,11 +2,32 @@
 
 typedef float float4 __attribute__((ext_vector_type(4)));
 typedef int int3 __attribute__((ext_vector_type(3)));
+typedef unsigned unsigned4 __attribute__((ext_vector_type(4)));
 
 struct Foo {
   char *p;
 };
 
+void test_builtin_elementwise_abs(int i, double d, float4 v, int3 iv, unsigned u, unsigned4 uv) {
+  struct Foo s = __builtin_elementwise_abs(i);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_elementwise_abs();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_elementwise_abs(i, i);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_elementwise_abs(v);
+  // expected-error@-1 {{assigning to 'int' from incompatible type 'float4' (vector of 4 'float' values)}}
+
+  u = __builtin_elementwise_abs(u);
+  // expected-error@-1 {{argument must have a signed integer or floating point type, but was an unsigned integer type}}
+
+  uv = __builtin_elementwise_abs(uv);
+  // expected-error@-1 {{argument must have a signed integer or floating point type, but was an unsigned integer type}}
+}
+
 void test_builtin_elementwise_max(int i, double d, float4 v, int3 iv) {
   i = __builtin_elementwise_max(i, d);
   // expected-error@-1 {{argument types do not match, 'int' != 'double'}}
Index: clang/test/CodeGen/builtins-elementwise-math.c
===
--- clang/test/CodeGen/builtins-elementwise-math.c
+++ clang/test/CodeGen/builtins-elementwise-math.c
@@ -4,12 +4,36 @@
 typedef short int si8 __attribute__((ext_vector_type(8)));
 typedef unsigned int u4 __attribute__((ext_vector_type(4)));
 
+void test_builtin_elementwise_abs(float f1, float f2, double d1, double d2,
+  float4 vf1, float4 vf2, si8 vi1, si8 vi2,
+  long long int i1, long long int i2) {
+  // CHECK-LABEL: define void @test_builtin_elementwise_abs(
+  // CHECK:  [[F1:%.+]] = load float, float* %f1.addr, align 4
+  // CHECK-NEXT:  call float @llvm.fabs.f32(float [[F1]])
+  f2 = __builtin_elementwise_abs(f1);
+
+  // CHECK:  [[D1:%.+]] = load double, double* %d1.addr, align 8
+  // CHECK-NEXT: call double @llvm.fabs.f64(double [[D1]])
+  d2 = __builtin_elementwise_abs(d1);
+
+  // CHECK:  [[VF1:%.+]] = load <4 x float>, <4 x float>* %vf1.addr, align 16
+  // CHECK-NEXT: call <4 x float> @llvm.fabs.v4f32(<4 x float> [[VF1]])
+  vf2 = __builtin_elementwise_abs(vf1);
+
+  // CHECK:  [[I1:%.+]] = load i64, i64* %i1.addr, align 8
+  // CHECK-NEXT: call i64 @llvm.abs.i64(i64 [[I1]], i1 false)
+  i2 = __builtin_elementwise_abs(i1);
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call <8 x i16> @llvm.abs.v8i16(<8 x i16> [[VI1]], i1 false)
+  vi2 = __builtin_elementwise_abs(vi1);
+}
+
 void test_builtin_elementwise_max(float f1, float f2, double d1, double d2,
   float4 vf1, float4 vf2, long long int i1,
   long long int i2, si8 vi1, si8 vi2,
   unsigned u1, unsigned u2, u4 vu1, u4 vu2) {
   // CHECK-LABEL: define void @test_builtin_elementwise_max(
-
   // CHECK:  [[F1:%.+]] = load float, float* %f1.addr, align 4
   // CHECK-NEXT: [[F2:%.+]] = load float, float* %f2.addr, align 4
   // CHECK-NEXT:  call float @llvm.maxnum.f32(float %0, float %1)
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -1976,9 +1976,12 @@
 break;
   }
 
+  case Builtin::BI__builtin_elementwise_abs:
+return SemaBuiltinElementwiseMathOneArg(TheCall, TheCallResult);
+
   case Builtin::BI__builtin_elementwise_min:
   case Builtin::BI__builtin_elementwise_max:
-return SemaBuiltinElementwiseMath(TheCall, TheCallResult);
+return SemaBuiltinElementwiseMathTwoArgs(TheCall, TheCallResult);
 
   case Builtin::BI__builtin_matrix_transpose:
 return SemaBuiltinMatrixTranspose(TheCal

[PATCH] D112001: [Clang] Add min/max reduction builtins.

2021-10-20 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 380948.
fhahn marked an inline comment as done.
fhahn added a comment.

rebase on top of recently updated patches.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112001

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-elementwise-math.c
  clang/test/Sema/builtins-elementwise-math.c

Index: clang/test/Sema/builtins-elementwise-math.c
===
--- clang/test/Sema/builtins-elementwise-math.c
+++ clang/test/Sema/builtins-elementwise-math.c
@@ -61,3 +61,31 @@
   i = __builtin_elementwise_min(v, iv);
   // expected-error@-1 {{argument types do not match, 'float4' (vector of 4 'float' values) != 'int3' (vector of 3 'int' values)}}
 }
+
+void test_builtin_reduce_max(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_max(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_reduce_max(v, v);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_reduce_max();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_reduce_max(i);
+  // expected-error@-1 {{argument must have a vector type, but was 'int'}}
+}
+
+void test_builtin_reduce_min(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_min(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_reduce_min(v, v);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_reduce_min();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_reduce_min(i);
+  // expected-error@-1 {{argument must have a vector type, but was 'int'}}
+}
Index: clang/test/CodeGen/builtins-elementwise-math.c
===
--- clang/test/CodeGen/builtins-elementwise-math.c
+++ clang/test/CodeGen/builtins-elementwise-math.c
@@ -110,3 +110,33 @@
   // CHECK-NEXT: call <4 x i32> @llvm.umin.v4i32(<4 x i32> [[VU1]], <4 x i32> [[VU2]])
   vu1 = __builtin_elementwise_min(vu1, vu2);
 }
+
+void test_builtin_reduce_max(float4 vf1, si8 vi1, u4 vu1) {
+  // CHECK-LABEL: define void @test_builtin_reduce_max(
+  // CHECK:  [[VF1:%.+]] = load <4 x float>, <4 x float>* %vf1.addr, align 16
+  // CHECK-NEXT: call float @llvm.vector.reduce.fmax.v4f32(<4 x float> [[VF1]])
+  float r1 = __builtin_reduce_max(vf1);
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.smax.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_max(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.umax.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_max(vu1);
+}
+
+void test_builtin_reduce_min(float4 vf1, si8 vi1, u4 vu1) {
+  // CHECK-LABEL: define void @test_builtin_reduce_min(
+  // CHECK:  [[VF1:%.+]] = load <4 x float>, <4 x float>* %vf1.addr, align 16
+  // CHECK-NEXT: call float @llvm.vector.reduce.fmin.v4f32(<4 x float> [[VF1]])
+  float r1 = __builtin_reduce_min(vf1);
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.smin.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_min(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.umin.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_min(vu1);
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -1978,11 +1978,14 @@
 
   case Builtin::BI__builtin_elementwise_abs:
 return SemaBuiltinElementwiseMathOneArg(TheCall, TheCallResult);
-
   case Builtin::BI__builtin_elementwise_min:
   case Builtin::BI__builtin_elementwise_max:
 return SemaBuiltinElementwiseMathTwoArgs(TheCall, TheCallResult);
 
+  case Builtin::BI__builtin_reduce_max:
+  case Builtin::BI__builtin_reduce_min:
+return SemaBuiltinReduceMath(TheCall, TheCallResult);
+
   case Builtin::BI__builtin_matrix_transpose:
 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
   case Builtin::BI__builtin_matrix_column_major_load:
@@ -16712,6 +16715,23 @@
   return CallResult;
 }
 
+ExprResult Sema::SemaBuiltinReduceMath(CallExpr *TheCall,
+   ExprResult CallResult) {
+  if (checkArgCount(*this, TheCall, 1))
+return ExprError();
+
+  Expr *A = TheCall->getArg(0);
+  QualType TyA = A->getType

[PATCH] D112050: [clang] NFC: return void in an alternative expression after call to void function.

2021-10-20 Thread zhouyizhou via Phabricator via cfe-commits
zhouyizhou added a comment.

I create this patch because I am also a Linux hobbyist,  in Linux kernel, 
return statement in a void function is always standalone. For example in 
kernel/event/core.c:

static void
perf_event_exit_event(struct perf_event *child_event,

  struct perf_event_context *child_ctx,
  struct task_struct *child)

{

  ...
  if (!parent_event) {
  perf_event_wakeup(child_event);
  return;
  }
  ...

}

In above code, return statement is standalone. It was rarely seen statement 
like "return perf_event_wakeup(child_event);" in Linux kernel.

Thanks
Zhouyi


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112050

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


[clang-tools-extra] c959da9 - [clangd] Only publish preamble after rebuilds

2021-10-20 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2021-10-20T16:32:32+02:00
New Revision: c959da9ef344a22e3753e2e62af46a63a33cd80f

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

LOG: [clangd] Only publish preamble after rebuilds

Don't invoke parsing callback for preamble if clangd is using a
previously built one.

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

Added: 


Modified: 
clang-tools-extra/clangd/TUScheduler.cpp
clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/TUScheduler.cpp 
b/clang-tools-extra/clangd/TUScheduler.cpp
index 700d8264555f..4dd7a06b8bce 100644
--- a/clang-tools-extra/clangd/TUScheduler.cpp
+++ b/clang-tools-extra/clangd/TUScheduler.cpp
@@ -901,15 +901,17 @@ void ASTWorker::runWithAST(
 void PreambleThread::build(Request Req) {
   assert(Req.CI && "Got preamble request with null compiler invocation");
   const ParseInputs &Inputs = Req.Inputs;
+  bool ReusedPreamble = false;
 
   Status.update([&](TUStatus &Status) {
 Status.PreambleActivity = PreambleAction::Building;
   });
-  auto _ = llvm::make_scope_exit([this, &Req] {
+  auto _ = llvm::make_scope_exit([this, &Req, &ReusedPreamble] {
 ASTPeer.updatePreamble(std::move(Req.CI), std::move(Req.Inputs),
LatestBuild, std::move(Req.CIDiags),
std::move(Req.WantDiags));
-Callbacks.onPreamblePublished(FileName);
+if (!ReusedPreamble)
+  Callbacks.onPreamblePublished(FileName);
   });
 
   if (!LatestBuild || Inputs.ForceRebuild) {
@@ -918,6 +920,7 @@ void PreambleThread::build(Request Req) {
   } else if (isPreambleCompatible(*LatestBuild, Inputs, FileName, *Req.CI)) {
 vlog("Reusing preamble version {0} for version {1} of {2}",
  LatestBuild->Version, Inputs.Version, FileName);
+ReusedPreamble = true;
 return;
   } else {
 vlog("Rebuilding invalidated preamble for {0} version {1} (previous was "

diff  --git a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp 
b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
index e15725d5120b..306392fb2731 100644
--- a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1165,6 +1165,32 @@ TEST_F(TUSchedulerTests, AsyncPreambleThread) {
   Ready.notify();
 }
 
+TEST_F(TUSchedulerTests, OnlyPublishWhenPreambleIsBuilt) {
+  struct PreamblePublishCounter : public ParsingCallbacks {
+PreamblePublishCounter(int &PreamblePublishCount)
+: PreamblePublishCount(PreamblePublishCount) {}
+void onPreamblePublished(PathRef File) override { ++PreamblePublishCount; }
+int &PreamblePublishCount;
+  };
+
+  int PreamblePublishCount = 0;
+  TUScheduler S(CDB, optsForTest(),
+
std::make_unique(PreamblePublishCount));
+
+  Path File = testPath("foo.cpp");
+  S.update(File, getInputs(File, ""), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 1);
+  // Same contents, no publish.
+  S.update(File, getInputs(File, ""), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 1);
+  // New contents, should publish.
+  S.update(File, getInputs(File, "#define FOO"), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 2);
+}
+
 // If a header file is missing from the CDB (or inferred using heuristics), and
 // it's included by another open file, then we parse it using that files flags.
 TEST_F(TUSchedulerTests, IncluderCache) {



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


[PATCH] D112137: [clangd] Only publish preamble after rebuilds

2021-10-20 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
kadircet marked an inline comment as done.
Closed by commit rGc959da9ef344: [clangd] Only publish preamble after rebuilds 
(authored by kadircet).

Changed prior to commit:
  https://reviews.llvm.org/D112137?vs=380931&id=380949#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112137

Files:
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp


Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1165,6 +1165,32 @@
   Ready.notify();
 }
 
+TEST_F(TUSchedulerTests, OnlyPublishWhenPreambleIsBuilt) {
+  struct PreamblePublishCounter : public ParsingCallbacks {
+PreamblePublishCounter(int &PreamblePublishCount)
+: PreamblePublishCount(PreamblePublishCount) {}
+void onPreamblePublished(PathRef File) override { ++PreamblePublishCount; }
+int &PreamblePublishCount;
+  };
+
+  int PreamblePublishCount = 0;
+  TUScheduler S(CDB, optsForTest(),
+
std::make_unique(PreamblePublishCount));
+
+  Path File = testPath("foo.cpp");
+  S.update(File, getInputs(File, ""), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 1);
+  // Same contents, no publish.
+  S.update(File, getInputs(File, ""), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 1);
+  // New contents, should publish.
+  S.update(File, getInputs(File, "#define FOO"), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 2);
+}
+
 // If a header file is missing from the CDB (or inferred using heuristics), and
 // it's included by another open file, then we parse it using that files flags.
 TEST_F(TUSchedulerTests, IncluderCache) {
Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -901,15 +901,17 @@
 void PreambleThread::build(Request Req) {
   assert(Req.CI && "Got preamble request with null compiler invocation");
   const ParseInputs &Inputs = Req.Inputs;
+  bool ReusedPreamble = false;
 
   Status.update([&](TUStatus &Status) {
 Status.PreambleActivity = PreambleAction::Building;
   });
-  auto _ = llvm::make_scope_exit([this, &Req] {
+  auto _ = llvm::make_scope_exit([this, &Req, &ReusedPreamble] {
 ASTPeer.updatePreamble(std::move(Req.CI), std::move(Req.Inputs),
LatestBuild, std::move(Req.CIDiags),
std::move(Req.WantDiags));
-Callbacks.onPreamblePublished(FileName);
+if (!ReusedPreamble)
+  Callbacks.onPreamblePublished(FileName);
   });
 
   if (!LatestBuild || Inputs.ForceRebuild) {
@@ -918,6 +920,7 @@
   } else if (isPreambleCompatible(*LatestBuild, Inputs, FileName, *Req.CI)) {
 vlog("Reusing preamble version {0} for version {1} of {2}",
  LatestBuild->Version, Inputs.Version, FileName);
+ReusedPreamble = true;
 return;
   } else {
 vlog("Rebuilding invalidated preamble for {0} version {1} (previous was "


Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1165,6 +1165,32 @@
   Ready.notify();
 }
 
+TEST_F(TUSchedulerTests, OnlyPublishWhenPreambleIsBuilt) {
+  struct PreamblePublishCounter : public ParsingCallbacks {
+PreamblePublishCounter(int &PreamblePublishCount)
+: PreamblePublishCount(PreamblePublishCount) {}
+void onPreamblePublished(PathRef File) override { ++PreamblePublishCount; }
+int &PreamblePublishCount;
+  };
+
+  int PreamblePublishCount = 0;
+  TUScheduler S(CDB, optsForTest(),
+std::make_unique(PreamblePublishCount));
+
+  Path File = testPath("foo.cpp");
+  S.update(File, getInputs(File, ""), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 1);
+  // Same contents, no publish.
+  S.update(File, getInputs(File, ""), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 1);
+  // New contents, should publish.
+  S.update(File, getInputs(File, "#define FOO"), WantDiagnostics::Auto);
+  S.blockUntilIdle(timeoutSeconds(10));
+  EXPECT_EQ(PreamblePublishCount, 2);
+}
+
 // If a header file is missing from the CDB (or inferred using heuristics), and
 // it's included by another open file, then we parse it using that files flags.
 TEST_F(TUSchedulerTests, IncluderCache) {
In

[PATCH] D111986: [Clang] Add elementwise abs builtin.

2021-10-20 Thread Florian Hahn via Phabricator via cfe-commits
fhahn marked 2 inline comments as done.
fhahn added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:16667
+
+  if (!TyA->getAs() && 
!ConstantMatrixType::isValidElementType(TyA))
+return Diag(A->getBeginLoc(), diag::err_elementwise_math_invalid_arg_type)

scanon wrote:
> Given that I expect this particular test to occur fairly frequently, maybe 
> worth abstracting into some sort of get-elementwise-type operation.
moved out to a helper in the previous patch in the series, D111985



Comment at: clang/test/Sema/builtins-elementwise-math.c:25
+  u = __builtin_elementwise_abs(u);
+  // expected-error@-1 {{argument must have a signed integer or floating point 
type, but was an unsigned integer type}}
+

scanon wrote:
> For the purposes of C++ templates it might be nice to allow `abs` on unsigned 
> (as the identity function). I don't have strong feelings though, and a 
> library wrapping the builtins can do this themselves.
yeah that would be an option. I don't have any strong feelings either


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111986

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


[PATCH] D112130: [clangd] Fix use-after-free in HeaderIncluderCache

2021-10-20 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet marked an inline comment as done.
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/TUScheduler.cpp:294
   invalidate(First);
+// MainToFirst entry should stay alive, as Associations might be pointing 
at
+// its key.

sammccall wrote:
> Hmm, this leaves MainToFirst pointing to an invalidated entry.
> Would it make more sense to just null out the value (i.e. First here)?
> 
> Then I think we need no code changes elsewhere, as update() already checks if 
> First already exists before invalidating.
> 
> (This special case would occur on a rarer path, but the real reason for my 
> preference is that I think the data structure is easier to interpret)
Thanks! Yeah that makes sense + now there's a point for `First` being a 
reference :P


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112130

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


[clang-tools-extra] 60e19f6 - [clangd] Fix use-after-free in HeaderIncluderCache

2021-10-20 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2021-10-20T16:36:07+02:00
New Revision: 60e19f6752b7f19b022d8bdca0937c59b49811f9

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

LOG: [clangd] Fix use-after-free in HeaderIncluderCache

Includer cache could get into a bad state when a main file went bad and
added back afterwards. This patch adds a check to invalidate to prevent
that.

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

Added: 


Modified: 
clang-tools-extra/clangd/TUScheduler.cpp
clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/TUScheduler.cpp 
b/clang-tools-extra/clangd/TUScheduler.cpp
index 4dd7a06b8bce..bbcda5bc0dfb 100644
--- a/clang-tools-extra/clangd/TUScheduler.cpp
+++ b/clang-tools-extra/clangd/TUScheduler.cpp
@@ -286,8 +286,12 @@ class TUScheduler::HeaderIncluderCache {
   void remove(PathRef MainFile) {
 std::lock_guard Lock(Mu);
 Association *&First = MainToFirst[MainFile];
-if (First)
+if (First) {
   invalidate(First);
+  First = nullptr;
+}
+// MainToFirst entry should stay alive, as Associations might be pointing 
at
+// its key.
   }
 
   /// Get the mainfile associated with Header, or the empty string if none.

diff  --git a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp 
b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
index 306392fb2731..833df03a20ea 100644
--- a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1200,10 +1200,10 @@ TEST_F(TUSchedulerTests, IncluderCache) {
  Unreliable = testPath("unreliable.h"),
  OK = testPath("ok.h"),
  NotIncluded = testPath("not_included.h");
-  class NoHeadersCDB : public GlobalCompilationDatabase {
+  struct NoHeadersCDB : public GlobalCompilationDatabase {
 llvm::Optional
 getCompileCommand(PathRef File) const override {
-  if (File == NoCmd || File == NotIncluded)
+  if (File == NoCmd || File == NotIncluded || FailAll)
 return llvm::None;
   auto Basic = getFallbackCommand(File);
   Basic.Heuristic.clear();
@@ -1218,6 +1218,8 @@ TEST_F(TUSchedulerTests, IncluderCache) {
   }
   return Basic;
 }
+
+std::atomic FailAll{false};
   } CDB;
   TUScheduler S(CDB, optsForTest());
   auto GetFlags = [&](PathRef Header) {
@@ -1288,6 +1290,21 @@ TEST_F(TUSchedulerTests, IncluderCache) {
   << "association invalidated but not reclaimed";
   EXPECT_THAT(GetFlags(NotIncluded), Contains("-DMAIN2"))
   << "association still valid";
+
+  // Delete the file from CDB, it should invalidate the associations.
+  CDB.FailAll = true;
+  EXPECT_THAT(GetFlags(NoCmd), Not(Contains("-DMAIN3")))
+  << "association should've been invalidated.";
+  // Also run update for Main3 to invalidate the preeamble to make sure next
+  // update populates include cache associations.
+  S.update(Main3, getInputs(Main3, SomeIncludes), WantDiagnostics::Yes);
+  EXPECT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  // Re-add the file and make sure nothing crashes.
+  CDB.FailAll = false;
+  S.update(Main3, getInputs(Main3, SomeIncludes), WantDiagnostics::Yes);
+  EXPECT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  EXPECT_THAT(GetFlags(NoCmd), Contains("-DMAIN3"))
+  << "association invalidated and then claimed by main3";
 }
 
 TEST_F(TUSchedulerTests, PreservesLastActiveFile) {



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


[PATCH] D112130: [clangd] Fix use-after-free in HeaderIncluderCache

2021-10-20 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
kadircet marked an inline comment as done.
Closed by commit rG60e19f6752b7: [clangd] Fix use-after-free in 
HeaderIncluderCache (authored by kadircet).

Changed prior to commit:
  https://reviews.llvm.org/D112130?vs=380895&id=380951#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112130

Files:
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp


Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1200,10 +1200,10 @@
  Unreliable = testPath("unreliable.h"),
  OK = testPath("ok.h"),
  NotIncluded = testPath("not_included.h");
-  class NoHeadersCDB : public GlobalCompilationDatabase {
+  struct NoHeadersCDB : public GlobalCompilationDatabase {
 llvm::Optional
 getCompileCommand(PathRef File) const override {
-  if (File == NoCmd || File == NotIncluded)
+  if (File == NoCmd || File == NotIncluded || FailAll)
 return llvm::None;
   auto Basic = getFallbackCommand(File);
   Basic.Heuristic.clear();
@@ -1218,6 +1218,8 @@
   }
   return Basic;
 }
+
+std::atomic FailAll{false};
   } CDB;
   TUScheduler S(CDB, optsForTest());
   auto GetFlags = [&](PathRef Header) {
@@ -1288,6 +1290,21 @@
   << "association invalidated but not reclaimed";
   EXPECT_THAT(GetFlags(NotIncluded), Contains("-DMAIN2"))
   << "association still valid";
+
+  // Delete the file from CDB, it should invalidate the associations.
+  CDB.FailAll = true;
+  EXPECT_THAT(GetFlags(NoCmd), Not(Contains("-DMAIN3")))
+  << "association should've been invalidated.";
+  // Also run update for Main3 to invalidate the preeamble to make sure next
+  // update populates include cache associations.
+  S.update(Main3, getInputs(Main3, SomeIncludes), WantDiagnostics::Yes);
+  EXPECT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  // Re-add the file and make sure nothing crashes.
+  CDB.FailAll = false;
+  S.update(Main3, getInputs(Main3, SomeIncludes), WantDiagnostics::Yes);
+  EXPECT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  EXPECT_THAT(GetFlags(NoCmd), Contains("-DMAIN3"))
+  << "association invalidated and then claimed by main3";
 }
 
 TEST_F(TUSchedulerTests, PreservesLastActiveFile) {
Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -286,8 +286,12 @@
   void remove(PathRef MainFile) {
 std::lock_guard Lock(Mu);
 Association *&First = MainToFirst[MainFile];
-if (First)
+if (First) {
   invalidate(First);
+  First = nullptr;
+}
+// MainToFirst entry should stay alive, as Associations might be pointing 
at
+// its key.
   }
 
   /// Get the mainfile associated with Header, or the empty string if none.


Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -1200,10 +1200,10 @@
  Unreliable = testPath("unreliable.h"),
  OK = testPath("ok.h"),
  NotIncluded = testPath("not_included.h");
-  class NoHeadersCDB : public GlobalCompilationDatabase {
+  struct NoHeadersCDB : public GlobalCompilationDatabase {
 llvm::Optional
 getCompileCommand(PathRef File) const override {
-  if (File == NoCmd || File == NotIncluded)
+  if (File == NoCmd || File == NotIncluded || FailAll)
 return llvm::None;
   auto Basic = getFallbackCommand(File);
   Basic.Heuristic.clear();
@@ -1218,6 +1218,8 @@
   }
   return Basic;
 }
+
+std::atomic FailAll{false};
   } CDB;
   TUScheduler S(CDB, optsForTest());
   auto GetFlags = [&](PathRef Header) {
@@ -1288,6 +1290,21 @@
   << "association invalidated but not reclaimed";
   EXPECT_THAT(GetFlags(NotIncluded), Contains("-DMAIN2"))
   << "association still valid";
+
+  // Delete the file from CDB, it should invalidate the associations.
+  CDB.FailAll = true;
+  EXPECT_THAT(GetFlags(NoCmd), Not(Contains("-DMAIN3")))
+  << "association should've been invalidated.";
+  // Also run update for Main3 to invalidate the preeamble to make sure next
+  // update populates include cache associations.
+  S.update(Main3, getInputs(Main3, SomeIncludes), WantDiagnostics::Yes);
+  EXPECT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  // Re-add the file and make sure nothing crashes.
+  CDB.FailAll = false;
+  S.update(M

[PATCH] D110068: [Clang][AST] Resolve FIXME: Remove ObjCObjectPointer from isSpecifierType

2021-10-20 Thread Alf via Phabricator via cfe-commits
gAlfonso-bit added a comment.

Any updates? I do not have commit permissions. @ahatanak


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

https://reviews.llvm.org/D110068

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


[PATCH] D111443: [Driver] Fix ToolChain::getSanitizerArgs

2021-10-20 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked an inline comment as done.
yaxunl added a comment.

ping


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

https://reviews.llvm.org/D111443

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


[PATCH] D111833: [clang] Fortify warning for scanf calls with field width too big.

2021-10-20 Thread Michael Benfield via Phabricator via cfe-commits
mbenfield updated this revision to Diff 380956.
mbenfield added a comment.

respond to comments: null to NUL, remove stray space, use function_ref


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111833

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/warn-fortify-scanf.c

Index: clang/test/Sema/warn-fortify-scanf.c
===
--- /dev/null
+++ clang/test/Sema/warn-fortify-scanf.c
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify
+
+typedef struct _FILE FILE;
+extern int scanf(const char *format, ...);
+extern int fscanf(FILE *f, const char *format, ...);
+extern int sscanf(const char *input, const char *format, ...);
+
+void call_scanf() {
+  char buf10[10];
+  char buf20[20];
+  char buf30[30];
+  scanf("%4s %5s %10s", buf20, buf30, buf10); // expected-warning {{'scanf' may overflow; destination buffer in argument 4 has size 10, but the corresponding field width plus NUL byte is 11}}
+  scanf("%4s %5s %11s", buf20, buf30, buf10); // expected-warning {{'scanf' may overflow; destination buffer in argument 4 has size 10, but the corresponding field width plus NUL byte is 12}}
+  scanf("%4s %5s %9s", buf20, buf30, buf10);
+  scanf("%20s %5s %9s", buf20, buf30, buf10); // expected-warning {{'scanf' may overflow; destination buffer in argument 2 has size 20, but the corresponding field width plus NUL byte is 21}}
+  scanf("%21s %5s %9s", buf20, buf30, buf10); // expected-warning {{'scanf' may overflow; destination buffer in argument 2 has size 20, but the corresponding field width plus NUL byte is 22}}
+  scanf("%19s %5s %9s", buf20, buf30, buf10);
+  scanf("%19s %29s %9s", buf20, buf30, buf10);
+}
+
+void call_sscanf() {
+  char buf10[10];
+  char buf20[20];
+  char buf30[30];
+  sscanf("a b c", "%4s %5s %10s", buf20, buf30, buf10); // expected-warning {{'sscanf' may overflow; destination buffer in argument 5 has size 10, but the corresponding field width plus NUL byte is 11}}
+  sscanf("a b c", "%4s %5s %11s", buf20, buf30, buf10); // expected-warning {{'sscanf' may overflow; destination buffer in argument 5 has size 10, but the corresponding field width plus NUL byte is 12}}
+  sscanf("a b c", "%4s %5s %9s", buf20, buf30, buf10);
+  sscanf("a b c", "%20s %5s %9s", buf20, buf30, buf10); // expected-warning {{'sscanf' may overflow; destination buffer in argument 3 has size 20, but the corresponding field width plus NUL byte is 21}}
+  sscanf("a b c", "%21s %5s %9s", buf20, buf30, buf10); // expected-warning {{'sscanf' may overflow; destination buffer in argument 3 has size 20, but the corresponding field width plus NUL byte is 22}}
+  sscanf("a b c", "%19s %5s %9s", buf20, buf30, buf10);
+  sscanf("a b c", "%19s %29s %9s", buf20, buf30, buf10);
+}
+
+void call_fscanf() {
+  char buf10[10];
+  char buf20[20];
+  char buf30[30];
+  fscanf(0, "%4s %5s %10s", buf20, buf30, buf10); // expected-warning {{'fscanf' may overflow; destination buffer in argument 5 has size 10, but the corresponding field width plus NUL byte is 11}}
+  fscanf(0, "%4s %5s %11s", buf20, buf30, buf10); // expected-warning {{'fscanf' may overflow; destination buffer in argument 5 has size 10, but the corresponding field width plus NUL byte is 12}}
+  fscanf(0, "%4s %5s %9s", buf20, buf30, buf10);
+  fscanf(0, "%20s %5s %9s", buf20, buf30, buf10); // expected-warning {{'fscanf' may overflow; destination buffer in argument 3 has size 20, but the corresponding field width plus NUL byte is 21}}
+  fscanf(0, "%21s %5s %9s", buf20, buf30, buf10); // expected-warning {{'fscanf' may overflow; destination buffer in argument 3 has size 20, but the corresponding field width plus NUL byte is 22}}
+  fscanf(0, "%19s %5s %9s", buf20, buf30, buf10);
+  fscanf(0, "%19s %29s %9s", buf20, buf30, buf10);
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -408,6 +408,50 @@
 
 namespace {
 
+class ScanfDiagnosticFormatHandler
+: public analyze_format_string::FormatStringHandler {
+  // Accepts the argument index (relative to the first destination index) of the
+  // argument whose size we want.
+  using ComputeSizeFunction =
+  llvm::function_ref(unsigned)>;
+
+  // Accepts the argument index (relative to the first destination index), the
+  // destination size, and the source size).
+  using DiagnoseFunction =
+  llvm::function_ref;
+
+  ComputeSizeFunction ComputeSizeArgument;
+  DiagnoseFunction Diagnose;
+
+public:
+  ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
+   DiagnoseFunction Diagnose)
+  : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
+
+  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier 

[PATCH] D110068: [Clang][AST] Resolve FIXME: Remove ObjCObjectPointer from isSpecifierType

2021-10-20 Thread Alf via Phabricator via cfe-commits
gAlfonso-bit updated this revision to Diff 380958.
gAlfonso-bit added a comment.

Rebased to main


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

https://reviews.llvm.org/D110068

Files:
  clang/lib/AST/DeclPrinter.cpp
  clang/lib/AST/Type.cpp


Index: clang/lib/AST/Type.cpp
===
--- clang/lib/AST/Type.cpp
+++ clang/lib/AST/Type.cpp
@@ -2785,7 +2785,6 @@
   case DependentTemplateSpecialization:
   case ObjCInterface:
   case ObjCObject:
-  case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
 return true;
   default:
 return false;
Index: clang/lib/AST/DeclPrinter.cpp
===
--- clang/lib/AST/DeclPrinter.cpp
+++ clang/lib/AST/DeclPrinter.cpp
@@ -153,11 +153,14 @@
   while (!BaseType->isSpecifierType()) {
 if (const PointerType *PTy = BaseType->getAs())
   BaseType = PTy->getPointeeType();
+else if (const ObjCObjectPointerType *OPT =
+ BaseType->getAs())
+  BaseType = OPT->getPointeeType();
 else if (const BlockPointerType *BPy = BaseType->getAs())
   BaseType = BPy->getPointeeType();
-else if (const ArrayType* ATy = dyn_cast(BaseType))
+else if (const ArrayType *ATy = dyn_cast(BaseType))
   BaseType = ATy->getElementType();
-else if (const FunctionType* FTy = BaseType->getAs())
+else if (const FunctionType *FTy = BaseType->getAs())
   BaseType = FTy->getReturnType();
 else if (const VectorType *VTy = BaseType->getAs())
   BaseType = VTy->getElementType();


Index: clang/lib/AST/Type.cpp
===
--- clang/lib/AST/Type.cpp
+++ clang/lib/AST/Type.cpp
@@ -2785,7 +2785,6 @@
   case DependentTemplateSpecialization:
   case ObjCInterface:
   case ObjCObject:
-  case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
 return true;
   default:
 return false;
Index: clang/lib/AST/DeclPrinter.cpp
===
--- clang/lib/AST/DeclPrinter.cpp
+++ clang/lib/AST/DeclPrinter.cpp
@@ -153,11 +153,14 @@
   while (!BaseType->isSpecifierType()) {
 if (const PointerType *PTy = BaseType->getAs())
   BaseType = PTy->getPointeeType();
+else if (const ObjCObjectPointerType *OPT =
+ BaseType->getAs())
+  BaseType = OPT->getPointeeType();
 else if (const BlockPointerType *BPy = BaseType->getAs())
   BaseType = BPy->getPointeeType();
-else if (const ArrayType* ATy = dyn_cast(BaseType))
+else if (const ArrayType *ATy = dyn_cast(BaseType))
   BaseType = ATy->getElementType();
-else if (const FunctionType* FTy = BaseType->getAs())
+else if (const FunctionType *FTy = BaseType->getAs())
   BaseType = FTy->getReturnType();
 else if (const VectorType *VTy = BaseType->getAs())
   BaseType = VTy->getElementType();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 0abb5d2 - [Sema, StaticAnalyzer] Use StringRef::contains (NFC)

2021-10-20 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2021-10-20T08:02:36-07:00
New Revision: 0abb5d293cf7289780542fd9c5f0d84e5aadbdc8

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

LOG: [Sema, StaticAnalyzer] Use StringRef::contains (NFC)

Added: 


Modified: 
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp
clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
clang/lib/StaticAnalyzer/Core/CallEvent.cpp
clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
clang/lib/StaticAnalyzer/Core/MemRegion.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 1ea9b9e58d4a..a7a48016fe1e 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -9773,8 +9773,7 @@ static void CheckFormatString(Sema &S, const 
FormatStringLiteral *FExpr,
 
   // Emit a warning if the string literal is truncated and does not contain an
   // embedded null character.
-  if (TypeSize <= StrRef.size() &&
-  StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
+  if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) 
{
 CheckFormatHandler::EmitFormatDiagnostic(
 S, inFunctionCall, Args[format_idx],
 S.PDiag(diag::warn_printf_format_string_not_null_terminated),

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index c6c35c6e0cee..5b9568c1ed95 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -3213,13 +3213,13 @@ static void handleCodeSegAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
   enum FirstParam { Unsupported, Duplicate, Unknown };
   enum SecondParam { None, Architecture, Tune };
-  if (AttrStr.find("fpmath=") != StringRef::npos)
+  if (AttrStr.contains("fpmath="))
 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
<< Unsupported << None << "fpmath=";
 
   // Diagnose use of tune if target doesn't support it.
   if (!Context.getTargetInfo().supportsTargetAttributeTune() &&
-  AttrStr.find("tune=") != StringRef::npos)
+  AttrStr.contains("tune="))
 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
<< Unsupported << None << "tune=";
 
@@ -7570,7 +7570,7 @@ static void handleOpenCLAccessAttr(Sema &S, Decl *D, 
const ParsedAttr &AL) {
   // C++ for OpenCL 2021 inherits rule from OpenCL C v3.0.
   if (const auto *PDecl = dyn_cast(D)) {
 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
-if (AL.getAttrName()->getName().find("read_write") != StringRef::npos) {
+if (AL.getAttrName()->getName().contains("read_write")) {
   bool ReadWriteImagesUnsupported =
   (S.getLangOpts().getOpenCLCompatibleVersion() < 200) ||
   (S.getLangOpts().getOpenCLCompatibleVersion() == 300 &&

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 04f8540fe3b1..2109ff25fe7a 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -12434,8 +12434,7 @@ static void diagnoseXorMisusedAsPow(Sema &S, const 
ExprResult &XorLHS,
   RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
   (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
   (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
-  LHSStrRef.find('\'') != StringRef::npos ||
-  RHSStrRef.find('\'') != StringRef::npos)
+  LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
 return;
 
   bool SuggestXor =

diff  --git a/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
index d06c87631bfb..61ff5e59f06d 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
@@ -785,9 +785,8 @@ void WalkAST::checkDeprecatedOrUnsafeBufferHandling(const 
CallExpr *CE,
 // real flow analysis.
 auto FormatString =
 dyn_cast(CE->getArg(ArgIndex)->IgnoreParenImpCasts());
-if (FormatString &&
-FormatString->getString().find("%s") == StringRef::npos &&
-FormatString->getString().find("%[") == StringRef::npos)
+if (FormatString && !FormatString->getString().contains("%s") &&
+!FormatString->getString().contains("%["))
   BoundsProvided = true;
   }
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp 
b/clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp
index df88b71ff0

[PATCH] D112013: [clang][ASTImporter] Fix for importing functions with EST_Unevaluated prototype.

2021-10-20 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

Thanks! The fix makes sense and looks good to me. Though, it would be nice if 
you could provide a test without the hand crafting of the setTypeSourceInfo, 
but I think that could be done in a follow-up patch.




Comment at: clang/unittests/AST/ASTImporterTest.cpp:6180
+  ASSERT_FALSE(FromCtor->getTypeSourceInfo());
+  // Set a TypeSourceInfo for the function, this state may occur in reality.
+  TypeSourceInfo *FromTSI = FromTU->getASTContext().getTrivialTypeSourceInfo(

shafik wrote:
> balazske wrote:
> > shafik wrote:
> > > steakhal wrote:
> > > > Perhaps, put here a `FIXME` to replace this with a real-world scenario.
> > > I think it is useful to have cases that we run into in practice as a 
> > > regression test but it would be nice to see a more general test as well.
> > What means a "more general test"? Code where the `setTypeSourceInfo` is not 
> > needed? I just could not find out why there is no TypeSourceInfo set. The 
> > involved code part looks like this (comes from Bitcoin):
> > ```
> > void 
> > RegisterSharedValidationInterface(std::shared_ptr 
> > pwalletIn) {
> > // Each connection captures pwalletIn to ensure that each callback is
> > // executed before pwalletIn is destroyed. For more details see #18338.
> > g_signals.m_internals->Register(std::move(pwalletIn));
> > }
> > 
> > void RegisterValidationInterface(CValidationInterface* callbacks)
> > {
> > // Create a shared_ptr with a no-op deleter - CValidationInterface 
> > lifecycle
> > // is managed by the caller.
> > RegisterSharedValidationInterface({callbacks, 
> > [](CValidationInterface*){}});
> > //^ This is the lambda to 
> > be imported.
> > }
> > ```
> > If the same code is used in the test and a simple `CValidationInterface` 
> > and `std::shared_ptr` with appropriate constructor is added there is still 
> > no `TypeSourceInfo` in the needed place.
> Yeah, that is what I meant, a test that did not require the 
> `setTypeSourceInfo` hand crafting.
On one hand, I think this is a through and precisely written test case and we 
had similar test cases before. On the other hand, I agree it is unfortunate 
that we have to change the AST in the test setup.
@balazske Perhaps creduce-ing the to be imported TU with the bitcoin case could 
provide a reduced case that does not require the hand crafting of the 
`setTypeSourceInfo` ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112013

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


[PATCH] D107339: [analyzer] Retrieve a character from StringLiteral as an initializer for constant arrays.

2021-10-20 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Why does `glob_invalid_index7()` and `glob_invalid_index8()` differ in behavior?
I would expect that the analyzer produces the same `Loc` symbolic value for 
both cases thus, the array access should result in the same behavior regardless 
if `glob_arr6` is used, or acquired a pointer and using that in a subsequent 
operation.
Could you elaborate on this?




Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1642
+  //
+  // Previous check for `Idx < 0` guarantee that `Idx` is non-negative.
+  const auto I = static_cast(Idx.getExtValue());

Instead of this comment, you can put an `assert(Idx.isStrictlyPositive())` here.


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

https://reviews.llvm.org/D107339

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


[PATCH] D112143: [X86][ABI] Do not return float/double from x87 registers when x87 is disabled

2021-10-20 Thread Pengfei Wang via Phabricator via cfe-commits
pengfei created this revision.
pengfei added reviewers: aturetsk, echristo, RKSimon, LuoYuanke, craig.topper.
Herald added subscribers: dang, hiraditya.
pengfei requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

This is aligned with GCC's behavior.
Also, alias `-mno-fp-ret-in-387` to `-mno-x87`, by which we can fix pr51498.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112143

Files:
  clang/include/clang/Driver/Options.td
  clang/test/Driver/x86-target-features.c
  llvm/lib/Target/X86/X86CallingConv.td
  llvm/test/CodeGen/X86/no-x87.ll


Index: llvm/test/CodeGen/X86/no-x87.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/no-x87.ll
@@ -0,0 +1,17 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc < %s -mtriple=i686-- | FileCheck %s -check-prefix=X87
+; RUN: llc < %s -mtriple=i686-- -mattr=-x87 | FileCheck %s -check-prefix=NOX87
+
+define float @foo(float %a, float %b) nounwind {
+; X87-LABEL: foo:
+; X87:   # %bb.0: # %entry
+; X87-NEXT:flds {{[0-9]+}}(%esp)
+; X87-NEXT:retl
+;
+; NOX87-LABEL: foo:
+; NOX87:   # %bb.0: # %entry
+; NOX87-NEXT:movl {{[0-9]+}}(%esp), %eax
+; NOX87-NEXT:retl
+entry:
+  ret float %b
+}
Index: llvm/lib/Target/X86/X86CallingConv.td
===
--- llvm/lib/Target/X86/X86CallingConv.td
+++ llvm/lib/Target/X86/X86CallingConv.td
@@ -273,6 +273,10 @@
   // conv.
   CCIfInReg>>>,
+  CCIfNotSubtarget<"hasX87()",
+CCIfType<[f32], CCAssignToReg<[AX, DX, CX]>>>,
+  CCIfNotSubtarget<"hasX87()",
+CCIfType<[f64], CCAssignToReg<[EAX, EDX, ECX]>>>,
   CCIfType<[f32,f64], CCAssignToReg<[FP0, FP1]>>,
   CCIfType<[f16], CCAssignToReg<[XMM0,XMM1,XMM2]>>,
   CCDelegateTo
Index: clang/test/Driver/x86-target-features.c
===
--- clang/test/Driver/x86-target-features.c
+++ clang/test/Driver/x86-target-features.c
@@ -2,6 +2,7 @@
 // RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-x87 %s -### -o 
%t.o 2>&1 | FileCheck -check-prefix=NO-X87 %s
 // RUN: %clang -target i386-unknown-linux-gnu -march=i386 -m80387 %s -### -o 
%t.o 2>&1 | FileCheck -check-prefix=X87 %s
 // RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-80387 %s -### 
-o %t.o 2>&1 | FileCheck -check-prefix=NO-X87 %s
+// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-fp-ret-in-387 
%s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-X87 %s
 // X87: "-target-feature" "+x87"
 // NO-X87: "-target-feature" "-x87"
 
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -4166,6 +4166,7 @@
 def mno_x87 : Flag<["-"], "mno-x87">, Group;
 def m80387 : Flag<["-"], "m80387">, Alias;
 def mno_80387 : Flag<["-"], "mno-80387">, Alias;
+def mno_fp_ret_in_387 : Flag<["-"], "mno-fp-ret-in-387">, Alias;
 def mmmx : Flag<["-"], "mmmx">, Group;
 def mno_mmx : Flag<["-"], "mno-mmx">, Group;
 def m3dnow : Flag<["-"], "m3dnow">, Group;


Index: llvm/test/CodeGen/X86/no-x87.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/no-x87.ll
@@ -0,0 +1,17 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc < %s -mtriple=i686-- | FileCheck %s -check-prefix=X87
+; RUN: llc < %s -mtriple=i686-- -mattr=-x87 | FileCheck %s -check-prefix=NOX87
+
+define float @foo(float %a, float %b) nounwind {
+; X87-LABEL: foo:
+; X87:   # %bb.0: # %entry
+; X87-NEXT:flds {{[0-9]+}}(%esp)
+; X87-NEXT:retl
+;
+; NOX87-LABEL: foo:
+; NOX87:   # %bb.0: # %entry
+; NOX87-NEXT:movl {{[0-9]+}}(%esp), %eax
+; NOX87-NEXT:retl
+entry:
+  ret float %b
+}
Index: llvm/lib/Target/X86/X86CallingConv.td
===
--- llvm/lib/Target/X86/X86CallingConv.td
+++ llvm/lib/Target/X86/X86CallingConv.td
@@ -273,6 +273,10 @@
   // conv.
   CCIfInReg>>>,
+  CCIfNotSubtarget<"hasX87()",
+CCIfType<[f32], CCAssignToReg<[AX, DX, CX]>>>,
+  CCIfNotSubtarget<"hasX87()",
+CCIfType<[f64], CCAssignToReg<[EAX, EDX, ECX]>>>,
   CCIfType<[f32,f64], CCAssignToReg<[FP0, FP1]>>,
   CCIfType<[f16], CCAssignToReg<[XMM0,XMM1,XMM2]>>,
   CCDelegateTo
Index: clang/test/Driver/x86-target-features.c
===
--- clang/test/Driver/x86-target-features.c
+++ clang/test/Driver/x86-target-features.c
@@ -2,6 +2,7 @@
 // RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-x87 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-X87 %s
 // RUN: %clang -target i386-unknown-linux-gnu -march=i386 -m80387 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=X87 %s
 // RUN: %clang -target i38

[PATCH] D106681: [analyzer][NFCI] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D106681#3074779 , @ASDenysPetrov 
wrote:

> In D106681#3074678 , @steakhal 
> wrote:
>
>> I think it's fine, maybe `NFCi` is would be slightly more accurate, while 
>> stating the minor behavior change and the reason for doing so in the patch 
>> summary could further improve the visibility of this issue.
>>
>> That being said, since it actually changes some behavior, I'd like to 
>> request some tests covering the following (uncovered lines):
>> L1646, L1689, L1699
>
> For **L1646** currently I'm not sure about the exact test, since it is a 
> heritage of the old code, so it just jumped here from the past. If you could 
> give an example I would appreciate this.
> For **L1689** I'll add it.
> For **L1699** I've added //TODO// cases in D104285 
> .

I just wanted you to think about these cases.
BTW this should work for **L1646**:

  extern const int arr[]; // Incomplete array type
  void top() {
(void)arr[42];
  }

And I'm okay with the rest of the uncovered lines.




Comment at: clang/test/Analysis/initialization.c:103
+void glob_arr_index4() {
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}

I'm pretty sure we should not get `Unknown` for simply loading from a global 
variable.
That would imply that loading two times subsequently we could not prove that 
the value remained the same.
But that should remain the same, thus compare equal unless some other code 
modifier that memory region.

That could happen for two reasons:
1) There is a racecondition, and another thread modified that location. But 
that would be UB, so that could not happen.
2) The global variable is //volatile//, so the hardware might changed its 
content- but this global is not volatile so this does not apply.

That being said, this load should have resulted in a //fresh// conjured 
symbolic value instead of //unknown//.
Could you please check if it did result in //unknown// before your patch, or 
you did introduce this behavior?


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

https://reviews.llvm.org/D106681

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


[clang] 16be17a - [analyzer][NFC] Refactor llvm::isa<> usages in the StaticAnalyzer

2021-10-20 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-10-20T17:43:31+02:00
New Revision: 16be17ad4b13deb23c893c3c668076e70b07f289

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

LOG: [analyzer][NFC] Refactor llvm::isa<> usages in the StaticAnalyzer

It turns out llvm::isa<> is variadic, and we could have used this at a
lot of places.

The following patterns:
  x && isa(x) || isa(x) ...
Will be replaced by:
  isa_and_non_null(x)

Sometimes it caused further simplifications, when it would cause even
more code smell.

Aside from this, keep in mind that within `assert()` or any macro
functions, we need to wrap the isa<> expression within a parenthesis,
due to the parsing of the comma.

Reviewed By: martong

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp
clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp
clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp

clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
clang/lib/StaticAnalyzer/Core/BugReporter.cpp
clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
clang/lib/StaticAnalyzer/Core/CallEvent.cpp
clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
clang/lib/StaticAnalyzer/Core/Environment.cpp
clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
clang/lib/StaticAnalyzer/Core/MemRegion.cpp
clang/lib/StaticAnalyzer/Core/RegionStore.cpp
clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
clang/lib/StaticAnalyzer/Core/Store.cpp
clang/lib/StaticAnalyzer/Core/SymbolManager.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp
index c06604b6cffef..6154eeb3419c0 100644
--- a/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp
@@ -93,11 +93,10 @@ void AnalyzerStatsChecker::checkEndAnalysis(ExplodedGraph 
&G,
   if (!Loc.isValid())
 return;
 
-  if (isa(D) || isa(D)) {
+  if (isa(D)) {
 const NamedDecl *ND = cast(D);
 output << *ND;
-  }
-  else if (isa(D)) {
+  } else if (isa(D)) {
 output << "block(line:" << Loc.getLine() << ":col:" << Loc.getColumn();
   }
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
index a157ee2da5df4..635eb00e4ca95 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
@@ -160,7 +160,7 @@ static bool isEnclosingFunctionParam(const Expr *E) {
   E = E->IgnoreParenCasts();
   if (const DeclRefExpr *DRE = dyn_cast(E)) {
 const ValueDecl *VD = DRE->getDecl();
-if (isa(VD) || isa(VD))
+if (isa(VD))
   return true;
   }
   return false;
@@ -199,8 +199,7 @@ unsigned 
MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
 static bool isBadDeallocationArgument(const MemRegion *Arg) {
   if (!Arg)
 return false;
-  return isa(Arg) || isa(Arg) ||
- isa(Arg);
+  return isa(Arg);
 }
 
 /// Given the address expression, retrieve the value it's pointing to. Assume

diff  --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index f6b5ba098849f..5db4c72515dc5 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -936,7 +936,7 @@ class MallocBugVisitor final : public BugReporterVisitor {
   /// Did not track -> allocated. Other state (released) -> allocated.
   static inline bool isAllocated(const RefState *RSCurr, const RefState 
*RSPrev,
  const Stmt *Stmt) {
-return (Stmt && (isa(Stmt) || isa(Stmt)) &&
+return (isa_and_nonnull(Stmt) &&
 (RSCurr &&
  (RSCurr->isAllocated() || RSCurr->isAllocatedOfSizeZero())) &&
 (!RSPrev ||
@@ -949,8 +949,7 @@ class MallocBugVisitor final : public BugReporterVisitor {
 const Stmt *Stmt) {
 bool IsReleased =
 (RSCurr && RSCurr->isReleased()) && (!RSPrev || !RSPrev->isReleased());
-assert(!IsReleased ||
-   (Stmt && (isa(Stmt) || isa(Stmt))) ||
+assert(!IsReleased || (isa_and_nonnull(Stmt)) ||
   

[PATCH] D111566: [SYCL] Fix function pointer address space

2021-10-20 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews added a comment.

ping


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

https://reviews.llvm.org/D111566

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


[PATCH] D111982: [analyzer][NFC] Refactor llvm::isa<> usages in the StaticAnalyzer

2021-10-20 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG16be17ad4b13: [analyzer][NFC] Refactor llvm::isa<> 
usages in the StaticAnalyzer (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D111982?vs=380329&id=380972#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111982

Files:
  clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp
  
clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
  clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporter.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
  clang/lib/StaticAnalyzer/Core/Environment.cpp
  clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
  clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp
  clang/lib/StaticAnalyzer/Core/SymbolManager.cpp

Index: clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
+++ clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
@@ -425,19 +425,7 @@
   // tell if anything still refers to this region. Unlike SymbolicRegions,
   // AllocaRegions don't have associated symbols, though, so we don't actually
   // have a way to track their liveness.
-  if (isa(MR))
-return true;
-
-  if (isa(MR))
-return true;
-
-  if (isa(MR))
-return true;
-
-  if (isa(MR))
-return true;
-
-  return false;
+  return isa(MR);
 }
 
 bool SymbolReaper::isLive(SymbolRef sym) {
Index: clang/lib/StaticAnalyzer/Core/Store.cpp
===
--- clang/lib/StaticAnalyzer/Core/Store.cpp
+++ clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -84,7 +84,7 @@
 // involved.  Blocks can be casted to/from 'id', as they can be treated
 // as Objective-C objects.  This could possibly be handled by enhancing
 // our reasoning of downcasts of symbolic objects.
-if (isa(R) || isa(R))
+if (isa(R))
   return R;
 
 // We don't know what to make of it.  Return a NULL region, which
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -254,8 +254,7 @@
 }
 
 DefinedSVal SValBuilder::getMemberPointer(const NamedDecl *ND) {
-  assert(!ND || isa(ND) || isa(ND) ||
- isa(ND));
+  assert(!ND || (isa(ND)));
 
   if (const auto *MD = dyn_cast_or_null(ND)) {
 // Sema treats pointers to static member functions as have function pointer
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -62,8 +62,8 @@
 : P(r, k), Data(offset) {
 assert(r && "Must have known regions.");
 assert(getOffset() == offset && "Failed to store offset");
-assert((r == r->getBaseRegion() || isa(r) ||
-isa (r)) &&
+assert((r == r->getBaseRegion() ||
+isa(r)) &&
"Not a base");
   }
 public:
@@ -1135,7 +1135,7 @@
   if (Regions)
 Regions->push_back(baseR);
 
-  if (isa(baseR) || isa(baseR)) {
+  if (isa(baseR)) {
 // Invalidate the region by setting its default value to
 // conjured symbol. The type of the symbol is irrelevant.
 DefinedOrUnknownSVal V =
@@ -1224,7 +1224,7 @@
   // detection.
   SVal V = I.getData();
   const MemRegion *R = V.getAsRegion();
-  if (R && isa(R))
+  if (isa_and_nonnull(R))
 VisitBinding(V);
 }
   }
Index: clang/lib/StaticAnalyzer/Core/MemRegion.cpp
===
--- clang/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ clang/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -1012,14 +1012,15 @@
   sReg = getUnknownRegion();
 } else {
   if (D->hasLocalStorage()) {
-sReg = isa(D) || isa(D)
-   ? static_cast(getStackArgumentsRegion(STC))
-   : static_cast(getStackLocalsRegion(STC));
+

[clang] a29dfc0 - [RISCV] Use clang_builtin_alias for all RISCV vector intrinsics.

2021-10-20 Thread Craig Topper via cfe-commits

Author: Craig Topper
Date: 2021-10-20T08:50:42-07:00
New Revision: a29dfc089d18b542694cd26a06bee822ab90fb56

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

LOG: [RISCV] Use clang_builtin_alias for all RISCV vector intrinsics.

Previously we used builtin_alias for overloaded intrinsics, but
macros for the non-overloaded version. This patch changes the
non-overloaded versions to also use builtin_alias, but without
the overloadable attribute.

Reviewed By: khchen, HsiangKai

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

Added: 


Modified: 
clang/utils/TableGen/RISCVVEmitter.cpp

Removed: 




diff  --git a/clang/utils/TableGen/RISCVVEmitter.cpp 
b/clang/utils/TableGen/RISCVVEmitter.cpp
index 6c6ae0ebbdc96..b4fa0e2884705 100644
--- a/clang/utils/TableGen/RISCVVEmitter.cpp
+++ b/clang/utils/TableGen/RISCVVEmitter.cpp
@@ -198,7 +198,7 @@ class RVVIntrinsic {
   void emitCodeGenSwitchBody(raw_ostream &o) const;
 
   // Emit the macros for mapping C/C++ intrinsic function to builtin functions.
-  void emitIntrinsicMacro(raw_ostream &o) const;
+  void emitIntrinsicFuncDef(raw_ostream &o) const;
 
   // Emit the mangled function definition.
   void emitMangledFuncDef(raw_ostream &o) const;
@@ -855,34 +855,30 @@ void RVVIntrinsic::emitCodeGenSwitchBody(raw_ostream &OS) 
const {
   OS << "  break;\n";
 }
 
-void RVVIntrinsic::emitIntrinsicMacro(raw_ostream &OS) const {
-  OS << "#define " << getName() << "(";
-  if (!InputTypes.empty()) {
-ListSeparator LS;
-for (unsigned i = 0, e = InputTypes.size(); i != e; ++i)
-  OS << LS << "op" << i;
-  }
-  OS << ") \\\n";
-  OS << "__builtin_rvv_" << getName() << "(";
+void RVVIntrinsic::emitIntrinsicFuncDef(raw_ostream &OS) const {
+  OS << "__attribute__((__clang_builtin_alias__(";
+  OS << "__builtin_rvv_" << getName() << ")))\n";
+  OS << OutputType->getTypeStr() << " " << getName() << "(";
+  // Emit function arguments
   if (!InputTypes.empty()) {
 ListSeparator LS;
-for (unsigned i = 0, e = InputTypes.size(); i != e; ++i)
-  OS << LS << "(" << InputTypes[i]->getTypeStr() << ")(op" << i << ")";
+for (unsigned i = 0; i < InputTypes.size(); ++i)
+  OS << LS << InputTypes[i]->getTypeStr();
   }
-  OS << ")\n";
+  OS << ");\n";
 }
 
 void RVVIntrinsic::emitMangledFuncDef(raw_ostream &OS) const {
-  OS << "__attribute__((clang_builtin_alias(";
+  OS << "__attribute__((__clang_builtin_alias__(";
   OS << "__builtin_rvv_" << getName() << ")))\n";
   OS << OutputType->getTypeStr() << " " << getMangledName() << "(";
   // Emit function arguments
   if (!InputTypes.empty()) {
 ListSeparator LS;
 for (unsigned i = 0; i < InputTypes.size(); ++i)
-  OS << LS << InputTypes[i]->getTypeStr() << " op" << i;
+  OS << LS << InputTypes[i]->getTypeStr();
   }
-  OS << ");\n\n";
+  OS << ");\n";
 }
 
 
//===--===//
@@ -980,24 +976,32 @@ void RVVEmitter::createHeader(raw_ostream &OS) {
 return A->getRISCVExtensions() < B->getRISCVExtensions();
   });
 
+  OS << "#define __rvv_ai static __inline__ "
+"__attribute__((__always_inline__, __nodebug__))\n";
+
   // Print intrinsic functions with macro
   emitArchMacroAndBody(Defs, OS, [](raw_ostream &OS, const RVVIntrinsic &Inst) 
{
-Inst.emitIntrinsicMacro(OS);
+OS << "__rvv_ai ";
+Inst.emitIntrinsicFuncDef(OS);
   });
 
+  OS << "#undef __rvv_ai\n\n";
+
   OS << "#define __riscv_v_intrinsic_overloading 1\n";
 
   // Print Overloaded APIs
-  OS << "#define __rvv_overloaded static inline "
+  OS << "#define __rvv_aio static __inline__ "
 "__attribute__((__always_inline__, __nodebug__, __overloadable__))\n";
 
   emitArchMacroAndBody(Defs, OS, [](raw_ostream &OS, const RVVIntrinsic &Inst) 
{
 if (!Inst.isMask() && !Inst.hasNoMaskedOverloaded())
   return;
-OS << "__rvv_overloaded ";
+OS << "__rvv_aio ";
 Inst.emitMangledFuncDef(OS);
   });
 
+  OS << "#undef __rvv_aio\n";
+
   OS << "\n#ifdef __cplusplus\n";
   OS << "}\n";
   OS << "#endif // __cplusplus\n";



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


[PATCH] D112020: [RISCV] Use clang_builtin_alias for all RISCV vector intrinsics.

2021-10-20 Thread Craig Topper 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 rGa29dfc089d18: [RISCV] Use clang_builtin_alias for all RISCV 
vector intrinsics. (authored by craig.topper).

Changed prior to commit:
  https://reviews.llvm.org/D112020?vs=380474&id=380976#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112020

Files:
  clang/utils/TableGen/RISCVVEmitter.cpp


Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -198,7 +198,7 @@
   void emitCodeGenSwitchBody(raw_ostream &o) const;
 
   // Emit the macros for mapping C/C++ intrinsic function to builtin functions.
-  void emitIntrinsicMacro(raw_ostream &o) const;
+  void emitIntrinsicFuncDef(raw_ostream &o) const;
 
   // Emit the mangled function definition.
   void emitMangledFuncDef(raw_ostream &o) const;
@@ -855,34 +855,30 @@
   OS << "  break;\n";
 }
 
-void RVVIntrinsic::emitIntrinsicMacro(raw_ostream &OS) const {
-  OS << "#define " << getName() << "(";
-  if (!InputTypes.empty()) {
-ListSeparator LS;
-for (unsigned i = 0, e = InputTypes.size(); i != e; ++i)
-  OS << LS << "op" << i;
-  }
-  OS << ") \\\n";
-  OS << "__builtin_rvv_" << getName() << "(";
+void RVVIntrinsic::emitIntrinsicFuncDef(raw_ostream &OS) const {
+  OS << "__attribute__((__clang_builtin_alias__(";
+  OS << "__builtin_rvv_" << getName() << ")))\n";
+  OS << OutputType->getTypeStr() << " " << getName() << "(";
+  // Emit function arguments
   if (!InputTypes.empty()) {
 ListSeparator LS;
-for (unsigned i = 0, e = InputTypes.size(); i != e; ++i)
-  OS << LS << "(" << InputTypes[i]->getTypeStr() << ")(op" << i << ")";
+for (unsigned i = 0; i < InputTypes.size(); ++i)
+  OS << LS << InputTypes[i]->getTypeStr();
   }
-  OS << ")\n";
+  OS << ");\n";
 }
 
 void RVVIntrinsic::emitMangledFuncDef(raw_ostream &OS) const {
-  OS << "__attribute__((clang_builtin_alias(";
+  OS << "__attribute__((__clang_builtin_alias__(";
   OS << "__builtin_rvv_" << getName() << ")))\n";
   OS << OutputType->getTypeStr() << " " << getMangledName() << "(";
   // Emit function arguments
   if (!InputTypes.empty()) {
 ListSeparator LS;
 for (unsigned i = 0; i < InputTypes.size(); ++i)
-  OS << LS << InputTypes[i]->getTypeStr() << " op" << i;
+  OS << LS << InputTypes[i]->getTypeStr();
   }
-  OS << ");\n\n";
+  OS << ");\n";
 }
 
 
//===--===//
@@ -980,24 +976,32 @@
 return A->getRISCVExtensions() < B->getRISCVExtensions();
   });
 
+  OS << "#define __rvv_ai static __inline__ "
+"__attribute__((__always_inline__, __nodebug__))\n";
+
   // Print intrinsic functions with macro
   emitArchMacroAndBody(Defs, OS, [](raw_ostream &OS, const RVVIntrinsic &Inst) 
{
-Inst.emitIntrinsicMacro(OS);
+OS << "__rvv_ai ";
+Inst.emitIntrinsicFuncDef(OS);
   });
 
+  OS << "#undef __rvv_ai\n\n";
+
   OS << "#define __riscv_v_intrinsic_overloading 1\n";
 
   // Print Overloaded APIs
-  OS << "#define __rvv_overloaded static inline "
+  OS << "#define __rvv_aio static __inline__ "
 "__attribute__((__always_inline__, __nodebug__, __overloadable__))\n";
 
   emitArchMacroAndBody(Defs, OS, [](raw_ostream &OS, const RVVIntrinsic &Inst) 
{
 if (!Inst.isMask() && !Inst.hasNoMaskedOverloaded())
   return;
-OS << "__rvv_overloaded ";
+OS << "__rvv_aio ";
 Inst.emitMangledFuncDef(OS);
   });
 
+  OS << "#undef __rvv_aio\n";
+
   OS << "\n#ifdef __cplusplus\n";
   OS << "}\n";
   OS << "#endif // __cplusplus\n";


Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -198,7 +198,7 @@
   void emitCodeGenSwitchBody(raw_ostream &o) const;
 
   // Emit the macros for mapping C/C++ intrinsic function to builtin functions.
-  void emitIntrinsicMacro(raw_ostream &o) const;
+  void emitIntrinsicFuncDef(raw_ostream &o) const;
 
   // Emit the mangled function definition.
   void emitMangledFuncDef(raw_ostream &o) const;
@@ -855,34 +855,30 @@
   OS << "  break;\n";
 }
 
-void RVVIntrinsic::emitIntrinsicMacro(raw_ostream &OS) const {
-  OS << "#define " << getName() << "(";
-  if (!InputTypes.empty()) {
-ListSeparator LS;
-for (unsigned i = 0, e = InputTypes.size(); i != e; ++i)
-  OS << LS << "op" << i;
-  }
-  OS << ") \\\n";
-  OS << "__builtin_rvv_" << getName() << "(";
+void RVVIntrinsic::emitIntrinsicFuncDef(raw_ostream &OS) const {
+  OS << "__attribute__((__clang_builtin_alias__(";
+  OS << "__builtin_rvv_" << getName() << ")))\n";
+  OS << OutputType->getTypeStr() << " " << getName() << "(";
+  // Emit fun

[PATCH] D99797: [analyzer] Implemented RangeSet::Factory::unite function to handle intersections and adjacency

2021-10-20 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:149
+
+RangeSet RangeSet::Factory::unite(RangeSet Original, llvm::APSInt Point) {
+  return unite(Original, Range(ValueFactory.getValue(Point)));

martong wrote:
> ASDenysPetrov wrote:
> > steakhal wrote:
> > > Why do you take `APSInt`s by value? Generally, we take them by reference.
> > I want to send a message to the caller that he can pass an arbitrary 
> > **APSInt** without warrying about making it permanent (aka stored by the 
> > Factory). But we can revise this contract and carry this responsibility to 
> > a caller.
> > Why do you take `APSInt`s by value? Generally, we take them by reference.
> 
> Actually, it is specific to `BasicValueFactory` to cache the `APSInt`s, 
> however, it might not be the best practice. I doubt that somebody has ever 
> measured the performance of passing APSInts by value, so my guess is the 
> caching of `APSInt`s might be an early optimization that might be more 
> harmful than advantageous. On top of all this, we do the caching 
> inconsistently, just consider the member functions of `APSIntType`, they all 
> return by value.
> 
> Perhaps (totally independently from this patch of course), it might be worth 
> to have a measurement/comparison with removed cache and pass by value.
> 
Okay, then we shall leave this as-is now.



Comment at: clang/unittests/StaticAnalyzer/RangeSetTest.cpp:81
   const llvm::APSInt &from(BaseType X) {
-llvm::APSInt Dummy = Base;
-Dummy = X;
-return BVF.getValue(Dummy);
+static llvm::APSInt Base{sizeof(BaseType) * 8,
+ std::is_unsigned::value};

ASDenysPetrov wrote:
> steakhal wrote:
> > Shouldn't you use `sizeof(BaseType) * CHAR_BIT` instead?
> Agree. It's better to avoid magic numbers. I'll fix.
It's not only that but just imagine testing a clang on a special hardware where 
they have let's say 9 bit bytes, for parity or something similar stuff.
The test would suddenly break.
Although I suspect there would be many more things to break TBH xD


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

https://reviews.llvm.org/D99797

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


[PATCH] D111566: [SYCL] Fix function pointer address space

2021-10-20 Thread Alexey Bader via Phabricator via cfe-commits
bader accepted this revision.
bader added a comment.
This revision is now accepted and ready to land.

@vlastik, your commit fixes function pointers on AVR - 
https://github.com/llvm/llvm-project/commit/57fd86de879cf2b4c7001b6d0a09df60877ce24d.
 I suppose this change is required for fixing lvalue references to function 
pointers on AVR as well. Right?


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

https://reviews.llvm.org/D111566

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


[clang] fe66433 - [clang] Add plugin ActionType to run command line plugin before main action

2021-10-20 Thread Arthur Eubanks via cfe-commits

Author: Arthur Eubanks
Date: 2021-10-20T08:58:20-07:00
New Revision: fe66433fe119819a033827610f7eae4cdd8b1470

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

LOG: [clang] Add plugin ActionType to run command line plugin before main action

Currently we have a way to run a plugin if specified on the command line
after the main action, and ways to unconditionally run the plugin before
or after the main action, but no way to run a plugin if specified on the
command line before the main action.

This introduces the missing option.

This is helpful because -clear-ast-before-backend clears the AST before
codegen, while some plugins may want access to the AST.

Reviewed By: dblaikie

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

Added: 
clang/examples/PluginsOrder/CMakeLists.txt
clang/examples/PluginsOrder/PluginsOrder.cpp
clang/test/Frontend/plugins-order.c

Modified: 
clang/examples/CMakeLists.txt
clang/include/clang/Frontend/FrontendAction.h
clang/lib/Frontend/FrontendAction.cpp
clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
clang/test/CMakeLists.txt

Removed: 




diff  --git a/clang/examples/CMakeLists.txt b/clang/examples/CMakeLists.txt
index 300d8d795c674..684d81d180278 100644
--- a/clang/examples/CMakeLists.txt
+++ b/clang/examples/CMakeLists.txt
@@ -8,3 +8,4 @@ add_subdirectory(PrintFunctionNames)
 add_subdirectory(AnnotateFunctions)
 add_subdirectory(Attribute)
 add_subdirectory(CallSuperAttribute)
+add_subdirectory(PluginsOrder)

diff  --git a/clang/examples/PluginsOrder/CMakeLists.txt 
b/clang/examples/PluginsOrder/CMakeLists.txt
new file mode 100644
index 0..289e234ac28c4
--- /dev/null
+++ b/clang/examples/PluginsOrder/CMakeLists.txt
@@ -0,0 +1,11 @@
+add_llvm_library(PluginsOrder MODULE PluginsOrder.cpp PLUGIN_TOOL clang)
+
+if(LLVM_ENABLE_PLUGINS AND (WIN32 OR CYGWIN))
+  set(LLVM_LINK_COMPONENTS
+Support
+  )
+  clang_target_link_libraries(PluginsOrder PRIVATE
+clangAST
+clangFrontend
+)
+endif()

diff  --git a/clang/examples/PluginsOrder/PluginsOrder.cpp 
b/clang/examples/PluginsOrder/PluginsOrder.cpp
new file mode 100644
index 0..e25ab7aceca85
--- /dev/null
+++ b/clang/examples/PluginsOrder/PluginsOrder.cpp
@@ -0,0 +1,117 @@
+//===- PluginsOrder.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/AST/AST.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/Frontend/FrontendPluginRegistry.h"
+using namespace clang;
+
+namespace {
+
+class AlwaysBeforeConsumer : public ASTConsumer {
+public:
+  void HandleTranslationUnit(ASTContext &) override {
+llvm::errs() << "always-before\n";
+  }
+};
+
+class AlwaysBeforeAction : public PluginASTAction {
+public:
+  std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
+ llvm::StringRef) override {
+return std::make_unique();
+  }
+
+  bool ParseArgs(const CompilerInstance &CI,
+ const std::vector &args) override {
+return true;
+  }
+
+  PluginASTAction::ActionType getActionType() override {
+return AddBeforeMainAction;
+  }
+};
+
+class AlwaysAfterConsumer : public ASTConsumer {
+public:
+  void HandleTranslationUnit(ASTContext &) override {
+llvm::errs() << "always-after\n";
+  }
+};
+
+class AlwaysAfterAction : public PluginASTAction {
+public:
+  std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
+ llvm::StringRef) override {
+return std::make_unique();
+  }
+
+  bool ParseArgs(const CompilerInstance &CI,
+ const std::vector &args) override {
+return true;
+  }
+
+  PluginASTAction::ActionType getActionType() override {
+return AddAfterMainAction;
+  }
+};
+
+class CmdAfterConsumer : public ASTConsumer {
+public:
+  void HandleTranslationUnit(ASTContext &) override {
+llvm::errs() << "cmd-after\n";
+  }
+};
+
+class CmdAfterAction : public PluginASTAction {
+public:
+  std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
+ llvm::StringRef) override {
+return std::make_unique();
+  }
+
+  bool ParseArgs(const CompilerInstance &CI,
+ const std::vector &args) override {
+return true;
+  }
+
+  PluginASTAction::ActionType getActionType() override {
+return CmdlineAfterMainAction;
+  }
+};
+
+class CmdBeforeConsumer : public ASTConsumer {
+public:
+  void HandleTranslationUnit(ASTCo

[PATCH] D112096: [clang] Add plugin ActionType to run command line plugin before main action

2021-10-20 Thread Arthur Eubanks via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfe66433fe119: [clang] Add plugin ActionType to run command 
line plugin before main action (authored by aeubanks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112096

Files:
  clang/examples/CMakeLists.txt
  clang/examples/PluginsOrder/CMakeLists.txt
  clang/examples/PluginsOrder/PluginsOrder.cpp
  clang/include/clang/Frontend/FrontendAction.h
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  clang/test/CMakeLists.txt
  clang/test/Frontend/plugins-order.c

Index: clang/test/Frontend/plugins-order.c
===
--- /dev/null
+++ clang/test/Frontend/plugins-order.c
@@ -0,0 +1,12 @@
+// REQUIRES: plugins, examples
+
+// RUN: %clang_cc1 -load %llvmshlibdir/PluginsOrder%pluginext %s 2>&1 | FileCheck %s --check-prefix=ALWAYS
+// ALWAYS: always-before
+// ALWAYS-NEXT: always-after
+
+// RUN: %clang_cc1 -load %llvmshlibdir/PluginsOrder%pluginext %s -add-plugin cmd-after -add-plugin cmd-before 2>&1 | FileCheck %s --check-prefix=ALL
+// RUN: %clang_cc1 -load %llvmshlibdir/PluginsOrder%pluginext %s -add-plugin cmd-before -add-plugin cmd-after 2>&1 | FileCheck %s --check-prefix=ALL
+// ALL: cmd-before
+// ALL-NEXT: always-before
+// ALL-NEXT: cmd-after
+// ALL-NEXT: always-after
Index: clang/test/CMakeLists.txt
===
--- clang/test/CMakeLists.txt
+++ clang/test/CMakeLists.txt
@@ -97,6 +97,7 @@
 AnnotateFunctions
 CallSuperAttr
 clang-interpreter
+PluginsOrder
 PrintFunctionNames
 )
 endif ()
Index: clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -79,7 +79,7 @@
   if (Plugin.getName() == CI.getFrontendOpts().ActionName) {
 std::unique_ptr P(Plugin.instantiate());
 if ((P->getActionType() != PluginASTAction::ReplaceAction &&
- P->getActionType() != PluginASTAction::Cmdline) ||
+ P->getActionType() != PluginASTAction::CmdlineAfterMainAction) ||
 !P->ParseArgs(
 CI,
 CI.getFrontendOpts().PluginArgs[std::string(Plugin.getName())]))
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -187,14 +187,19 @@
FrontendPluginRegistry::entries()) {
 std::unique_ptr P = Plugin.instantiate();
 PluginASTAction::ActionType ActionType = P->getActionType();
-if (ActionType == PluginASTAction::Cmdline) {
+if (ActionType == PluginASTAction::CmdlineAfterMainAction ||
+ActionType == PluginASTAction::CmdlineBeforeMainAction) {
   // This is O(|plugins| * |add_plugins|), but since both numbers are
   // way below 50 in practice, that's ok.
   if (llvm::any_of(CI.getFrontendOpts().AddPluginActions,
[&](const std::string &PluginAction) {
  return PluginAction == Plugin.getName();
-   }))
-ActionType = PluginASTAction::AddAfterMainAction;
+   })) {
+if (ActionType == PluginASTAction::CmdlineBeforeMainAction)
+  ActionType = PluginASTAction::AddBeforeMainAction;
+else
+  ActionType = PluginASTAction::AddAfterMainAction;
+  }
 }
 if ((ActionType == PluginASTAction::AddBeforeMainAction ||
  ActionType == PluginASTAction::AddAfterMainAction) &&
Index: clang/include/clang/Frontend/FrontendAction.h
===
--- clang/include/clang/Frontend/FrontendAction.h
+++ clang/include/clang/Frontend/FrontendAction.h
@@ -270,17 +270,18 @@
  const std::vector &arg) = 0;
 
   enum ActionType {
-Cmdline, ///< Action is determined by the cc1 command-line
-ReplaceAction,   ///< Replace the main action
-AddBeforeMainAction, ///< Execute the action before the main action
-AddAfterMainAction   ///< Execute the action after the main action
+CmdlineBeforeMainAction, ///< Execute the action before the main action if
+ ///< on the command line
+CmdlineAfterMainAction,  ///< Execute the action after the main action if on
+ ///< the command line
+ReplaceAction,   ///< Replace the main action
+AddBeforeMainAction, ///< Execute the action before the main action
+AddAfterMainAction   ///< Execute the action after the main action
   };
   /// Get the action type for this plugin
   ///
-  /// \return The action 

[PATCH] D112102: [RISCV] Reduce the number of RISCV vector builtins by an order of magnitude.

2021-10-20 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

In D112102#3074656 , @frasercrmck 
wrote:

> Minor typo in the description: `differnet`
>
> Does this help with compile times, binary sizes, etc?

This reduces the clang binary size by 2.34 megabytes according to my local 
release+asserts build.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112102

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


[PATCH] D112146: [WebAssembly] Add prototype relaxed float min max instructions

2021-10-20 Thread Ng Zhi An via Phabricator via cfe-commits
ngzhian created this revision.
ngzhian added a reviewer: tlively.
Herald added subscribers: ecnelises, sunfish, hiraditya, jgravelle-google, 
sbc100, dschuff.
ngzhian requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, aheejin.
Herald added projects: clang, LLVM.

Add relaxed. f32x4.min, f32x4.max, f64x2.min, f64x2.max. These are only
exposed as builtins, and require user opt-in.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112146

Files:
  clang/include/clang/Basic/BuiltinsWebAssembly.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtins-wasm.c
  llvm/include/llvm/IR/IntrinsicsWebAssembly.td
  llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
  llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
  llvm/test/MC/WebAssembly/simd-encodings.s

Index: llvm/test/MC/WebAssembly/simd-encodings.s
===
--- llvm/test/MC/WebAssembly/simd-encodings.s
+++ llvm/test/MC/WebAssembly/simd-encodings.s
@@ -806,4 +806,16 @@
 # CHECK: i8x16.relaxed_swizzle # encoding: [0xfd,0xa2,0x01]
 i8x16.relaxed_swizzle
 
+# CHECK: f32x4.relaxed_min # encoding: [0xfd,0xb4,0x01]
+f32x4.relaxed_min
+
+# CHECK: f32x4.relaxed_max # encoding: [0xfd,0xe2,0x01]
+f32x4.relaxed_max
+
+# CHECK: f64x2.relaxed_min # encoding: [0xfd,0xd4,0x01]
+f64x2.relaxed_min
+
+# CHECK: f64x2.relaxed_max # encoding: [0xfd,0xee,0x01]
+f64x2.relaxed_max
+
 end_function
Index: llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
===
--- llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
+++ llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
@@ -682,6 +682,30 @@
   ret <4 x float> %v
 }
 
+; CHECK-LABEL: relaxed_min_v4f32:
+; CHECK-NEXT: .functype relaxed_min_v4f32 (v128, v128) -> (v128){{$}}
+; CHECK-NEXT: f32x4.relaxed_min $push[[R:[0-9]+]]=, $0, $1{{$}}
+; CHECK-NEXT: return $pop[[R]]{{$}}
+declare <4 x float> @llvm.wasm.relaxed.min.v4f32(<4 x float>, <4 x float>)
+define <4 x float> @relaxed_min_v4f32(<4 x float> %a, <4 x float> %b) {
+  %v = call <4 x float> @llvm.wasm.relaxed.min.v4f32(
+<4 x float> %a, <4 x float> %b
+  )
+  ret <4 x float> %v
+}
+
+; CHECK-LABEL: relaxed_max_v4f32:
+; CHECK-NEXT: .functype relaxed_max_v4f32 (v128, v128) -> (v128){{$}}
+; CHECK-NEXT: f32x4.relaxed_max $push[[R:[0-9]+]]=, $0, $1{{$}}
+; CHECK-NEXT: return $pop[[R]]{{$}}
+declare <4 x float> @llvm.wasm.relaxed.max.v4f32(<4 x float>, <4 x float>)
+define <4 x float> @relaxed_max_v4f32(<4 x float> %a, <4 x float> %b) {
+  %v = call <4 x float> @llvm.wasm.relaxed.max.v4f32(
+<4 x float> %a, <4 x float> %b
+  )
+  ret <4 x float> %v
+}
+
 ; ==
 ; 2 x f64
 ; ==
@@ -780,3 +804,27 @@
   )
   ret <2 x double> %v
 }
+
+; CHECK-LABEL: relaxed_min_v2f64:
+; CHECK-NEXT: .functype relaxed_min_v2f64 (v128, v128) -> (v128){{$}}
+; CHECK-NEXT: f64x2.relaxed_min $push[[R:[0-9]+]]=, $0, $1{{$}}
+; CHECK-NEXT: return $pop[[R]]{{$}}
+declare <2 x double> @llvm.wasm.relaxed.min.v2f64(<2 x double>, <2 x double>)
+define <2 x double> @relaxed_min_v2f64(<2 x double> %a, <2 x double> %b) {
+  %v = call <2 x double> @llvm.wasm.relaxed.min.v2f64(
+<2 x double> %a, <2 x double> %b
+  )
+  ret <2 x double> %v
+}
+
+; CHECK-LABEL: relaxed_max_v2f64:
+; CHECK-NEXT: .functype relaxed_max_v2f64 (v128, v128) -> (v128){{$}}
+; CHECK-NEXT: f64x2.relaxed_max $push[[R:[0-9]+]]=, $0, $1{{$}}
+; CHECK-NEXT: return $pop[[R]]{{$}}
+declare <2 x double> @llvm.wasm.relaxed.max.v2f64(<2 x double>, <2 x double>)
+define <2 x double> @relaxed_max_v2f64(<2 x double> %a, <2 x double> %b) {
+  %v = call <2 x double> @llvm.wasm.relaxed.max.v2f64(
+<2 x double> %a, <2 x double> %b
+  )
+  ret <2 x double> %v
+}
Index: llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
===
--- llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
+++ llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
@@ -1372,3 +1372,23 @@
  [(set (v16i8 V128:$dst),
(int_wasm_relaxed_swizzle (v16i8 V128:$src), (v16i8 V128:$mask)))],
  "i8x16.relaxed_swizzle\t$dst, $src, $mask", "i8x16.relaxed_swizzle", 162>;
+
+//===--===//
+// Relaxed floating-point min and max.
+//===--===//
+
+multiclass SIMD_RELAXED_FMINMAX simdopMin, bits<32> simdopMax> {
+  defm RELAXED_FMIN_#vec :
+RELAXED_I<(outs V128:$dst), (ins V128:$a, V128:$b), (outs), (ins),
+  [(set (vec.vt V128:$dst), (int_wasm_relaxed_min
+(vec.vt V128:$a), (vec.vt V128:$b)))],
+  vec.prefix#".relaxed_min\t$dst, $a, $b", vec.prefix#".relaxed_min", simdopMi

[PATCH] D110068: [Clang][AST] Resolve FIXME: Remove ObjCObjectPointer from isSpecifierType

2021-10-20 Thread Alf via Phabricator via cfe-commits
gAlfonso-bit added a comment.

@dexonsmith Could you please commit this?


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

https://reviews.llvm.org/D110068

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


[PATCH] D112102: [RISCV] Reduce the number of RISCV vector builtins by an order of magnitude.

2021-10-20 Thread Craig Topper via Phabricator via cfe-commits
craig.topper updated this revision to Diff 380982.
craig.topper added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112102

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/RISCV/riscv-attr-builtin-alias.c
  clang/test/CodeGen/RISCV/rvv-intrinsics-overloaded/vmerge.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vmerge.c
  clang/utils/TableGen/RISCVVEmitter.cpp
  llvm/lib/Target/RISCV/RISCVInstrInfoVPseudos.td
  llvm/test/CodeGen/RISCV/rvv/vmerge-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/vmerge-rv64.ll

Index: llvm/test/CodeGen/RISCV/rvv/vmerge-rv64.ll
===
--- llvm/test/CodeGen/RISCV/rvv/vmerge-rv64.ll
+++ llvm/test/CodeGen/RISCV/rvv/vmerge-rv64.ll
@@ -1,5 +1,5 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
-; RUN: llc -mtriple=riscv64 -mattr=+experimental-v,+d -verify-machineinstrs \
+; RUN: llc -mtriple=riscv64 -mattr=+experimental-v,+d,+experimental-zfh -verify-machineinstrs \
 ; RUN:   < %s | FileCheck %s
 declare  @llvm.riscv.vmerge.nxv1i8.nxv1i8(
   ,
@@ -1320,3 +1320,333 @@
 
   ret  %a
 }
+
+declare  @llvm.riscv.vmerge.nxv1f16.nxv1f16(
+  ,
+  ,
+  ,
+  i64);
+
+define  @intrinsic_vmerge_vvm_nxv1f16_nxv1f16_nxv1f16( %0,  %1,  %2, i64 %3) nounwind {
+; CHECK-LABEL: intrinsic_vmerge_vvm_nxv1f16_nxv1f16_nxv1f16:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:vsetvli zero, a0, e16, mf4, ta, mu
+; CHECK-NEXT:vmerge.vvm v8, v8, v9, v0
+; CHECK-NEXT:ret
+entry:
+  %a = call  @llvm.riscv.vmerge.nxv1f16.nxv1f16(
+ %0,
+ %1,
+ %2,
+i64 %3)
+
+  ret  %a
+}
+
+declare  @llvm.riscv.vmerge.nxv2f16.nxv2f16(
+  ,
+  ,
+  ,
+  i64);
+
+define  @intrinsic_vmerge_vvm_nxv2f16_nxv2f16_nxv2f16( %0,  %1,  %2, i64 %3) nounwind {
+; CHECK-LABEL: intrinsic_vmerge_vvm_nxv2f16_nxv2f16_nxv2f16:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:vsetvli zero, a0, e16, mf2, ta, mu
+; CHECK-NEXT:vmerge.vvm v8, v8, v9, v0
+; CHECK-NEXT:ret
+entry:
+  %a = call  @llvm.riscv.vmerge.nxv2f16.nxv2f16(
+ %0,
+ %1,
+ %2,
+i64 %3)
+
+  ret  %a
+}
+
+declare  @llvm.riscv.vmerge.nxv4f16.nxv4f16(
+  ,
+  ,
+  ,
+  i64);
+
+define  @intrinsic_vmerge_vvm_nxv4f16_nxv4f16_nxv4f16( %0,  %1,  %2, i64 %3) nounwind {
+; CHECK-LABEL: intrinsic_vmerge_vvm_nxv4f16_nxv4f16_nxv4f16:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:vsetvli zero, a0, e16, m1, ta, mu
+; CHECK-NEXT:vmerge.vvm v8, v8, v9, v0
+; CHECK-NEXT:ret
+entry:
+  %a = call  @llvm.riscv.vmerge.nxv4f16.nxv4f16(
+ %0,
+ %1,
+ %2,
+i64 %3)
+
+  ret  %a
+}
+
+declare  @llvm.riscv.vmerge.nxv8f16.nxv8f16(
+  ,
+  ,
+  ,
+  i64);
+
+define  @intrinsic_vmerge_vvm_nxv8f16_nxv8f16_nxv8f16( %0,  %1,  %2, i64 %3) nounwind {
+; CHECK-LABEL: intrinsic_vmerge_vvm_nxv8f16_nxv8f16_nxv8f16:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:vsetvli zero, a0, e16, m2, ta, mu
+; CHECK-NEXT:vmerge.vvm v8, v8, v10, v0
+; CHECK-NEXT:ret
+entry:
+  %a = call  @llvm.riscv.vmerge.nxv8f16.nxv8f16(
+ %0,
+ %1,
+ %2,
+i64 %3)
+
+  ret  %a
+}
+
+declare  @llvm.riscv.vmerge.nxv16f16.nxv16f16(
+  ,
+  ,
+  ,
+  i64);
+
+define  @intrinsic_vmerge_vvm_nxv16f16_nxv16f16_nxv16f16( %0,  %1,  %2, i64 %3) nounwind {
+; CHECK-LABEL: intrinsic_vmerge_vvm_nxv16f16_nxv16f16_nxv16f16:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:vsetvli zero, a0, e16, m4, ta, mu
+; CHECK-NEXT:vmerge.vvm v8, v8, v12, v0
+; CHECK-NEXT:ret
+entry:
+  %a = call  @llvm.riscv.vmerge.nxv16f16.nxv16f16(
+ %0,
+ %1,
+ %2,
+i64 %3)
+
+  ret  %a
+}
+
+declare  @llvm.riscv.vmerge.nxv32f16.nxv32f16(
+  ,
+  ,
+  ,
+  i64);
+
+define  @intrinsic_vmerge_vvm_nxv32f16_nxv32f16_nxv32f16( %0,  %1,  %2, i64 %3) nounwind {
+; CHECK-LABEL: intrinsic_vmerge_vvm_nxv32f16_nxv32f16_nxv32f16:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:vsetvli zero, a0, e16, m8, ta, mu
+; CHECK-NEXT:vmerge.vvm v8, v8, v16, v0
+; CHECK-NEXT:ret
+entry:
+  %a = call  @llvm.riscv.vmerge.nxv32f16.nxv32f16(
+ %0,
+ %1,
+ %2,
+i64 %3)
+
+  ret  %a
+}
+
+declare  @llvm.riscv.vmerge.nxv1f32.nxv1f32(
+  ,
+  ,
+  ,
+  i64);
+
+define  @intrinsic_vmerge_vvm_nxv1f32_nxv1f32_nxv1f32( %0,  %1,  %2, i64 %3) nounwind {
+; CHECK-LABEL: intrinsic_vmerge_vvm_nxv1f32_nxv1f32_nxv1f32:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:vsetvli zero, a0, e32, mf2, ta, mu
+; CHECK-NEXT:vmerge.vvm v8, v8, v9, v0
+; CHECK-NEXT:ret
+entry:
+  %a = call  @llvm.riscv.vmerge.nxv1f32.nxv1f32(
+ %0,
+ %1,
+ %2,
+i64 %3)
+
+  ret  %a
+}
+
+declare  @llvm.riscv.vmerge.nxv2f32.nxv2f32(
+  ,
+  ,
+  ,
+  i64);
+
+define  @intrinsic_vmerge_vvm_nxv2f32_nxv2f32_nxv2f32( %0,  %1,  %2, i64 %3) nounwind {
+; CHECK-LABEL: intrinsic_vmerge_vvm_nxv2f32_nxv2f32_nxv2f32:
+; CHECK:   # %bb.0

[PATCH] D111542: [analyzer] Retrieve incomplete array extent from its redeclaration.

2021-10-20 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1649-1653
+  // NOTE: `VD` is always non-null if `Init` is non-null, so we can check for
+  // null only one of them.
+  const Expr *Init = VD->getAnyInitializer(VD);
   if (!Init)
 return None;

Wait. But if `VD` is null, you get a null-dereference.
But you already dereferenced `VD` multiple times, so it cannot be null.

Oh, but the `getAnyInitializer()` will overwrite it! That's a surprise.
TBH I would rather pass a fresh uninitialized pointer if you really need the 
exact decl which actually provided the initialized expression to make this 
behavior explicit.

That way, with a properly chosen name you could spare the NOTE comment as well.


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

https://reviews.llvm.org/D111542

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


[PATCH] D106681: [analyzer][NFCI] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

In D106681#3075337 , @steakhal wrote:

> I just wanted you to think about these cases.
> BTW this should work for **L1646**:
>
>   extern const int arr[]; // Incomplete array type
>   void top() {
> (void)arr[42];
>   }

Yes this will work for **L1646**. But I've already added similar tests for this 
line: `glob_array_index4` and `struct_arr_index1` functions in 
//initialization.cpp//. I mean it doesn't matter whether it is an incomplete or 
complete type.




Comment at: clang/test/Analysis/initialization.c:103
+void glob_arr_index4() {
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}

steakhal wrote:
> I'm pretty sure we should not get `Unknown` for simply loading from a global 
> variable.
> That would imply that loading two times subsequently we could not prove that 
> the value remained the same.
> But that should remain the same, thus compare equal unless some other code 
> modifier that memory region.
> 
> That could happen for two reasons:
> 1) There is a racecondition, and another thread modified that location. But 
> that would be UB, so that could not happen.
> 2) The global variable is //volatile//, so the hardware might changed its 
> content- but this global is not volatile so this does not apply.
> 
> That being said, this load should have resulted in a //fresh// conjured 
> symbolic value instead of //unknown//.
> Could you please check if it did result in //unknown// before your patch, or 
> you did introduce this behavior?
I'm not sure I caught your thoughts.
But I think the things is much simplier:
`clang_analyzer_eval` can only produce `UNKNOWN` or `TRUE` or `FALSE`. If we 
know the constraint of `glob_arr_no_init[2]` we return `TRUE` or `FALSE`, and 
`UNKNOWN` otherwise.
But in fact I should use `clang_analyzer_dump` here instead of 
`clang_analyzer_eval`. This is actually my fault. I'll update this.


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

https://reviews.llvm.org/D106681

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


[PATCH] D106681: [analyzer][NFCI] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

Thanks, this looks good to me! But, please wait for an approve from @steakhal 
as well.




Comment at: clang/test/Analysis/initialization.c:103
+void glob_arr_index4() {
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}

ASDenysPetrov wrote:
> steakhal wrote:
> > I'm pretty sure we should not get `Unknown` for simply loading from a 
> > global variable.
> > That would imply that loading two times subsequently we could not prove 
> > that the value remained the same.
> > But that should remain the same, thus compare equal unless some other code 
> > modifier that memory region.
> > 
> > That could happen for two reasons:
> > 1) There is a racecondition, and another thread modified that location. But 
> > that would be UB, so that could not happen.
> > 2) The global variable is //volatile//, so the hardware might changed its 
> > content- but this global is not volatile so this does not apply.
> > 
> > That being said, this load should have resulted in a //fresh// conjured 
> > symbolic value instead of //unknown//.
> > Could you please check if it did result in //unknown// before your patch, 
> > or you did introduce this behavior?
> I'm not sure I caught your thoughts.
> But I think the things is much simplier:
> `clang_analyzer_eval` can only produce `UNKNOWN` or `TRUE` or `FALSE`. If we 
> know the constraint of `glob_arr_no_init[2]` we return `TRUE` or `FALSE`, and 
> `UNKNOWN` otherwise.
> But in fact I should use `clang_analyzer_dump` here instead of 
> `clang_analyzer_eval`. This is actually my fault. I'll update this.
> Could you please check if it did result in unknown before your patch, or you 
> did introduce this behavior?

I've just checked it, it was `Unknown` before this patch as well. 
And actually, that is wrong because the array has static storage duration and 
as such, we know that it is initialized with zeros according to the C standard. 
But, that should be addressed in a follow-up patch (if someone has the 
capacity).
https://stackoverflow.com/questions/32708161/value-of-uninitialized-elements-in-array-of-c-language/32708288


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

https://reviews.llvm.org/D106681

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


[PATCH] D106681: [analyzer][NFCI] Move a block from `getBindingForElement` to separate functions

2021-10-20 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/test/Analysis/initialization.c:103
+void glob_arr_index4() {
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}

martong wrote:
> ASDenysPetrov wrote:
> > steakhal wrote:
> > > I'm pretty sure we should not get `Unknown` for simply loading from a 
> > > global variable.
> > > That would imply that loading two times subsequently we could not prove 
> > > that the value remained the same.
> > > But that should remain the same, thus compare equal unless some other 
> > > code modifier that memory region.
> > > 
> > > That could happen for two reasons:
> > > 1) There is a racecondition, and another thread modified that location. 
> > > But that would be UB, so that could not happen.
> > > 2) The global variable is //volatile//, so the hardware might changed its 
> > > content- but this global is not volatile so this does not apply.
> > > 
> > > That being said, this load should have resulted in a //fresh// conjured 
> > > symbolic value instead of //unknown//.
> > > Could you please check if it did result in //unknown// before your patch, 
> > > or you did introduce this behavior?
> > I'm not sure I caught your thoughts.
> > But I think the things is much simplier:
> > `clang_analyzer_eval` can only produce `UNKNOWN` or `TRUE` or `FALSE`. If 
> > we know the constraint of `glob_arr_no_init[2]` we return `TRUE` or 
> > `FALSE`, and `UNKNOWN` otherwise.
> > But in fact I should use `clang_analyzer_dump` here instead of 
> > `clang_analyzer_eval`. This is actually my fault. I'll update this.
> > Could you please check if it did result in unknown before your patch, or 
> > you did introduce this behavior?
> 
> I've just checked it, it was `Unknown` before this patch as well. 
> And actually, that is wrong because the array has static storage duration and 
> as such, we know that it is initialized with zeros according to the C 
> standard. But, that should be addressed in a follow-up patch (if someone has 
> the capacity).
> https://stackoverflow.com/questions/32708161/value-of-uninitialized-elements-in-array-of-c-language/32708288
Oh true. I was actually tricked by the `initialization.cpp:38`, where I 
actually caught this. And in that case, you use `dump()` yet you get `Unknown` 
as a result. But the issue remains the same.


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

https://reviews.llvm.org/D106681

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


[PATCH] D111542: [analyzer] Retrieve incomplete array extent from its redeclaration.

2021-10-20 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.

In D111542#3074926 , @ASDenysPetrov 
wrote:

> Updated according to the latest suggestions.
> @martong I think now this patch is way more simple and clear than before.

Thanks, indeed! LGTM (with nits about `VD`)!




Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1649-1653
+  // NOTE: `VD` is always non-null if `Init` is non-null, so we can check for
+  // null only one of them.
+  const Expr *Init = VD->getAnyInitializer(VD);
   if (!Init)
 return None;

steakhal wrote:
> Wait. But if `VD` is null, you get a null-dereference.
> But you already dereferenced `VD` multiple times, so it cannot be null.
> 
> Oh, but the `getAnyInitializer()` will overwrite it! That's a surprise.
> TBH I would rather pass a fresh uninitialized pointer if you really need the 
> exact decl which actually provided the initialized expression to make this 
> behavior explicit.
> 
> That way, with a properly chosen name you could spare the NOTE comment as 
> well.
Yes I agree, probably it is easier to follow the code if you make it explicit 
that `VD` is overwritten here.


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

https://reviews.llvm.org/D111542

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


[PATCH] D112146: [WebAssembly] Add prototype relaxed float min max instructions

2021-10-20 Thread Thomas Lively via Phabricator via cfe-commits
tlively accepted this revision.
tlively added a comment.
This revision is now accepted and ready to land.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112146

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


[PATCH] D110287: [modules] While merging ObjCInterfaceDecl definitions, merge them as decl contexts too.

2021-10-20 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D110287#3074175 , @vsapsai wrote:

> In D110287#3074082 , @dblaikie 
> wrote:
>
>> In D110287#3073804 , @vsapsai 
>> wrote:
>>
>>> Pre-merge checks are passing now after the rebase. I believe it is a 
>>> straightforward change and we are merging decl contexts for other Decls 
>>> already, so merging them for `ObjCInterfaceDecl` makes sense. If there are 
>>> no objections, I plan to land the change on Friday, October 22. If any 
>>> issues come up later, post-commit reviews are welcome as always.
>>
>> Generally this sort of "if no one says anything I'll commit at this time" 
>> thing is to be avoided: The idea is that once something's been sent for 
>> review/the author has requested a second opinion, we want to avoid people 
>> committing that code without review only due to lack of feedback. Please 
>> reach out to reviewers to get a second set of eyes on this before committing.
>
> What would be a better way to deal with changes in areas where I'm more 
> experienced in (Obj-C decl merging on AST deserialization) and still want to 
> run pre-merge checks on other platforms? I got unofficial sign-offs 
> internally but people defer to me because I've worked more in this area.

Oh, sure - you can use Phabricator's draft support to just send the change for 
CI testing without sending a review to the mailing list: 
https://llvm.org/docs/Phabricator.html#requesting-a-review-via-the-command-line

> I believe this change is pretty trivial, while for D110452 
>  I want another opinion. But one-line 
> change in D110453  is trivial too and I 
> don't think that waiting for reviews for half a year would improve its 
> quality substantially.

Reviews shouldn't/generally don't take half a year, especially for smaller, 
clearly correct changes. Pinging reviews if they're not getting traction can 
help get some attention, though sometimes more direct calls for assistance may 
be necessary/beneficial.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110287

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


[clang] e1fb134 - [WebAssembly] Add prototype relaxed float min max instructions

2021-10-20 Thread Thomas Lively via cfe-commits

Author: Zhi An Ng
Date: 2021-10-20T09:41:51-07:00
New Revision: e1fb13401e1b90a912ba83c6d1a82794cfdb8aec

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

LOG: [WebAssembly] Add prototype relaxed float min max instructions

Add relaxed. f32x4.min, f32x4.max, f64x2.min, f64x2.max. These are only
exposed as builtins, and require user opt-in.

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

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsWebAssembly.def
clang/lib/CodeGen/CGBuiltin.cpp
clang/test/CodeGen/builtins-wasm.c
llvm/include/llvm/IR/IntrinsicsWebAssembly.td
llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
llvm/test/MC/WebAssembly/simd-encodings.s

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsWebAssembly.def 
b/clang/include/clang/Basic/BuiltinsWebAssembly.def
index 0eecab3c31f26..c30a2a6060169 100644
--- a/clang/include/clang/Basic/BuiltinsWebAssembly.def
+++ b/clang/include/clang/Basic/BuiltinsWebAssembly.def
@@ -174,5 +174,10 @@ TARGET_BUILTIN(__builtin_wasm_laneselect_i64x2, 
"V2LLiV2LLiV2LLiV2LLi", "nc", "r
 
 TARGET_BUILTIN(__builtin_wasm_relaxed_swizzle_i8x16, "V16ScV16ScV16Sc", "nc", 
"relaxed-simd")
 
+TARGET_BUILTIN(__builtin_wasm_relaxed_min_f32x4, "V4fV4fV4f", "nc", 
"relaxed-simd")
+TARGET_BUILTIN(__builtin_wasm_relaxed_max_f32x4, "V4fV4fV4f", "nc", 
"relaxed-simd")
+TARGET_BUILTIN(__builtin_wasm_relaxed_min_f64x2, "V2dV2dV2d", "nc", 
"relaxed-simd")
+TARGET_BUILTIN(__builtin_wasm_relaxed_max_f64x2, "V2dV2dV2d", "nc", 
"relaxed-simd")
+
 #undef BUILTIN
 #undef TARGET_BUILTIN

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 9ef9d4f1c2d9e..d20415f1ced6c 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -18325,6 +18325,28 @@ Value 
*CodeGenFunction::EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
 Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_relaxed_swizzle);
 return Builder.CreateCall(Callee, {Src, Indices});
   }
+  case WebAssembly::BI__builtin_wasm_relaxed_min_f32x4:
+  case WebAssembly::BI__builtin_wasm_relaxed_max_f32x4:
+  case WebAssembly::BI__builtin_wasm_relaxed_min_f64x2:
+  case WebAssembly::BI__builtin_wasm_relaxed_max_f64x2: {
+Value *LHS = EmitScalarExpr(E->getArg(0));
+Value *RHS = EmitScalarExpr(E->getArg(1));
+unsigned IntNo;
+switch (BuiltinID) {
+case WebAssembly::BI__builtin_wasm_relaxed_min_f32x4:
+case WebAssembly::BI__builtin_wasm_relaxed_min_f64x2:
+  IntNo = Intrinsic::wasm_relaxed_min;
+  break;
+case WebAssembly::BI__builtin_wasm_relaxed_max_f32x4:
+case WebAssembly::BI__builtin_wasm_relaxed_max_f64x2:
+  IntNo = Intrinsic::wasm_relaxed_max;
+  break;
+default:
+  llvm_unreachable("unexpected builtin ID");
+}
+Function *Callee = CGM.getIntrinsic(IntNo, LHS->getType());
+return Builder.CreateCall(Callee, {LHS, RHS});
+  }
   default:
 return nullptr;
   }

diff  --git a/clang/test/CodeGen/builtins-wasm.c 
b/clang/test/CodeGen/builtins-wasm.c
index 489565ee09d15..8eb8522d90b5b 100644
--- a/clang/test/CodeGen/builtins-wasm.c
+++ b/clang/test/CodeGen/builtins-wasm.c
@@ -737,3 +737,31 @@ i8x16 relaxed_swizzle_i8x16(i8x16 x, i8x16 y) {
   return __builtin_wasm_relaxed_swizzle_i8x16(x, y);
   // WEBASSEMBLY: call <16 x i8> @llvm.wasm.relaxed.swizzle(<16 x i8> %x, <16 
x i8> %y)
 }
+
+f32x4 relaxed_min_f32x4(f32x4 a, f32x4 b) {
+  return __builtin_wasm_relaxed_min_f32x4(a, b);
+  // WEBASSEMBLY: call <4 x float> @llvm.wasm.relaxed.min.v4f32(
+  // WEBASSEMBLY-SAME: <4 x float> %a, <4 x float> %b)
+  // WEBASSEMBLY-NEXT: ret
+}
+
+f32x4 relaxed_max_f32x4(f32x4 a, f32x4 b) {
+  return __builtin_wasm_relaxed_max_f32x4(a, b);
+  // WEBASSEMBLY: call <4 x float> @llvm.wasm.relaxed.max.v4f32(
+  // WEBASSEMBLY-SAME: <4 x float> %a, <4 x float> %b)
+  // WEBASSEMBLY-NEXT: ret
+}
+
+f64x2 relaxed_min_f64x2(f64x2 a, f64x2 b) {
+  return __builtin_wasm_relaxed_min_f64x2(a, b);
+  // WEBASSEMBLY: call <2 x double> @llvm.wasm.relaxed.min.v2f64(
+  // WEBASSEMBLY-SAME: <2 x double> %a, <2 x double> %b)
+  // WEBASSEMBLY-NEXT: ret
+}
+
+f64x2 relaxed_max_f64x2(f64x2 a, f64x2 b) {
+  return __builtin_wasm_relaxed_max_f64x2(a, b);
+  // WEBASSEMBLY: call <2 x double> @llvm.wasm.relaxed.max.v2f64(
+  // WEBASSEMBLY-SAME: <2 x double> %a, <2 x double> %b)
+  // WEBASSEMBLY-NEXT: ret
+}

diff  --git a/llvm/include/llvm/IR/IntrinsicsWebAssembly.td 
b/llvm/include/llvm/IR/IntrinsicsWebAssembly.td
index d832195609f09..53d63a0d4dcc7 100644
--- a/llvm/include/llvm/IR/IntrinsicsWebAssembly.td
+++ b/llvm/include/llvm/IR/IntrinsicsWebAssembly.td
@@ -205,6 +205,15 @@ def int_wasm_relaxed_swizzle :
   

[PATCH] D112146: [WebAssembly] Add prototype relaxed float min max instructions

2021-10-20 Thread Thomas Lively 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 rGe1fb13401e1b: [WebAssembly] Add prototype relaxed float min 
max instructions (authored by ngzhian, committed by tlively).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112146

Files:
  clang/include/clang/Basic/BuiltinsWebAssembly.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtins-wasm.c
  llvm/include/llvm/IR/IntrinsicsWebAssembly.td
  llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
  llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
  llvm/test/MC/WebAssembly/simd-encodings.s

Index: llvm/test/MC/WebAssembly/simd-encodings.s
===
--- llvm/test/MC/WebAssembly/simd-encodings.s
+++ llvm/test/MC/WebAssembly/simd-encodings.s
@@ -806,4 +806,16 @@
 # CHECK: i8x16.relaxed_swizzle # encoding: [0xfd,0xa2,0x01]
 i8x16.relaxed_swizzle
 
+# CHECK: f32x4.relaxed_min # encoding: [0xfd,0xb4,0x01]
+f32x4.relaxed_min
+
+# CHECK: f32x4.relaxed_max # encoding: [0xfd,0xe2,0x01]
+f32x4.relaxed_max
+
+# CHECK: f64x2.relaxed_min # encoding: [0xfd,0xd4,0x01]
+f64x2.relaxed_min
+
+# CHECK: f64x2.relaxed_max # encoding: [0xfd,0xee,0x01]
+f64x2.relaxed_max
+
 end_function
Index: llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
===
--- llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
+++ llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
@@ -682,6 +682,30 @@
   ret <4 x float> %v
 }
 
+; CHECK-LABEL: relaxed_min_v4f32:
+; CHECK-NEXT: .functype relaxed_min_v4f32 (v128, v128) -> (v128){{$}}
+; CHECK-NEXT: f32x4.relaxed_min $push[[R:[0-9]+]]=, $0, $1{{$}}
+; CHECK-NEXT: return $pop[[R]]{{$}}
+declare <4 x float> @llvm.wasm.relaxed.min.v4f32(<4 x float>, <4 x float>)
+define <4 x float> @relaxed_min_v4f32(<4 x float> %a, <4 x float> %b) {
+  %v = call <4 x float> @llvm.wasm.relaxed.min.v4f32(
+<4 x float> %a, <4 x float> %b
+  )
+  ret <4 x float> %v
+}
+
+; CHECK-LABEL: relaxed_max_v4f32:
+; CHECK-NEXT: .functype relaxed_max_v4f32 (v128, v128) -> (v128){{$}}
+; CHECK-NEXT: f32x4.relaxed_max $push[[R:[0-9]+]]=, $0, $1{{$}}
+; CHECK-NEXT: return $pop[[R]]{{$}}
+declare <4 x float> @llvm.wasm.relaxed.max.v4f32(<4 x float>, <4 x float>)
+define <4 x float> @relaxed_max_v4f32(<4 x float> %a, <4 x float> %b) {
+  %v = call <4 x float> @llvm.wasm.relaxed.max.v4f32(
+<4 x float> %a, <4 x float> %b
+  )
+  ret <4 x float> %v
+}
+
 ; ==
 ; 2 x f64
 ; ==
@@ -780,3 +804,27 @@
   )
   ret <2 x double> %v
 }
+
+; CHECK-LABEL: relaxed_min_v2f64:
+; CHECK-NEXT: .functype relaxed_min_v2f64 (v128, v128) -> (v128){{$}}
+; CHECK-NEXT: f64x2.relaxed_min $push[[R:[0-9]+]]=, $0, $1{{$}}
+; CHECK-NEXT: return $pop[[R]]{{$}}
+declare <2 x double> @llvm.wasm.relaxed.min.v2f64(<2 x double>, <2 x double>)
+define <2 x double> @relaxed_min_v2f64(<2 x double> %a, <2 x double> %b) {
+  %v = call <2 x double> @llvm.wasm.relaxed.min.v2f64(
+<2 x double> %a, <2 x double> %b
+  )
+  ret <2 x double> %v
+}
+
+; CHECK-LABEL: relaxed_max_v2f64:
+; CHECK-NEXT: .functype relaxed_max_v2f64 (v128, v128) -> (v128){{$}}
+; CHECK-NEXT: f64x2.relaxed_max $push[[R:[0-9]+]]=, $0, $1{{$}}
+; CHECK-NEXT: return $pop[[R]]{{$}}
+declare <2 x double> @llvm.wasm.relaxed.max.v2f64(<2 x double>, <2 x double>)
+define <2 x double> @relaxed_max_v2f64(<2 x double> %a, <2 x double> %b) {
+  %v = call <2 x double> @llvm.wasm.relaxed.max.v2f64(
+<2 x double> %a, <2 x double> %b
+  )
+  ret <2 x double> %v
+}
Index: llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
===
--- llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
+++ llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
@@ -1372,3 +1372,23 @@
  [(set (v16i8 V128:$dst),
(int_wasm_relaxed_swizzle (v16i8 V128:$src), (v16i8 V128:$mask)))],
  "i8x16.relaxed_swizzle\t$dst, $src, $mask", "i8x16.relaxed_swizzle", 162>;
+
+//===--===//
+// Relaxed floating-point min and max.
+//===--===//
+
+multiclass SIMD_RELAXED_FMINMAX simdopMin, bits<32> simdopMax> {
+  defm RELAXED_FMIN_#vec :
+RELAXED_I<(outs V128:$dst), (ins V128:$a, V128:$b), (outs), (ins),
+  [(set (vec.vt V128:$dst), (int_wasm_relaxed_min
+(vec.vt V128:$a), (vec.vt V128:$b)))],
+  vec.prefix#".relaxed_min\t$dst, $a, $b", vec.prefix#".relaxed_min", simdopMin>;
+  defm RELAXED_FMAX_#vec :
+RELAXED_I<(outs V128:$dst), (ins V128:$a, V1

[PATCH] D107878: [SampleFDO] Flow Sensitive Sample FDO (FSAFDO) profile loader

2021-10-20 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added inline comments.



Comment at: llvm/lib/LTO/LTOBackend.cpp:234
+  if (TM)
+TM->setPGOOption(PGOOpt);
 

@xur Why does TM need a null check - afaict it's already been dereferenced in 
the call tree, and will be again below.

Noticed in a scan-build warning: 
https://llvm.org/reports/scan-build/report-LTOBackend.cpp-runNewPMPasses-34-35dfe9.html#EndPath


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107878

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


[PATCH] D112157: [clang] Disallow mixing SEH and Objective-C exceptions

2021-10-20 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.
thakis added a reviewer: rnk.
thakis requested review of this revision.

We already disallow mixing SEH and C++ exceptions, and
mixing SEH and Objective-C exceptions seems to not work (see PR52233).
Emitting an error is friendlier than crashing.


https://reviews.llvm.org/D112157

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/ScopeInfo.h
  clang/lib/Sema/ScopeInfo.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/test/SemaCXX/exceptions-seh.mm

Index: clang/test/SemaCXX/exceptions-seh.mm
===
--- /dev/null
+++ clang/test/SemaCXX/exceptions-seh.mm
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -fms-extensions -fsyntax-only -fexceptions -fobjc-exceptions -verify %s
+
+void might_crash();
+
+void use_seh_after_objc() {
+  @try { // expected-note {{conflicting '@try' here}}
+might_crash();
+  } @finally {
+  }
+  __try { // expected-error {{cannot use Objective-C '@try' in the same function as SEH '__try'}}
+might_crash();
+  } __except(1) {
+  }
+}
+
+void use_objc_after_seh() {
+  __try { // expected-note {{conflicting '__try' here}}
+might_crash();
+  } __except(1) {
+  }
+  @try { // expected-error {{cannot use Objective-C '@try' in the same function as SEH '__try'}}
+might_crash();
+  } @finally {
+  }
+}
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -4187,7 +4187,14 @@
   if (!getLangOpts().ObjCExceptions)
 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
 
-  setFunctionHasBranchProtectedScope();
+  // Objective-C try is incompatible with SEH __try.
+  sema::FunctionScopeInfo *FSI = getCurFunction();
+  if (FSI->FirstSEHTryLoc.isValid()) {
+Diag(AtLoc, diag::err_mixing_cxx_try_seh_try) << 1;
+Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
+  }
+
+  FSI->setHasObjCTry(AtLoc);
   unsigned NumCatchStmts = CatchStmts.size();
   return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
NumCatchStmts, Finally);
@@ -4423,7 +4430,7 @@
 
   // C++ try is incompatible with SEH __try.
   if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
-Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
+Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << 0;
 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
   }
 
@@ -4507,9 +4514,12 @@
   // SEH __try is incompatible with C++ try. Borland appears to support this,
   // however.
   if (!getLangOpts().Borland) {
-if (FSI->FirstCXXTryLoc.isValid()) {
-  Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
-  Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
+if (FSI->FirstCXXOrObjCTryLoc.isValid()) {
+  Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << FSI->FirstTryType;
+  Diag(FSI->FirstCXXOrObjCTryLoc, diag::note_conflicting_try_here)
+  << (FSI->FirstTryType == sema::FunctionScopeInfo::TryLocIsCXX
+  ? "'try'"
+  : "'@try'");
 }
   }
 
Index: clang/lib/Sema/ScopeInfo.cpp
===
--- clang/lib/Sema/ScopeInfo.cpp
+++ clang/lib/Sema/ScopeInfo.cpp
@@ -37,7 +37,7 @@
   ObjCIsSecondaryInit = false;
   ObjCWarnForNoInitDelegation = false;
   FirstReturnLoc = SourceLocation();
-  FirstCXXTryLoc = SourceLocation();
+  FirstCXXOrObjCTryLoc = SourceLocation();
   FirstSEHTryLoc = SourceLocation();
 
   // Coroutine state
Index: clang/include/clang/Sema/ScopeInfo.h
===
--- clang/include/clang/Sema/ScopeInfo.h
+++ clang/include/clang/Sema/ScopeInfo.h
@@ -175,8 +175,9 @@
   /// First 'return' statement in the current function.
   SourceLocation FirstReturnLoc;
 
-  /// First C++ 'try' statement in the current function.
-  SourceLocation FirstCXXTryLoc;
+  /// First C++ 'try' or ObjC @try statement in the current function.
+  SourceLocation FirstCXXOrObjCTryLoc;
+  enum { TryLocIsCXX, TryLocIsObjC, Unknown } FirstTryType = Unknown;
 
   /// First SEH '__try' statement in the current function.
   SourceLocation FirstSEHTryLoc;
@@ -446,7 +447,14 @@
 
   void setHasCXXTry(SourceLocation TryLoc) {
 setHasBranchProtectedScope();
-FirstCXXTryLoc = TryLoc;
+FirstCXXOrObjCTryLoc = TryLoc;
+FirstTryType = TryLocIsCXX;
+  }
+
+  void setHasObjCTry(SourceLocation TryLoc) {
+setHasBranchProtectedScope();
+FirstCXXOrObjCTryLoc = TryLoc;
+FirstTryType = TryLocIsObjC;
   }
 
   void setHasSEHTry(SourceLocation TryLoc) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7516,7 +7516,8 @@

[clang] 7562f3d - InvalidPtrChecker - don't dereference a dyn_cast<> - use cast<> instead.

2021-10-20 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2021-10-20T18:06:00+01:00
New Revision: 7562f3df89066ab92a816dc23005c45fd642bdf9

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

LOG: InvalidPtrChecker - don't dereference a dyn_cast<> - use cast<> instead.

Avoid dereferencing a nullptr returned by dyn_cast<>, by using cast<> instead 
which asserts that the cast is valid.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp
index 18893c2fda15b..378d7ce8150af 100644
--- a/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp
@@ -146,7 +146,7 @@ void InvalidPtrChecker::postPreviousReturnInvalidatingCall(
   State = State->BindExpr(CE, LCtx, RetVal);
 
   // Remember to this region.
-  const auto *SymRegOfRetVal = dyn_cast(RetVal.getAsRegion());
+  const auto *SymRegOfRetVal = cast(RetVal.getAsRegion());
   const MemRegion *MR =
   const_cast(SymRegOfRetVal->getBaseRegion());
   State = State->set(FD, MR);



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


[PATCH] D112158: mips: fix search path for multilib o32

2021-10-20 Thread YunQiang Su via Phabricator via cfe-commits
wzssyqa created this revision.
wzssyqa added a reviewer: atanasyan.
Herald added subscribers: arichardson, sdardis.
wzssyqa requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

In the situation of multilib, the gcc objects are in a /32 directory.
On Debian, the libraries is under /libo32 to avoid confliction.

This patch enables clang find gcc in /32, and C lib in /libo32.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112158

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Linux.cpp


Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -261,6 +261,10 @@
   const std::string OSLibDir = std::string(getOSLibDir(Triple, Args));
   const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
 
+  // mips32: Debian multilib, we use /libo32, while in other case, /lib is
+  // used. We need add both libo32 and /lib.
+  if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel)
+Generic_GCC::AddMultilibPaths(D, SysRoot, "libo32", MultiarchTriple, 
Paths);
   Generic_GCC::AddMultilibPaths(D, SysRoot, OSLibDir, MultiarchTriple, Paths);
 
   addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -1086,7 +1086,8 @@
.flag("-m32")
.flag("-mabi=n32");
 
-Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
+Multilib M32 =
+
Multilib().gccSuffix("/32").flag("-m64").flag("+m32").flag("-mabi=n32");
 
 DebianMipsMultilibs =
 MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
@@ -2125,11 +2126,11 @@
   static const char *const M68kTriples[] = {
   "m68k-linux-gnu", "m68k-unknown-linux-gnu", "m68k-suse-linux"};
 
-  static const char *const MIPSLibDirs[] = {"/lib"};
+  static const char *const MIPSLibDirs[] = {"/libo32", "/lib"};
   static const char *const MIPSTriples[] = {
   "mips-linux-gnu", "mips-mti-linux", "mips-mti-linux-gnu",
   "mips-img-linux-gnu", "mipsisa32r6-linux-gnu"};
-  static const char *const MIPSELLibDirs[] = {"/lib"};
+  static const char *const MIPSELLibDirs[] = {"/libo32", "/lib"};
   static const char *const MIPSELTriples[] = {
   "mipsel-linux-gnu", "mips-img-linux-gnu", "mipsisa32r6el-linux-gnu"};
 


Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -261,6 +261,10 @@
   const std::string OSLibDir = std::string(getOSLibDir(Triple, Args));
   const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
 
+  // mips32: Debian multilib, we use /libo32, while in other case, /lib is
+  // used. We need add both libo32 and /lib.
+  if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel)
+Generic_GCC::AddMultilibPaths(D, SysRoot, "libo32", MultiarchTriple, Paths);
   Generic_GCC::AddMultilibPaths(D, SysRoot, OSLibDir, MultiarchTriple, Paths);
 
   addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -1086,7 +1086,8 @@
.flag("-m32")
.flag("-mabi=n32");
 
-Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
+Multilib M32 =
+Multilib().gccSuffix("/32").flag("-m64").flag("+m32").flag("-mabi=n32");
 
 DebianMipsMultilibs =
 MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
@@ -2125,11 +2126,11 @@
   static const char *const M68kTriples[] = {
   "m68k-linux-gnu", "m68k-unknown-linux-gnu", "m68k-suse-linux"};
 
-  static const char *const MIPSLibDirs[] = {"/lib"};
+  static const char *const MIPSLibDirs[] = {"/libo32", "/lib"};
   static const char *const MIPSTriples[] = {
   "mips-linux-gnu", "mips-mti-linux", "mips-mti-linux-gnu",
   "mips-img-linux-gnu", "mipsisa32r6-linux-gnu"};
-  static const char *const MIPSELLibDirs[] = {"/lib"};
+  static const char *const MIPSELLibDirs[] = {"/libo32", "/lib"};
   static const char *const MIPSELTriples[] = {
   "mipsel-linux-gnu", "mips-img-linux-gnu", "mipsisa32r6el-linux-gnu"};
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D112159: Relax assert in ExprConstant to a return None.

2021-10-20 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield created this revision.
JonChesterfield added reviewers: gribozavr, rsmith, ABataev, dblaikie, 
aaron.ballman, jdoerfert.
JonChesterfield requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Fixes a compiler assert on passing a compile time integer to atomic builtins.

Assert introduced in D61522 
Function changed from ->bool to ->Optional in D76646 

Most call sites for getIntegerConstantExpr check the returned optional.
Some check for isValueDependent before calling it.

This leaves some call sites with a redundant call to !isValueDependent
which could be folded into the following call to getIntegerConstantExpr.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112159

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaTemplate/atomics.cpp


Index: clang/test/SemaTemplate/atomics.cpp
===
--- clang/test/SemaTemplate/atomics.cpp
+++ clang/test/SemaTemplate/atomics.cpp
@@ -15,3 +15,13 @@
   }
   void h() { g(0); }
 }
+
+// Can pass value dependent integer to atomic builtin
+template 
+void fetchAdd(int *A, int V) {
+  __atomic_fetch_add(A, V, Order);
+}
+
+void fetchAddUse(int *A, int V) {
+  fetchAdd<__ATOMIC_ACQ_REL>(A, V);
+}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -15501,8 +15501,10 @@
 Optional Expr::getIntegerConstantExpr(const ASTContext &Ctx,
 SourceLocation *Loc,
 bool isEvaluated) const {
-  assert(!isValueDependent() &&
- "Expression evaluator can't be called on a dependent expression.");
+  if (isValueDependent()) {
+// Expression evaluator can't succeed on a dependent expression.
+return None;
+  }
 
   APSInt Value;
 


Index: clang/test/SemaTemplate/atomics.cpp
===
--- clang/test/SemaTemplate/atomics.cpp
+++ clang/test/SemaTemplate/atomics.cpp
@@ -15,3 +15,13 @@
   }
   void h() { g(0); }
 }
+
+// Can pass value dependent integer to atomic builtin
+template 
+void fetchAdd(int *A, int V) {
+  __atomic_fetch_add(A, V, Order);
+}
+
+void fetchAddUse(int *A, int V) {
+  fetchAdd<__ATOMIC_ACQ_REL>(A, V);
+}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -15501,8 +15501,10 @@
 Optional Expr::getIntegerConstantExpr(const ASTContext &Ctx,
 SourceLocation *Loc,
 bool isEvaluated) const {
-  assert(!isValueDependent() &&
- "Expression evaluator can't be called on a dependent expression.");
+  if (isValueDependent()) {
+// Expression evaluator can't succeed on a dependent expression.
+return None;
+  }
 
   APSInt Value;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D111993: [libomptarget][WIP] Patch amdgpu DeviceRTL until it compiles

2021-10-20 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: openmp/libomptarget/DeviceRTL/src/Synchronization.cpp:92
+}
+// clang/lib/AST/ExprConstant.cpp:14739: bool 
clang::Expr::EvaluateAsInt(clang::Expr::EvalResult&, const clang::ASTContext&, 
clang::Expr::SideEffectsKind, bool) const: Assertion `!isValueDependent() && 
"Expression evaluator can't be called on a dependent expression."' failed.
+

The assert in clang was unrelated to amdgpu, posted a diff at D112159 with a 
fix.

The other atomic builtins codegen with a switch on order when passed a 
variable. That seems like the right thing to do for the amdgpu-specific atomic 
builtins.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111993

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


[PATCH] D112059: Fix inline builtin handling in case of redefinition

2021-10-20 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 381011.
serge-sans-paille added a comment.

Reduce the number of time we would walk redecls.
Simplify test case


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

https://reviews.llvm.org/D112059

Files:
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/test/CodeGen/strlen-inline-builtin-redecl.c


Index: clang/test/CodeGen/strlen-inline-builtin-redecl.c
===
--- /dev/null
+++ clang/test/CodeGen/strlen-inline-builtin-redecl.c
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple x86_64 -S -emit-llvm -disable-llvm-passes -o - %s | 
FileCheck %s
+//
+// Verifies that clang-generated *.inline are removed when shadowed by an 
external definition
+
+// CHECK-NOT: strlen.inline
+
+unsigned long strnlen(const char *, unsigned long);
+void fortify_panic(const char *);
+
+extern inline __attribute__((always_inline)) __attribute__((gnu_inline)) 
unsigned long strlen(const char *p) {
+  return 1;
+}
+unsigned long mystrlen(char const *s) {
+  return strlen(s);
+}
+unsigned long strlen(const char *s) {
+  return 2;
+}
+unsigned long yourstrlen(char const *s) {
+  return strlen(s);
+}
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1299,18 +1299,34 @@
   // When generating code for a builtin with an inline declaration, use a
   // mangled name to hold the actual body, while keeping an external definition
   // in case the function pointer is referenced somewhere.
-  if (FD->isInlineBuiltinDeclaration() && Fn) {
+  if (Fn) {
 std::string FDInlineName = (Fn->getName() + ".inline").str();
 llvm::Module *M = Fn->getParent();
 llvm::Function *Clone = M->getFunction(FDInlineName);
-if (!Clone) {
-  Clone = llvm::Function::Create(Fn->getFunctionType(),
- llvm::GlobalValue::InternalLinkage,
- Fn->getAddressSpace(), FDInlineName, M);
-  Clone->addFnAttr(llvm::Attribute::AlwaysInline);
+if (FD->isInlineBuiltinDeclaration()) {
+  if (!Clone) {
+Clone = llvm::Function::Create(Fn->getFunctionType(),
+   llvm::GlobalValue::InternalLinkage,
+   Fn->getAddressSpace(), FDInlineName, M);
+Clone->addFnAttr(llvm::Attribute::AlwaysInline);
+  }
+  Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
+  Fn = Clone;
+}
+
+// detect the unusual situation where an inline version is shadowed by a
+// non-inline version. In that case we should pick the external one
+// everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
+// to detect that situation before we reach codegen, so do some late
+// replacement.
+else if (Clone) {
+  for (auto const *Redecl : FD->redecls()) {
+if (Redecl->isInlineBuiltinDeclaration()) {
+  Clone->replaceAllUsesWith(Fn);
+  Clone->eraseFromParent();
+}
+  }
 }
-Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
-Fn = Clone;
   }
 
   // Check if we should generate debug info for this function.


Index: clang/test/CodeGen/strlen-inline-builtin-redecl.c
===
--- /dev/null
+++ clang/test/CodeGen/strlen-inline-builtin-redecl.c
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple x86_64 -S -emit-llvm -disable-llvm-passes -o - %s | FileCheck %s
+//
+// Verifies that clang-generated *.inline are removed when shadowed by an external definition
+
+// CHECK-NOT: strlen.inline
+
+unsigned long strnlen(const char *, unsigned long);
+void fortify_panic(const char *);
+
+extern inline __attribute__((always_inline)) __attribute__((gnu_inline)) unsigned long strlen(const char *p) {
+  return 1;
+}
+unsigned long mystrlen(char const *s) {
+  return strlen(s);
+}
+unsigned long strlen(const char *s) {
+  return 2;
+}
+unsigned long yourstrlen(char const *s) {
+  return strlen(s);
+}
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1299,18 +1299,34 @@
   // When generating code for a builtin with an inline declaration, use a
   // mangled name to hold the actual body, while keeping an external definition
   // in case the function pointer is referenced somewhere.
-  if (FD->isInlineBuiltinDeclaration() && Fn) {
+  if (Fn) {
 std::string FDInlineName = (Fn->getName() + ".inline").str();
 llvm::Module *M = Fn->getParent();
 llvm::Function *Clone = M->getFunction(FDInlineName);
-if (!Clone) {
-  Clone = llvm::Function::Create(Fn->getFunctionType(),
- llvm::GlobalValue::InternalLinkage,
- 

[PATCH] D112159: Relax assert in ExprConstant to a return None.

2021-10-20 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

This makes sense, any reason we don't remove the check at the call sites right 
away?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112159

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


[PATCH] D108872: [IR] Refactor GlobalIFunc to inherit from GlobalObject, Remove GlobalIndirectSymbol

2021-10-20 Thread Fangrui Song 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 rG08ed216000b6: [IR] Refactor GlobalIFunc to inherit from 
GlobalObject, Remove… (authored by ibookstein, committed by MaskRay).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108872

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  llvm/include/llvm-c/Core.h
  llvm/include/llvm/AsmParser/LLParser.h
  llvm/include/llvm/CodeGen/AsmPrinter.h
  llvm/include/llvm/IR/GlobalAlias.h
  llvm/include/llvm/IR/GlobalIFunc.h
  llvm/include/llvm/IR/GlobalIndirectSymbol.h
  llvm/include/llvm/IR/GlobalObject.h
  llvm/include/llvm/IR/Value.h
  llvm/include/llvm/Transforms/Utils/ValueMapper.h
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Reader/MetadataLoader.cpp
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/IR/AsmWriter.cpp
  llvm/lib/IR/Globals.cpp
  llvm/lib/Linker/IRMover.cpp
  llvm/lib/Object/ModuleSymbolTable.cpp
  llvm/lib/Transforms/IPO/LowerTypeTests.cpp
  llvm/lib/Transforms/Utils/SplitModule.cpp
  llvm/lib/Transforms/Utils/ValueMapper.cpp
  llvm/unittests/IR/ConstantsTest.cpp

Index: llvm/unittests/IR/ConstantsTest.cpp
===
--- llvm/unittests/IR/ConstantsTest.cpp
+++ llvm/unittests/IR/ConstantsTest.cpp
@@ -385,7 +385,7 @@
   new GlobalVariable(*M, PtrTy, false, GlobalValue::ExternalLinkage, GEP);
   ASSERT_EQ(GEP, Ref->getInitializer());
 
-  auto *Global = new GlobalVariable(*M, PtrTy, false,
+  auto *Global = new GlobalVariable(*M, IntTy, false,
 GlobalValue::ExternalLinkage, nullptr);
   auto *Alias = GlobalAlias::create(IntTy, 0, GlobalValue::ExternalLinkage,
 "alias", Global, M.get());
Index: llvm/lib/Transforms/Utils/ValueMapper.cpp
===
--- llvm/lib/Transforms/Utils/ValueMapper.cpp
+++ llvm/lib/Transforms/Utils/ValueMapper.cpp
@@ -26,7 +26,8 @@
 #include "llvm/IR/DebugInfoMetadata.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/Function.h"
-#include "llvm/IR/GlobalIndirectSymbol.h"
+#include "llvm/IR/GlobalAlias.h"
+#include "llvm/IR/GlobalIFunc.h"
 #include "llvm/IR/GlobalObject.h"
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/InlineAsm.h"
@@ -68,7 +69,7 @@
   enum EntryKind {
 MapGlobalInit,
 MapAppendingVar,
-MapGlobalIndirectSymbol,
+MapAliasOrIFunc,
 RemapFunction
   };
   struct GVInitTy {
@@ -79,8 +80,8 @@
 GlobalVariable *GV;
 Constant *InitPrefix;
   };
-  struct GlobalIndirectSymbolTy {
-GlobalIndirectSymbol *GIS;
+  struct AliasOrIFuncTy {
+GlobalValue *GV;
 Constant *Target;
   };
 
@@ -91,7 +92,7 @@
   union {
 GVInitTy GVInit;
 AppendingGVTy AppendingGV;
-GlobalIndirectSymbolTy GlobalIndirectSymbol;
+AliasOrIFuncTy AliasOrIFunc;
 Function *RemapF;
   } Data;
 };
@@ -163,8 +164,8 @@
 bool IsOldCtorDtor,
 ArrayRef NewMembers,
 unsigned MCID);
-  void scheduleMapGlobalIndirectSymbol(GlobalIndirectSymbol &GIS, Constant &Target,
-   unsigned MCID);
+  void scheduleMapAliasOrIFunc(GlobalValue &GV, Constant &Target,
+   unsigned MCID);
   void scheduleRemapFunction(Function &F, unsigned MCID);
 
   void flush();
@@ -873,10 +874,17 @@
E.AppendingGVIsOldCtorDtor, makeArrayRef(NewInits));
   break;
 }
-case WorklistEntry::MapGlobalIndirectSymbol:
-  E.Data.GlobalIndirectSymbol.GIS->setIndirectSymbol(
-  mapConstant(E.Data.GlobalIndirectSymbol.Target));
+case WorklistEntry::MapAliasOrIFunc: {
+  GlobalValue *GV = E.Data.AliasOrIFunc.GV;
+  Constant *Target = mapConstant(E.Data.AliasOrIFunc.Target);
+  if (auto *GA = dyn_cast(GV))
+GA->setAliasee(Target);
+  else if (auto *GI = dyn_cast(GV))
+GI->setResolver(Target);
+  else
+llvm_unreachable("Not alias or ifunc");
   break;
+}
 case WorklistEntry::RemapFunction:
   remapFunction(*E.Data.RemapF);
   break;
@@ -1069,16 +1077,18 @@
   AppendingInits.append(NewMembers.begin(), NewMembers.end());
 }
 
-void Mapper::scheduleMapGlobalIndirectSymbol(GlobalIndirectSymbol &GIS,
- Constant &Target, unsigned MCID) {
-  assert(AlreadyScheduled.insert(&GIS).second && "Should not reschedule");
+void Mapper::scheduleMapAliasOrIFunc(GlobalValue &GV, Constant &Target,
+ unsigned MCID) {
+  assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
+  assert((isa

[clang] 08ed216 - [IR] Refactor GlobalIFunc to inherit from GlobalObject, Remove GlobalIndirectSymbol

2021-10-20 Thread Fangrui Song via cfe-commits

Author: Itay Bookstein
Date: 2021-10-20T10:29:47-07:00
New Revision: 08ed216000b6503a4a4be52f18394d008d5fb8f4

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

LOG: [IR] Refactor GlobalIFunc to inherit from GlobalObject, Remove 
GlobalIndirectSymbol

As discussed in:
* https://reviews.llvm.org/D94166
* https://lists.llvm.org/pipermail/llvm-dev/2020-September/145031.html

The GlobalIndirectSymbol class lost most of its meaning in
https://reviews.llvm.org/D109792, which disambiguated getBaseObject
(now getAliaseeObject) between GlobalIFunc and everything else.
In addition, as long as GlobalIFunc is not a GlobalObject and
getAliaseeObject returns GlobalObjects, a GlobalAlias whose aliasee
is a GlobalIFunc cannot currently be modeled properly. Creating
aliases for GlobalIFuncs does happen in the wild (e.g. glibc). In addition,
calling getAliaseeObject on a GlobalIFunc will currently return nullptr,
which is undesirable because it should return the object itself for
non-aliases.

This patch refactors the GlobalIFunc class to inherit directly from
GlobalObject, and removes GlobalIndirectSymbol (while inlining the
relevant parts into GlobalAlias and GlobalIFunc). This allows for
calling getAliaseeObject() on a GlobalIFunc to return the GlobalIFunc
itself, making getAliaseeObject() more consistent and enabling
alias-to-ifunc to be properly modeled in the IR.

I exercised some judgement in the API clients of GlobalIndirectSymbol:
some were 'monomorphized' for GlobalAlias and GlobalIFunc, and
some remained shared (with the type adapted to become GlobalValue).

Reviewed By: MaskRay

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

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
llvm/include/llvm-c/Core.h
llvm/include/llvm/AsmParser/LLParser.h
llvm/include/llvm/CodeGen/AsmPrinter.h
llvm/include/llvm/IR/GlobalAlias.h
llvm/include/llvm/IR/GlobalIFunc.h
llvm/include/llvm/IR/GlobalObject.h
llvm/include/llvm/IR/Value.h
llvm/include/llvm/Transforms/Utils/ValueMapper.h
llvm/lib/AsmParser/LLParser.cpp
llvm/lib/Bitcode/Reader/BitcodeReader.cpp
llvm/lib/Bitcode/Reader/MetadataLoader.cpp
llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
llvm/lib/IR/AsmWriter.cpp
llvm/lib/IR/Globals.cpp
llvm/lib/Linker/IRMover.cpp
llvm/lib/Object/ModuleSymbolTable.cpp
llvm/lib/Transforms/IPO/LowerTypeTests.cpp
llvm/lib/Transforms/Utils/SplitModule.cpp
llvm/lib/Transforms/Utils/ValueMapper.cpp
llvm/unittests/IR/ConstantsTest.cpp

Removed: 
llvm/include/llvm/IR/GlobalIndirectSymbol.h



diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 57454a59563a2..e53a8a36974ae 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -317,21 +317,21 @@ void CodeGenModule::applyGlobalValReplacements() {
 
 // This is only used in aliases that we created and we know they have a
 // linear structure.
-static const llvm::GlobalObject *getAliasedGlobal(
-const llvm::GlobalIndirectSymbol &GIS) {
-  llvm::SmallPtrSet Visited;
-  const llvm::Constant *C = &GIS;
+static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
+  llvm::SmallPtrSet Visited;
   for (;;) {
-C = C->stripPointerCasts();
-if (auto *GO = dyn_cast(C))
-  return GO;
-// stripPointerCasts will not walk over weak aliases.
-auto *GIS2 = dyn_cast(C);
-if (!GIS2)
+if (!GV || !Visited.insert(GV).second)
   return nullptr;
-if (!Visited.insert(GIS2).second)
-  return nullptr;
-C = GIS2->getIndirectSymbol();
+
+const llvm::Constant *C;
+if (auto *GA = dyn_cast(GV))
+  C = GA->getAliasee();
+else if (auto *GI = dyn_cast(GV))
+  C = GI->getResolver();
+else
+  return GV;
+
+GV = dyn_cast(C->stripPointerCasts());
   }
 }
 
@@ -350,9 +350,8 @@ void CodeGenModule::checkAliases() {
 else
   llvm_unreachable("Not an alias or ifunc?");
 StringRef MangledName = getMangledName(GD);
-llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
-auto *Alias  = cast(Entry);
-const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
+llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
+const llvm::GlobalValue *GV = getAliasedGlobal(Alias);
 if (!GV) {
   Error = true;
   Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
@@ -369,7 +368,10 @@ void CodeGenModule::checkAliases() {
 Diags.Report(Location, diag::err_ifunc_resolver_return);
 }
 
-llvm::Constant *Aliasee = Alias->getIndirectSymbol();
+llvm::Constant *Aliasee =
+IsIFunc ? cast(Alias)->getResolver()
+: cast(Alias)->getAliasee();
+
 llvm::GlobalValue *AliaseeGV;
 if (auto

[PATCH] D112059: Fix inline builtin handling in case of redefinition

2021-10-20 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 381014.
serge-sans-paille added a comment.

Avoid walking redecls


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

https://reviews.llvm.org/D112059

Files:
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/test/CodeGen/strlen-inline-builtin-redecl.c


Index: clang/test/CodeGen/strlen-inline-builtin-redecl.c
===
--- /dev/null
+++ clang/test/CodeGen/strlen-inline-builtin-redecl.c
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple x86_64 -S -emit-llvm -disable-llvm-passes -o - %s | 
FileCheck %s
+//
+// Verifies that clang-generated *.inline are removed when shadowed by an 
external definition
+
+// CHECK-NOT: strlen.inline
+
+unsigned long strnlen(const char *, unsigned long);
+void fortify_panic(const char *);
+
+extern inline __attribute__((always_inline)) __attribute__((gnu_inline)) 
unsigned long strlen(const char *p) {
+  return 1;
+}
+unsigned long mystrlen(char const *s) {
+  return strlen(s);
+}
+unsigned long strlen(const char *s) {
+  return 2;
+}
+unsigned long yourstrlen(char const *s) {
+  return strlen(s);
+}
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1299,18 +1299,30 @@
   // When generating code for a builtin with an inline declaration, use a
   // mangled name to hold the actual body, while keeping an external definition
   // in case the function pointer is referenced somewhere.
-  if (FD->isInlineBuiltinDeclaration() && Fn) {
+  if (Fn) {
 std::string FDInlineName = (Fn->getName() + ".inline").str();
 llvm::Module *M = Fn->getParent();
 llvm::Function *Clone = M->getFunction(FDInlineName);
-if (!Clone) {
-  Clone = llvm::Function::Create(Fn->getFunctionType(),
- llvm::GlobalValue::InternalLinkage,
- Fn->getAddressSpace(), FDInlineName, M);
-  Clone->addFnAttr(llvm::Attribute::AlwaysInline);
+if (FD->isInlineBuiltinDeclaration()) {
+  if (!Clone) {
+Clone = llvm::Function::Create(Fn->getFunctionType(),
+   llvm::GlobalValue::InternalLinkage,
+   Fn->getAddressSpace(), FDInlineName, M);
+Clone->addFnAttr(llvm::Attribute::AlwaysInline);
+  }
+  Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
+  Fn = Clone;
+}
+
+// Detect the unusual situation where an inline version is shadowed by a
+// non-inline version. In that case we should pick the external one
+// everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
+// to detect that situation before we reach codegen, so do some late
+// replacement.
+else if (Clone) {
+  Clone->replaceAllUsesWith(Fn);
+  Clone->eraseFromParent();
 }
-Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
-Fn = Clone;
   }
 
   // Check if we should generate debug info for this function.


Index: clang/test/CodeGen/strlen-inline-builtin-redecl.c
===
--- /dev/null
+++ clang/test/CodeGen/strlen-inline-builtin-redecl.c
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple x86_64 -S -emit-llvm -disable-llvm-passes -o - %s | FileCheck %s
+//
+// Verifies that clang-generated *.inline are removed when shadowed by an external definition
+
+// CHECK-NOT: strlen.inline
+
+unsigned long strnlen(const char *, unsigned long);
+void fortify_panic(const char *);
+
+extern inline __attribute__((always_inline)) __attribute__((gnu_inline)) unsigned long strlen(const char *p) {
+  return 1;
+}
+unsigned long mystrlen(char const *s) {
+  return strlen(s);
+}
+unsigned long strlen(const char *s) {
+  return 2;
+}
+unsigned long yourstrlen(char const *s) {
+  return strlen(s);
+}
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1299,18 +1299,30 @@
   // When generating code for a builtin with an inline declaration, use a
   // mangled name to hold the actual body, while keeping an external definition
   // in case the function pointer is referenced somewhere.
-  if (FD->isInlineBuiltinDeclaration() && Fn) {
+  if (Fn) {
 std::string FDInlineName = (Fn->getName() + ".inline").str();
 llvm::Module *M = Fn->getParent();
 llvm::Function *Clone = M->getFunction(FDInlineName);
-if (!Clone) {
-  Clone = llvm::Function::Create(Fn->getFunctionType(),
- llvm::GlobalValue::InternalLinkage,
- Fn->getAddressSpace(), FDInlineName, M);
-  Clone->addFnAttr(llvm::Attribute::AlwaysInline);
+if (FD->isInlineBuiltinDeclaration()) {
+  if (!Clone) {
+C

  1   2   >