[clang] [compiler-rt] [nsan] Add shared runtime (PR #98415)

2024-07-10 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov approved this pull request.

LG, thanks

https://github.com/llvm/llvm-project/pull/98415
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Link nsan runtime (PR #97364)

2024-07-02 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov closed 
https://github.com/llvm/llvm-project/pull/97364
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Link nsan runtime (PR #97364)

2024-07-02 Thread Alexander Shaposhnikov via cfe-commits


@@ -627,6 +627,20 @@
 // CHECK-COV-LINUX: "-lpthread"
 // CHECK-COV-LINUX: "-lresolv"
 
+// RUN: %clang -### %s 2>&1 \
+// RUN: --target=x86_64-unknown-linux -fuse-ld=ld -fsanitize=numerical \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-NSAN-LINUX %s
+//
+// CHECK-NSAN-LINUX: "{{(.*[^-.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
+// CHECK-NSAN-LINUX-NOT: "-lc"
+// CHECK-NSAN-LINUX-NOT: libclang_rt.ubsan
+// CHECK-NSAN-LINUX: libclang_rt.nsan.a"
+// CHECK-NSAN-LINUX: "-lpthread"

alexander-shaposhnikov wrote:

done

https://github.com/llvm/llvm-project/pull/97364
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Link nsan runtime (PR #97364)

2024-07-02 Thread Alexander Shaposhnikov via cfe-commits


@@ -627,6 +627,20 @@
 // CHECK-COV-LINUX: "-lpthread"
 // CHECK-COV-LINUX: "-lresolv"
 
+// RUN: %clang -### %s 2>&1 \
+// RUN: --target=x86_64-unknown-linux -fuse-ld=ld -fsanitize=numerical \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-NSAN-LINUX %s
+//
+// CHECK-NSAN-LINUX: "{{(.*[^-.0-9A-Z_a-z])?}}ld{{(.exe)?}}"

alexander-shaposhnikov wrote:

done

https://github.com/llvm/llvm-project/pull/97364
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Driver] Link nsan runtime (PR #97364)

2024-07-02 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/97364

>From 1e5ab152d018c9cfe15ba849c2a287efafa7bbc0 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Mon, 1 Jul 2024 23:29:57 +
Subject: [PATCH] [Clang][Driver] Link nsan runtime

---
 clang/lib/Driver/ToolChains/CommonArgs.cpp |  2 ++
 clang/test/Driver/sanitizer-ld.c   | 12 
 2 files changed, 14 insertions(+)

diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 2a4c1369f5a73..be4d7d2cffb16 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1469,6 +1469,8 @@ collectSanitizerRuntimes(const ToolChain &TC, const 
ArgList &Args,
 if (SanArgs.linkCXXRuntimes())
   StaticRuntimes.push_back("msan_cxx");
   }
+  if (SanArgs.needsNsanRt())
+StaticRuntimes.push_back("nsan");
   if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt()) {
 StaticRuntimes.push_back("tsan");
 if (SanArgs.linkCXXRuntimes())
diff --git a/clang/test/Driver/sanitizer-ld.c b/clang/test/Driver/sanitizer-ld.c
index 1dc8b446d7b6d..93702f456229f 100644
--- a/clang/test/Driver/sanitizer-ld.c
+++ b/clang/test/Driver/sanitizer-ld.c
@@ -627,6 +627,18 @@
 // CHECK-COV-LINUX: "-lpthread"
 // CHECK-COV-LINUX: "-lresolv"
 
+// RUN: %clang -### %s 2>&1 \
+// RUN: --target=x86_64-unknown-linux -fuse-ld=ld -fsanitize=numerical \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-NSAN-LINUX %s
+//
+// CHECK-NSAN-LINUX: "{{.*}}ld{{(.exe)?}}"
+// CHECK-NSAN-LINUX-NOT: "-lc"
+// CHECK-NSAN-LINUX-NOT: libclang_rt.ubsan
+// CHECK-NSAN-LINUX: libclang_rt.nsan.a"
+// CHECK-NSAN-LINUX: "-lpthread" "-lrt" "-lm" "-ldl" "-lresolv"
+
 // CFI by itself does not link runtime libraries.
 // RUN: not %clang -fsanitize=cfi -### %s 2>&1 \
 // RUN: --target=x86_64-unknown-linux -fuse-ld=ld -rtlib=platform \

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


[clang] [Clang] Enable nsan instrumentation pass (PR #97359)

2024-07-02 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov closed 
https://github.com/llvm/llvm-project/pull/97359
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Enable nsan instrumentation pass (PR #97359)

2024-07-02 Thread Alexander Shaposhnikov via cfe-commits


@@ -707,6 +708,9 @@ static void addSanitizers(const Triple &TargetTriple,
   MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
 }
 
+if (LangOpts.Sanitize.has(SanitizerKind::NumericalStability))
+  MPM.addPass(NumericalStabilitySanitizerPass());

alexander-shaposhnikov wrote:

debugging would be a bit harder - so would prefer to postpone adding them, but 
yeah, thanks for the suggestion, will keep it in mind. 

https://github.com/llvm/llvm-project/pull/97359
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Enable nsan instrumentation pass (PR #97359)

2024-07-02 Thread Alexander Shaposhnikov via cfe-commits


@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - 
-fsanitize=numerical %s | FileCheck %s

alexander-shaposhnikov wrote:

done

https://github.com/llvm/llvm-project/pull/97359
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Enable nsan instrumentation pass (PR #97359)

2024-07-02 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/97359

>From b231f0be6963a9cf0233c307b0b9030f9bdc120a Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Mon, 1 Jul 2024 22:20:29 +
Subject: [PATCH] [Clang] Add nsan instrumentation pass to the pipeline

---
 clang/lib/CodeGen/BackendUtil.cpp| 4 
 clang/test/CodeGen/no-skipped-passes-O0-opt-bisect.c | 1 +
 clang/test/CodeGen/nsan-basic.c  | 7 +++
 clang/test/CodeGen/sanitizer-module-constructor.c| 1 +
 4 files changed, 13 insertions(+)
 create mode 100644 clang/test/CodeGen/nsan-basic.c

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 22b593e8f2b7a..4195bb87cf0dd 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -76,6 +76,7 @@
 #include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
+#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
 #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
@@ -707,6 +708,9 @@ static void addSanitizers(const Triple &TargetTriple,
   MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
 }
 
+if (LangOpts.Sanitize.has(SanitizerKind::NumericalStability))
+  MPM.addPass(NumericalStabilitySanitizerPass());
+
 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
   if (LangOpts.Sanitize.has(Mask)) {
 bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
diff --git a/clang/test/CodeGen/no-skipped-passes-O0-opt-bisect.c 
b/clang/test/CodeGen/no-skipped-passes-O0-opt-bisect.c
index 381803a00ede7..6d3e6359d37c7 100644
--- a/clang/test/CodeGen/no-skipped-passes-O0-opt-bisect.c
+++ b/clang/test/CodeGen/no-skipped-passes-O0-opt-bisect.c
@@ -9,6 +9,7 @@
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -O0 %s -fdebug-pass-manager 
-emit-llvm -o /dev/null -fsanitize=local-bounds 2>&1 | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -O0 %s -fdebug-pass-manager 
-emit-llvm -o /dev/null -fsanitize=dataflow 2>&1 | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -O0 %s -fdebug-pass-manager 
-emit-llvm -o /dev/null -fsanitize-coverage-trace-pc-guard 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -O0 %s -fdebug-pass-manager 
-emit-llvm -o /dev/null -fsanitize=numerical 2>&1 | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -O0 %s -fdebug-pass-manager 
-emit-llvm -o /dev/null -fmemory-profile 2>&1 | FileCheck %s
 
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -mllvm -opt-bisect-limit=0 %s 
-fdebug-pass-manager -emit-llvm -o /dev/null 2>&1 | FileCheck %s
diff --git a/clang/test/CodeGen/nsan-basic.c b/clang/test/CodeGen/nsan-basic.c
new file mode 100644
index 0..7aedaa38d881d
--- /dev/null
+++ b/clang/test/CodeGen/nsan-basic.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -triple x86_64 -emit-llvm -o - -fsanitize=numerical %s | 
FileCheck %s
+
+// CHECK: Function Attrs: noinline nounwind optnone 
sanitize_numerical_stability
+float add(float x, float y) {
+  float z = x + y;
+  return z;
+}
diff --git a/clang/test/CodeGen/sanitizer-module-constructor.c 
b/clang/test/CodeGen/sanitizer-module-constructor.c
index e4d08cde2620a..06dc57304a7e1 100644
--- a/clang/test/CodeGen/sanitizer-module-constructor.c
+++ b/clang/test/CodeGen/sanitizer-module-constructor.c
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=address -O3 -emit-llvm 
-fdebug-pass-manager -o - %s 2>&1 | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=thread -O3 -emit-llvm 
-fdebug-pass-manager -o - %s 2>&1 | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=memory -O3 -emit-llvm 
-fdebug-pass-manager -o - %s 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=numerical -O3 
-emit-llvm -fdebug-pass-manager -o - %s 2>&1 | FileCheck %s
 
 // This is regression test for PR42877
 

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


[clang] [Clang][Driver] Link nsan runtime (PR #97364)

2024-07-01 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov created 
https://github.com/llvm/llvm-project/pull/97364

Link nsan runtime.

>From ac52e1dc1ceabdefb6230173c42181f2c098dc58 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Mon, 1 Jul 2024 23:29:57 +
Subject: [PATCH] [Clang][Driver] Link nsan runtime

---
 clang/lib/Driver/ToolChains/CommonArgs.cpp |  2 ++
 clang/test/Driver/sanitizer-ld.c   | 14 ++
 2 files changed, 16 insertions(+)

diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 2a4c1369f5a73..be4d7d2cffb16 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1469,6 +1469,8 @@ collectSanitizerRuntimes(const ToolChain &TC, const 
ArgList &Args,
 if (SanArgs.linkCXXRuntimes())
   StaticRuntimes.push_back("msan_cxx");
   }
+  if (SanArgs.needsNsanRt())
+StaticRuntimes.push_back("nsan");
   if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt()) {
 StaticRuntimes.push_back("tsan");
 if (SanArgs.linkCXXRuntimes())
diff --git a/clang/test/Driver/sanitizer-ld.c b/clang/test/Driver/sanitizer-ld.c
index 1dc8b446d7b6d..38769ba01ed04 100644
--- a/clang/test/Driver/sanitizer-ld.c
+++ b/clang/test/Driver/sanitizer-ld.c
@@ -627,6 +627,20 @@
 // CHECK-COV-LINUX: "-lpthread"
 // CHECK-COV-LINUX: "-lresolv"
 
+// RUN: %clang -### %s 2>&1 \
+// RUN: --target=x86_64-unknown-linux -fuse-ld=ld -fsanitize=numerical \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-NSAN-LINUX %s
+//
+// CHECK-NSAN-LINUX: "{{(.*[^-.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
+// CHECK-NSAN-LINUX-NOT: "-lc"
+// CHECK-NSAN-LINUX-NOT: libclang_rt.ubsan
+// CHECK-NSAN-LINUX: libclang_rt.nsan.a"
+// CHECK-NSAN-LINUX: "-lpthread"
+// CHECK-NSAN-LINUX: "-ldl"
+// CHECK-NSAN-LINUX: "-lresolv"
+
 // CFI by itself does not link runtime libraries.
 // RUN: not %clang -fsanitize=cfi -### %s 2>&1 \
 // RUN: --target=x86_64-unknown-linux -fuse-ld=ld -rtlib=platform \

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


[clang] [Clang] Enable nsan instrumentation pass (PR #97359)

2024-07-01 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov created 
https://github.com/llvm/llvm-project/pull/97359

Enable nsan instrumentation pass

>From 6b7f292ba467beb973099ca0e4994563ef5db381 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Mon, 1 Jul 2024 22:20:29 +
Subject: [PATCH] [Clang] Add nsan instrumentation pass to the pipeline

---
 clang/lib/CodeGen/BackendUtil.cpp| 4 
 clang/test/CodeGen/no-skipped-passes-O0-opt-bisect.c | 1 +
 clang/test/CodeGen/nsan-basic.c  | 7 +++
 clang/test/CodeGen/sanitizer-module-constructor.c| 1 +
 4 files changed, 13 insertions(+)
 create mode 100644 clang/test/CodeGen/nsan-basic.c

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 22b593e8f2b7a..4195bb87cf0dd 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -76,6 +76,7 @@
 #include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
+#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
 #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
@@ -707,6 +708,9 @@ static void addSanitizers(const Triple &TargetTriple,
   MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
 }
 
+if (LangOpts.Sanitize.has(SanitizerKind::NumericalStability))
+  MPM.addPass(NumericalStabilitySanitizerPass());
+
 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
   if (LangOpts.Sanitize.has(Mask)) {
 bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
diff --git a/clang/test/CodeGen/no-skipped-passes-O0-opt-bisect.c 
b/clang/test/CodeGen/no-skipped-passes-O0-opt-bisect.c
index 381803a00ede7..6d3e6359d37c7 100644
--- a/clang/test/CodeGen/no-skipped-passes-O0-opt-bisect.c
+++ b/clang/test/CodeGen/no-skipped-passes-O0-opt-bisect.c
@@ -9,6 +9,7 @@
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -O0 %s -fdebug-pass-manager 
-emit-llvm -o /dev/null -fsanitize=local-bounds 2>&1 | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -O0 %s -fdebug-pass-manager 
-emit-llvm -o /dev/null -fsanitize=dataflow 2>&1 | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -O0 %s -fdebug-pass-manager 
-emit-llvm -o /dev/null -fsanitize-coverage-trace-pc-guard 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -O0 %s -fdebug-pass-manager 
-emit-llvm -o /dev/null -fsanitize=numerical 2>&1 | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -O0 %s -fdebug-pass-manager 
-emit-llvm -o /dev/null -fmemory-profile 2>&1 | FileCheck %s
 
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -mllvm -opt-bisect-limit=0 %s 
-fdebug-pass-manager -emit-llvm -o /dev/null 2>&1 | FileCheck %s
diff --git a/clang/test/CodeGen/nsan-basic.c b/clang/test/CodeGen/nsan-basic.c
new file mode 100644
index 0..1e992ff064e7f
--- /dev/null
+++ b/clang/test/CodeGen/nsan-basic.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - 
-fsanitize=numerical %s | FileCheck %s
+
+// CHECK: Function Attrs: noinline nounwind optnone 
sanitize_numerical_stability
+float add(float x, float y) {
+  float z = x + y;
+  return z;
+}
diff --git a/clang/test/CodeGen/sanitizer-module-constructor.c 
b/clang/test/CodeGen/sanitizer-module-constructor.c
index e4d08cde2620a..06dc57304a7e1 100644
--- a/clang/test/CodeGen/sanitizer-module-constructor.c
+++ b/clang/test/CodeGen/sanitizer-module-constructor.c
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=address -O3 -emit-llvm 
-fdebug-pass-manager -o - %s 2>&1 | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=thread -O3 -emit-llvm 
-fdebug-pass-manager -o - %s 2>&1 | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=memory -O3 -emit-llvm 
-fdebug-pass-manager -o - %s 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=numerical -O3 
-emit-llvm -fdebug-pass-manager -o - %s 2>&1 | FileCheck %s
 
 // This is regression test for PR42877
 

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


[clang] [Clang][Sanitizers] Enable NSAN on Linux only (PR #96120)

2024-06-19 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov created 
https://github.com/llvm/llvm-project/pull/96120

Enable nsan on Linux only.
Adding support for X86_64 MacOS requires minimal efforts
(might need to copy some bits from other sanitizers (in compiler-rt)).
Currently the functionality has been tested on Linux only.


>From 35f34c7f5bb22cc5e0038f9ec7d07f568fb630c8 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Wed, 19 Jun 2024 22:40:02 +
Subject: [PATCH] [Clang][Sanitizers] Enable NSAN on Linux only

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 3 ---
 clang/test/Driver/fsanitize.c  | 4 ++--
 2 files changed, 2 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 64ab328a6d25f..ec509831bf60c 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -3474,9 +3474,6 @@ SanitizerMask Darwin::getSupportedSanitizers() const {
 Res |= SanitizerKind::Thread;
   }
 
-  if (IsX86_64)
-Res |= SanitizerKind::NumericalStability;
-
   return Res;
 }
 
diff --git a/clang/test/Driver/fsanitize.c b/clang/test/Driver/fsanitize.c
index db14f6e195c64..aaea518aa634e 100644
--- a/clang/test/Driver/fsanitize.c
+++ b/clang/test/Driver/fsanitize.c
@@ -468,8 +468,8 @@
 // RUN: not %clang --target=mips-unknown-linux -fsanitize=numerical %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-NSAN-MIPS-LINUX
 // CHECK-NSAN-MIPS-LINUX: error: unsupported option '-fsanitize=numerical' for 
target 'mips-unknown-linux'
 
-// RUN: %clang --target=x86_64-apple-macos -fsanitize=numerical %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-NSAN-X86-64-MACOS
-// CHECK-NSAN-X86-64-MACOS: "-fsanitize=numerical"
+// RUN: not %clang --target=x86_64-apple-macos -fsanitize=numerical %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-NSAN-X86-64-MACOS
+// CHECK-NSAN-X86-64-MACOS: error: unsupported option '-fsanitize=numerical' 
for target 'x86_64-apple-macos'
 
 // RUN: not %clang --target=arm64-apple-macos -fsanitize=numerical %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-NSAN-ARM64-MACOS
 // CHECK-NSAN-ARM64-MACOS: error: unsupported option '-fsanitize=numerical' 
for target 'arm64-apple-macos'

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


[clang] [Clang][Sanitizers] Enable NSAN on X86_64 only (PR #95885)

2024-06-18 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov closed 
https://github.com/llvm/llvm-project/pull/95885
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sanitizers] Enable NSAN on X86_64 only (PR #95885)

2024-06-18 Thread Alexander Shaposhnikov via cfe-commits

alexander-shaposhnikov wrote:

yeah, but I  kind of wanted to be defensive - people will try the tool and I 
wanted to avoid any potential confusions / overpromises.

https://github.com/llvm/llvm-project/pull/95885
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sanitizers] Enable NSAN on X86_64 only (PR #95885)

2024-06-18 Thread Alexander Shaposhnikov via cfe-commits

alexander-shaposhnikov wrote:

~90% of the functionality would work on aarch64, but there are a few 
x86_64-specific quirks (__float128, x86-64-specific assumptions about long 
double in the helper routines) that need to be refactored (beyond my current 
bandwidth).

https://github.com/llvm/llvm-project/pull/95885
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sanitizers] Enable NSAN on X86_64 only (PR #95885)

2024-06-17 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov edited 
https://github.com/llvm/llvm-project/pull/95885
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sanitizers] Enable NSAN on X86_64 only (PR #95885)

2024-06-17 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov edited 
https://github.com/llvm/llvm-project/pull/95885
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sanitizers] Enable NSAN on X86_64 only (PR #95885)

2024-06-17 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/95885

>From 7c286a320256732eca6a9183a1ba21ae60b99746 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Tue, 18 Jun 2024 06:15:12 +
Subject: [PATCH] [Clang][Sanitizers] Enable NSAN on X86_64 only

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 5 -
 clang/lib/Driver/ToolChains/Linux.cpp  | 2 +-
 clang/test/Driver/fsanitize.c  | 8 
 3 files changed, 9 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index f742db7668cd2..64ab328a6d25f 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -3457,7 +3457,6 @@ SanitizerMask Darwin::getSupportedSanitizers() const {
   Res |= SanitizerKind::PointerCompare;
   Res |= SanitizerKind::PointerSubtract;
   Res |= SanitizerKind::Leak;
-  Res |= SanitizerKind::NumericalStability;
   Res |= SanitizerKind::Fuzzer;
   Res |= SanitizerKind::FuzzerNoLink;
   Res |= SanitizerKind::ObjCCast;
@@ -3474,6 +3473,10 @@ SanitizerMask Darwin::getSupportedSanitizers() const {
isTargetTvOSSimulator() || isTargetWatchOSSimulator())) {
 Res |= SanitizerKind::Thread;
   }
+
+  if (IsX86_64)
+Res |= SanitizerKind::NumericalStability;
+
   return Res;
 }
 
diff --git a/clang/lib/Driver/ToolChains/Linux.cpp 
b/clang/lib/Driver/ToolChains/Linux.cpp
index dea431c3c..49e029e7c9ab7 100644
--- a/clang/lib/Driver/ToolChains/Linux.cpp
+++ b/clang/lib/Driver/ToolChains/Linux.cpp
@@ -826,7 +826,7 @@ SanitizerMask Linux::getSupportedSanitizers() const {
   if (IsX86_64 || IsAArch64) {
 Res |= SanitizerKind::KernelHWAddress;
   }
-  if (IsX86_64 || IsAArch64)
+  if (IsX86_64)
 Res |= SanitizerKind::NumericalStability;
 
   // Work around "Cannot represent a difference across sections".
diff --git a/clang/test/Driver/fsanitize.c b/clang/test/Driver/fsanitize.c
index 08e9c78f9d1d2..db14f6e195c64 100644
--- a/clang/test/Driver/fsanitize.c
+++ b/clang/test/Driver/fsanitize.c
@@ -462,8 +462,8 @@
 // RUN: %clang --target=x86_64-linux-gnu -fsanitize=numerical %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-NSAN-X86-64-LINUX
 // CHECK-NSAN-X86-64-LINUX: "-fsanitize=numerical"
 
-// RUN: %clang --target=aarch64-unknown-linux-gnu -fsanitize=numerical %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-NSAN-AARCH64-LINUX
-// CHECK-NSAN-AARCH64-LINUX: "-fsanitize=numerical"
+// RUN: not %clang --target=aarch64-unknown-linux-gnu -fsanitize=numerical %s 
-### 2>&1 | FileCheck %s --check-prefix=CHECK-NSAN-AARCH64-LINUX
+// CHECK-NSAN-AARCH64-LINUX: error: unsupported option '-fsanitize=numerical' 
for target 'aarch64-unknown-linux-gnu'
 
 // RUN: not %clang --target=mips-unknown-linux -fsanitize=numerical %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-NSAN-MIPS-LINUX
 // CHECK-NSAN-MIPS-LINUX: error: unsupported option '-fsanitize=numerical' for 
target 'mips-unknown-linux'
@@ -471,8 +471,8 @@
 // RUN: %clang --target=x86_64-apple-macos -fsanitize=numerical %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-NSAN-X86-64-MACOS
 // CHECK-NSAN-X86-64-MACOS: "-fsanitize=numerical"
 
-// RUN: %clang --target=arm64-apple-macos -fsanitize=numerical %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-NSAN-ARM64-MACOS
-// CHECK-NSAN-ARM64-MACOS: "-fsanitize=numerical"
+// RUN: not %clang --target=arm64-apple-macos -fsanitize=numerical %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-NSAN-ARM64-MACOS
+// CHECK-NSAN-ARM64-MACOS: error: unsupported option '-fsanitize=numerical' 
for target 'arm64-apple-macos'
 
 // RUN: %clang --target=x86_64-apple-darwin -fsanitize=thread %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-TSAN-X86-64-DARWIN
 // CHECK-TSAN-X86-64-DARWIN-NOT: unsupported option

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


[clang] [Clang][Sanitizers] Enable NSAN on X86_64 only (PR #95885)

2024-06-17 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov created 
https://github.com/llvm/llvm-project/pull/95885

This is a follow-up to https://github.com/llvm/llvm-project/pull/93783.
The current set of patches covers only x86_64 (in particular, on compiler-rt's 
side),
therefore we should now enable this flag on arm64.


>From c73818aa6b2a7effad9349843fe5a7d0df5076c0 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Tue, 18 Jun 2024 06:15:12 +
Subject: [PATCH] [Clang][Sanitizers] Enable NSAN on X86_64 only

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 4 +++-
 clang/lib/Driver/ToolChains/Linux.cpp  | 2 +-
 clang/test/Driver/fsanitize.c  | 8 
 3 files changed, 8 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index f742db7668cd2..0ae356ca91b22 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -3457,7 +3457,6 @@ SanitizerMask Darwin::getSupportedSanitizers() const {
   Res |= SanitizerKind::PointerCompare;
   Res |= SanitizerKind::PointerSubtract;
   Res |= SanitizerKind::Leak;
-  Res |= SanitizerKind::NumericalStability;
   Res |= SanitizerKind::Fuzzer;
   Res |= SanitizerKind::FuzzerNoLink;
   Res |= SanitizerKind::ObjCCast;
@@ -3474,6 +3473,9 @@ SanitizerMask Darwin::getSupportedSanitizers() const {
isTargetTvOSSimulator() || isTargetWatchOSSimulator())) {
 Res |= SanitizerKind::Thread;
   }
+
+  if (IsX86_64)
+Res |= SanitizerKind::NumericalStability;
   return Res;
 }
 
diff --git a/clang/lib/Driver/ToolChains/Linux.cpp 
b/clang/lib/Driver/ToolChains/Linux.cpp
index dea431c3c..49e029e7c9ab7 100644
--- a/clang/lib/Driver/ToolChains/Linux.cpp
+++ b/clang/lib/Driver/ToolChains/Linux.cpp
@@ -826,7 +826,7 @@ SanitizerMask Linux::getSupportedSanitizers() const {
   if (IsX86_64 || IsAArch64) {
 Res |= SanitizerKind::KernelHWAddress;
   }
-  if (IsX86_64 || IsAArch64)
+  if (IsX86_64)
 Res |= SanitizerKind::NumericalStability;
 
   // Work around "Cannot represent a difference across sections".
diff --git a/clang/test/Driver/fsanitize.c b/clang/test/Driver/fsanitize.c
index 08e9c78f9d1d2..db14f6e195c64 100644
--- a/clang/test/Driver/fsanitize.c
+++ b/clang/test/Driver/fsanitize.c
@@ -462,8 +462,8 @@
 // RUN: %clang --target=x86_64-linux-gnu -fsanitize=numerical %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-NSAN-X86-64-LINUX
 // CHECK-NSAN-X86-64-LINUX: "-fsanitize=numerical"
 
-// RUN: %clang --target=aarch64-unknown-linux-gnu -fsanitize=numerical %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-NSAN-AARCH64-LINUX
-// CHECK-NSAN-AARCH64-LINUX: "-fsanitize=numerical"
+// RUN: not %clang --target=aarch64-unknown-linux-gnu -fsanitize=numerical %s 
-### 2>&1 | FileCheck %s --check-prefix=CHECK-NSAN-AARCH64-LINUX
+// CHECK-NSAN-AARCH64-LINUX: error: unsupported option '-fsanitize=numerical' 
for target 'aarch64-unknown-linux-gnu'
 
 // RUN: not %clang --target=mips-unknown-linux -fsanitize=numerical %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-NSAN-MIPS-LINUX
 // CHECK-NSAN-MIPS-LINUX: error: unsupported option '-fsanitize=numerical' for 
target 'mips-unknown-linux'
@@ -471,8 +471,8 @@
 // RUN: %clang --target=x86_64-apple-macos -fsanitize=numerical %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-NSAN-X86-64-MACOS
 // CHECK-NSAN-X86-64-MACOS: "-fsanitize=numerical"
 
-// RUN: %clang --target=arm64-apple-macos -fsanitize=numerical %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-NSAN-ARM64-MACOS
-// CHECK-NSAN-ARM64-MACOS: "-fsanitize=numerical"
+// RUN: not %clang --target=arm64-apple-macos -fsanitize=numerical %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-NSAN-ARM64-MACOS
+// CHECK-NSAN-ARM64-MACOS: error: unsupported option '-fsanitize=numerical' 
for target 'arm64-apple-macos'
 
 // RUN: %clang --target=x86_64-apple-darwin -fsanitize=thread %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-TSAN-X86-64-DARWIN
 // CHECK-TSAN-X86-64-DARWIN-NOT: unsupported option

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


[clang] [Clang][Sanitizers] Add numerical sanitizer (PR #93783)

2024-06-10 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov closed 
https://github.com/llvm/llvm-project/pull/93783
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sanitizers] Add numerical sanitizer (PR #93783)

2024-06-10 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/93783

>From 8c5199181b94d1ae79f3ca7758ed8574774da551 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Thu, 30 May 2024 08:15:44 +
Subject: [PATCH] [Clang][Sanitizers] Add numerical sanitizer

---
 clang/include/clang/Basic/Features.def|  1 +
 clang/include/clang/Basic/Sanitizers.def  |  3 ++
 clang/include/clang/Driver/SanitizerArgs.h|  3 ++
 clang/lib/CodeGen/CGDeclCXX.cpp   |  4 +++
 clang/lib/CodeGen/CodeGenFunction.cpp |  2 ++
 clang/lib/Driver/SanitizerArgs.cpp|  7 ++--
 clang/lib/Driver/ToolChains/Darwin.cpp|  1 +
 clang/lib/Driver/ToolChains/Linux.cpp |  3 ++
 .../sanitize-numerical-stability-attr.cpp | 34 +++
 clang/test/Driver/fsanitize.c | 15 
 ..._feature_numerical_stability_sanitizer.cpp | 11 ++
 11 files changed, 82 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGen/sanitize-numerical-stability-attr.cpp
 create mode 100644 
clang/test/Lexer/has_feature_numerical_stability_sanitizer.cpp

diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index b762e44e755ec..53f410d3cb4bd 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -96,6 +96,7 @@ FEATURE(nullability, true)
 FEATURE(nullability_on_arrays, true)
 FEATURE(nullability_on_classes, true)
 FEATURE(nullability_nullable_result, true)
+FEATURE(numerical_stability_sanitizer, 
LangOpts.Sanitize.has(SanitizerKind::NumericalStability))
 FEATURE(memory_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Memory |
SanitizerKind::KernelMemory))
diff --git a/clang/include/clang/Basic/Sanitizers.def 
b/clang/include/clang/Basic/Sanitizers.def
index b228ffd07ee74..bee35e9dca7c3 100644
--- a/clang/include/clang/Basic/Sanitizers.def
+++ b/clang/include/clang/Basic/Sanitizers.def
@@ -76,6 +76,9 @@ SANITIZER("fuzzer-no-link", FuzzerNoLink)
 // ThreadSanitizer
 SANITIZER("thread", Thread)
 
+// Numerical stability sanitizer.
+SANITIZER("numerical", NumericalStability)
+
 // LeakSanitizer
 SANITIZER("leak", Leak)
 
diff --git a/clang/include/clang/Driver/SanitizerArgs.h 
b/clang/include/clang/Driver/SanitizerArgs.h
index 07070ec4fc065..47ef175302679 100644
--- a/clang/include/clang/Driver/SanitizerArgs.h
+++ b/clang/include/clang/Driver/SanitizerArgs.h
@@ -103,6 +103,9 @@ class SanitizerArgs {
   bool needsCfiDiagRt() const;
   bool needsStatsRt() const { return Stats; }
   bool needsScudoRt() const { return Sanitizers.has(SanitizerKind::Scudo); }
+  bool needsNsanRt() const {
+return Sanitizers.has(SanitizerKind::NumericalStability);
+  }
 
   bool hasMemTag() const {
 return hasMemtagHeap() || hasMemtagStack() || hasMemtagGlobals();
diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index b047279912f6b..a88bb2af59fee 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -476,6 +476,10 @@ llvm::Function 
*CodeGenModule::CreateGlobalInitOrCleanUpFunction(
   !isInNoSanitizeList(SanitizerKind::Thread, Fn, Loc))
 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
 
+  if (getLangOpts().Sanitize.has(SanitizerKind::NumericalStability) &&
+  !isInNoSanitizeList(SanitizerKind::NumericalStability, Fn, Loc))
+Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
+
   if (getLangOpts().Sanitize.has(SanitizerKind::Memory) &&
   !isInNoSanitizeList(SanitizerKind::Memory, Fn, Loc))
 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index f84b3b08220fd..cea0d84c64bc4 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -818,6 +818,8 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType 
RetTy,
   Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
 if (SanOpts.has(SanitizerKind::Thread))
   Fn->addFnAttr(llvm::Attribute::SanitizeThread);
+if (SanOpts.has(SanitizerKind::NumericalStability))
+  Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
 if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
   Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
   }
diff --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 273f215ca94a8..86825a6ccf7a1 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -41,7 +41,8 @@ static const SanitizerMask NotAllowedWithExecuteOnly =
 SanitizerKind::Function | SanitizerKind::KCFI;
 static const SanitizerMask NeedsUnwindTables =
 SanitizerKind::Address | SanitizerKind::HWAddress | SanitizerKind::Thread |
-SanitizerKind::Memory | SanitizerKind::DataFlow;
+SanitizerKind::Memory | SanitizerKind::DataFlow |
+   

[clang] [llvm] [Clang][Sanitizers] Add numerical sanitizer (PR #93783)

2024-06-06 Thread Alexander Shaposhnikov via cfe-commits


@@ -826,6 +826,10 @@ SanitizerMask Linux::getSupportedSanitizers() const {
   if (IsX86_64 || IsAArch64) {
 Res |= SanitizerKind::KernelHWAddress;
   }
+  if (IsX86_64) {
+Res |= SanitizerKind::NumericalStability;

alexander-shaposhnikov wrote:

Done

https://github.com/llvm/llvm-project/pull/93783
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [Clang][Sanitizers] Add numerical sanitizer (PR #93783)

2024-06-06 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/93783

>From 8556f6f2a255379e1f78db3354b1f750833c10a9 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Thu, 30 May 2024 08:15:44 +
Subject: [PATCH] [Clang][Sanitizers] Add numerical sanitizer

---
 clang/include/clang/Basic/Features.def|  1 +
 clang/include/clang/Basic/Sanitizers.def  |  3 ++
 clang/include/clang/Driver/SanitizerArgs.h|  3 ++
 clang/lib/CodeGen/CGDeclCXX.cpp   |  4 +++
 clang/lib/CodeGen/CodeGenFunction.cpp |  2 ++
 clang/lib/Driver/SanitizerArgs.cpp|  7 ++--
 clang/lib/Driver/ToolChains/Darwin.cpp|  1 +
 clang/lib/Driver/ToolChains/Linux.cpp |  3 ++
 .../sanitize-numerical-stability-attr.cpp | 34 +++
 clang/test/Driver/fsanitize.c | 15 
 ..._feature_numerical_stability_sanitizer.cpp | 11 ++
 llvm/include/llvm/IR/Attributes.td|  3 ++
 12 files changed, 85 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGen/sanitize-numerical-stability-attr.cpp
 create mode 100644 
clang/test/Lexer/has_feature_numerical_stability_sanitizer.cpp

diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index b762e44e755ec..53f410d3cb4bd 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -96,6 +96,7 @@ FEATURE(nullability, true)
 FEATURE(nullability_on_arrays, true)
 FEATURE(nullability_on_classes, true)
 FEATURE(nullability_nullable_result, true)
+FEATURE(numerical_stability_sanitizer, 
LangOpts.Sanitize.has(SanitizerKind::NumericalStability))
 FEATURE(memory_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Memory |
SanitizerKind::KernelMemory))
diff --git a/clang/include/clang/Basic/Sanitizers.def 
b/clang/include/clang/Basic/Sanitizers.def
index b228ffd07ee74..bee35e9dca7c3 100644
--- a/clang/include/clang/Basic/Sanitizers.def
+++ b/clang/include/clang/Basic/Sanitizers.def
@@ -76,6 +76,9 @@ SANITIZER("fuzzer-no-link", FuzzerNoLink)
 // ThreadSanitizer
 SANITIZER("thread", Thread)
 
+// Numerical stability sanitizer.
+SANITIZER("numerical", NumericalStability)
+
 // LeakSanitizer
 SANITIZER("leak", Leak)
 
diff --git a/clang/include/clang/Driver/SanitizerArgs.h 
b/clang/include/clang/Driver/SanitizerArgs.h
index 07070ec4fc065..47ef175302679 100644
--- a/clang/include/clang/Driver/SanitizerArgs.h
+++ b/clang/include/clang/Driver/SanitizerArgs.h
@@ -103,6 +103,9 @@ class SanitizerArgs {
   bool needsCfiDiagRt() const;
   bool needsStatsRt() const { return Stats; }
   bool needsScudoRt() const { return Sanitizers.has(SanitizerKind::Scudo); }
+  bool needsNsanRt() const {
+return Sanitizers.has(SanitizerKind::NumericalStability);
+  }
 
   bool hasMemTag() const {
 return hasMemtagHeap() || hasMemtagStack() || hasMemtagGlobals();
diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index b047279912f6b..a88bb2af59fee 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -476,6 +476,10 @@ llvm::Function 
*CodeGenModule::CreateGlobalInitOrCleanUpFunction(
   !isInNoSanitizeList(SanitizerKind::Thread, Fn, Loc))
 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
 
+  if (getLangOpts().Sanitize.has(SanitizerKind::NumericalStability) &&
+  !isInNoSanitizeList(SanitizerKind::NumericalStability, Fn, Loc))
+Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
+
   if (getLangOpts().Sanitize.has(SanitizerKind::Memory) &&
   !isInNoSanitizeList(SanitizerKind::Memory, Fn, Loc))
 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index f0345f3b191b8..681ecfda004d4 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -818,6 +818,8 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType 
RetTy,
   Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
 if (SanOpts.has(SanitizerKind::Thread))
   Fn->addFnAttr(llvm::Attribute::SanitizeThread);
+if (SanOpts.has(SanitizerKind::NumericalStability))
+  Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
 if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
   Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
   }
diff --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 273f215ca94a8..86825a6ccf7a1 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -41,7 +41,8 @@ static const SanitizerMask NotAllowedWithExecuteOnly =
 SanitizerKind::Function | SanitizerKind::KCFI;
 static const SanitizerMask NeedsUnwindTables =
 SanitizerKind::Address | SanitizerKind::HWAddress | SanitizerKind::Thread |
-SanitizerKind::Memory | SanitizerKind::DataFlow;
+   

[clang] [llvm] [Clang][Sanitizers] Add numerical sanitizer (PR #93783)

2024-05-30 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov ready_for_review 
https://github.com/llvm/llvm-project/pull/93783
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [Clang][Sanitizers] Add numerical sanitizer (PR #93783)

2024-05-30 Thread Alexander Shaposhnikov via cfe-commits


@@ -285,6 +285,9 @@ def SanitizeHWAddress : EnumAttr<"sanitize_hwaddress", 
[FnAttr]>;
 /// MemTagSanitizer is on.
 def SanitizeMemTag : EnumAttr<"sanitize_memtag", [FnAttr]>;
 
+/// NumericalStabilitySanitizer is on.
+def SanitizeNumericalStability : EnumAttr<"sanitize_numericalstability", 
[FnAttr]>;

alexander-shaposhnikov wrote:

yeah, it's already included into the first patch 
(https://github.com/llvm/llvm-project/pull/85916), duplicated here to unblock 
myself (Clang needs this in clang/lib/CodeGen/CGDeclCXX.cpp) (otherwise this PR 
would have a hard dependency on the first one)

https://github.com/llvm/llvm-project/pull/93783
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [Clang][Sanitizers] Add numerical sanitizer (PR #93783)

2024-05-30 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/93783

>From 50a524b17ce31e1e781a480c2cdf10a9153f9b9c Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Thu, 30 May 2024 08:15:44 +
Subject: [PATCH] [Clang][Sanitizers] Add numerical sanitizer

---
 clang/include/clang/Basic/Features.def|  1 +
 clang/include/clang/Basic/Sanitizers.def  |  3 ++
 clang/include/clang/Driver/SanitizerArgs.h|  3 ++
 clang/lib/CodeGen/CGDeclCXX.cpp   |  4 +++
 clang/lib/CodeGen/CodeGenFunction.cpp |  2 ++
 clang/lib/Driver/SanitizerArgs.cpp|  7 ++--
 clang/lib/Driver/ToolChains/Linux.cpp |  4 +++
 .../sanitize-numerical-stability-attr.cpp | 34 +++
 ..._feature_numerical_stability_sanitizer.cpp | 11 ++
 llvm/include/llvm/IR/Attributes.td|  3 ++
 10 files changed, 70 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGen/sanitize-numerical-stability-attr.cpp
 create mode 100644 
clang/test/Lexer/has_feature_numerical_stability_sanitizer.cpp

diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index b762e44e755ec..53f410d3cb4bd 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -96,6 +96,7 @@ FEATURE(nullability, true)
 FEATURE(nullability_on_arrays, true)
 FEATURE(nullability_on_classes, true)
 FEATURE(nullability_nullable_result, true)
+FEATURE(numerical_stability_sanitizer, 
LangOpts.Sanitize.has(SanitizerKind::NumericalStability))
 FEATURE(memory_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Memory |
SanitizerKind::KernelMemory))
diff --git a/clang/include/clang/Basic/Sanitizers.def 
b/clang/include/clang/Basic/Sanitizers.def
index b228ffd07ee74..bee35e9dca7c3 100644
--- a/clang/include/clang/Basic/Sanitizers.def
+++ b/clang/include/clang/Basic/Sanitizers.def
@@ -76,6 +76,9 @@ SANITIZER("fuzzer-no-link", FuzzerNoLink)
 // ThreadSanitizer
 SANITIZER("thread", Thread)
 
+// Numerical stability sanitizer.
+SANITIZER("numerical", NumericalStability)
+
 // LeakSanitizer
 SANITIZER("leak", Leak)
 
diff --git a/clang/include/clang/Driver/SanitizerArgs.h 
b/clang/include/clang/Driver/SanitizerArgs.h
index 07070ec4fc065..47ef175302679 100644
--- a/clang/include/clang/Driver/SanitizerArgs.h
+++ b/clang/include/clang/Driver/SanitizerArgs.h
@@ -103,6 +103,9 @@ class SanitizerArgs {
   bool needsCfiDiagRt() const;
   bool needsStatsRt() const { return Stats; }
   bool needsScudoRt() const { return Sanitizers.has(SanitizerKind::Scudo); }
+  bool needsNsanRt() const {
+return Sanitizers.has(SanitizerKind::NumericalStability);
+  }
 
   bool hasMemTag() const {
 return hasMemtagHeap() || hasMemtagStack() || hasMemtagGlobals();
diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index b047279912f6b..a88bb2af59fee 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -476,6 +476,10 @@ llvm::Function 
*CodeGenModule::CreateGlobalInitOrCleanUpFunction(
   !isInNoSanitizeList(SanitizerKind::Thread, Fn, Loc))
 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
 
+  if (getLangOpts().Sanitize.has(SanitizerKind::NumericalStability) &&
+  !isInNoSanitizeList(SanitizerKind::NumericalStability, Fn, Loc))
+Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
+
   if (getLangOpts().Sanitize.has(SanitizerKind::Memory) &&
   !isInNoSanitizeList(SanitizerKind::Memory, Fn, Loc))
 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index f0345f3b191b8..681ecfda004d4 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -818,6 +818,8 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType 
RetTy,
   Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
 if (SanOpts.has(SanitizerKind::Thread))
   Fn->addFnAttr(llvm::Attribute::SanitizeThread);
+if (SanOpts.has(SanitizerKind::NumericalStability))
+  Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
 if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
   Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
   }
diff --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 273f215ca94a8..86825a6ccf7a1 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -41,7 +41,8 @@ static const SanitizerMask NotAllowedWithExecuteOnly =
 SanitizerKind::Function | SanitizerKind::KCFI;
 static const SanitizerMask NeedsUnwindTables =
 SanitizerKind::Address | SanitizerKind::HWAddress | SanitizerKind::Thread |
-SanitizerKind::Memory | SanitizerKind::DataFlow;
+SanitizerKind::Memory | SanitizerKind::DataFlow |
+SanitizerKind::NumericalStability;
 static const Sanitizer

[clang] [llvm] [Clang][Sanitizers] Add numerical sanitizer (PR #93783)

2024-05-30 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov converted_to_draft 
https://github.com/llvm/llvm-project/pull/93783
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [Clang][Sanitizers] Add numerical sanitizer (PR #93783)

2024-05-30 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/93783

>From c02e1911abb04c4f9ec36d30984d3b10a87e1739 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Thu, 30 May 2024 08:15:44 +
Subject: [PATCH] [Clang][Sanitizers] Add numerical sanitizer

---
 clang/include/clang/Basic/Features.def|  1 +
 clang/include/clang/Basic/Sanitizers.def  |  3 ++
 clang/include/clang/Driver/SanitizerArgs.h|  3 ++
 clang/lib/CodeGen/CGDeclCXX.cpp   |  4 ++
 clang/lib/CodeGen/CodeGenFunction.cpp |  2 +
 clang/lib/Driver/SanitizerArgs.cpp|  7 ++-
 clang/lib/Driver/ToolChains/Linux.cpp |  4 ++
 .../sanitize-numerical-stability-attr.cpp | 49 +++
 ..._feature_numerical_stability_sanitizer.cpp | 11 +
 llvm/include/llvm/IR/Attributes.td|  3 ++
 10 files changed, 85 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGen/sanitize-numerical-stability-attr.cpp
 create mode 100644 
clang/test/Lexer/has_feature_numerical_stability_sanitizer.cpp

diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index b762e44e755ec..53f410d3cb4bd 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -96,6 +96,7 @@ FEATURE(nullability, true)
 FEATURE(nullability_on_arrays, true)
 FEATURE(nullability_on_classes, true)
 FEATURE(nullability_nullable_result, true)
+FEATURE(numerical_stability_sanitizer, 
LangOpts.Sanitize.has(SanitizerKind::NumericalStability))
 FEATURE(memory_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Memory |
SanitizerKind::KernelMemory))
diff --git a/clang/include/clang/Basic/Sanitizers.def 
b/clang/include/clang/Basic/Sanitizers.def
index b228ffd07ee74..bee35e9dca7c3 100644
--- a/clang/include/clang/Basic/Sanitizers.def
+++ b/clang/include/clang/Basic/Sanitizers.def
@@ -76,6 +76,9 @@ SANITIZER("fuzzer-no-link", FuzzerNoLink)
 // ThreadSanitizer
 SANITIZER("thread", Thread)
 
+// Numerical stability sanitizer.
+SANITIZER("numerical", NumericalStability)
+
 // LeakSanitizer
 SANITIZER("leak", Leak)
 
diff --git a/clang/include/clang/Driver/SanitizerArgs.h 
b/clang/include/clang/Driver/SanitizerArgs.h
index 07070ec4fc065..47ef175302679 100644
--- a/clang/include/clang/Driver/SanitizerArgs.h
+++ b/clang/include/clang/Driver/SanitizerArgs.h
@@ -103,6 +103,9 @@ class SanitizerArgs {
   bool needsCfiDiagRt() const;
   bool needsStatsRt() const { return Stats; }
   bool needsScudoRt() const { return Sanitizers.has(SanitizerKind::Scudo); }
+  bool needsNsanRt() const {
+return Sanitizers.has(SanitizerKind::NumericalStability);
+  }
 
   bool hasMemTag() const {
 return hasMemtagHeap() || hasMemtagStack() || hasMemtagGlobals();
diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index b047279912f6b..a88bb2af59fee 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -476,6 +476,10 @@ llvm::Function 
*CodeGenModule::CreateGlobalInitOrCleanUpFunction(
   !isInNoSanitizeList(SanitizerKind::Thread, Fn, Loc))
 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
 
+  if (getLangOpts().Sanitize.has(SanitizerKind::NumericalStability) &&
+  !isInNoSanitizeList(SanitizerKind::NumericalStability, Fn, Loc))
+Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
+
   if (getLangOpts().Sanitize.has(SanitizerKind::Memory) &&
   !isInNoSanitizeList(SanitizerKind::Memory, Fn, Loc))
 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index f0345f3b191b8..681ecfda004d4 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -818,6 +818,8 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType 
RetTy,
   Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
 if (SanOpts.has(SanitizerKind::Thread))
   Fn->addFnAttr(llvm::Attribute::SanitizeThread);
+if (SanOpts.has(SanitizerKind::NumericalStability))
+  Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
 if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
   Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
   }
diff --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 273f215ca94a8..86825a6ccf7a1 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -41,7 +41,8 @@ static const SanitizerMask NotAllowedWithExecuteOnly =
 SanitizerKind::Function | SanitizerKind::KCFI;
 static const SanitizerMask NeedsUnwindTables =
 SanitizerKind::Address | SanitizerKind::HWAddress | SanitizerKind::Thread |
-SanitizerKind::Memory | SanitizerKind::DataFlow;
+SanitizerKind::Memory | SanitizerKind::DataFlow |
+SanitizerKind::NumericalStability;
 static const SanitizerMask 

[clang] [llvm] [Clang][Sanitizers] Add numerical sanitizer (PR #93783)

2024-05-30 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov created 
https://github.com/llvm/llvm-project/pull/93783

Add plumbing for the numerical sanitizer on Clang's side.
This patch was extracted from https://github.com/llvm/llvm-project/pull/85916 

Test plan: ninja check-all

>From 1b02427f1dce543ef5ada06def84f307d5fed540 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Thu, 30 May 2024 08:15:44 +
Subject: [PATCH] [Clang][Sanitizers] Add numerical sanitizer

---
 clang/include/clang/Basic/Features.def|  1 +
 clang/include/clang/Basic/Sanitizers.def  |  3 ++
 clang/include/clang/Driver/SanitizerArgs.h|  3 ++
 clang/lib/CodeGen/CGDeclCXX.cpp   |  4 ++
 clang/lib/CodeGen/CodeGenFunction.cpp |  2 +
 clang/lib/Driver/SanitizerArgs.cpp|  7 ++-
 clang/lib/Driver/ToolChains/Linux.cpp |  4 ++
 .../sanitize-numerical-stability-attr.cpp | 49 +++
 ..._feature_numerical_stability_sanitizer.cpp | 11 +
 llvm/include/llvm/IR/Attributes.td|  3 ++
 10 files changed, 85 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGen/sanitize-numerical-stability-attr.cpp
 create mode 100644 
clang/test/Lexer/has_feature_numerical_stability_sanitizer.cpp

diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index b762e44e755ec..53f410d3cb4bd 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -96,6 +96,7 @@ FEATURE(nullability, true)
 FEATURE(nullability_on_arrays, true)
 FEATURE(nullability_on_classes, true)
 FEATURE(nullability_nullable_result, true)
+FEATURE(numerical_stability_sanitizer, 
LangOpts.Sanitize.has(SanitizerKind::NumericalStability))
 FEATURE(memory_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Memory |
SanitizerKind::KernelMemory))
diff --git a/clang/include/clang/Basic/Sanitizers.def 
b/clang/include/clang/Basic/Sanitizers.def
index b228ffd07ee74..bee35e9dca7c3 100644
--- a/clang/include/clang/Basic/Sanitizers.def
+++ b/clang/include/clang/Basic/Sanitizers.def
@@ -76,6 +76,9 @@ SANITIZER("fuzzer-no-link", FuzzerNoLink)
 // ThreadSanitizer
 SANITIZER("thread", Thread)
 
+// Numerical stability sanitizer.
+SANITIZER("numerical", NumericalStability)
+
 // LeakSanitizer
 SANITIZER("leak", Leak)
 
diff --git a/clang/include/clang/Driver/SanitizerArgs.h 
b/clang/include/clang/Driver/SanitizerArgs.h
index 07070ec4fc065..47ef175302679 100644
--- a/clang/include/clang/Driver/SanitizerArgs.h
+++ b/clang/include/clang/Driver/SanitizerArgs.h
@@ -103,6 +103,9 @@ class SanitizerArgs {
   bool needsCfiDiagRt() const;
   bool needsStatsRt() const { return Stats; }
   bool needsScudoRt() const { return Sanitizers.has(SanitizerKind::Scudo); }
+  bool needsNsanRt() const {
+return Sanitizers.has(SanitizerKind::NumericalStability);
+  }
 
   bool hasMemTag() const {
 return hasMemtagHeap() || hasMemtagStack() || hasMemtagGlobals();
diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index b047279912f6b..a88bb2af59fee 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -476,6 +476,10 @@ llvm::Function 
*CodeGenModule::CreateGlobalInitOrCleanUpFunction(
   !isInNoSanitizeList(SanitizerKind::Thread, Fn, Loc))
 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
 
+  if (getLangOpts().Sanitize.has(SanitizerKind::NumericalStability) &&
+  !isInNoSanitizeList(SanitizerKind::NumericalStability, Fn, Loc))
+Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
+
   if (getLangOpts().Sanitize.has(SanitizerKind::Memory) &&
   !isInNoSanitizeList(SanitizerKind::Memory, Fn, Loc))
 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index f0345f3b191b8..681ecfda004d4 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -818,6 +818,8 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType 
RetTy,
   Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
 if (SanOpts.has(SanitizerKind::Thread))
   Fn->addFnAttr(llvm::Attribute::SanitizeThread);
+if (SanOpts.has(SanitizerKind::NumericalStability))
+  Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
 if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
   Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
   }
diff --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 273f215ca94a8..86825a6ccf7a1 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -41,7 +41,8 @@ static const SanitizerMask NotAllowedWithExecuteOnly =
 SanitizerKind::Function | SanitizerKind::KCFI;
 static const SanitizerMask NeedsUnwindTables =
 SanitizerKind::Address | SanitizerKind::HWAddress | SanitizerKind::Thread |
-Saniti

[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-26 Thread Alexander Shaposhnikov via cfe-commits

alexander-shaposhnikov wrote:

@vitalybuka , @arsenm - thanks a lot, yeah, sure, I can split the patch.
P.S. will update/address comments soon.

https://github.com/llvm/llvm-project/pull/85916
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-20 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov edited 
https://github.com/llvm/llvm-project/pull/85916
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-20 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov edited 
https://github.com/llvm/llvm-project/pull/85916
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [llvm] [ConstraintElim] Add facts implied by llvm.abs (PR #73189)

2023-12-03 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/73189

>From a9e76a878edc8bc9cb81b8aa169bbbc467d32026 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Thu, 23 Nov 2023 00:37:08 +
Subject: [PATCH] [ConstraintElim] Add a fact implied by llvm.abs

---
 .../Scalar/ConstraintElimination.cpp  | 10 +++
 .../Transforms/ConstraintElimination/abs.ll   | 26 +++
 2 files changed, 36 insertions(+)
 create mode 100644 llvm/test/Transforms/ConstraintElimination/abs.ll

diff --git a/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp 
b/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
index 7aadd810c1da3..59aaa677ccbf9 100644
--- a/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
+++ b/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
@@ -995,6 +995,11 @@ void State::addInfoFor(BasicBlock &BB) {
   continue;
 }
 
+if (match(&I, m_Intrinsic())) {
+  WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
+  continue;
+}
+
 Value *A, *B;
 CmpInst::Predicate Pred;
 // For now, just handle assumes with a single compare as condition.
@@ -1629,6 +1634,11 @@ static bool eliminateConstraints(Function &F, 
DominatorTree &DT, LoopInfo &LI,
 
 ICmpInst::Predicate Pred;
 if (!CB.isConditionFact()) {
+  if (Value *X; match(CB.Inst, m_Intrinsic(m_Value(X {
+AddFact(CmpInst::ICMP_SGE, CB.Inst, X);
+continue;
+  }
+
   if (auto *MinMax = dyn_cast(CB.Inst)) {
 Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
 AddFact(Pred, MinMax, MinMax->getLHS());
diff --git a/llvm/test/Transforms/ConstraintElimination/abs.ll 
b/llvm/test/Transforms/ConstraintElimination/abs.ll
new file mode 100644
index 0..1cf56c6e37a8c
--- /dev/null
+++ b/llvm/test/Transforms/ConstraintElimination/abs.ll
@@ -0,0 +1,26 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --version 4
+; RUN: opt -passes=constraint-elimination -S %s | FileCheck %s
+
+define i1 @abs_false(i32 %arg) {
+; CHECK-LABEL: define i1 @abs_false(
+; CHECK-SAME: i32 [[ARG:%.*]]) {
+; CHECK-NEXT:[[ABS:%.*]] = tail call i32 @llvm.abs.i32(i32 [[ARG]], i1 
false)
+; CHECK-NEXT:ret i1 true
+;
+  %abs = tail call i32 @llvm.abs.i32(i32 %arg, i1 false)
+  %cmp = icmp sge i32 %abs, %arg
+  ret i1 %cmp
+}
+
+define i1 @abs_true(i32 %arg) {
+; CHECK-LABEL: define i1 @abs_true(
+; CHECK-SAME: i32 [[ARG:%.*]]) {
+; CHECK-NEXT:[[ABS:%.*]] = tail call i32 @llvm.abs.i32(i32 [[ARG]], i1 
true)
+; CHECK-NEXT:ret i1 true
+;
+  %abs = tail call i32 @llvm.abs.i32(i32 %arg, i1 true)
+  %cmp = icmp sge i32 %abs, %arg
+  ret i1 %cmp
+}
+
+declare i32 @llvm.abs.i32(i32, i1 immarg)

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


[clang] [clang] Predefined macros for float128 support (PR #67196)

2023-09-26 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov approved this pull request.

LG

https://github.com/llvm/llvm-project/pull/67196
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Predefined macros for float128 support (PR #67196)

2023-09-25 Thread Alexander Shaposhnikov via cfe-commits


@@ -1076,6 +1076,8 @@ static void InitializePredefinedMacros(const TargetInfo 
&TI,
   DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat(), "F");
   DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat(), "");
   DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat(), "L");
+  if (TI.hasFloat128Type())
+DefineFloatMacros(Builder, "FLT128", &TI.getFloat128Format(), "Q");

alexander-shaposhnikov wrote:

This needs tests (see e.g. https://reviews.llvm.org/D111382, 
https://github.com/llvm/llvm-project/blob/main/clang/test/Preprocessor)

https://github.com/llvm/llvm-project/pull/67196
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] Implement __extendxftf2 for x86_64 (PR #66918)

2023-09-22 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/66918

>From 84cb5de329c228702da9f864312df31dc00692dc Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Wed, 20 Sep 2023 14:25:46 +
Subject: [PATCH] Implement __extendxftf2 for x86_64

---
 compiler-rt/lib/builtins/CMakeLists.txt   |  1 +
 compiler-rt/lib/builtins/extendxftf2.c| 23 +++
 compiler-rt/lib/builtins/fp_extend.h  | 24 +++
 compiler-rt/lib/builtins/fp_extend_impl.inc   | 48 ++
 compiler-rt/test/builtins/Unit/addtf3_test.c  |  2 +-
 compiler-rt/test/builtins/Unit/divtf3_test.c  |  2 +-
 .../test/builtins/Unit/extenddftf2_test.c |  2 +-
 .../test/builtins/Unit/extendhftf2_test.c |  2 +-
 .../test/builtins/Unit/extendsftf2_test.c |  2 +-
 .../test/builtins/Unit/extendxftf2_test.c | 66 +++
 .../test/builtins/Unit/floatditf_test.c   |  2 +-
 .../test/builtins/Unit/floatsitf_test.c   |  2 +-
 .../test/builtins/Unit/floatunditf_test.c |  2 +-
 .../test/builtins/Unit/floatunsitf_test.c |  2 +-
 compiler-rt/test/builtins/Unit/fp_test.h  | 55 +---
 compiler-rt/test/builtins/Unit/multf3_test.c  |  2 +-
 compiler-rt/test/builtins/Unit/subtf3_test.c  |  2 +-
 17 files changed, 205 insertions(+), 34 deletions(-)
 create mode 100644 compiler-rt/lib/builtins/extendxftf2.c
 create mode 100644 compiler-rt/test/builtins/Unit/extendxftf2_test.c

diff --git a/compiler-rt/lib/builtins/CMakeLists.txt 
b/compiler-rt/lib/builtins/CMakeLists.txt
index 43ef62ffb115d9d..b3e6e8c8b517d83 100644
--- a/compiler-rt/lib/builtins/CMakeLists.txt
+++ b/compiler-rt/lib/builtins/CMakeLists.txt
@@ -280,6 +280,7 @@ endif ()
 # long double is not 80 bits on Android or MSVC.
 set(x86_80_BIT_SOURCES
   divxc3.c
+  extendxftf2.c
   fixxfdi.c
   fixxfti.c
   fixunsxfdi.c
diff --git a/compiler-rt/lib/builtins/extendxftf2.c 
b/compiler-rt/lib/builtins/extendxftf2.c
new file mode 100644
index 000..aa5355e94839f93
--- /dev/null
+++ b/compiler-rt/lib/builtins/extendxftf2.c
@@ -0,0 +1,23 @@
+//===-- lib/extendxftf2.c - long double -> quad conversion *- C 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// Assumption: long double is a IEEE 80 bit floating point type padded to 128
+// bits.
+
+// TODO: use fp_lib.h once QUAD_PRECISION is available on x86_64.
+#if __LDBL_MANT_DIG__ == 64 && defined(__x86_64__) \
+   && (defined(__FLOAT128__) || 
defined(__SIZEOF_FLOAT128__))
+#define SRC_80
+#define DST_QUAD
+#include "fp_extend_impl.inc"
+
+COMPILER_RT_ABI __float128 __extendxftf2(long double a) {
+  return __extendXfYf2__(a);
+}
+
+#endif
diff --git a/compiler-rt/lib/builtins/fp_extend.h 
b/compiler-rt/lib/builtins/fp_extend.h
index eee4722bf90e69f..fc23c1c2d7a6a81 100644
--- a/compiler-rt/lib/builtins/fp_extend.h
+++ b/compiler-rt/lib/builtins/fp_extend.h
@@ -20,14 +20,18 @@
 typedef float src_t;
 typedef uint32_t src_rep_t;
 #define SRC_REP_C UINT32_C
+static const int srcBits = sizeof(src_t) * CHAR_BIT;
 static const int srcSigBits = 23;
+static const int srcSigFracBits = 23;
 #define src_rep_t_clz clzsi
 
 #elif defined SRC_DOUBLE
 typedef double src_t;
 typedef uint64_t src_rep_t;
 #define SRC_REP_C UINT64_C
+static const int srcBits = sizeof(src_t) * CHAR_BIT;
 static const int srcSigBits = 52;
+static const int srcSigFracBits = 52;
 static __inline int src_rep_t_clz(src_rep_t a) {
 #if defined __LP64__
   return __builtin_clzl(a);
@@ -39,6 +43,16 @@ static __inline int src_rep_t_clz(src_rep_t a) {
 #endif
 }
 
+#elif defined SRC_80
+typedef long double src_t;
+typedef __uint128_t src_rep_t;
+#define SRC_REP_C (__uint128_t)
+// sign bit, exponent and significand occupy the lower 80 bits.
+static const int srcBits = 80;
+// significand stores the integer bit.
+static const int srcSigBits = 64;
+static const int srcSigFracBits = 63;
+
 #elif defined SRC_HALF
 #ifdef COMPILER_RT_HAS_FLOAT16
 typedef _Float16 src_t;
@@ -47,7 +61,9 @@ typedef uint16_t src_t;
 #endif
 typedef uint16_t src_rep_t;
 #define SRC_REP_C UINT16_C
+static const int srcBits = sizeof(src_t) * CHAR_BIT;
 static const int srcSigBits = 10;
+static const int srcSigFracBits = 10;
 #define src_rep_t_clz __builtin_clz
 
 #else
@@ -59,18 +75,26 @@ typedef float dst_t;
 typedef uint32_t dst_rep_t;
 #define DST_REP_C UINT32_C
 static const int dstSigBits = 23;
+static const int dstSigFracBits = 23;
 
 #elif defined DST_DOUBLE
 typedef double dst_t;
 typedef uint64_t dst_rep_t;
 #define DST_REP_C UINT64_C
 static const int dstSigBits = 52;
+static const int dstSigFracBits = 52;
 
 #elif defined DST_QUAD
+// TODO: use fp_lib.h once QUAD_PRECISION is available on x86_64.
+#if __LDBL_MA

[clang-tools-extra] [compiler-rt] Implement __extendxftf2 for x86_64 (PR #66918)

2023-09-22 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/66918

>From 84cb5de329c228702da9f864312df31dc00692dc Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Wed, 20 Sep 2023 14:25:46 +
Subject: [PATCH] Implement __extendxftf2 for x86_64

---
 compiler-rt/lib/builtins/CMakeLists.txt   |  1 +
 compiler-rt/lib/builtins/extendxftf2.c| 23 +++
 compiler-rt/lib/builtins/fp_extend.h  | 24 +++
 compiler-rt/lib/builtins/fp_extend_impl.inc   | 48 ++
 compiler-rt/test/builtins/Unit/addtf3_test.c  |  2 +-
 compiler-rt/test/builtins/Unit/divtf3_test.c  |  2 +-
 .../test/builtins/Unit/extenddftf2_test.c |  2 +-
 .../test/builtins/Unit/extendhftf2_test.c |  2 +-
 .../test/builtins/Unit/extendsftf2_test.c |  2 +-
 .../test/builtins/Unit/extendxftf2_test.c | 66 +++
 .../test/builtins/Unit/floatditf_test.c   |  2 +-
 .../test/builtins/Unit/floatsitf_test.c   |  2 +-
 .../test/builtins/Unit/floatunditf_test.c |  2 +-
 .../test/builtins/Unit/floatunsitf_test.c |  2 +-
 compiler-rt/test/builtins/Unit/fp_test.h  | 55 +---
 compiler-rt/test/builtins/Unit/multf3_test.c  |  2 +-
 compiler-rt/test/builtins/Unit/subtf3_test.c  |  2 +-
 17 files changed, 205 insertions(+), 34 deletions(-)
 create mode 100644 compiler-rt/lib/builtins/extendxftf2.c
 create mode 100644 compiler-rt/test/builtins/Unit/extendxftf2_test.c

diff --git a/compiler-rt/lib/builtins/CMakeLists.txt 
b/compiler-rt/lib/builtins/CMakeLists.txt
index 43ef62ffb115d9d..b3e6e8c8b517d83 100644
--- a/compiler-rt/lib/builtins/CMakeLists.txt
+++ b/compiler-rt/lib/builtins/CMakeLists.txt
@@ -280,6 +280,7 @@ endif ()
 # long double is not 80 bits on Android or MSVC.
 set(x86_80_BIT_SOURCES
   divxc3.c
+  extendxftf2.c
   fixxfdi.c
   fixxfti.c
   fixunsxfdi.c
diff --git a/compiler-rt/lib/builtins/extendxftf2.c 
b/compiler-rt/lib/builtins/extendxftf2.c
new file mode 100644
index 000..aa5355e94839f93
--- /dev/null
+++ b/compiler-rt/lib/builtins/extendxftf2.c
@@ -0,0 +1,23 @@
+//===-- lib/extendxftf2.c - long double -> quad conversion *- C 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// Assumption: long double is a IEEE 80 bit floating point type padded to 128
+// bits.
+
+// TODO: use fp_lib.h once QUAD_PRECISION is available on x86_64.
+#if __LDBL_MANT_DIG__ == 64 && defined(__x86_64__) \
+   && (defined(__FLOAT128__) || 
defined(__SIZEOF_FLOAT128__))
+#define SRC_80
+#define DST_QUAD
+#include "fp_extend_impl.inc"
+
+COMPILER_RT_ABI __float128 __extendxftf2(long double a) {
+  return __extendXfYf2__(a);
+}
+
+#endif
diff --git a/compiler-rt/lib/builtins/fp_extend.h 
b/compiler-rt/lib/builtins/fp_extend.h
index eee4722bf90e69f..fc23c1c2d7a6a81 100644
--- a/compiler-rt/lib/builtins/fp_extend.h
+++ b/compiler-rt/lib/builtins/fp_extend.h
@@ -20,14 +20,18 @@
 typedef float src_t;
 typedef uint32_t src_rep_t;
 #define SRC_REP_C UINT32_C
+static const int srcBits = sizeof(src_t) * CHAR_BIT;
 static const int srcSigBits = 23;
+static const int srcSigFracBits = 23;
 #define src_rep_t_clz clzsi
 
 #elif defined SRC_DOUBLE
 typedef double src_t;
 typedef uint64_t src_rep_t;
 #define SRC_REP_C UINT64_C
+static const int srcBits = sizeof(src_t) * CHAR_BIT;
 static const int srcSigBits = 52;
+static const int srcSigFracBits = 52;
 static __inline int src_rep_t_clz(src_rep_t a) {
 #if defined __LP64__
   return __builtin_clzl(a);
@@ -39,6 +43,16 @@ static __inline int src_rep_t_clz(src_rep_t a) {
 #endif
 }
 
+#elif defined SRC_80
+typedef long double src_t;
+typedef __uint128_t src_rep_t;
+#define SRC_REP_C (__uint128_t)
+// sign bit, exponent and significand occupy the lower 80 bits.
+static const int srcBits = 80;
+// significand stores the integer bit.
+static const int srcSigBits = 64;
+static const int srcSigFracBits = 63;
+
 #elif defined SRC_HALF
 #ifdef COMPILER_RT_HAS_FLOAT16
 typedef _Float16 src_t;
@@ -47,7 +61,9 @@ typedef uint16_t src_t;
 #endif
 typedef uint16_t src_rep_t;
 #define SRC_REP_C UINT16_C
+static const int srcBits = sizeof(src_t) * CHAR_BIT;
 static const int srcSigBits = 10;
+static const int srcSigFracBits = 10;
 #define src_rep_t_clz __builtin_clz
 
 #else
@@ -59,18 +75,26 @@ typedef float dst_t;
 typedef uint32_t dst_rep_t;
 #define DST_REP_C UINT32_C
 static const int dstSigBits = 23;
+static const int dstSigFracBits = 23;
 
 #elif defined DST_DOUBLE
 typedef double dst_t;
 typedef uint64_t dst_rep_t;
 #define DST_REP_C UINT64_C
 static const int dstSigBits = 52;
+static const int dstSigFracBits = 52;
 
 #elif defined DST_QUAD
+// TODO: use fp_lib.h once QUAD_PRECISION is available on x86_64.
+#if __LDBL_MA

[clang] 8b0ea48 - [Clang][CUDA] Disable diagnostics for neon attrs for GPU-side CUDA compilation

2023-06-09 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-06-09T09:27:01Z
New Revision: 8b0ea48740935d819618d8254fc45d98179b672c

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

LOG: [Clang][CUDA] Disable diagnostics for neon attrs for GPU-side CUDA 
compilation

Disable diagnostics for neon attributes for GPU-side CUDA compilation.

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D152403

Added: 
clang/test/SemaCUDA/neon-attrs.cu

Modified: 
clang/lib/Sema/SemaType.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 039082ecb29ba..2b2d17b469057 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -8169,10 +8169,18 @@ static bool verifyValidIntegerConstantExpr(Sema &S, 
const ParsedAttr &Attr,
 /// match one of the standard Neon vector types.
 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
  Sema &S, VectorType::VectorKind VecKind) {
+  bool IsTargetCUDAAndHostARM = false;
+  if (S.getLangOpts().CUDAIsDevice) {
+const TargetInfo *AuxTI = S.getASTContext().getAuxTargetInfo();
+IsTargetCUDAAndHostARM =
+AuxTI && (AuxTI->getTriple().isAArch64() || 
AuxTI->getTriple().isARM());
+  }
+
   // Target must have NEON (or MVE, whose vectors are similar enough
   // not to need a separate attribute)
-  if (!S.Context.getTargetInfo().hasFeature("neon") &&
-  !S.Context.getTargetInfo().hasFeature("mve")) {
+  if (!(S.Context.getTargetInfo().hasFeature("neon") ||
+S.Context.getTargetInfo().hasFeature("mve") ||
+IsTargetCUDAAndHostARM)) {
 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
 << Attr << "'neon' or 'mve'";
 Attr.setInvalid();
@@ -8180,8 +8188,8 @@ static void HandleNeonVectorTypeAttr(QualType &CurType, 
const ParsedAttr &Attr,
   }
   // Check the attribute arguments.
   if (Attr.getNumArgs() != 1) {
-S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
-  << 1;
+S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
+<< Attr << 1;
 Attr.setInvalid();
 return;
   }
@@ -8191,7 +8199,8 @@ static void HandleNeonVectorTypeAttr(QualType &CurType, 
const ParsedAttr &Attr,
 return;
 
   // Only certain element types are supported for Neon vectors.
-  if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
+  if (!isPermittedNeonBaseType(CurType, VecKind, S) &&
+  !IsTargetCUDAAndHostARM) {
 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
 Attr.setInvalid();
 return;

diff  --git a/clang/test/SemaCUDA/neon-attrs.cu 
b/clang/test/SemaCUDA/neon-attrs.cu
new file mode 100644
index 0..a72b03f3bbbd7
--- /dev/null
+++ b/clang/test/SemaCUDA/neon-attrs.cu
@@ -0,0 +1,21 @@
+// CPU-side compilation on ARM with neon enabled (no errors expected).
+// RUN: %clang_cc1 -triple arm64-linux-gnu -target-feature +neon -aux-triple 
nvptx64 -x cuda -fsyntax-only -verify=quiet %s
+
+// CPU-side compilation on ARM with neon disabled.
+// RUN: %clang_cc1 -triple arm64-linux-gnu -target-feature -neon -aux-triple 
nvptx64 -x cuda -fsyntax-only -verify %s
+
+// GPU-side compilation on ARM (no errors expected).
+// RUN: %clang_cc1 -triple nvptx64 -aux-triple arm64-linux-gnu 
-fcuda-is-device -x cuda -fsyntax-only -verify=quiet %s
+
+// Regular C++ compilation on ARM with neon enabled (no errors expected).
+// RUN: %clang_cc1 -triple arm64-linux-gnu -target-feature +neon -x c++ 
-fsyntax-only -verify=quiet %s
+
+// Regular C++ compilation on ARM with neon disabled.
+// RUN: %clang_cc1 -triple arm64-linux-gnu -target-feature -neon -x c++ 
-fsyntax-only -verify %s
+
+// quiet-no-diagnostics
+typedef __attribute__((neon_vector_type(4))) float float32x4_t;
+// expected-error@-1 {{'neon_vector_type' attribute is not supported on 
targets missing 'neon' or 'mve'}}
+typedef unsigned char poly8_t;
+typedef __attribute__((neon_polyvector_type(8))) poly8_t poly8x8_t;
+// expected-error@-1 {{'neon_polyvector_type' attribute is not supported on 
targets missing 'neon' or 'mve'}}



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


[clang] 7c26919 - [Clang] Fix typo in ReleaseNotes.rst

2023-05-18 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-05-18T20:08:54Z
New Revision: 7c26919c32f0620441417805329867884a5efc7b

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

LOG: [Clang] Fix typo in ReleaseNotes.rst

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5c6459d01b14..b0f848d47a67 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -82,7 +82,7 @@ C++20 Feature Support
   This fixes:
   `#49620 `_,
   `#60231 `_,
-  `#61414 `_,
+  `#61414 `_,
   `#61809 `_.
 - Lambda templates with a requires clause directly after the template 
parameters now parse
   correctly if the requires clause consists of a variable with a dependent 
type.



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


[clang] cd4677f - [Clang] Update release notes

2023-05-18 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-05-18T20:02:37Z
New Revision: cd4677f207041e74f55d0cac6145942f04301ee7

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

LOG: [Clang] Update release notes

Update release notes.
This is a follow-up to https://reviews.llvm.org/D146178

Differential revision: https://reviews.llvm.org/D149906

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9420a9e687ca7..5c6459d01b14c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -77,8 +77,13 @@ C++ Language Changes
 
 C++20 Feature Support
 ^
-- Support for out-of-line definitions of constrained templates has been 
improved.
-  This partially fixes `#49620 
`_.
+- Implemented the rule introduced by `CA104 `_  for 
comparison of
+  constraint-expressions. Improved support for out-of-line definitions of 
constrained templates.
+  This fixes:
+  `#49620 `_,
+  `#60231 `_,
+  `#61414 `_,
+  `#61809 `_.
 - Lambda templates with a requires clause directly after the template 
parameters now parse
   correctly if the requires clause consists of a variable with a dependent 
type.
   (`#61278 `_)



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


[clang] 122b938 - [Clang][Sema] Substitute constraints only for declarations with different lexical contexts

2023-05-17 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-05-17T21:24:44Z
New Revision: 122b938944ceb966e04d7a4d253f7f9ba27c477d

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

LOG: [Clang][Sema] Substitute constraints only for declarations with different 
lexical contexts

Substitute constraints only for declarations with different lexical contexts.
This results in avoiding the substitution of constraints during the 
redeclaration check
inside a class (and by product caching the wrong substitution result).

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D150730

Added: 
clang/test/SemaTemplate/concepts-no-early-substitution.cpp

Modified: 
clang/lib/Sema/SemaConcept.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 1126c2c517fe4..2f5fb8f8d029e 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -780,7 +780,9 @@ bool Sema::AreConstraintExpressionsEqual(const NamedDecl 
*Old,
  const Expr *NewConstr) {
   if (OldConstr == NewConstr)
 return true;
-  if (Old && New && Old != New) {
+  // C++ [temp.constr.decl]p4
+  if (Old && New && Old != New &&
+  Old->getLexicalDeclContext() != New->getLexicalDeclContext()) {
 if (const Expr *SubstConstr =
 SubstituteConstraintExpression(*this, Old, OldConstr))
   OldConstr = SubstConstr;

diff  --git a/clang/test/SemaTemplate/concepts-no-early-substitution.cpp 
b/clang/test/SemaTemplate/concepts-no-early-substitution.cpp
new file mode 100644
index 0..9e576f16a263b
--- /dev/null
+++ b/clang/test/SemaTemplate/concepts-no-early-substitution.cpp
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -std=c++20 -x c++ %s -verify -fsyntax-only
+// expected-no-diagnostics
+
+template 
+concept HasMemberBegin = requires(T0 t) { t.begin(); };
+
+struct GetBegin {
+  template 
+  void operator()(T1);
+};
+
+GetBegin begin;
+
+template 
+concept Concept = requires(T2 t) { begin(t); };
+
+struct Subrange;
+
+template 
+struct View {
+  Subrange &getSubrange();
+
+  operator bool()
+requires true;
+
+  operator bool()
+requires requires { begin(getSubrange()); };
+
+  void begin();
+};
+
+struct Subrange : View {};
+static_assert(Concept);



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


[clang] 6db007a - [Clang][Sema] Fix comparison of constraint expressions

2023-05-09 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-05-09T18:14:39Z
New Revision: 6db007a0654ed7a6ed5c3aa3b61a937c19a6bc6b

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

LOG: [Clang][Sema] Fix comparison of constraint expressions

This diff switches the approach to comparison of constraint expressions
to the new one based on template args substitution.
It continues the effort to fix our handling of out-of-line definitions
of constrained templates.
This is a recommit of 3a54022934.

Differential revision: https://reviews.llvm.org/D146178

Added: 


Modified: 
clang/include/clang/AST/DeclTemplate.h
clang/include/clang/Sema/Template.h
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaTemplate/concepts-friends.cpp
clang/test/SemaTemplate/concepts-out-of-line-def.cpp
clang/test/SemaTemplate/concepts.cpp

Removed: 




diff  --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 3677335fa176f..7cd505218f2b9 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -2309,9 +2309,15 @@ class ClassTemplateDecl : public 
RedeclarableTemplateDecl {
 return static_cast(RedeclarableTemplateDecl::getCommonPtr());
   }
 
+  void setCommonPtr(Common *C) {
+RedeclarableTemplateDecl::Common = C;
+  }
+
 public:
+
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
+  friend class TemplateDeclInstantiator;
 
   /// Load any lazily-loaded specializations from the external source.
   void LoadLazySpecializations() const;

diff  --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index 48e8b78311e12..1de2cc6917b42 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -232,9 +232,21 @@ enum class TemplateSubstitutionKind : char {
 /// Replaces the current 'innermost' level with the provided argument list.
 /// This is useful for type deduction cases where we need to get the entire
 /// list from the AST, but then add the deduced innermost list.
-void replaceInnermostTemplateArguments(ArgList Args) {
-  assert(TemplateArgumentLists.size() > 0 && "Replacing in an empty 
list?");
-  TemplateArgumentLists[0].Args = Args;
+void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args) 
{
+  assert((!TemplateArgumentLists.empty() || NumRetainedOuterLevels) &&
+ "Replacing in an empty list?");
+
+  if (!TemplateArgumentLists.empty()) {
+assert((TemplateArgumentLists[0].AssociatedDeclAndFinal.getPointer() ||
+TemplateArgumentLists[0].AssociatedDeclAndFinal.getPointer() ==
+AssociatedDecl) &&
+   "Trying to change incorrect declaration?");
+TemplateArgumentLists[0].Args = Args;
+  } else {
+--NumRetainedOuterLevels;
+TemplateArgumentLists.push_back(
+{{AssociatedDecl, /*Final=*/false}, Args});
+  }
 }
 
 /// Add an outermost level that we are not substituting. We have no

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 7aa06b615fec2..1126c2c517fe4 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -722,7 +722,7 @@ CalculateTemplateDepthForConstraints(Sema &S, const 
NamedDecl *ND,
   ND, /*Final=*/false, /*Innermost=*/nullptr, /*RelativeToPrimary=*/true,
   /*Pattern=*/nullptr,
   /*ForConstraintInstantiation=*/true, SkipForSpecialization);
-  return MLTAL.getNumSubstitutedLevels();
+  return MLTAL.getNumLevels();
 }
 
 namespace {
@@ -753,27 +753,44 @@ namespace {
   };
 } // namespace
 
+static const Expr *SubstituteConstraintExpression(Sema &S, const NamedDecl *ND,
+  const Expr *ConstrExpr) {
+  MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
+  ND, /*Final=*/false, /*Innermost=*/nullptr,
+  /*RelativeToPrimary=*/true,
+  /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
+  /*SkipForSpecialization*/ false);
+  if (MLTAL.getNumSubstitutedLevels() == 0)
+return ConstrExpr;
+
+  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
+  std::optional ThisScope;
+  if (auto *RD = dyn_cast(ND->getDeclContext()))
+ThisScope.emplace(S, const_cast(RD), Qualifiers());
+  ExprResult SubstConstr =
+  S.SubstConstraintExpr(const_cast(ConstrExpr), MLTAL);
+  if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
+return nullptr;
+  return SubstConstr.get();
+}
+
 bool Sema::AreConstraintExpressionsEqual(co

[clang] 3b9ed6e - Revert "[Clang][Sema] Fix comparison of constraint expressions"

2023-05-04 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-05-05T00:02:26Z
New Revision: 3b9ed6e5323176550925f3b0a2c50ced1b61438d

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

LOG: Revert "[Clang][Sema] Fix comparison of constraint expressions"

This reverts commit 3a540229341e3c8dc6d8ee61309eafaf943ea254.
A new regression is discovered and needs to be investigated.

Added: 


Modified: 
clang/include/clang/AST/DeclTemplate.h
clang/include/clang/Sema/Template.h
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaTemplate/concepts-friends.cpp
clang/test/SemaTemplate/concepts-out-of-line-def.cpp
clang/test/SemaTemplate/concepts.cpp

Removed: 




diff  --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 7cd505218f2b9..3677335fa176f 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -2309,15 +2309,9 @@ class ClassTemplateDecl : public 
RedeclarableTemplateDecl {
 return static_cast(RedeclarableTemplateDecl::getCommonPtr());
   }
 
-  void setCommonPtr(Common *C) {
-RedeclarableTemplateDecl::Common = C;
-  }
-
 public:
-
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
-  friend class TemplateDeclInstantiator;
 
   /// Load any lazily-loaded specializations from the external source.
   void LoadLazySpecializations() const;

diff  --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index 1de2cc6917b42..48e8b78311e12 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -232,21 +232,9 @@ enum class TemplateSubstitutionKind : char {
 /// Replaces the current 'innermost' level with the provided argument list.
 /// This is useful for type deduction cases where we need to get the entire
 /// list from the AST, but then add the deduced innermost list.
-void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args) 
{
-  assert((!TemplateArgumentLists.empty() || NumRetainedOuterLevels) &&
- "Replacing in an empty list?");
-
-  if (!TemplateArgumentLists.empty()) {
-assert((TemplateArgumentLists[0].AssociatedDeclAndFinal.getPointer() ||
-TemplateArgumentLists[0].AssociatedDeclAndFinal.getPointer() ==
-AssociatedDecl) &&
-   "Trying to change incorrect declaration?");
-TemplateArgumentLists[0].Args = Args;
-  } else {
---NumRetainedOuterLevels;
-TemplateArgumentLists.push_back(
-{{AssociatedDecl, /*Final=*/false}, Args});
-  }
+void replaceInnermostTemplateArguments(ArgList Args) {
+  assert(TemplateArgumentLists.size() > 0 && "Replacing in an empty 
list?");
+  TemplateArgumentLists[0].Args = Args;
 }
 
 /// Add an outermost level that we are not substituting. We have no

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 1126c2c517fe4..7aa06b615fec2 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -722,7 +722,7 @@ CalculateTemplateDepthForConstraints(Sema &S, const 
NamedDecl *ND,
   ND, /*Final=*/false, /*Innermost=*/nullptr, /*RelativeToPrimary=*/true,
   /*Pattern=*/nullptr,
   /*ForConstraintInstantiation=*/true, SkipForSpecialization);
-  return MLTAL.getNumLevels();
+  return MLTAL.getNumSubstitutedLevels();
 }
 
 namespace {
@@ -753,44 +753,27 @@ namespace {
   };
 } // namespace
 
-static const Expr *SubstituteConstraintExpression(Sema &S, const NamedDecl *ND,
-  const Expr *ConstrExpr) {
-  MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
-  ND, /*Final=*/false, /*Innermost=*/nullptr,
-  /*RelativeToPrimary=*/true,
-  /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
-  /*SkipForSpecialization*/ false);
-  if (MLTAL.getNumSubstitutedLevels() == 0)
-return ConstrExpr;
-
-  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
-  std::optional ThisScope;
-  if (auto *RD = dyn_cast(ND->getDeclContext()))
-ThisScope.emplace(S, const_cast(RD), Qualifiers());
-  ExprResult SubstConstr =
-  S.SubstConstraintExpr(const_cast(ConstrExpr), MLTAL);
-  if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
-return nullptr;
-  return SubstConstr.get();
-}
-
 bool Sema::AreConstraintExpressionsEqual(const NamedDecl *Old,
  const Expr *OldConstr,
  const NamedDecl *New,
   

[clang] 3a54022 - [Clang][Sema] Fix comparison of constraint expressions

2023-05-03 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-05-03T21:06:12Z
New Revision: 3a540229341e3c8dc6d8ee61309eafaf943ea254

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

LOG: [Clang][Sema] Fix comparison of constraint expressions

This diff switches the approach to comparison of constraint expressions
to the new one based on template args substitution.
It continues the effort to fix our handling of out-of-line definitions
of constrained templates.
This is a recommit of e3b1083e00.

Differential revision: https://reviews.llvm.org/D146178

Added: 


Modified: 
clang/include/clang/AST/DeclTemplate.h
clang/include/clang/Sema/Template.h
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaTemplate/concepts-friends.cpp
clang/test/SemaTemplate/concepts-out-of-line-def.cpp
clang/test/SemaTemplate/concepts.cpp

Removed: 




diff  --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 3677335fa176f..7cd505218f2b9 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -2309,9 +2309,15 @@ class ClassTemplateDecl : public 
RedeclarableTemplateDecl {
 return static_cast(RedeclarableTemplateDecl::getCommonPtr());
   }
 
+  void setCommonPtr(Common *C) {
+RedeclarableTemplateDecl::Common = C;
+  }
+
 public:
+
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
+  friend class TemplateDeclInstantiator;
 
   /// Load any lazily-loaded specializations from the external source.
   void LoadLazySpecializations() const;

diff  --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index 48e8b78311e12..1de2cc6917b42 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -232,9 +232,21 @@ enum class TemplateSubstitutionKind : char {
 /// Replaces the current 'innermost' level with the provided argument list.
 /// This is useful for type deduction cases where we need to get the entire
 /// list from the AST, but then add the deduced innermost list.
-void replaceInnermostTemplateArguments(ArgList Args) {
-  assert(TemplateArgumentLists.size() > 0 && "Replacing in an empty 
list?");
-  TemplateArgumentLists[0].Args = Args;
+void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args) 
{
+  assert((!TemplateArgumentLists.empty() || NumRetainedOuterLevels) &&
+ "Replacing in an empty list?");
+
+  if (!TemplateArgumentLists.empty()) {
+assert((TemplateArgumentLists[0].AssociatedDeclAndFinal.getPointer() ||
+TemplateArgumentLists[0].AssociatedDeclAndFinal.getPointer() ==
+AssociatedDecl) &&
+   "Trying to change incorrect declaration?");
+TemplateArgumentLists[0].Args = Args;
+  } else {
+--NumRetainedOuterLevels;
+TemplateArgumentLists.push_back(
+{{AssociatedDecl, /*Final=*/false}, Args});
+  }
 }
 
 /// Add an outermost level that we are not substituting. We have no

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 328d66bf33afa..f208cdbd1d87d 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -721,7 +721,7 @@ CalculateTemplateDepthForConstraints(Sema &S, const 
NamedDecl *ND,
   ND, /*Final=*/false, /*Innermost=*/nullptr, /*RelativeToPrimary=*/true,
   /*Pattern=*/nullptr,
   /*ForConstraintInstantiation=*/true, SkipForSpecialization);
-  return MLTAL.getNumSubstitutedLevels();
+  return MLTAL.getNumLevels();
 }
 
 namespace {
@@ -752,27 +752,44 @@ namespace {
   };
 } // namespace
 
+static const Expr *SubstituteConstraintExpression(Sema &S, const NamedDecl *ND,
+  const Expr *ConstrExpr) {
+  MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
+  ND, /*Final=*/false, /*Innermost=*/nullptr,
+  /*RelativeToPrimary=*/true,
+  /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
+  /*SkipForSpecialization*/ false);
+  if (MLTAL.getNumSubstitutedLevels() == 0)
+return ConstrExpr;
+
+  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
+  std::optional ThisScope;
+  if (auto *RD = dyn_cast(ND->getDeclContext()))
+ThisScope.emplace(S, const_cast(RD), Qualifiers());
+  ExprResult SubstConstr =
+  S.SubstConstraintExpr(const_cast(ConstrExpr), MLTAL);
+  if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
+return nullptr;
+  return SubstConstr.get();
+}
+
 bool Sema::AreConstraintExpressionsEqual(co

[clang] ce861ec - [Clang][Sema] Add a temporary workaround in SemaConcept.cpp

2023-04-27 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-04-27T23:34:03Z
New Revision: ce861ec782ae3f41807b61e855512aaccf3c2149

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

LOG: [Clang][Sema] Add a temporary workaround in SemaConcept.cpp

This commit adds FIXME and a temporary workaround to repair
CUDA build bots after e3b1083e00e62f.

Added: 


Modified: 
clang/lib/Sema/SemaConcept.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index f208cdbd1d87..a9335d6689ec 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -260,6 +260,11 @@ calculateConstraintSatisfaction(Sema &S, const Expr 
*ConstraintExpr,
 return SubstitutedAtomicExpr;
   }
 
+  // FIXME: Remove this workaround.
+  // It's necessary to investigate how we get here.
+  if (SubstitutedAtomicExpr.get()->isValueDependent())
+return SubstitutedAtomicExpr;
+
   EnterExpressionEvaluationContext ConstantEvaluated(
   S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
   SmallVector EvaluationDiags;



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


[clang] e3b1083 - [Clang][Sema] Fix comparison of constraint expressions

2023-04-27 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-04-27T21:33:32Z
New Revision: e3b1083e00e62f5d157d15cb8c63a1c3dfdf12e2

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

LOG: [Clang][Sema] Fix comparison of constraint expressions

This diff switches the approach to comparison of constraint expressions
to the new one based on template args substitution.
It continues the effort to fix our handling of out-of-line definitions
of constrained templates.
This is a recommit of 60bee9ff5445.

Differential revision: https://reviews.llvm.org/D146178

Added: 


Modified: 
clang/include/clang/AST/DeclTemplate.h
clang/include/clang/Sema/Template.h
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaTemplate/concepts-friends.cpp
clang/test/SemaTemplate/concepts-out-of-line-def.cpp
clang/test/SemaTemplate/concepts.cpp

Removed: 




diff  --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 3677335fa176f..7cd505218f2b9 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -2309,9 +2309,15 @@ class ClassTemplateDecl : public 
RedeclarableTemplateDecl {
 return static_cast(RedeclarableTemplateDecl::getCommonPtr());
   }
 
+  void setCommonPtr(Common *C) {
+RedeclarableTemplateDecl::Common = C;
+  }
+
 public:
+
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
+  friend class TemplateDeclInstantiator;
 
   /// Load any lazily-loaded specializations from the external source.
   void LoadLazySpecializations() const;

diff  --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index 48e8b78311e12..1de2cc6917b42 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -232,9 +232,21 @@ enum class TemplateSubstitutionKind : char {
 /// Replaces the current 'innermost' level with the provided argument list.
 /// This is useful for type deduction cases where we need to get the entire
 /// list from the AST, but then add the deduced innermost list.
-void replaceInnermostTemplateArguments(ArgList Args) {
-  assert(TemplateArgumentLists.size() > 0 && "Replacing in an empty 
list?");
-  TemplateArgumentLists[0].Args = Args;
+void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args) 
{
+  assert((!TemplateArgumentLists.empty() || NumRetainedOuterLevels) &&
+ "Replacing in an empty list?");
+
+  if (!TemplateArgumentLists.empty()) {
+assert((TemplateArgumentLists[0].AssociatedDeclAndFinal.getPointer() ||
+TemplateArgumentLists[0].AssociatedDeclAndFinal.getPointer() ==
+AssociatedDecl) &&
+   "Trying to change incorrect declaration?");
+TemplateArgumentLists[0].Args = Args;
+  } else {
+--NumRetainedOuterLevels;
+TemplateArgumentLists.push_back(
+{{AssociatedDecl, /*Final=*/false}, Args});
+  }
 }
 
 /// Add an outermost level that we are not substituting. We have no

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 328d66bf33afa..f208cdbd1d87d 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -721,7 +721,7 @@ CalculateTemplateDepthForConstraints(Sema &S, const 
NamedDecl *ND,
   ND, /*Final=*/false, /*Innermost=*/nullptr, /*RelativeToPrimary=*/true,
   /*Pattern=*/nullptr,
   /*ForConstraintInstantiation=*/true, SkipForSpecialization);
-  return MLTAL.getNumSubstitutedLevels();
+  return MLTAL.getNumLevels();
 }
 
 namespace {
@@ -752,27 +752,44 @@ namespace {
   };
 } // namespace
 
+static const Expr *SubstituteConstraintExpression(Sema &S, const NamedDecl *ND,
+  const Expr *ConstrExpr) {
+  MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
+  ND, /*Final=*/false, /*Innermost=*/nullptr,
+  /*RelativeToPrimary=*/true,
+  /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
+  /*SkipForSpecialization*/ false);
+  if (MLTAL.getNumSubstitutedLevels() == 0)
+return ConstrExpr;
+
+  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
+  std::optional ThisScope;
+  if (auto *RD = dyn_cast(ND->getDeclContext()))
+ThisScope.emplace(S, const_cast(RD), Qualifiers());
+  ExprResult SubstConstr =
+  S.SubstConstraintExpr(const_cast(ConstrExpr), MLTAL);
+  if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
+return nullptr;
+  return SubstConstr.get();
+}
+
 bool Sema::AreConstraintExpressionsEqual(

[clang] f799901 - [Clang][Sema] Add MultiLevelTemplateArgumentList::dump

2023-04-07 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-04-07T19:36:59Z
New Revision: f799901c06c015cc30cf123a8f0c01f8b107669e

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

LOG: [Clang][Sema] Add MultiLevelTemplateArgumentList::dump

Add MultiLevelTemplateArgumentList::dump
(similarly to TemplateArgument::dump).

Differential revision: https://reviews.llvm.org/D147744

Added: 


Modified: 
clang/include/clang/Sema/Template.h

Removed: 




diff  --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index 908389438389f..48e8b78311e12 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -261,6 +261,23 @@ enum class TemplateSubstitutionKind : char {
 }
 ArgListsIterator end() { return TemplateArgumentLists.end(); }
 ConstArgListsIterator end() const { return TemplateArgumentLists.end(); }
+
+LLVM_DUMP_METHOD void dump() const {
+  LangOptions LO;
+  LO.CPlusPlus = true;
+  LO.Bool = true;
+  PrintingPolicy PP(LO);
+  llvm::errs() << "NumRetainedOuterLevels: " << NumRetainedOuterLevels
+   << "\n";
+  for (unsigned Depth = NumRetainedOuterLevels; Depth < getNumLevels();
+   ++Depth) {
+llvm::errs() << Depth << ": ";
+printTemplateArgumentList(
+llvm::errs(),
+TemplateArgumentLists[getNumLevels() - Depth - 1].Args, PP);
+llvm::errs() << "\n";
+  }
+}
   };
 
   /// The context in which partial ordering of function templates occurs.



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


[clang] 13d44a8 - Revert "[Clang][Sema] Fix comparison of constraint expressions"

2023-04-07 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-04-07T18:41:57Z
New Revision: 13d44a8f5647819efd3ef57af384a3666f99d066

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

LOG: Revert "[Clang][Sema] Fix comparison of constraint expressions"

This temporarily reverts commit
60bee9ff544541e83ffbd4be31923d0e8b644690.
The diff will be recommitted once the newly discovered
regressions are fixed.

Added: 


Modified: 
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaTemplate/concepts-out-of-line-def.cpp
clang/test/SemaTemplate/concepts.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 4e7033c9d588..2882b10613fd 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -260,9 +260,6 @@ calculateConstraintSatisfaction(Sema &S, const Expr 
*ConstraintExpr,
 return SubstitutedAtomicExpr;
   }
 
-  if (SubstitutedAtomicExpr.get()->isValueDependent())
-return SubstitutedAtomicExpr;
-
   EnterExpressionEvaluationContext ConstantEvaluated(
   S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
   SmallVector EvaluationDiags;
@@ -755,43 +752,27 @@ namespace {
   };
 } // namespace
 
-static const Expr *SubstituteConstraintExpression(Sema &S, const NamedDecl *ND,
-  const Expr *ConstrExpr) {
-  MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
-  ND, /*Final=*/false, /*Innermost=*/nullptr,
-  /*RelativeToPrimary=*/true,
-  /*Pattern=*/nullptr,
-  /*ForConstraintInstantiation=*/true, /*SkipForSpecialization*/ false);
-  if (MLTAL.getNumSubstitutedLevels() == 0)
-return ConstrExpr;
-  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
-  std::optional ThisScope;
-  if (auto *RD = dyn_cast(ND->getDeclContext()))
-ThisScope.emplace(S, const_cast(RD), Qualifiers());
-  ExprResult SubstConstr =
-  S.SubstConstraintExpr(const_cast(ConstrExpr), MLTAL);
-  if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
-return nullptr;
-  return SubstConstr.get();
-}
-
 bool Sema::AreConstraintExpressionsEqual(const NamedDecl *Old,
  const Expr *OldConstr,
  const NamedDecl *New,
  const Expr *NewConstr) {
-  if (OldConstr == NewConstr)
-return true;
   if (Old && New && Old != New) {
-if (const Expr *SubstConstr =
-SubstituteConstraintExpression(*this, Old, OldConstr))
-  OldConstr = SubstConstr;
-else
-  return false;
-if (const Expr *SubstConstr =
-SubstituteConstraintExpression(*this, New, NewConstr))
-  NewConstr = SubstConstr;
-else
-  return false;
+unsigned Depth1 = CalculateTemplateDepthForConstraints(
+*this, Old);
+unsigned Depth2 = CalculateTemplateDepthForConstraints(
+*this, New);
+
+// Adjust the 'shallowest' verison of this to increase the depth to match
+// the 'other'.
+if (Depth2 > Depth1) {
+  OldConstr = AdjustConstraintDepth(*this, Depth2 - Depth1)
+  .TransformExpr(const_cast(OldConstr))
+  .get();
+} else if (Depth1 > Depth2) {
+  NewConstr = AdjustConstraintDepth(*this, Depth1 - Depth2)
+  .TransformExpr(const_cast(NewConstr))
+  .get();
+}
   }
 
   llvm::FoldingSetNodeID ID1, ID2;

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index aa40bff4c575..ab4300518ecf 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -1294,7 +1294,7 @@ bool Sema::IsOverload(FunctionDecl *New, FunctionDecl 
*Old,
 // We check the return type and template parameter lists for function
 // templates first; the remaining checks follow.
 bool SameTemplateParameterList = TemplateParameterListsAreEqual(
-NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
+NewTemplate->getTemplateParameters(),
 OldTemplate->getTemplateParameters(), false, TPL_TemplateMatch);
 bool SameReturnType = Context.hasSameType(Old->getDeclaredReturnType(),
   New->getDeclaredReturnType());

diff  --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index bdcee77ce67c..526f19b8aedc 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -208,10 +208,6 @@ Response HandleFunction(const FunctionDecl *Function,
   return Response::UseNextDecl(Function);

[clang] 60bee9f - [Clang][Sema] Fix comparison of constraint expressions

2023-04-03 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-04-04T02:31:13Z
New Revision: 60bee9ff544541e83ffbd4be31923d0e8b644690

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

LOG: [Clang][Sema] Fix comparison of constraint expressions

This diff switches the approach to comparison of constraint expressions
to the new one based on template args substitution.
It continues the effort to fix our handling of out-of-line definitions
of constrained templates.

The associated GitHub issue: https://github.com/llvm/llvm-project/issues/61414

Test plan:
1/ ninja check-all
2/ bootstrapped Clang passes tests

Differential revision: https://reviews.llvm.org/D146178

Added: 


Modified: 
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaTemplate/concepts-out-of-line-def.cpp
clang/test/SemaTemplate/concepts.cpp
clang/www/cxx_status.html

Removed: 




diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 2882b10613fdc..4e7033c9d588d 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -260,6 +260,9 @@ calculateConstraintSatisfaction(Sema &S, const Expr 
*ConstraintExpr,
 return SubstitutedAtomicExpr;
   }
 
+  if (SubstitutedAtomicExpr.get()->isValueDependent())
+return SubstitutedAtomicExpr;
+
   EnterExpressionEvaluationContext ConstantEvaluated(
   S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
   SmallVector EvaluationDiags;
@@ -752,27 +755,43 @@ namespace {
   };
 } // namespace
 
+static const Expr *SubstituteConstraintExpression(Sema &S, const NamedDecl *ND,
+  const Expr *ConstrExpr) {
+  MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
+  ND, /*Final=*/false, /*Innermost=*/nullptr,
+  /*RelativeToPrimary=*/true,
+  /*Pattern=*/nullptr,
+  /*ForConstraintInstantiation=*/true, /*SkipForSpecialization*/ false);
+  if (MLTAL.getNumSubstitutedLevels() == 0)
+return ConstrExpr;
+  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
+  std::optional ThisScope;
+  if (auto *RD = dyn_cast(ND->getDeclContext()))
+ThisScope.emplace(S, const_cast(RD), Qualifiers());
+  ExprResult SubstConstr =
+  S.SubstConstraintExpr(const_cast(ConstrExpr), MLTAL);
+  if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
+return nullptr;
+  return SubstConstr.get();
+}
+
 bool Sema::AreConstraintExpressionsEqual(const NamedDecl *Old,
  const Expr *OldConstr,
  const NamedDecl *New,
  const Expr *NewConstr) {
+  if (OldConstr == NewConstr)
+return true;
   if (Old && New && Old != New) {
-unsigned Depth1 = CalculateTemplateDepthForConstraints(
-*this, Old);
-unsigned Depth2 = CalculateTemplateDepthForConstraints(
-*this, New);
-
-// Adjust the 'shallowest' verison of this to increase the depth to match
-// the 'other'.
-if (Depth2 > Depth1) {
-  OldConstr = AdjustConstraintDepth(*this, Depth2 - Depth1)
-  .TransformExpr(const_cast(OldConstr))
-  .get();
-} else if (Depth1 > Depth2) {
-  NewConstr = AdjustConstraintDepth(*this, Depth1 - Depth2)
-  .TransformExpr(const_cast(NewConstr))
-  .get();
-}
+if (const Expr *SubstConstr =
+SubstituteConstraintExpression(*this, Old, OldConstr))
+  OldConstr = SubstConstr;
+else
+  return false;
+if (const Expr *SubstConstr =
+SubstituteConstraintExpression(*this, New, NewConstr))
+  NewConstr = SubstConstr;
+else
+  return false;
   }
 
   llvm::FoldingSetNodeID ID1, ID2;

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index f10d937ed74d5..5cbd9e8a46234 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -1294,7 +1294,7 @@ bool Sema::IsOverload(FunctionDecl *New, FunctionDecl 
*Old,
 // We check the return type and template parameter lists for function
 // templates first; the remaining checks follow.
 bool SameTemplateParameterList = TemplateParameterListsAreEqual(
-NewTemplate->getTemplateParameters(),
+NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
 OldTemplate->getTemplateParameters(), false, TPL_TemplateMatch);
 bool SameReturnType = Context.hasSameType(Old->getDeclaredReturnType(),
   New->getDeclaredReturnType());

diff  --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/c

[clang] 8403ccd - [Clang][CodeGen] Fix linkage and visibility of template parameter objects

2023-03-14 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-03-14T18:23:06Z
New Revision: 8403ccdcd28c2ff30c1e980ce4a8c851fae01a9d

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

LOG: [Clang][CodeGen] Fix linkage and visibility of template parameter objects

This diff fixes linkage and visibility of template parameter objects.
The associated GitHub issue: https://github.com/llvm/llvm-project/issues/51571#

Test plan:
1/ ninja check-all
2/ bootstrapped Clang passes tests

Differential revision: https://reviews.llvm.org/D145859

Added: 
clang/test/CodeGenCXX/template-param-objects-linkage.cpp
clang/test/CodeGenCXX/template-param-objects-visibility.cpp

Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/test/CodeGenCXX/template-param-objects.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index b512fb576a2c0..7055205862ded 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3238,9 +3238,13 @@ ConstantAddress 
CodeGenModule::GetAddrOfTemplateParamObject(
 return ConstantAddress::invalid();
   }
 
-  auto *GV = new llvm::GlobalVariable(
-  getModule(), Init->getType(),
-  /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
+  llvm::GlobalValue::LinkageTypes Linkage =
+  isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage())
+  ? llvm::GlobalValue::LinkOnceODRLinkage
+  : llvm::GlobalValue::InternalLinkage;
+  auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
+  /*isConstant=*/true, Linkage, Init, 
Name);
+  setGVProperties(GV, TPO);
   if (supportsCOMDAT())
 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
   Emitter.finalize(GV);

diff  --git a/clang/test/CodeGenCXX/template-param-objects-linkage.cpp 
b/clang/test/CodeGenCXX/template-param-objects-linkage.cpp
new file mode 100644
index 0..63e7d8c646869
--- /dev/null
+++ b/clang/test/CodeGenCXX/template-param-objects-linkage.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++20 %s -emit-llvm -o - | 
FileCheck %s
+
+struct S { char buf[32]; };
+template constexpr const char* f() { return s.buf; }
+const char* fbuf = f();
+// CHECK: @_ZTAXtl1StlA32_cLc97 = linkonce_odr constant { <{ i8, [31 x i8] 
}> }
+
+namespace {
+  struct UN { char buf[64]; };
+}
+template  constexpr const char* g() { return un.buf; }
+const char* gbuf = g();
+// CHECK: @_ZTAXtlN12_GLOBAL__N_12UNEtlA64_cLc98 = internal constant { <{ 
i8, [63 x i8] }> }
+
+struct Foo { int *i; };
+int m = 0;
+namespace { int n; }
+
+template 
+const int* h() { return foo.i; }
+
+const int* hm = h();
+// CHECK: @_ZTAXtl3FooadL_Z1mEEE = linkonce_odr constant %struct.Foo { ptr @m }
+
+const int* hn = h();
+// CHECK: @_ZTAXtl3FooadL_ZN12_GLOBAL__N_11n = internal constant 
%struct.Foo { ptr @_ZN12_GLOBAL__N_11nE }

diff  --git a/clang/test/CodeGenCXX/template-param-objects-visibility.cpp 
b/clang/test/CodeGenCXX/template-param-objects-visibility.cpp
new file mode 100644
index 0..bf85016b0aff6
--- /dev/null
+++ b/clang/test/CodeGenCXX/template-param-objects-visibility.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++20 %s -emit-llvm -o - | 
FileCheck %s
+
+struct S { char buf[32]; };
+template constexpr const char* f() { return s.buf; }
+const char* fbuf = f();
+// CHECK: @_ZTAXtl1StlA32_cLc97 = linkonce_odr constant { <{ i8, [31 x i8] 
}> }
+
+struct __attribute__ ((visibility ("hidden"))) HN { char buf[64]; };
+template  constexpr const char* g() { return hn.buf; }
+const char* gbuf = g();
+// CHECK: @_ZTAXtl2HNtlA64_cLc98 = linkonce_odr hidden constant { <{ i8, 
[63 x i8] }> }

diff  --git a/clang/test/CodeGenCXX/template-param-objects.cpp 
b/clang/test/CodeGenCXX/template-param-objects.cpp
index e36b27185b526..11ebd21521e83 100644
--- a/clang/test/CodeGenCXX/template-param-objects.cpp
+++ b/clang/test/CodeGenCXX/template-param-objects.cpp
@@ -7,7 +7,9 @@ template constexpr const char *end() { return s.buf + 
__builtin_strlen(s.bu
 
 // ITANIUM: 
[[HELLO:@_ZTAXtl1StlA32_cLc104ELc101ELc108ELc108ELc111ELc32ELc119ELc111ELc114ELc108ELc100]]
 // MSABI: 
[[HELLO:@"[?][?]__N2US@@3D0GI@@0GF@@0GM@@0GM@@0GP@@0CA@@0HH@@0GP@@0HC@@0GM@@0GE@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@"]]
-// CHECK-SAME: = linkonce_odr constant { <{ [11 x i8], [21 x i8] }> } { <{ [11 
x i8], [21 x i8] }> <{ [11 x i8] c"hello world", [21 x i8] zeroinitializer }> 
}, comdat
+// ITANIUM-SAME: = linkonce_odr constant { <{ [11 x i8], [21 x i8] }> } { <{ 
[11 x i8], [21 x i8] }> <{ [11 x i8] c"hello world", [21 x i8] zeroinitializer 
}> }, comdat
+// MSABI-SAME:

[clang] 421c098 - [Clang][Sema] Start fixing handling of out-of-line definitions of constrained templates

2023-03-10 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-03-10T09:21:09Z
New Revision: 421c098b32bd50122de8de03a71092c7f36994eb

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

LOG: [Clang][Sema] Start fixing handling of out-of-line definitions of 
constrained templates

This diff starts fixing our handling of out-of-line definitions of constrained 
templates.
Initially it was motivated by https://github.com/llvm/llvm-project/issues/49620 
and
https://github.com/llvm/llvm-project/issues/60231.
In particular, this diff adjusts Sema::computeDeclContext to work properly in 
the case of
constrained template parameters.

Test plan:
1/ ninja check-all
2/ Bootstrapped Clang passes all the tests
3/ Internal testing

Differential revision: https://reviews.llvm.org/D145034

Added: 
clang/test/SemaTemplate/concepts-out-of-line-def.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/DeclSpec.h
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Sema/SemaCXXScopeSpec.cpp

clang/test/CXX/temp/temp.decls/temp.class.spec/temp.class.spec.mfunc/p1-neg.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 332431e08ce07..8d880a4fba266 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -78,6 +78,8 @@ C++ Language Changes
 
 C++20 Feature Support
 ^
+- Support for out-of-line definitions of constrained templates has been 
improved.
+  This partially fixes `https://github.com/llvm/llvm-project/issues/49620`.
 
 C++2b Feature Support
 ^

diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index 96963fb6aa807..65111b1ac6b36 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -2513,7 +2513,8 @@ class Parser : public CodeCompletionHandler {
   /// this is a constructor declarator.
   bool isConstructorDeclarator(
   bool Unqualified, bool DeductionGuide = false,
-  DeclSpec::FriendSpecified IsFriend = DeclSpec::FriendSpecified::No);
+  DeclSpec::FriendSpecified IsFriend = DeclSpec::FriendSpecified::No,
+  const ParsedTemplateInfo *TemplateInfo = nullptr);
 
   /// Specifies the context in which type-id/expression
   /// disambiguation will occur.

diff  --git a/clang/include/clang/Sema/DeclSpec.h 
b/clang/include/clang/Sema/DeclSpec.h
index 69fe2c541607b..b0bf87dc18d79 100644
--- a/clang/include/clang/Sema/DeclSpec.h
+++ b/clang/include/clang/Sema/DeclSpec.h
@@ -62,9 +62,18 @@ namespace clang {
 /// often used as if it meant "present".
 ///
 /// The actual scope is described by getScopeRep().
+///
+/// If the kind of getScopeRep() is TypeSpec then TemplateParamLists may be 
empty
+/// or contain the template parameter lists attached to the current 
declaration.
+/// Consider the following example:
+/// template  void SomeType::some_method() {}
+/// If CXXScopeSpec refers to SomeType then TemplateParamLists will contain
+/// a single element referring to template .
+
 class CXXScopeSpec {
   SourceRange Range;
   NestedNameSpecifierLocBuilder Builder;
+  ArrayRef TemplateParamLists;
 
 public:
   SourceRange getRange() const { return Range; }
@@ -74,6 +83,13 @@ class CXXScopeSpec {
   SourceLocation getBeginLoc() const { return Range.getBegin(); }
   SourceLocation getEndLoc() const { return Range.getEnd(); }
 
+  void setTemplateParamLists(ArrayRef L) {
+TemplateParamLists = L;
+  }
+  ArrayRef getTemplateParamLists() const {
+return TemplateParamLists;
+  }
+
   /// Retrieve the representation of the nested-name-specifier.
   NestedNameSpecifier *getScopeRep() const {
 return Builder.getRepresentation();

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 3106571728692..da84da04e43d0 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -3380,6 +3380,8 @@ void Parser::ParseDeclarationSpecifiers(
 goto DoneWithDeclSpec;
 
   CXXScopeSpec SS;
+  if (TemplateInfo.TemplateParams)
+SS.setTemplateParamLists(*TemplateInfo.TemplateParams);
   Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
Tok.getAnnotationRange(),
SS);
@@ -3475,7 +3477,8 @@ void Parser::ParseDeclarationSpecifiers(
  &SS) &&
   isConstructorDeclarator(/*Unqualified=*/false,
   /*DeductionGuide=*/false,
-  DS.isFriendSpecified()))
+  DS.isFriendSpecified(),
+  &TemplateInfo))

[clang] 8f5d815 - [Clang][LLVM] Enable __arithmetic_fence and fprotect-parens on AArch64

2023-02-13 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-02-13T19:26:11Z
New Revision: 8f5d81585aa9261342d5304e460925916ea1f851

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

LOG: [Clang][LLVM] Enable __arithmetic_fence and fprotect-parens on AArch64

Enable __arithmetic_fence and fprotect-parens on AArch64.

Test plan: ninja check-clang check-clang-tools check-llvm

Differential revision: https://reviews.llvm.org/D143781

Added: 
llvm/test/CodeGen/AArch64/arithmetic_fence.ll

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Basic/Targets/AArch64.h
clang/test/AST/arithmetic-fence-builtin.c
clang/test/CodeGen/arithmetic-fence-builtin.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 06f0bdcc796d6..0dcd9b9f04b1d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -181,13 +181,16 @@ DWARF Support in Clang
 Arm and AArch64 Support in Clang
 
 
-* The hard-float ABI is now available in Armv8.1-M configurations that
+- The hard-float ABI is now available in Armv8.1-M configurations that
   have integer MVE instructions (and therefore have FP registers) but
   no scalar or vector floating point computation. Previously, trying
   to select the hard-float ABI on such a target (via
   ``-mfloat-abi=hard`` or a triple ending in ``hf``) would silently
   use the soft-float ABI instead.
 
+- Clang builtin ``__arithmetic_fence`` and the command line option 
``-fprotect-parens``
+  are now enabled for AArch64.
+
 Floating Point Support in Clang
 ---
 - Add ``__builtin_elementwise_log`` builtin for floating point types only.

diff  --git a/clang/lib/Basic/Targets/AArch64.h 
b/clang/lib/Basic/Targets/AArch64.h
index 7f88f3516780f..23cabc5885104 100644
--- a/clang/lib/Basic/Targets/AArch64.h
+++ b/clang/lib/Basic/Targets/AArch64.h
@@ -155,6 +155,8 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
   ParsedTargetAttr parseTargetAttr(StringRef Str) const override;
   bool supportsTargetAttributeTune() const override { return true; }
 
+  bool checkArithmeticFenceSupported() const override { return true; }
+
   bool hasBFloat16Type() const override;
 
   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override;

diff  --git a/clang/test/AST/arithmetic-fence-builtin.c 
b/clang/test/AST/arithmetic-fence-builtin.c
index 4b3c8bed5..acdefade0748a 100644
--- a/clang/test/AST/arithmetic-fence-builtin.c
+++ b/clang/test/AST/arithmetic-fence-builtin.c
@@ -2,30 +2,54 @@
 // RUN: %clang_cc1 -ast-dump -triple i386-pc-linux-gnu %s \
 // RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK1
 //
+// RUN: %clang_cc1 -ast-dump -triple aarch64-unknown-linux-gnu %s \
+// RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK1
+//
 // RUN: %clang_cc1 -ast-dump -triple i386-pc-linux-gnu -DFAST -mreassociate %s 
\
 // RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK1
 //
+// RUN: %clang_cc1 -ast-dump -triple aarch64-unknown-linux-gnu -DFAST 
-mreassociate %s \
+// RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK1
+//
 // RUN: %clang_cc1 -ast-dump -triple i386-pc-linux-gnu -DFAST -mreassociate %s 
\
 // RUN: -fprotect-parens \
 // RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK2
 //
+// RUN: %clang_cc1 -ast-dump -triple aarch64-unknown-linux-gnu -DFAST 
-mreassociate %s \
+// RUN: -fprotect-parens \
+// RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK2
+//
 // Tests with serialization:
 // RUN: %clang_cc1 -ast-dump -triple i386-pc-linux-gnu -emit-pch -o %t %s
 // RUN: %clang_cc1 -triple i386-pc-linux-gnu -include-pch %t -ast-dump-all 
/dev/null \
 // RUN: | FileCheck %s --strict-whitespace
 //
+// RUN: %clang_cc1 -ast-dump -triple aarch64-unknown-linux-gnu -emit-pch -o %t 
%s
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -include-pch %t 
-ast-dump-all /dev/null \
+// RUN: | FileCheck %s --strict-whitespace
+//
 // RUN: %clang_cc1 -ast-dump -triple i386-pc-linux-gnu -DFAST -mreassociate %s 
\
 // RUN: -emit-pch -o %t
 // RUN: %clang_cc1 -triple i386-pc-linux-gnu -include-pch %t -ast-dump-all 
/dev/null \
 // RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK1
 //
+// RUN: %clang_cc1 -ast-dump -triple aarch64-unknown-linux-gnu -DFAST 
-mreassociate %s \
+// RUN: -emit-pch -o %t
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -include-pch %t 
-ast-dump-all /dev/null \
+// RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK1
+//
 // RUN: %clang_cc1 -ast-dump -triple i386-pc-linux-gnu -DFAST -mreassociate %s 
\
 // RUN: -fprotect-parens \
 // RUN: -emit-pch -o %t
 // RUN: %clang_cc1 -triple i3

[clang] 0fd9c37 - [Clang] Treat `std::forward_like` as builtin

2023-01-28 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-01-29T00:13:46Z
New Revision: 0fd9c37d8cf20d1ee42263872ab2135265c3ac3d

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

LOG: [Clang] Treat `std::forward_like` as builtin

This diff extends D123345 by adding support for std::forward_like.

Test plan: ninja check-clang check-clang-tools check-llvm

Differential revision: https://reviews.llvm.org/D142430

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/Builtins.def
clang/lib/AST/ExprConstant.cpp
clang/lib/Analysis/BodyFarm.cpp
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaDecl.cpp
clang/test/CodeGenCXX/builtin-std-move.cpp
clang/test/SemaCXX/attr-lifetimebound.cpp
clang/test/SemaCXX/builtin-std-move-nobuiltin.cpp
clang/test/SemaCXX/builtin-std-move.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 28345f144fd33..4c72ec64f6e19 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -97,6 +97,9 @@ C2x Feature Support
 
 C++ Language Changes in Clang
 -
+- Improved ``-O0`` code generation for calls to ``std::forward_like``. 
Similarly to
+  ``std::move, std::forward`` et al. it is now treated as a compiler builtin 
and implemented
+  directly rather than instantiating the definition from the standard library.
 
 C++20 Feature Support
 ^

diff  --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index 41f1245564465..6b54ff7c40e82 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -1565,6 +1565,7 @@ LIBBUILTIN(addressof, "v*v&", "zfncThE", MEMORY, CXX_LANG)
 LANGBUILTIN(__addressof, "v*v&", "zfncTE", CXX_LANG)
 LIBBUILTIN(as_const, "v&v&", "zfncThE", UTILITY, CXX_LANG)
 LIBBUILTIN(forward, "v&v&", "zfncThE", UTILITY, CXX_LANG)
+LIBBUILTIN(forward_like, "v&v&", "zfncThE", UTILITY, CXX_LANG)
 LIBBUILTIN(move, "v&v&", "zfncThE", UTILITY, CXX_LANG)
 LIBBUILTIN(move_if_noexcept, "v&v&", "zfncThE", UTILITY, CXX_LANG)
 

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 912a210fd2545..2a5b5c3520b4d 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8339,6 +8339,7 @@ bool LValueExprEvaluator::VisitCallExpr(const CallExpr 
*E) {
 return false;
   case Builtin::BIas_const:
   case Builtin::BIforward:
+  case Builtin::BIforward_like:
   case Builtin::BImove:
   case Builtin::BImove_if_noexcept:
 if (cast(E->getCalleeDecl())->isConstexpr())

diff  --git a/clang/lib/Analysis/BodyFarm.cpp b/clang/lib/Analysis/BodyFarm.cpp
index c05534886cb50..b989b8422cfc8 100644
--- a/clang/lib/Analysis/BodyFarm.cpp
+++ b/clang/lib/Analysis/BodyFarm.cpp
@@ -717,6 +717,7 @@ Stmt *BodyFarm::getBody(const FunctionDecl *D) {
 switch (BuiltinID) {
 case Builtin::BIas_const:
 case Builtin::BIforward:
+case Builtin::BIforward_like:
 case Builtin::BImove:
 case Builtin::BImove_if_noexcept:
   FF = create_std_move_forward;

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index f72e04a425d9f..bf23774c3fe12 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -4674,6 +4674,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   case Builtin::BImove:
   case Builtin::BImove_if_noexcept:
   case Builtin::BIforward:
+  case Builtin::BIforward_like:
   case Builtin::BIas_const:
 return RValue::get(EmitLValue(E->getArg(0)).getPointer(*this));
   case Builtin::BI__GetExceptionInfo: {

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index ea21171aaac62..d414dcf549f38 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2471,6 +2471,7 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, 
unsigned BuiltinID,
   case Builtin::BIaddressof:
   case Builtin::BI__addressof:
   case Builtin::BIforward:
+  case Builtin::BIforward_like:
   case Builtin::BImove:
   case Builtin::BImove_if_noexcept:
   case Builtin::BIas_const: {

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b2ac4173410a8..6740a495a8a27 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -9556,6 +9556,7 @@ static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl 
*FD,
   case Builtin::BIaddressof:
   case Builtin::BI__addressof:
   case Builtin::BIforward:
+  case Builtin::BIforward_like:
   case Builtin::BImove:
   case Builtin::BImove_if_noexcept:
   case Builtin::BIas_const: {
@@ -16196,6 +16197,7 @@ void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) 

[clang] 31b0be4 - [Clang] Add lifetimebound attribute to std::move/std::forward

2023-01-19 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-01-19T20:57:24Z
New Revision: 31b0be4eba9e8e9244799f0ebcb18175faff69ab

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

LOG: [Clang] Add lifetimebound attribute to std::move/std::forward

Clang now automatically adds [[clang::lifetimebound]] to the parameters of
std::move, std::forward et al, this enables Clang to diagnose more cases
where the returned reference outlives the object.
Associated GitHub issue: https://github.com/llvm/llvm-project/issues/60020

Test plan: ninja check-clang check-all

Differential revision: https://reviews.llvm.org/D141744

Added: 


Modified: 
clang/docs/LanguageExtensions.rst
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDecl.cpp
clang/test/SemaCXX/attr-lifetimebound.cpp
clang/test/SemaCXX/builtin-std-move.cpp
clang/test/SemaCXX/builtins.cpp

Removed: 




diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index dbec1cd7c196..2e99a6072a94 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -2933,7 +2933,8 @@ implementation details of ``__sync_lock_test_and_set()``. 
 The
 ``__builtin_addressof`` performs the functionality of the built-in ``&``
 operator, ignoring any ``operator&`` overload.  This is useful in constant
 expressions in C++11, where there is no other way to take the address of an
-object that overloads ``operator&``.
+object that overloads ``operator&``. Clang automatically adds
+``[[clang::lifetimebound]]`` to the parameter of ``__builtin_addressof``.
 
 **Example of use**:
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 97ce8866d3cc..541f8e1eb671 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -458,6 +458,9 @@ Improvements to Clang's diagnostics
   only when ``x`` is a string literal.
 - Clang will now reject the GNU extension address of label in coroutines 
explicitly.
   This fixes `Issue 56436 
`_.
+- Clang now automatically adds ``[[clang::lifetimebound]]`` to the parameters 
of
+  ``std::move, std::forward`` et al, this enables Clang to diagnose more cases
+  where the returned reference outlives the object.
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index faa75f671fde..3ae3e33a6704 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -16182,6 +16182,24 @@ void Sema::AddKnownFunctionAttributes(FunctionDecl 
*FD) {
 default:
   break;
 }
+
+// Add lifetime attribute to std::move, std::fowrard et al.
+switch (BuiltinID) {
+case Builtin::BIaddressof:
+case Builtin::BI__addressof:
+case Builtin::BI__builtin_addressof:
+case Builtin::BIas_const:
+case Builtin::BIforward:
+case Builtin::BImove:
+case Builtin::BImove_if_noexcept:
+  if (ParmVarDecl *P = FD->getParamDecl(0u);
+  !P->hasAttr())
+P->addAttr(
+LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
+  break;
+default:
+  break;
+}
   }
 
   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);

diff  --git a/clang/test/SemaCXX/attr-lifetimebound.cpp 
b/clang/test/SemaCXX/attr-lifetimebound.cpp
index 90124c323d02..22cf5d0ab001 100644
--- a/clang/test/SemaCXX/attr-lifetimebound.cpp
+++ b/clang/test/SemaCXX/attr-lifetimebound.cpp
@@ -113,3 +113,77 @@ namespace p0936r0_examples {
   std::map m;
   const std::string &v = findOrDefault(m, "foo"s, "bar"s); // expected-warning 
{{temporary bound to local reference 'v'}}
 }
+
+// definitions for std::move, std::forward et al.
+namespace std {
+inline namespace foo {
+
+template  struct remove_reference {
+typedef T type;
+};
+template  struct remove_reference {
+typedef T type;
+};
+template  struct remove_reference {
+typedef T type;
+};
+
+template  constexpr typename remove_reference::type &&move(T &&t) {
+return static_cast::type>(t);
+}
+
+template 
+constexpr T &&forward(typename remove_reference::type &t) {
+return static_cast(t);
+}
+
+template 
+constexpr T &&forward(typename remove_reference::type &&t) {
+return static_cast(t);
+}
+
+template  constexpr const T &as_const(T &x) { return x; }
+
+template  struct PickRef {
+using type = typename remove_reference::type &;
+};
+template  struct PickRef {
+using type = typename remove_reference::type &&;
+};
+
+template 
+auto move_if_noexcept(T &t) ->
+typename PickRef(t)))>::type {
+return static_cast<
+typename PickRef(t)))>::type>(t);
+}
+
+template  T *addressof(T &arg) {
+return reinterpret_cast(
+  

[clang] f102fe7 - Revert "Revert "[opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm""

2022-11-18 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-18T08:58:31Z
New Revision: f102fe73044062542f022182381c17172a999db2

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

LOG: Revert "Revert "[opt][clang] Enable using -module-summary/-flto=thin with 
-S/-emit-llvm""

This reverts commit 7f608a2497c7578b9f3ca98014176ab95cffe3c0
and removes the dependency of Object on IRPrinter.

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/split-lto-unit.c
llvm/include/llvm/IRPrinter/IRPrintingPasses.h
llvm/lib/IRPrinter/CMakeLists.txt
llvm/lib/IRPrinter/IRPrintingPasses.cpp
llvm/test/Bitcode/thinlto-function-summary.ll
llvm/tools/opt/NewPMDriver.cpp
utils/bazel/llvm-project-overlay/llvm/BUILD.bazel

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 9c677140b4a5d..d6a7a9800ec58 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -983,19 +983,24 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
-  switch (Action) {
-  case Backend_EmitBC:
+  if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
-  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
-ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
-if (!ThinLinkOS)
-  return;
-  }
   if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  CodeGenOpts.EnableSplitLTOUnit);
-  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
-   : nullptr));
+  if (Action == Backend_EmitBC) {
+if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
+  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
+  if (!ThinLinkOS)
+return;
+}
+MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
&ThinLinkOS->os()
+ : nullptr));
+  } else {
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+/*EmitLTOSummary=*/true));
+  }
+
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
@@ -1007,17 +1012,13 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-  MPM.addPass(
-  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 
EmitLTOSummary));
+  if (Action == Backend_EmitBC)
+MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
+  EmitLTOSummary));
+  else
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+EmitLTOSummary));
 }
-break;
-
-  case Backend_EmitLL:
-MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
-break;
-
-  default:
-break;
   }
 
   // Now that we have all of the passes ready, run them.

diff  --git a/clang/test/CodeGen/split-lto-unit.c 
b/clang/test/CodeGen/split-lto-unit.c
index 941aebafd01b3..b1560b61f3e30 100644
--- a/clang/test/CodeGen/split-lto-unit.c
+++ b/clang/test/CodeGen/split-lto-unit.c
@@ -1,12 +1,15 @@
 // ; Check that -flto=thin without -fsplit-lto-unit has EnableSplitLTOUnit = 0
 // RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
+// RUN: %clang_cc1 -flto=thin -emit-llvm < %s | FileCheck %s
 // CHECK: !{i32 1, !"EnableSplitLTOUnit", i32 0}
 //
 // ; Check that -flto=thin with -fsplit-lto-unit has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm-bc < %s | llvm-dis 
-o - | FileCheck %s --check-prefix=SPLIT
+// RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm < %s | FileCheck %s 
--check-prefix=SPLIT
 // SPLIT: !{i32 1, !"EnableSplitLTOUnit", i32 1}
 //
 // ; Check that regular LTO has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
+// RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm < %s | 
FileCheck %s --implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
 
 int main(void) {}

diff  --git a/llvm/include/llvm/IRPrinter/IRPrintingPasses.h 
b/llvm/include/llvm/IRPrinter/IRPrintingPasses.h
index 6cfa7a87af933..8eb7973365172 100644

[clang] 34ab474 - [opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm

2022-11-17 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-18T05:04:07Z
New Revision: 34ab474348e2623cc67abddb7bb662385297ac65

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

LOG: [opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm

Enable using -module-summary with -S
(similarly to what currently can be achieved with opt  -o - | llvm-dis).
This is a recommit of ef9e62469.

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D137768

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/split-lto-unit.c
llvm/include/llvm/IRPrinter/IRPrintingPasses.h
llvm/lib/IRPrinter/CMakeLists.txt
llvm/lib/IRPrinter/IRPrintingPasses.cpp
llvm/test/Bitcode/thinlto-function-summary.ll
llvm/tools/opt/NewPMDriver.cpp
utils/bazel/llvm-project-overlay/llvm/BUILD.bazel

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 9c677140b4a5d..d6a7a9800ec58 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -983,19 +983,24 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
-  switch (Action) {
-  case Backend_EmitBC:
+  if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
-  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
-ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
-if (!ThinLinkOS)
-  return;
-  }
   if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  CodeGenOpts.EnableSplitLTOUnit);
-  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
-   : nullptr));
+  if (Action == Backend_EmitBC) {
+if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
+  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
+  if (!ThinLinkOS)
+return;
+}
+MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
&ThinLinkOS->os()
+ : nullptr));
+  } else {
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+/*EmitLTOSummary=*/true));
+  }
+
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
@@ -1007,17 +1012,13 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-  MPM.addPass(
-  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 
EmitLTOSummary));
+  if (Action == Backend_EmitBC)
+MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
+  EmitLTOSummary));
+  else
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+EmitLTOSummary));
 }
-break;
-
-  case Backend_EmitLL:
-MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
-break;
-
-  default:
-break;
   }
 
   // Now that we have all of the passes ready, run them.

diff  --git a/clang/test/CodeGen/split-lto-unit.c 
b/clang/test/CodeGen/split-lto-unit.c
index 941aebafd01b3..b1560b61f3e30 100644
--- a/clang/test/CodeGen/split-lto-unit.c
+++ b/clang/test/CodeGen/split-lto-unit.c
@@ -1,12 +1,15 @@
 // ; Check that -flto=thin without -fsplit-lto-unit has EnableSplitLTOUnit = 0
 // RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
+// RUN: %clang_cc1 -flto=thin -emit-llvm < %s | FileCheck %s
 // CHECK: !{i32 1, !"EnableSplitLTOUnit", i32 0}
 //
 // ; Check that -flto=thin with -fsplit-lto-unit has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm-bc < %s | llvm-dis 
-o - | FileCheck %s --check-prefix=SPLIT
+// RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm < %s | FileCheck %s 
--check-prefix=SPLIT
 // SPLIT: !{i32 1, !"EnableSplitLTOUnit", i32 1}
 //
 // ; Check that regular LTO has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
+// RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm < %s | 
FileCheck %s --implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
 
 int main(void) {}

diff  --git a/llvm/include/llvm/IRPrinter/IRPrintingPas

[clang] 7059a6c - [IR] Split out IR printing passes into IRPrinter

2022-11-17 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-18T01:47:56Z
New Revision: 7059a6c32cfad8f272fad47265e3890cd7a1a7e1

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

LOG: [IR] Split out IR printing passes into IRPrinter

This diff splits out (from LLVMCore) IR printing passes into IRPrinter.
This structure is similar to what we already have for IRReader and
enables us to avoid circular dependencies between LLVMCore and Analysis
(this is a preparation for https://reviews.llvm.org/D137768).
The legacy interface is left unchanged, once the legacy pass manager
is removed (in the future) we will be able to clean it up further.
The bazel build configuration has been updated as well.

Test plan:
1/ Tested the following cmake configurations: static/dynamic linking * lld/gold 
* clang/gcc
2/ bazel build --config=generic_clang @llvm-project//...

Differential revision: https://reviews.llvm.org/D138081

Added: 
llvm/include/llvm/IRPrinter/IRPrintingPasses.h
llvm/lib/IRPrinter/CMakeLists.txt
llvm/lib/IRPrinter/IRPrintingPasses.cpp

Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/CodeGen/CMakeLists.txt
llvm/include/llvm/CodeGen/CodeGenPassBuilder.h
llvm/include/llvm/IR/IRPrintingPasses.h
llvm/lib/CMakeLists.txt
llvm/lib/IR/IRPrintingPasses.cpp
llvm/lib/Passes/CMakeLists.txt
llvm/lib/Passes/PassBuilder.cpp
llvm/lib/Target/DirectX/DirectXTargetMachine.cpp
llvm/tools/llc/llc.cpp
llvm/tools/opt/CMakeLists.txt
llvm/tools/opt/NewPMDriver.cpp
utils/bazel/llvm-project-overlay/clang/BUILD.bazel
utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
utils/bazel/llvm-project-overlay/mlir/BUILD.bazel

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 8498ca2e63388..9c677140b4a5d 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -31,7 +31,7 @@
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/DebugInfo.h"
-#include "llvm/IR/IRPrintingPasses.h"
+#include "llvm/IRPrinter/IRPrintingPasses.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/ModuleSummaryIndex.h"

diff  --git a/clang/lib/CodeGen/CMakeLists.txt 
b/clang/lib/CodeGen/CMakeLists.txt
index a97042ee2008b..802c34b5b7e19 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -10,6 +10,7 @@ set(LLVM_LINK_COMPONENTS
   FrontendHLSL
   FrontendOpenMP
   IPO
+  IRPrinter
   IRReader
   AggressiveInstCombine
   InstCombine

diff  --git a/llvm/include/llvm/CodeGen/CodeGenPassBuilder.h 
b/llvm/include/llvm/CodeGen/CodeGenPassBuilder.h
index 15f46cf46ba7e..95625d13021eb 100644
--- a/llvm/include/llvm/CodeGen/CodeGenPassBuilder.h
+++ b/llvm/include/llvm/CodeGen/CodeGenPassBuilder.h
@@ -29,7 +29,7 @@
 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
 #include "llvm/CodeGen/ReplaceWithVeclib.h"
 #include "llvm/CodeGen/UnreachableBlockElim.h"
-#include "llvm/IR/IRPrintingPasses.h"
+#include "llvm/IRPrinter/IRPrintingPasses.h"
 #include "llvm/IR/PassManager.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/MC/MCAsmInfo.h"

diff  --git a/llvm/include/llvm/IR/IRPrintingPasses.h 
b/llvm/include/llvm/IR/IRPrintingPasses.h
index 3fba5b81e37a9..942e420a2d659 100644
--- a/llvm/include/llvm/IR/IRPrintingPasses.h
+++ b/llvm/include/llvm/IR/IRPrintingPasses.h
@@ -7,18 +7,14 @@
 
//===--===//
 /// \file
 ///
-/// This file defines passes to print out IR in various granularities. The
-/// PrintModulePass pass simply prints out the entire module when it is
-/// executed. The PrintFunctionPass class is designed to be pipelined with
-/// other FunctionPass's, and prints out the functions of the module as they
-/// are processed.
+/// This file contains an interface for creating legacy passes to print out IR
+/// in various granularities.
 ///
 
//===--===//
 
 #ifndef LLVM_IR_IRPRINTINGPASSES_H
 #define LLVM_IR_IRPRINTINGPASSES_H
 
-#include "llvm/IR/PassManager.h"
 #include 
 
 namespace llvm {
@@ -50,40 +46,6 @@ void printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef 
Name);
 /// Return true if a pass is for IR printing.
 bool isIRPrintingPass(Pass *P);
 
-/// Pass for printing a Module as LLVM's text IR assembly.
-///
-/// Note: This pass is for use with the new pass manager. Use the create...Pass
-/// functions above to create passes for use with the legacy pass manager.
-class PrintModulePass : public PassInfoMixin {
-  raw_ostream &OS;
-  std::string Banner;
-  bool ShouldPreserveUseListOrder;
-
-public:
-  PrintModulePass();
-  PrintModulePass(raw_ostream &O

[clang-tools-extra] 2483a7f - [include-cleaner] Fix the build of include-cleaner with LLVM_BUILD_LLVM_DYLIB=ON

2022-11-17 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-18T00:54:45Z
New Revision: 2483a7fffbdf8e04addfbbf9f333155edc2c0346

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

LOG: [include-cleaner] Fix the build of include-cleaner with 
LLVM_BUILD_LLVM_DYLIB=ON

Added: 


Modified: 
clang-tools-extra/include-cleaner/tool/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/tool/CMakeLists.txt 
b/clang-tools-extra/include-cleaner/tool/CMakeLists.txt
index 3fc8c44081cd2..3b9b03141ce1b 100644
--- a/clang-tools-extra/include-cleaner/tool/CMakeLists.txt
+++ b/clang-tools-extra/include-cleaner/tool/CMakeLists.txt
@@ -5,6 +5,7 @@ add_clang_tool(clang-include-cleaner IncludeCleaner.cpp)
 clang_target_link_libraries(clang-include-cleaner PRIVATE
   clangBasic
   clangFrontend
+  clangLex
   clangSerialization
   clangTooling
   )



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


[clang] bf8381a - [opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm

2022-11-14 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-14T23:24:08Z
New Revision: bf8381a8bce28fc69857645cc7e84a72317e693e

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

LOG: [opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm

Enable using -module-summary with -S
(similarly to what currently can be achieved with opt  -o - | llvm-dis).
This is a recommit of ef9e62469.

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D137768

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/split-lto-unit.c
llvm/include/llvm/IR/IRPrintingPasses.h
llvm/lib/Analysis/ModuleSummaryAnalysis.cpp
llvm/lib/IR/IRPrintingPasses.cpp
llvm/test/Bitcode/thinlto-function-summary.ll
llvm/tools/opt/NewPMDriver.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 41f9ce3a009da..26633f8007037 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -978,19 +978,24 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
-  switch (Action) {
-  case Backend_EmitBC:
+  if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
-  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
-ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
-if (!ThinLinkOS)
-  return;
-  }
   if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  CodeGenOpts.EnableSplitLTOUnit);
-  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
-   : nullptr));
+  if (Action == Backend_EmitBC) {
+if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
+  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
+  if (!ThinLinkOS)
+return;
+}
+MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
&ThinLinkOS->os()
+ : nullptr));
+  } else {
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+true /* EmitLTOSummary */));
+  }
+
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
@@ -1002,17 +1007,13 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-  MPM.addPass(
-  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 
EmitLTOSummary));
+  if (Action == Backend_EmitBC)
+MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
+  EmitLTOSummary));
+  else
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+EmitLTOSummary));
 }
-break;
-
-  case Backend_EmitLL:
-MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
-break;
-
-  default:
-break;
   }
 
   // Now that we have all of the passes ready, run them.

diff  --git a/clang/test/CodeGen/split-lto-unit.c 
b/clang/test/CodeGen/split-lto-unit.c
index 941aebafd01b3..b1560b61f3e30 100644
--- a/clang/test/CodeGen/split-lto-unit.c
+++ b/clang/test/CodeGen/split-lto-unit.c
@@ -1,12 +1,15 @@
 // ; Check that -flto=thin without -fsplit-lto-unit has EnableSplitLTOUnit = 0
 // RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
+// RUN: %clang_cc1 -flto=thin -emit-llvm < %s | FileCheck %s
 // CHECK: !{i32 1, !"EnableSplitLTOUnit", i32 0}
 //
 // ; Check that -flto=thin with -fsplit-lto-unit has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm-bc < %s | llvm-dis 
-o - | FileCheck %s --check-prefix=SPLIT
+// RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm < %s | FileCheck %s 
--check-prefix=SPLIT
 // SPLIT: !{i32 1, !"EnableSplitLTOUnit", i32 1}
 //
 // ; Check that regular LTO has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
+// RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm < %s | 
FileCheck %s --implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
 
 int main(void) {}

diff  --git a/llvm/include/llvm/IR/IRPrintingPasses.h 
b/llvm/include/llvm/IR/IRPrintingPasses.h
index 3fba5b81

[clang] 8c15c17 - Revert "[opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm"

2022-11-14 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-14T21:31:30Z
New Revision: 8c15c17e3ba7916b2efb2a100495c710bae04fb6

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

LOG: Revert "[opt][clang] Enable using -module-summary/-flto=thin with 
-S/-emit-llvm"

This reverts commit ef9e624694c0f125c53f7d0d3472fd486bada57d
for further investigation offline.
It appears to break the buildbot
llvm-clang-x86_64-sie-ubuntu-fast.

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/split-lto-unit.c
llvm/include/llvm/IR/IRPrintingPasses.h
llvm/lib/IR/CMakeLists.txt
llvm/lib/IR/IRPrintingPasses.cpp
llvm/test/Bitcode/thinlto-function-summary.ll
llvm/tools/opt/NewPMDriver.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 26633f8007037..41f9ce3a009da 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -978,24 +978,19 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
-  if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
+  switch (Action) {
+  case Backend_EmitBC:
 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
+  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
+ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
+if (!ThinLinkOS)
+  return;
+  }
   if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  CodeGenOpts.EnableSplitLTOUnit);
-  if (Action == Backend_EmitBC) {
-if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
-  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
-  if (!ThinLinkOS)
-return;
-}
-MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
&ThinLinkOS->os()
- : nullptr));
-  } else {
-MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
-true /* EmitLTOSummary */));
-  }
-
+  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
+   : nullptr));
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
@@ -1007,13 +1002,17 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-  if (Action == Backend_EmitBC)
-MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
-  EmitLTOSummary));
-  else
-MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
-EmitLTOSummary));
+  MPM.addPass(
+  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 
EmitLTOSummary));
 }
+break;
+
+  case Backend_EmitLL:
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
+break;
+
+  default:
+break;
   }
 
   // Now that we have all of the passes ready, run them.

diff  --git a/clang/test/CodeGen/split-lto-unit.c 
b/clang/test/CodeGen/split-lto-unit.c
index b1560b61f3e30..941aebafd01b3 100644
--- a/clang/test/CodeGen/split-lto-unit.c
+++ b/clang/test/CodeGen/split-lto-unit.c
@@ -1,15 +1,12 @@
 // ; Check that -flto=thin without -fsplit-lto-unit has EnableSplitLTOUnit = 0
 // RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
-// RUN: %clang_cc1 -flto=thin -emit-llvm < %s | FileCheck %s
 // CHECK: !{i32 1, !"EnableSplitLTOUnit", i32 0}
 //
 // ; Check that -flto=thin with -fsplit-lto-unit has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm-bc < %s | llvm-dis 
-o - | FileCheck %s --check-prefix=SPLIT
-// RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm < %s | FileCheck %s 
--check-prefix=SPLIT
 // SPLIT: !{i32 1, !"EnableSplitLTOUnit", i32 1}
 //
 // ; Check that regular LTO has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
-// RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm < %s | 
FileCheck %s --implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
 
 int main(void) {}

diff  --git a/llvm/include/llvm/IR/IRPrintingPasses.h 
b/llvm/include/llvm/IR/IRPrintingPasses.h
index 5f4880643c52d..3fba5b81e37a9 100644
--- a/llvm/include/llvm/IR/IRPrintingPasses

[clang] ef9e624 - [opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm

2022-11-14 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-14T21:11:07Z
New Revision: ef9e624694c0f125c53f7d0d3472fd486bada57d

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

LOG: [opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm

Enable using -module-summary with -S
(similarly to what currently can be achieved with opt  -o - | llvm-dis).

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D137768

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/split-lto-unit.c
llvm/include/llvm/IR/IRPrintingPasses.h
llvm/lib/IR/CMakeLists.txt
llvm/lib/IR/IRPrintingPasses.cpp
llvm/test/Bitcode/thinlto-function-summary.ll
llvm/tools/opt/NewPMDriver.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 41f9ce3a009da..26633f8007037 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -978,19 +978,24 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
-  switch (Action) {
-  case Backend_EmitBC:
+  if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
-  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
-ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
-if (!ThinLinkOS)
-  return;
-  }
   if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  CodeGenOpts.EnableSplitLTOUnit);
-  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
-   : nullptr));
+  if (Action == Backend_EmitBC) {
+if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
+  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
+  if (!ThinLinkOS)
+return;
+}
+MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
&ThinLinkOS->os()
+ : nullptr));
+  } else {
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+true /* EmitLTOSummary */));
+  }
+
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
@@ -1002,17 +1007,13 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-  MPM.addPass(
-  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 
EmitLTOSummary));
+  if (Action == Backend_EmitBC)
+MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
+  EmitLTOSummary));
+  else
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+EmitLTOSummary));
 }
-break;
-
-  case Backend_EmitLL:
-MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
-break;
-
-  default:
-break;
   }
 
   // Now that we have all of the passes ready, run them.

diff  --git a/clang/test/CodeGen/split-lto-unit.c 
b/clang/test/CodeGen/split-lto-unit.c
index 941aebafd01b3..b1560b61f3e30 100644
--- a/clang/test/CodeGen/split-lto-unit.c
+++ b/clang/test/CodeGen/split-lto-unit.c
@@ -1,12 +1,15 @@
 // ; Check that -flto=thin without -fsplit-lto-unit has EnableSplitLTOUnit = 0
 // RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
+// RUN: %clang_cc1 -flto=thin -emit-llvm < %s | FileCheck %s
 // CHECK: !{i32 1, !"EnableSplitLTOUnit", i32 0}
 //
 // ; Check that -flto=thin with -fsplit-lto-unit has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm-bc < %s | llvm-dis 
-o - | FileCheck %s --check-prefix=SPLIT
+// RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm < %s | FileCheck %s 
--check-prefix=SPLIT
 // SPLIT: !{i32 1, !"EnableSplitLTOUnit", i32 1}
 //
 // ; Check that regular LTO has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
+// RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm < %s | 
FileCheck %s --implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
 
 int main(void) {}

diff  --git a/llvm/include/llvm/IR/IRPrintingPasses.h 
b/llvm/include/llvm/IR/IRPrintingPasses.h
index 3fba5b81e37a9..5f4880643c52d 100644
--- a/llvm/include/llv

[clang-tools-extra] 29e4606 - [clang-tidy] Skip template ctors in modernize-use-equals-default

2022-10-27 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-10-28T05:30:19Z
New Revision: 29e4606ced7284c87a88fdcd34a6d179a1350fe9

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

LOG: [clang-tidy] Skip template ctors in modernize-use-equals-default

Skip template ctors in modernize-use-equals-default,
such constructors may be enabled/disabled via SFINAE,
it is not safe to make them "= default".

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D136797

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index 60e0f80da2878..a545fae26a3bb 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -241,7 +241,9 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   this);
   Finder->addMatcher(
   cxxConstructorDecl(
-  unless(hasParent(IsUnionLikeClass)), isDefinition(),
+  unless(
+  hasParent(decl(anyOf(IsUnionLikeClass, 
functionTemplateDecl(),
+  isDefinition(),
   anyOf(
   // Default constructor.
   allOf(unless(hasAnyConstructorInitializer(isWritten())),
@@ -257,8 +259,9 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   this);
   // Copy-assignment operator.
   Finder->addMatcher(
-  cxxMethodDecl(unless(hasParent(IsUnionLikeClass)), isDefinition(),
-isCopyAssignmentOperator(),
+  cxxMethodDecl(unless(hasParent(
+decl(anyOf(IsUnionLikeClass, 
functionTemplateDecl(),
+isDefinition(), isCopyAssignmentOperator(),
 // isCopyAssignmentOperator() allows the parameter to be
 // passed by value, and in this case it cannot be
 // defaulted.

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index d7ae8dfdcf364..c5cc967259afe 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -158,9 +158,9 @@ Changes in existing checks
   The check now skips unions/union-like classes since in this case a default 
constructor
   with empty body is not equivalent to the explicitly defaulted one, variadic 
constructors
   since they cannot be explicitly defaulted. The check also skips copy 
assignment operators
-  with nonstandard return types, private/protected default constructors for 
C++17 or earlier.
-  The automatic fixit has been adjusted to avoid adding superfluous semicolon.
-  The check is restricted to C++11 or later.
+  with nonstandard return types, template constructors, private/protected 
default constructors
+  for C++17 or earlier. The automatic fixit has been adjusted to avoid adding 
superfluous
+  semicolon. The check is restricted to C++11 or later.
 
 - Change the default behavior of :doc:`readability-avoid-const-params-in-decls
   ` to not

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
index 7a21ebe439cc1..cc5d379b3c3de 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
@@ -58,6 +58,18 @@ struct VA {
   VA(...) {}
 };
 
+// Skip template constructors.
+struct TC {
+  template 
+  TC() {}
+
+  template 
+  TC(const TC &) {}
+
+  template 
+  TC& operator = (const TC &) { return *this; }
+};
+
 // Initializer or arguments.
 class IA {
 public:



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


[clang-tools-extra] 6c07bda - [clang-tidy] Avoid adding unnecessary semicolon in modernize-use-equals-default

2022-10-21 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-10-22T00:42:50Z
New Revision: 6c07bda7a75c68aa14a1e5f1ca0eac9ba6220cbb

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

LOG: [clang-tidy] Avoid adding unnecessary semicolon in 
modernize-use-equals-default

Adjust the automatic fixit to avoid adding superfluous semicolon.

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D136399

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index e72ea76114783..60e0f80da2878 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -337,10 +337,13 @@ void UseEqualsDefaultCheck::check(const 
MatchFinder::MatchResult &Result) {
   Diag << MemberType;
 
   if (ApplyFix) {
+SourceLocation UnifiedEnd = utils::lexer::getUnifiedEndLoc(
+*Body, Result.Context->getSourceManager(),
+Result.Context->getLangOpts());
 // Skipping comments, check for a semicolon after Body->getSourceRange()
 Optional Token = utils::lexer::findNextTokenSkippingComments(
-Body->getSourceRange().getEnd().getLocWithOffset(1),
-Result.Context->getSourceManager(), Result.Context->getLangOpts());
+UnifiedEnd, Result.Context->getSourceManager(),
+Result.Context->getLangOpts());
 StringRef Replacement =
 Token && Token->is(tok::semi) ? "= default" : "= default;";
 Diag << FixItHint::CreateReplacement(Body->getSourceRange(), Replacement)

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 68995a9d3f190..d7ae8dfdcf364 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -159,6 +159,7 @@ Changes in existing checks
   with empty body is not equivalent to the explicitly defaulted one, variadic 
constructors
   since they cannot be explicitly defaulted. The check also skips copy 
assignment operators
   with nonstandard return types, private/protected default constructors for 
C++17 or earlier.
+  The automatic fixit has been adjusted to avoid adding superfluous semicolon.
   The check is restricted to C++11 or later.
 
 - Change the default behavior of :doc:`readability-avoid-const-params-in-decls

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
index 6482c3a82241e..7a21ebe439cc1 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
@@ -91,7 +91,7 @@ class CM {
 // Private constructor/destructor.
 class Priv {
   Priv();
-  ~Priv() {};
+  ~Priv() {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
   // CHECK-FIXES: ~Priv() = default;
 };
@@ -100,14 +100,28 @@ Priv::Priv() {}
 // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use '= default'
 // CHECK-FIXES: Priv::Priv() = default;
 
+struct SemiColon {
+  SemiColon() {};
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
+  // CHECK-FIXES: SemiColon() = default;{{$}}
+};
+
+struct SemiColonOutOfLine {
+  SemiColonOutOfLine();
+};
+
+SemiColonOutOfLine::SemiColonOutOfLine() {};
+// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: use '= default'
+// CHECK-FIXES: SemiColonOutOfLine::SemiColonOutOfLine() = default;{{$}}
+
 // struct.
 struct ST {
   ST() {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
-  // CHECK-FIXES: ST() = default;
+  // CHECK-FIXES: ST() = default;{{$}}
   ~ST() {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
-  // CHECK-FIXES: ST() = default;
+  // CHECK-FIXES: ST() = default;{{$}}
 };
 
 // Deleted constructor/destructor.
@@ -200,7 +214,13 @@ struct DC : KW {
   DC() : KW() {}
   ~DC() override {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
-  // CHECK-FIXES: ~DC() override = default;
+  // CHECK-FIXES: ~DC() override = default;{{$}}
+};
+
+struct OverrideWithSemiColon : KW {
+  ~OverrideWithSemiColon() override {};
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
+  // CHECK-FIXES: ~OverrideWithSemiColon() override = default;{{$}}
 };
 
 struct Comments {



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


[clang-tools-extra] 90d42b1 - [clang-tidy] Skip private default ctors in modernize-use-equals-default

2022-10-20 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-10-20T22:04:33Z
New Revision: 90d42b1cab04b76e9e934f1e5076f014d1195e72

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

LOG: [clang-tidy] Skip private default ctors in modernize-use-equals-default

For c++17 (i.e. before c++20) making a private default ctor explicitly defaulted
might expose the previously intentionally disallowed initializations, e.g.
class Tag { Tag() {} friend class Widget; }; is not equivalent to
class Tag { Tag() = default; friend class Widget; };
since in the latter case Tag is treated as an aggregate despite having a 
declaration
of the default constructor. This diff makes modernize-use-equals-default skip
in-class empty nonpublic default ctors to avoid code breakages.

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D136224

Added: 

clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx17.cpp

clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx20.cpp

Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index 165840b72e7aa..e72ea76114783 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -217,6 +217,10 @@ void 
UseEqualsDefaultCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "IgnoreMacros", IgnoreMacros);
 }
 
+namespace {
+AST_MATCHER(CXXMethodDecl, isOutOfLine) { return Node.isOutOfLine(); }
+} // namespace
+
 void UseEqualsDefaultCheck::registerMatchers(MatchFinder *Finder) {
   // Skip unions/union-like classes since their constructors behave 
diff erently
   // when defaulted vs. empty.
@@ -224,6 +228,12 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   anyOf(isUnion(),
 has(fieldDecl(isImplicit(), hasType(cxxRecordDecl(isUnion()));
 
+  const LangOptions &LangOpts = getLangOpts();
+  auto IsPublicOrOutOfLineUntilCPP20 =
+  LangOpts.CPlusPlus20
+  ? cxxConstructorDecl()
+  : cxxConstructorDecl(anyOf(isOutOfLine(), isPublic()));
+
   // Destructor.
   Finder->addMatcher(
   cxxDestructorDecl(unless(hasParent(IsUnionLikeClass)), isDefinition())
@@ -235,7 +245,8 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   anyOf(
   // Default constructor.
   allOf(unless(hasAnyConstructorInitializer(isWritten())),
-unless(isVariadic()), parameterCountIs(0)),
+unless(isVariadic()), parameterCountIs(0),
+IsPublicOrOutOfLineUntilCPP20),
   // Copy constructor.
   allOf(isCopyConstructor(),
 // Discard constructors that can be used as a copy

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 735fedbce5496..68995a9d3f190 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -158,7 +158,8 @@ Changes in existing checks
   The check now skips unions/union-like classes since in this case a default 
constructor
   with empty body is not equivalent to the explicitly defaulted one, variadic 
constructors
   since they cannot be explicitly defaulted. The check also skips copy 
assignment operators
-  with nonstandard return types. The check is restricted to c++11-or-later.
+  with nonstandard return types, private/protected default constructors for 
C++17 or earlier.
+  The check is restricted to C++11 or later.
 
 - Change the default behavior of :doc:`readability-avoid-const-params-in-decls
   ` to not

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx17.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx17.cpp
new file mode 100644
index 0..3bbc6296816b1
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx17.cpp
@@ -0,0 +1,17 @@
+// RUN: %check_clang_tidy -std=c++17 %s modernize-use-equals-default %t -- -- 
-fno-delayed-template-parsing -fexceptions
+
+// Private constructor/destructor.
+class Priv {
+  Priv() {}
+  ~Priv() {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
+  // CHECK-FIXES: ~Priv() = default;
+};
+
+class PrivOutOfLine {
+  PrivOutOfLine();
+};
+
+PrivOutOfLine::PrivOutOfLine() {}
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: use '= defau

[clang-tools-extra] d4e8109 - [clang-tidy] Skip variadic ctors in modernize-use-equals-default

2022-09-30 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-09-30T22:16:28Z
New Revision: d4e81097ea3daf37b5480281a17ad5b20cd7ee8d

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

LOG: [clang-tidy] Skip variadic ctors in modernize-use-equals-default

Skip variadic constructors in modernize-use-equals-default
(such constructors cannot be explicitly defaulted).

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D134929

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index d5c402c4bdeb7..165840b72e7aa 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -235,7 +235,7 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   anyOf(
   // Default constructor.
   allOf(unless(hasAnyConstructorInitializer(isWritten())),
-parameterCountIs(0)),
+unless(isVariadic()), parameterCountIs(0)),
   // Copy constructor.
   allOf(isCopyConstructor(),
 // Discard constructors that can be used as a copy

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 9447cbfba73e0..8e65ed214a21d 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -145,9 +145,9 @@ Changes in existing checks
   check.
 
   The check now skips unions/union-like classes since in this case a default 
constructor
-  with empty body is not equivalent to the explicitly defaulted one. The check 
also skips
-  copy assignment operators with nonstandard return types. The check is 
restricted to
-  c++11-or-later.
+  with empty body is not equivalent to the explicitly defaulted one, variadic 
constructors
+  since they cannot be explicitly defaulted. The check also skips copy 
assignment operators
+  with nonstandard return types. The check is restricted to c++11-or-later.
 
 - Change the default behavior of :doc:`readability-avoid-const-params-in-decls
   ` to not

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
index ba252792cf3a6..493cfa21a8371 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
@@ -53,6 +53,11 @@ struct SU {
   };
 };
 
+// Skip variadic constructors.
+struct VA {
+  VA(...) {}
+};
+
 // Initializer or arguments.
 class IA {
 public:



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


[clang] b6965f7 - [IR] Add alignment for llvm.threadlocal.address

2022-09-13 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-09-13T23:10:55Z
New Revision: b6965f7246bba1b399755f56d8ae34893e815198

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

LOG: [IR] Add alignment for llvm.threadlocal.address

This diff sets the alignment attribute for the return value
and the argument of llvm.threadlocal.address.

(https://github.com/llvm/llvm-project/issues/57438)

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D133741

Added: 


Modified: 
clang/test/CodeGenCXX/cxx11-thread-local-instantiated.cpp
clang/test/CodeGenCXX/cxx11-thread-local-reference.cpp
clang/test/CodeGenCXX/cxx11-thread-local.cpp
clang/test/CodeGenCXX/cxx1y-variable-template.cpp
clang/test/CodeGenCXX/cxx2a-thread-local-constinit.cpp
clang/test/CodeGenCXX/microsoft-abi-thread-safe-statics.cpp
clang/test/CodeGenCXX/pr18635.cpp
clang/test/CodeGenCXX/threadlocal_address.cpp
clang/test/Modules/initializers.cpp
clang/test/OpenMP/parallel_copyin_codegen.cpp
clang/test/OpenMP/parallel_copyin_combined_codegen.c
clang/test/OpenMP/parallel_master_codegen.cpp
clang/test/OpenMP/teams_distribute_parallel_for_copyin_codegen.cpp
clang/test/OpenMP/threadprivate_codegen.cpp
llvm/lib/IR/IRBuilder.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/cxx11-thread-local-instantiated.cpp 
b/clang/test/CodeGenCXX/cxx11-thread-local-instantiated.cpp
index 46c16bdd94e39..fc3514a8b17da 100644
--- a/clang/test/CodeGenCXX/cxx11-thread-local-instantiated.cpp
+++ b/clang/test/CodeGenCXX/cxx11-thread-local-instantiated.cpp
@@ -17,7 +17,7 @@ S *current() { return TLS::mData; };
 
 // CHECK-LABEL: define weak_odr hidden {{.*}} @_ZTWN3TLSI1SE5mDataE() {{.*}} 
comdat {
 // CHECK: call void @_ZTHN3TLSI1SE5mDataE()
-// CHECK: [[TLSmData_ADDR:%[^ ]+]] = call ptr @llvm.threadlocal.address.p0(ptr 
@_ZN3TLSI1SE5mDataE)
+// CHECK: [[TLSmData_ADDR:%[^ ]+]] = call align 8 ptr 
@llvm.threadlocal.address.p0(ptr align 8 @_ZN3TLSI1SE5mDataE)
 // CHECK: ret {{.*}} [[TLSmData_ADDR]]
 
 // Unlike for a global, the global initialization function must not be in a

diff  --git a/clang/test/CodeGenCXX/cxx11-thread-local-reference.cpp 
b/clang/test/CodeGenCXX/cxx11-thread-local-reference.cpp
index 3fc960f1eefc4..1d5143f1d3510 100644
--- a/clang/test/CodeGenCXX/cxx11-thread-local-reference.cpp
+++ b/clang/test/CodeGenCXX/cxx11-thread-local-reference.cpp
@@ -15,7 +15,7 @@ int &g() { return r; }
 
 // CHECK: define {{.*}} @[[R_INIT:.*]]()
 // CHECK: call noundef nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) 
i32* @_Z1fv()
-// CHECK: %[[R_ADDR:.+]] = call i32** @llvm.threadlocal.address.p0p0i32(i32** 
@r)
+// CHECK: %[[R_ADDR:.+]] = call align 8 i32** 
@llvm.threadlocal.address.p0p0i32(i32** align 8 @r)
 // CHECK: store i32* %{{.*}}, i32** %[[R_ADDR]], align 8
 
 // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} 
dereferenceable({{[0-9]+}}) i32* @_Z1gv()
@@ -27,7 +27,7 @@ int &g() { return r; }
 // DARWIN: define cxx_fast_tlscc noundef i32* @_ZTW1r() [[ATTR1:#[0-9]+]] {
 // LINUX_AIX: call void @_ZTH1r()
 // DARWIN: call cxx_fast_tlscc void @_ZTH1r()
-// CHECK: %[[R_ADDR2:.+]] = call i32** @llvm.threadlocal.address.p0p0i32(i32** 
@r)
+// CHECK: %[[R_ADDR2:.+]] = call align 8 i32** 
@llvm.threadlocal.address.p0p0i32(i32** align 8 @r)
 // CHECK: load i32*, i32** %[[R_ADDR2]], align 8
 // CHECK: ret i32* %{{.*}}
 

diff  --git a/clang/test/CodeGenCXX/cxx11-thread-local.cpp 
b/clang/test/CodeGenCXX/cxx11-thread-local.cpp
index 4023daa8192ab..7b53211e9ceb0 100644
--- a/clang/test/CodeGenCXX/cxx11-thread-local.cpp
+++ b/clang/test/CodeGenCXX/cxx11-thread-local.cpp
@@ -108,7 +108,7 @@ void *e2 = V::m + W::m + &X::m;
 
 // CHECK: define {{.*}} @[[A_INIT:.*]]()
 // CHECK: call{{.*}} i32 @_Z1fv()
-// CHECK: [[A_ADDR:%.+]] = call i32* @llvm.threadlocal.address.p0i32(i32* @a)
+// CHECK: [[A_ADDR:%.+]] = call align 4 i32* 
@llvm.threadlocal.address.p0i32(i32* align 4 @a)
 // CHECK-NEXT: store i32 {{.*}}, i32* [[A_ADDR]], align 4
 
 // CHECK-LABEL: define{{.*}} i32 @_Z1fv()
@@ -118,13 +118,13 @@ int f() {
   // CHECK: br i1 %[[NEED_INIT]]{{.*}}
 
   // CHECK: %[[CALL:.*]] = call{{.*}} i32 @_Z1gv()
-  // CHECK: [[N_ADDR:%.+]] = call i32* @llvm.threadlocal.address.p0i32(i32* 
@_ZZ1fvE1n)
+  // CHECK: [[N_ADDR:%.+]] = call align 4 i32* 
@llvm.threadlocal.address.p0i32(i32* align 4 @_ZZ1fvE1n)
   // CHECK: store i32 %[[CALL]], i32* [[N_ADDR]], align 4
   // CHECK: store i8 1, i8* @_ZGVZ1fvE1n
   // CHECK: br label
   static thread_local int n = g();
-  
-  // CHECK: [[N_ADDR2:%.+]] = call i32* @llvm.threadlocal.address.p0i32(i32* 
@_ZZ1fvE1n)
+
+  // CHECK: [[N_ADDR2:%.+]] = call align 4 i32* 
@llvm.threadlocal.address.p0i32(i32* align 4 @_ZZ1fvE1n)
   // CHECK: load i32, i32* [[N_ADD

[clang-tools-extra] 4450348 - [clang-tidy] Skip union-like classes in use-equals-default

2022-09-06 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-09-06T20:19:47Z
New Revision: 44503482e0af189d3a7fc57b80238ea4151992b9

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

LOG: [clang-tidy] Skip union-like classes in use-equals-default

Skip unions/union-like classes since in this case constructors
with empty bodies behave differently in comparison with regular
structs/classes.

Test plan: ninja check-clang-tools

Differential revision: https://reviews.llvm.org/D132713

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index 2de677d2735fe..d5c402c4bdeb7 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -218,17 +218,20 @@ void 
UseEqualsDefaultCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 }
 
 void UseEqualsDefaultCheck::registerMatchers(MatchFinder *Finder) {
-  // Skip unions since constructors with empty bodies behave 
diff erently
-  // in comparison with structs/classes.
+  // Skip unions/union-like classes since their constructors behave 
diff erently
+  // when defaulted vs. empty.
+  auto IsUnionLikeClass = recordDecl(
+  anyOf(isUnion(),
+has(fieldDecl(isImplicit(), hasType(cxxRecordDecl(isUnion()));
 
   // Destructor.
-  
Finder->addMatcher(cxxDestructorDecl(unless(hasParent(recordDecl(isUnion(,
-   isDefinition())
- .bind(SpecialFunction),
- this);
+  Finder->addMatcher(
+  cxxDestructorDecl(unless(hasParent(IsUnionLikeClass)), isDefinition())
+  .bind(SpecialFunction),
+  this);
   Finder->addMatcher(
   cxxConstructorDecl(
-  unless(hasParent(recordDecl(isUnion(, isDefinition(),
+  unless(hasParent(IsUnionLikeClass)), isDefinition(),
   anyOf(
   // Default constructor.
   allOf(unless(hasAnyConstructorInitializer(isWritten())),
@@ -243,7 +246,7 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   this);
   // Copy-assignment operator.
   Finder->addMatcher(
-  cxxMethodDecl(unless(hasParent(recordDecl(isUnion(, isDefinition(),
+  cxxMethodDecl(unless(hasParent(IsUnionLikeClass)), isDefinition(),
 isCopyAssignmentOperator(),
 // isCopyAssignmentOperator() allows the parameter to be
 // passed by value, and in this case it cannot be

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 7c91ea00dca84..89dd7e746e587 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -144,9 +144,10 @@ Changes in existing checks
 - Improved :doc:`modernize-use-equals-default 
`
   check.
 
-  The check now skips unions since in this case a default constructor with 
empty body
-  is not equivalent to the explicitly defaulted one. The check also skips copy 
assignment
-  operators with nonstandard return types. The check is restricted to 
c++11-or-later.
+  The check now skips unions/union-like classes since in this case a default 
constructor
+  with empty body is not equivalent to the explicitly defaulted one. The check 
also skips
+  copy assignment operators with nonstandard return types. The check is 
restricted to
+  c++11-or-later.
 
 Removed checks
 ^^

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
index 70fc521ebb7ae..eaa600ad86438 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
@@ -44,6 +44,20 @@ union NU {
   IL Field;
 };
 
+// Skip structs/classes containing anonymous unions.
+struct SU {
+  SU(const SU &Other) : Field(Other.Field) {}
+  // CHECK-FIXES: SU(const SU &Other) :
+  SU &operator=(const SU &Other) {
+Field = Other.Field;
+return *this;
+  }
+  // CHECK-FIXES: SU &operator=(const SU &Other) {
+  union {
+IL Field;
+  };
+};
+
 // Wrong type.
 struct WT {
   WT(const IL &Other) {}

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp 
b/clang-tools-extra/test/clang-tidy/

[clang-tools-extra] a7395b8 - [clang-tidy] Skip copy assignment operators with nonstandard return types

2022-09-02 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-09-02T22:43:39Z
New Revision: a7395b860bc247c9e4e917bf5786c04d4cccf1d7

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

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

Skip copy assignment operators with nonstandard return types
since they cannot be defaulted.

Test plan: ninja check-clang-tools

Differential revision: https://reviews.llvm.org/D133006

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index f321c0b2e693..2de677d2735f 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -8,6 +8,7 @@
 
 #include "UseEqualsDefaultCheck.h"
 #include "../utils/LexerUtils.h"
+#include "../utils/Matchers.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/Lexer.h"
@@ -247,7 +248,12 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
 // isCopyAssignmentOperator() allows the parameter to be
 // passed by value, and in this case it cannot be
 // defaulted.
-hasParameter(0, hasType(lValueReferenceType(
+hasParameter(0, hasType(lValueReferenceType())),
+// isCopyAssignmentOperator() allows non lvalue reference
+// return types, and in this case it cannot be defaulted.
+returns(qualType(hasCanonicalType(
+allOf(lValueReferenceType(pointee(type())),
+  unless(matchers::isReferenceToConst()))
   .bind(SpecialFunction),
   this);
 }

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index e0907b23c84c..7c91ea00dca8 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -145,7 +145,8 @@ Changes in existing checks
   check.
 
   The check now skips unions since in this case a default constructor with 
empty body
-  is not equivalent to the explicitly defaulted one. The check is restricted 
to c++11-or-later.
+  is not equivalent to the explicitly defaulted one. The check also skips copy 
assignment
+  operators with nonstandard return types. The check is restricted to 
c++11-or-later.
 
 Removed checks
 ^^

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
index 78a03f02eed5..70fc521ebb7a 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
@@ -444,6 +444,13 @@ IL &WRT::operator=(const WRT &Other) {
   return *this;
 }
 
+// Wrong return type.
+struct WRTConstRef {
+  const WRTConstRef &operator = (const WRTConstRef &) {
+return *this;
+  }
+};
+
 // Try-catch.
 struct ITC {
   ITC(const ITC &Other)



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


[clang-tools-extra] 47dbacb - [clang-tidy] Restrict use-equals-default to c++11-or-later

2022-09-02 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-09-02T22:19:11Z
New Revision: 47dbacbc8ae2c13f970096814de8f677d80859af

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

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

Restrict use-equals-default to c++11-or-later.

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D132998

Added: 

clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp

Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
index a992177522f75..4ffed8c406481 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
@@ -38,7 +38,7 @@ class UseEqualsDefaultCheck : public ClangTidyCheck {
 public:
   UseEqualsDefaultCheck(StringRef Name, ClangTidyContext *Context);
   bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
-return LangOpts.CPlusPlus;
+return LangOpts.CPlusPlus11;
   }
   void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 55c8c341bff3a..e0907b23c84c7 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -145,7 +145,7 @@ Changes in existing checks
   check.
 
   The check now skips unions since in this case a default constructor with 
empty body
-  is not equivalent to the explicitly defaulted one.
+  is not equivalent to the explicitly defaulted one. The check is restricted 
to c++11-or-later.
 
 Removed checks
 ^^

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp
new file mode 100644
index 0..d43c1e58c2606
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp
@@ -0,0 +1,8 @@
+// RUN: %check_clang_tidy -std=c++98 %s modernize-use-equals-default %t
+
+struct S {
+  S() {}
+  // CHECK-FIXES: S() {}
+  ~S() {}
+  // CHECK-FIXES: ~S() {}
+};



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


[clang-tools-extra] 083e3a1 - [clang-tidy] Skip unions in use-equals-default

2022-08-23 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-08-23T20:09:47Z
New Revision: 083e3a173d9e9d71733e0445e6f4a93e7f918dfa

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

LOG: [clang-tidy] Skip unions in use-equals-default

For unions constructors with empty bodies behave differently
(in comparison with structs/classes) and clang-tidy's fix
might break the code. This diff adjusts the check to skip unions
for now (it seems to be a relatively rare case).

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D132290

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index c3e3759af32fd..f321c0b2e693d 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -217,12 +217,17 @@ void 
UseEqualsDefaultCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 }
 
 void UseEqualsDefaultCheck::registerMatchers(MatchFinder *Finder) {
+  // Skip unions since constructors with empty bodies behave 
diff erently
+  // in comparison with structs/classes.
+
   // Destructor.
-  Finder->addMatcher(cxxDestructorDecl(isDefinition()).bind(SpecialFunction),
+  
Finder->addMatcher(cxxDestructorDecl(unless(hasParent(recordDecl(isUnion(,
+   isDefinition())
+ .bind(SpecialFunction),
  this);
   Finder->addMatcher(
   cxxConstructorDecl(
-  isDefinition(),
+  unless(hasParent(recordDecl(isUnion(, isDefinition(),
   anyOf(
   // Default constructor.
   allOf(unless(hasAnyConstructorInitializer(isWritten())),
@@ -237,7 +242,8 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   this);
   // Copy-assignment operator.
   Finder->addMatcher(
-  cxxMethodDecl(isDefinition(), isCopyAssignmentOperator(),
+  cxxMethodDecl(unless(hasParent(recordDecl(isUnion(, isDefinition(),
+isCopyAssignmentOperator(),
 // isCopyAssignmentOperator() allows the parameter to be
 // passed by value, and in this case it cannot be
 // defaulted.

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 9e5e176336468..fbe47316d23ae 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -127,6 +127,11 @@ Changes in existing checks
   ``push_front`` on STL-style containers and replacing them with ``emplace``
   or ``emplace_front``.
 
+- Improved `modernize-use-equals-default 
`_ check.
+
+  The check now skips unions since in this case a default constructor with 
empty body
+  is not equivalent to the explicitly defaulted one.
+
 Removed checks
 ^^
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
index 429e72497b1b4..78a03f02eed52 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
@@ -32,6 +32,18 @@ struct IL {
   int Field;
 };
 
+// Skip unions.
+union NU {
+  NU(const NU &Other) : Field(Other.Field) {}
+  // CHECK-FIXES: NU(const NU &Other) :
+  NU &operator=(const NU &Other) {
+Field = Other.Field;
+return *this;
+  }
+  // CHECK-FIXES: NU &operator=(const NU &Other) {
+  IL Field;
+};
+
 // Wrong type.
 struct WT {
   WT(const IL &Other) {}

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
index 40311a1435dd4..1de4957ceb1b9 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
@@ -33,6 +33,15 @@ class NE {
   ~NE() { f(); }
 };
 
+// Skip unions.
+union NU {
+  NU() {}
+  // CHECK-FIXES: NU() {}
+  ~NU() {}
+  // CHECK-FIXES: ~NU() {}
+  NE Field;
+};
+
 // Initializer or arguments.
 class IA {
 public:



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

[clang] d68ba43 - [Intrinsics] Add initial support for NonNull attribute

2022-08-16 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-08-16T21:28:23Z
New Revision: d68ba43ad24791181280fdb0f34b6be380db7a32

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

LOG: [Intrinsics] Add initial support for NonNull attribute

Add initial support for NonNull attribute.
(https://github.com/llvm/llvm-project/issues/57113)

Test plan:

verify that for
__thread int x;
int main() {

int* y = &x;
return *y;
}
(with this patch) clang -O -fsanitize=null -S -emit-llvm -o -
doesn't emit a null-pointer check

Differential revision: https://reviews.llvm.org/D131872

Added: 


Modified: 
clang/test/CodeGenCXX/threadlocal_address.cpp
llvm/include/llvm/IR/Intrinsics.td
llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86.mir
llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86_64.mir
llvm/test/CodeGen/X86/threadlocal_address.ll
llvm/utils/TableGen/CodeGenIntrinsics.h
llvm/utils/TableGen/CodeGenTarget.cpp
llvm/utils/TableGen/IntrinsicEmitter.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/threadlocal_address.cpp 
b/clang/test/CodeGenCXX/threadlocal_address.cpp
index a55b1ee6e08de..625db30dd0e7b 100644
--- a/clang/test/CodeGenCXX/threadlocal_address.cpp
+++ b/clang/test/CodeGenCXX/threadlocal_address.cpp
@@ -20,11 +20,11 @@ int g() {
 // CHECK-NEXT: %[[RET:.+]] = load i32, ptr %[[IA2]], align 4
 // CHECK-NEXT: ret i32 %[[RET]]
 //
-// CHECK: declare ptr @llvm.threadlocal.address.p0(ptr) #[[ATTR_NUM:.+]]
+// CHECK: declare nonnull ptr @llvm.threadlocal.address.p0(ptr nonnull) 
#[[ATTR_NUM:.+]]
 //
 // CHECK-O1-LABEL: @_Z1gv
 // CHECK-O1-NEXT: entry:
-// CHECK-O1-NEXT:   %[[I_ADDR:.+]] = {{.*}}call ptr 
@llvm.threadlocal.address.p0(ptr nonnull @i)
+// CHECK-O1-NEXT:   %[[I_ADDR:.+]] = {{.*}}call ptr 
@llvm.threadlocal.address.p0(ptr @i)
 // CHECK-O1-NEXT:   %[[VAL:.+]] = load i32, ptr %[[I_ADDR]]
 // CHECK-O1-NEXT:   %[[INC:.+]] = add nsw i32 %[[VAL]], 1
 // CHECK-O1-NEXT:   store i32 %[[INC]], ptr %[[I_ADDR]]
@@ -56,7 +56,7 @@ int f() {
 //
 // CHECK-O1-LABEL: @_Z1fv
 // CHECK-O1-NEXT: entry:
-// CHECK-O1-NEXT:   %[[J_ADDR:.+]] = {{.*}}call ptr 
@llvm.threadlocal.address.p0(ptr nonnull @_ZZ1fvE1j)
+// CHECK-O1-NEXT:   %[[J_ADDR:.+]] = {{.*}}call ptr 
@llvm.threadlocal.address.p0(ptr @_ZZ1fvE1j)
 // CHECK-O1-NEXT:   %[[VAL:.+]] = load i32, ptr %[[J_ADDR]]
 // CHECK-O1-NEXT:   %[[INC:.+]] = add nsw i32 %[[VAL]], 1
 // CHECK-O1-NEXT:   store i32 %[[INC]], ptr %[[J_ADDR]]

diff  --git a/llvm/include/llvm/IR/Intrinsics.td 
b/llvm/include/llvm/IR/Intrinsics.td
index 2fb29a4f3eb9d..8a04c495edb11 100644
--- a/llvm/include/llvm/IR/Intrinsics.td
+++ b/llvm/include/llvm/IR/Intrinsics.td
@@ -84,6 +84,11 @@ class NoUndef : IntrinsicProperty {
   int ArgNo = idx.Value;
 }
 
+// NonNull - The specified argument is not null.
+class NonNull : IntrinsicProperty {
+  int ArgNo = idx.Value;
+}
+
 class Align : IntrinsicProperty {
   int ArgNo = idx.Value;
   int Align = align;
@@ -1407,7 +1412,8 @@ def int_ptrmask: DefaultAttrsIntrinsic<[llvm_anyptr_ty], 
[LLVMMatchType<0>, llvm
 
 // Intrinsic to wrap a thread local variable.
 def int_threadlocal_address : DefaultAttrsIntrinsic<[llvm_anyptr_ty], 
[LLVMMatchType<0>],
-   [IntrNoMem, IntrSpeculatable, IntrWillReturn]>;
+[NonNull, 
NonNull>,
+ IntrNoMem, 
IntrSpeculatable, IntrWillReturn]>;
 
 def int_experimental_stepvector : DefaultAttrsIntrinsic<[llvm_anyvector_ty],
 [], [IntrNoMem]>;

diff  --git a/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86.mir 
b/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86.mir
index 8d03401df9cfd..6dce371138e94 100644
--- a/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86.mir
+++ b/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86.mir
@@ -33,7 +33,7 @@
   }
 
   ; Function Attrs: nocallback nofree nosync nounwind readnone speculatable 
willreturn
-  declare ptr @llvm.threadlocal.address.p0(ptr) #0
+  declare nonnull ptr @llvm.threadlocal.address.p0(ptr nonnull) #0
 
   attributes #0 = { nocallback nofree nosync nounwind readnone speculatable 
willreturn }
 

diff  --git a/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86_64.mir 
b/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86_64.mir
index dadd1be16c5b9..afc9ff5374de5 100644
--- a/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86_64.mir
+++ b/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86_64.mir
@@ -23,7 +23,7 @@
   }
 
   ; Function Attrs: nocallback nofree nosync nounwind readnone speculatable 
willreturn
-  declare ptr @llvm.threadlocal.address.p0(ptr) #0
+  declare nonnull ptr @llvm.threadlocal.address.p0(ptr nonnull) #0
 
   attributes #0 = { nocallback nofree nosync nounwind readnone

r345558 - [analyzer] Allow padding checker to traverse simple class hierarchies

2018-10-29 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Oct 29 18:20:37 2018
New Revision: 345558

URL: http://llvm.org/viewvc/llvm-project?rev=345558&view=rev
Log:
[analyzer] Allow padding checker to traverse simple class hierarchies

The existing padding checker skips classes that have any base classes. 
This patch allows the checker to traverse very simple cases: 
classes that have no fields and have exactly one base class. 
This is important mostly in the case of array declarations.

Patch by Max Bernstein!

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D53206

Added:
cfe/trunk/test/Analysis/padding_inherit.cpp
Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp?rev=345558&r1=345557&r2=345558&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp Mon Oct 29 
18:20:37 2018
@@ -75,6 +75,20 @@ public:
 if (shouldSkipDecl(RD))
   return;
 
+// TODO: Figure out why we are going through declarations and not only
+// definitions.
+if (!(RD = RD->getDefinition()))
+  return;
+
+// This is the simplest correct case: a class with no fields and one base
+// class. Other cases are more complicated because of how the base classes
+// & fields might interact, so we don't bother dealing with them.
+// TODO: Support other combinations of base classes and fields.
+if (auto *CXXRD = dyn_cast(RD))
+  if (CXXRD->field_empty() && CXXRD->getNumBases() == 1)
+return 
visitRecord(CXXRD->bases().begin()->getType()->getAsRecordDecl(),
+   PadMultiplier);
+
 auto &ASTContext = RD->getASTContext();
 const ASTRecordLayout &RL = ASTContext.getASTRecordLayout(RD);
 assert(llvm::isPowerOf2_64(RL.getAlignment().getQuantity()));
@@ -112,12 +126,15 @@ public:
 if (RT == nullptr)
   return;
 
-// TODO: Recurse into the fields and base classes to see if any
-// of those have excess padding.
+// TODO: Recurse into the fields to see if they have excess padding.
 visitRecord(RT->getDecl(), Elts);
   }
 
   bool shouldSkipDecl(const RecordDecl *RD) const {
+// TODO: Figure out why we are going through declarations and not only
+// definitions.
+if (!(RD = RD->getDefinition()))
+  return true;
 auto Location = RD->getLocation();
 // If the construct doesn't have a source file, then it's not something
 // we want to diagnose.
@@ -132,13 +149,14 @@ public:
 // Not going to attempt to optimize unions.
 if (RD->isUnion())
   return true;
-// How do you reorder fields if you haven't got any?
-if (RD->field_empty())
-  return true;
 if (auto *CXXRD = dyn_cast(RD)) {
   // Tail padding with base classes ends up being very complicated.
-  // We will skip objects with base classes for now.
-  if (CXXRD->getNumBases() != 0)
+  // We will skip objects with base classes for now, unless they do not
+  // have fields.
+  // TODO: Handle more base class scenarios.
+  if (!CXXRD->field_empty() && CXXRD->getNumBases() != 0)
+return true;
+  if (CXXRD->field_empty() && CXXRD->getNumBases() != 1)
 return true;
   // Virtual bases are complicated, skipping those for now.
   if (CXXRD->getNumVBases() != 0)
@@ -150,6 +168,10 @@ public:
   if (CXXRD->getTypeForDecl()->isInstantiationDependentType())
 return true;
 }
+// How do you reorder fields if you haven't got any?
+else if (RD->field_empty())
+  return true;
+
 auto IsTrickyField = [](const FieldDecl *FD) -> bool {
   // Bitfield layout is hard.
   if (FD->isBitField())
@@ -323,7 +345,7 @@ public:
 BR->emitReport(std::move(Report));
   }
 };
-}
+} // namespace
 
 void ento::registerPaddingChecker(CheckerManager &Mgr) {
   Mgr.registerChecker();

Added: cfe/trunk/test/Analysis/padding_inherit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/padding_inherit.cpp?rev=345558&view=auto
==
--- cfe/trunk/test/Analysis/padding_inherit.cpp (added)
+++ cfe/trunk/test/Analysis/padding_inherit.cpp Mon Oct 29 18:20:37 2018
@@ -0,0 +1,28 @@
+// RUN: %clang_analyze_cc1 -std=c++14 -analyzer-checker=optin.performance 
-analyzer-config optin.performance.Padding:AllowedPad=20 -verify %s
+
+// A class that has no fields and one base class should visit that base class
+// instead. Note that despite having excess padding of 2, this is flagged
+// because of its usage in an array of 100 elements below (`ais').
+// TODO: Add a note to the bug report with BugReport::addNote() to mention the
+// variable using the class and a

r337148 - [Sema] Add fixit for unused lambda captures

2018-07-16 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Jul 16 00:23:47 2018
New Revision: 337148

URL: http://llvm.org/viewvc/llvm-project?rev=337148&view=rev
Log:
[Sema] Add fixit for unused lambda captures

This diff adds a fixit to suggest removing unused lambda captures 
in the appropriate diagnostic.

Patch by Andrew Comminos!

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D48845

Added:
cfe/trunk/test/FixIt/fixit-unused-lambda-capture.cpp
Modified:
cfe/trunk/include/clang/Sema/DeclSpec.h
cfe/trunk/include/clang/Sema/ScopeInfo.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Parse/ParseExprCXX.cpp
cfe/trunk/lib/Sema/SemaLambda.cpp

Modified: cfe/trunk/include/clang/Sema/DeclSpec.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/DeclSpec.h?rev=337148&r1=337147&r2=337148&view=diff
==
--- cfe/trunk/include/clang/Sema/DeclSpec.h (original)
+++ cfe/trunk/include/clang/Sema/DeclSpec.h Mon Jul 16 00:23:47 2018
@@ -2540,12 +2540,16 @@ struct LambdaIntroducer {
 LambdaCaptureInitKind InitKind;
 ExprResult Init;
 ParsedType InitCaptureType;
+SourceRange ExplicitRange;
+
 LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
   IdentifierInfo *Id, SourceLocation EllipsisLoc,
   LambdaCaptureInitKind InitKind, ExprResult Init,
-  ParsedType InitCaptureType)
+  ParsedType InitCaptureType,
+  SourceRange ExplicitRange)
 : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
-  InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType) {}
+  InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType),
+  ExplicitRange(ExplicitRange) {}
   };
 
   SourceRange Range;
@@ -2563,9 +2567,10 @@ struct LambdaIntroducer {
   SourceLocation EllipsisLoc,
   LambdaCaptureInitKind InitKind,
   ExprResult Init, 
-  ParsedType InitCaptureType) {
+  ParsedType InitCaptureType,
+  SourceRange ExplicitRange) {
 Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, 
Init,
- InitCaptureType));
+ InitCaptureType, ExplicitRange));
   }
 };
 

Modified: cfe/trunk/include/clang/Sema/ScopeInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/ScopeInfo.h?rev=337148&r1=337147&r2=337148&view=diff
==
--- cfe/trunk/include/clang/Sema/ScopeInfo.h (original)
+++ cfe/trunk/include/clang/Sema/ScopeInfo.h Mon Jul 16 00:23:47 2018
@@ -829,6 +829,9 @@ public:
   ///  if the enclosing full-expression is instantiation dependent).
   llvm::SmallSet NonODRUsedCapturingExprs;
 
+  /// A map of explicit capture indices to their introducer source ranges.
+  llvm::DenseMap ExplicitCaptureRanges;
+
   /// Contains all of the variables defined in this lambda that shadow 
variables
   /// that were defined in parent contexts. Used to avoid warnings when the
   /// shadowed variables are uncaptured by this lambda.

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=337148&r1=337147&r2=337148&view=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Mon Jul 16 00:23:47 2018
@@ -5602,8 +5602,10 @@ public:
   /// Does copying/destroying the captured variable have side effects?
   bool CaptureHasSideEffects(const sema::Capture &From);
 
-  /// Diagnose if an explicit lambda capture is unused.
-  void DiagnoseUnusedLambdaCapture(const sema::Capture &From);
+  /// Diagnose if an explicit lambda capture is unused. Returns true if a
+  /// diagnostic is emitted.
+  bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
+   const sema::Capture &From);
 
   /// Complete a lambda-expression having processed and attached the
   /// lambda body.

Modified: cfe/trunk/lib/Parse/ParseExprCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseExprCXX.cpp?rev=337148&r1=337147&r2=337148&view=diff
==
--- cfe/trunk/lib/Parse/ParseExprCXX.cpp (original)
+++ cfe/trunk/lib/Parse/ParseExprCXX.cpp Mon Jul 16 00:23:47 2018
@@ -808,6 +808,7 @@ Optional Parser::ParseLambdaIn
 IdentifierInfo *Id = nullptr;
 SourceLocation EllipsisLoc;
 ExprResult Init;
+SourceLocation LocStart = Tok.getLocation();
 
 if (Tok.is(tok::star)) {
   Loc = ConsumeToken(); 
@@ -981,8 +982,11 @@ Optional Parser::ParseLambdaIn
   Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
   Init = InitExpr;
 }

r323382 - [analyzer] Do not attempt to get the pointee of void*

2018-01-24 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Wed Jan 24 14:17:30 2018
New Revision: 323382

URL: http://llvm.org/viewvc/llvm-project?rev=323382&view=rev
Log:
[analyzer] Do not attempt to get the pointee of void*

Do not attempt to get the pointee of void* while generating a bug report 
(otherwise it will trigger an assert inside RegionStoreManager::getBinding 
assert(!T->isVoidType() && "Attempting to dereference a void pointer!")).

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D42396

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
cfe/trunk/test/Analysis/malloc.c

Modified: cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp?rev=323382&r1=323381&r2=323382&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp Wed Jan 24 14:17:30 
2018
@@ -1211,6 +1211,9 @@ std::string StackHintGeneratorForSymbol:
 
 // Check if the parameter is a pointer to the symbol.
 if (Optional Reg = SV.getAs()) {
+  // Do not attempt to dereference void*.
+  if ((*I)->getType()->isVoidPointerType())
+continue;
   SVal PSV = N->getState()->getSVal(Reg->getRegion());
   SymbolRef AS = PSV.getAsLocSymbol();
   if (AS == Sym) {

Modified: cfe/trunk/test/Analysis/malloc.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/malloc.c?rev=323382&r1=323381&r2=323382&view=diff
==
--- cfe/trunk/test/Analysis/malloc.c (original)
+++ cfe/trunk/test/Analysis/malloc.c Wed Jan 24 14:17:30 2018
@@ -1786,6 +1786,18 @@ void cstringchecker_bounds_nocrash() {
   free(p);
 }
 
+void allocateSomeMemory(void *offendingParameter, void **ptr) {
+  *ptr = malloc(1);
+}
+
+void testNoCrashOnOffendingParameter() {
+  // "extern" is necessary to avoid unrelated warnings 
+  // on passing uninitialized value.
+  extern void *offendingParameter;
+  void* ptr;
+  allocateSomeMemory(offendingParameter, &ptr);
+} // expected-warning {{Potential leak of memory pointed to by 'ptr'}}
+
 // 
 // False negatives.
 


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


r323146 - [analyzer] Protect against dereferencing a null pointer

2018-01-22 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Jan 22 12:18:42 2018
New Revision: 323146

URL: http://llvm.org/viewvc/llvm-project?rev=323146&view=rev
Log:
[analyzer] Protect against dereferencing a null pointer

The check (inside StackHintGeneratorForSymbol::getMessage)
if (!N)
return getMessageForSymbolNotFound()
is moved to the beginning of the function.

Differential revision: https://reviews.llvm.org/D42388

Test plan: make check-all

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp?rev=323146&r1=323145&r2=323146&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp Mon Jan 22 12:18:42 
2018
@@ -1185,6 +1185,9 @@ void PathDiagnostic::FullProfile(llvm::F
 StackHintGenerator::~StackHintGenerator() {}
 
 std::string StackHintGeneratorForSymbol::getMessage(const ExplodedNode *N){
+  if (!N)
+return getMessageForSymbolNotFound();
+
   ProgramPoint P = N->getLocation();
   CallExitEnd CExit = P.castAs();
 
@@ -1194,9 +1197,6 @@ std::string StackHintGeneratorForSymbol:
   if (!CE)
 return "";
 
-  if (!N)
-return getMessageForSymbolNotFound();
-
   // Check if one of the parameters are set to the interesting symbol.
   unsigned ArgIndex = 0;
   for (CallExpr::const_arg_iterator I = CE->arg_begin(),


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


r318705 - [analyzer] Diagnose stack leaks via block captures

2017-11-20 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Nov 20 14:53:30 2017
New Revision: 318705

URL: http://llvm.org/viewvc/llvm-project?rev=318705&view=rev
Log:
[analyzer] Diagnose stack leaks via block captures

This diff extends StackAddrEscapeChecker
to catch stack addresses leaks via block captures
if the block is executed asynchronously or
returned from a function.

Differential revision: https://reviews.llvm.org/D39438

Added:
cfe/trunk/test/Analysis/stack-capture-leak-arc.mm
cfe/trunk/test/Analysis/stack-capture-leak-no-arc.mm
Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp?rev=318705&r1=318704&r2=318705&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp Mon Nov 20 
14:53:30 2017
@@ -18,6 +18,7 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "llvm/ADT/SmallString.h"
@@ -26,85 +27,131 @@ using namespace clang;
 using namespace ento;
 
 namespace {
-class StackAddrEscapeChecker : public Checker< check::PreStmt,
-   check::EndFunction > {
+class StackAddrEscapeChecker
+: public Checker,
+ check::EndFunction> {
+  mutable IdentifierInfo *dispatch_semaphore_tII;
   mutable std::unique_ptr BT_stackleak;
   mutable std::unique_ptr BT_returnstack;
+  mutable std::unique_ptr BT_capturedstackasync;
+  mutable std::unique_ptr BT_capturedstackret;
 
 public:
+  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
   void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
   void checkEndFunction(CheckerContext &Ctx) const;
+
 private:
+  void checkReturnedBlockCaptures(const BlockDataRegion &B,
+  CheckerContext &C) const;
+  void checkAsyncExecutedBlockCaptures(const BlockDataRegion &B,
+   CheckerContext &C) const;
   void EmitStackError(CheckerContext &C, const MemRegion *R,
   const Expr *RetE) const;
+  bool isSemaphoreCaptured(const BlockDecl &B) const;
   static SourceRange genName(raw_ostream &os, const MemRegion *R,
  ASTContext &Ctx);
+  static SmallVector
+  getCapturedStackRegions(const BlockDataRegion &B, CheckerContext &C);
+  static bool isArcManagedBlock(const MemRegion *R, CheckerContext &C);
+  static bool isNotInCurrentFrame(const MemRegion *R, CheckerContext &C);
 };
-}
+} // namespace
 
 SourceRange StackAddrEscapeChecker::genName(raw_ostream &os, const MemRegion 
*R,
 ASTContext &Ctx) {
-// Get the base region, stripping away fields and elements.
+  // Get the base region, stripping away fields and elements.
   R = R->getBaseRegion();
   SourceManager &SM = Ctx.getSourceManager();
   SourceRange range;
   os << "Address of ";
 
   // Check if the region is a compound literal.
-  if (const CompoundLiteralRegion* CR = dyn_cast(R)) {
+  if (const auto *CR = dyn_cast(R)) {
 const CompoundLiteralExpr *CL = CR->getLiteralExpr();
 os << "stack memory associated with a compound literal "
   "declared on line "
-<< SM.getExpansionLineNumber(CL->getLocStart())
-<< " returned to caller";
+   << SM.getExpansionLineNumber(CL->getLocStart()) << " returned to 
caller";
 range = CL->getSourceRange();
-  }
-  else if (const AllocaRegion* AR = dyn_cast(R)) {
+  } else if (const auto *AR = dyn_cast(R)) {
 const Expr *ARE = AR->getExpr();
 SourceLocation L = ARE->getLocStart();
 range = ARE->getSourceRange();
 os << "stack memory allocated by call to alloca() on line "
<< SM.getExpansionLineNumber(L);
-  }
-  else if (const BlockDataRegion *BR = dyn_cast(R)) {
+  } else if (const auto *BR = dyn_cast(R)) {
 const BlockDecl *BD = BR->getCodeRegion()->getDecl();
 SourceLocation L = BD->getLocStart();
 range = BD->getSourceRange();
 os << "stack-allocated block declared on line "
<< SM.getExpansionLineNumber(L);
-  }
-  else if (const VarRegion *VR = dyn_cast(R)) {
-os << "stack memory associated with local variable '"
-   << VR->getString() << '\'';
+  } else if (const auto *VR = dyn_cast(R)) {
+os << "stack memory associated with local variable '" << VR->getString()
+   << '\'';
 range = VR->getDecl()->getSourceRange();
-  }
-  else if (const CXXTempObject

r316399 - [analyzer] Fix handling of labels in getLValueElement

2017-10-23 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Oct 23 16:46:06 2017
New Revision: 316399

URL: http://llvm.org/viewvc/llvm-project?rev=316399&view=rev
Log:
[analyzer] Fix handling of labels in getLValueElement

In getLValueElement Base may represent the address of a label 
(as in the newly-added test case), in this case it's not a loc::MemRegionVal 
and Base.castAs() triggers an assert, this diff makes 
getLValueElement return UnknownVal instead.

Differential revision: https://reviews.llvm.org/D39174

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
cfe/trunk/test/Analysis/ptr-arith.c

Modified: cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp?rev=316399&r1=316398&r2=316399&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp Mon Oct 23 16:46:06 2017
@@ -440,7 +440,10 @@ SVal StoreManager::getLValueElement(Qual
   //  value. See also the similar FIXME in getLValueFieldOrIvar().
   if (Base.isUnknownOrUndef() || Base.getAs())
 return Base;
-
+  
+  if (Base.getAs())
+return UnknownVal();
+  
   const SubRegion *BaseRegion =
   Base.castAs().getRegionAs();
 

Modified: cfe/trunk/test/Analysis/ptr-arith.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ptr-arith.c?rev=316399&r1=316398&r2=316399&view=diff
==
--- cfe/trunk/test/Analysis/ptr-arith.c (original)
+++ cfe/trunk/test/Analysis/ptr-arith.c Mon Oct 23 16:46:06 2017
@@ -342,3 +342,8 @@ void negativeIndex(char *str) {
   clang_analyzer_eval(*ptr3 == 'a'); // expected-warning{{UNKNOWN}}
 }
 
+void test_no_crash_on_pointer_to_label() {
+  char *a = &&label;
+  a[0] = 0;
+label:;
+}


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


r315665 - [clang] Enable clang build with LLVM_BUILD_INSTRUMENTED without setting LLVM_PROFTDATA

2017-10-12 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Thu Oct 12 20:21:39 2017
New Revision: 315665

URL: http://llvm.org/viewvc/llvm-project?rev=315665&view=rev
Log:
[clang] Enable clang build with LLVM_BUILD_INSTRUMENTED without setting 
LLVM_PROFTDATA

At the moment if LLVM_BUILD_INSTRUMENTED is set to True 
one has to set LLVM_PROFTDATA even if it's not really used 
(because of message(FATAL_ERROR ...)). 
Building the instrumented version of Clang can be useful even if 
one doesn't plan to build the target generate-profdata
(currently that target would only compile 
utils/perf-training/cxx/hello_world.cpp).
For example, one can run the instrumented version of Clang 
via a separate build system against a different codebase, 
collect/analyze the profiles and merge them by llvm-profdata later.

Differential revision: https://reviews.llvm.org/D38859

Modified:
cfe/trunk/utils/perf-training/CMakeLists.txt

Modified: cfe/trunk/utils/perf-training/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/perf-training/CMakeLists.txt?rev=315665&r1=315664&r2=315665&view=diff
==
--- cfe/trunk/utils/perf-training/CMakeLists.txt (original)
+++ cfe/trunk/utils/perf-training/CMakeLists.txt Thu Oct 12 20:21:39 2017
@@ -30,13 +30,13 @@ if(LLVM_BUILD_INSTRUMENTED)
   endif()
 
   if(NOT LLVM_PROFDATA)
-message(FATAL_ERROR "Must set LLVM_PROFDATA to point to llvm-profdata to 
use for merging PGO data")
+message(STATUS "To enable merging PGO data LLVM_PROFDATA has to point to 
llvm-profdata")
+  else()
+add_custom_target(generate-profdata
+  COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py 
merge ${LLVM_PROFDATA} ${CMAKE_CURRENT_BINARY_DIR}/clang.profdata 
${CMAKE_CURRENT_BINARY_DIR}
+  COMMENT "Merging profdata"
+  DEPENDS generate-profraw)
   endif()
-
-  add_custom_target(generate-profdata
-COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py 
merge ${LLVM_PROFDATA} ${CMAKE_CURRENT_BINARY_DIR}/clang.profdata 
${CMAKE_CURRENT_BINARY_DIR}
-COMMENT "Merging profdata"
-DEPENDS generate-profraw)
 endif()
 
 find_program(DTRACE dtrace)


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


r314470 - [clang] Add getUnsignedPointerDiffType method

2017-09-28 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Thu Sep 28 16:11:31 2017
New Revision: 314470

URL: http://llvm.org/viewvc/llvm-project?rev=314470&view=rev
Log:
[clang] Add getUnsignedPointerDiffType method

C11 standard refers to the unsigned counterpart of the type ptrdiff_t 
in the paragraph 7.21.6.1p7 where it defines the format specifier %tu.
In Clang (in PrintfFormatString.cpp, lines 508-510) there is a FIXME for this 
case,
in particular, Clang didn't diagnose %tu issues at all, i.e.
it didn't emit any warnings on the code printf("%tu", 3.14).
In this diff we add a method getUnsignedPointerDiffType for getting the 
corresponding type
similarly to how it's already done in the other analogous cases (size_t, 
ssize_t, ptrdiff_t etc)
and fix -Wformat diagnostics for %tu plus the emitted fix-it as well.

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D38270

Modified:
cfe/trunk/include/clang/AST/ASTContext.h
cfe/trunk/include/clang/Basic/TargetInfo.h
cfe/trunk/lib/AST/ASTContext.cpp
cfe/trunk/lib/Analysis/PrintfFormatString.cpp
cfe/trunk/lib/Analysis/ScanfFormatString.cpp
cfe/trunk/test/FixIt/format.m
cfe/trunk/test/Sema/format-strings-scanf.c

Modified: cfe/trunk/include/clang/AST/ASTContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTContext.h?rev=314470&r1=314469&r2=314470&view=diff
==
--- cfe/trunk/include/clang/AST/ASTContext.h (original)
+++ cfe/trunk/include/clang/AST/ASTContext.h Thu Sep 28 16:11:31 2017
@@ -1489,6 +1489,11 @@ public:
   /// . Pointer - pointer requires this (C99 6.5.6p9).
   QualType getPointerDiffType() const;
 
+  /// \brief Return the unique unsigned counterpart of "ptrdiff_t"
+  /// integer type. The standard (C11 7.21.6.1p7) refers to this type
+  /// in the definition of %tu format specifier.
+  QualType getUnsignedPointerDiffType() const;
+
   /// \brief Return the unique type for "pid_t" defined in
   /// . We need this to compute the correct type for vfork().
   QualType getProcessIDType() const;

Modified: cfe/trunk/include/clang/Basic/TargetInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/TargetInfo.h?rev=314470&r1=314469&r2=314470&view=diff
==
--- cfe/trunk/include/clang/Basic/TargetInfo.h (original)
+++ cfe/trunk/include/clang/Basic/TargetInfo.h Thu Sep 28 16:11:31 2017
@@ -248,6 +248,9 @@ public:
   IntType getPtrDiffType(unsigned AddrSpace) const {
 return AddrSpace == 0 ? PtrDiffType : getPtrDiffTypeV(AddrSpace);
   }
+  IntType getUnsignedPtrDiffType(unsigned AddrSpace) const {
+return getCorrespondingUnsignedType(getPtrDiffType(AddrSpace));
+  }
   IntType getIntPtrType() const { return IntPtrType; }
   IntType getUIntPtrType() const {
 return getCorrespondingUnsignedType(IntPtrType);

Modified: cfe/trunk/lib/AST/ASTContext.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTContext.cpp?rev=314470&r1=314469&r2=314470&view=diff
==
--- cfe/trunk/lib/AST/ASTContext.cpp (original)
+++ cfe/trunk/lib/AST/ASTContext.cpp Thu Sep 28 16:11:31 2017
@@ -4571,6 +4571,13 @@ QualType ASTContext::getPointerDiffType(
   return getFromTargetType(Target->getPtrDiffType(0));
 }
 
+/// \brief Return the unique unsigned counterpart of "ptrdiff_t"
+/// integer type. The standard (C11 7.21.6.1p7) refers to this type
+/// in the definition of %tu format specifier.
+QualType ASTContext::getUnsignedPointerDiffType() const {
+  return getFromTargetType(Target->getUnsignedPtrDiffType(0));
+}
+
 /// \brief Return the unique type for "pid_t" defined in
 /// . We need this to compute the correct type for vfork().
 QualType ASTContext::getProcessIDType() const {

Modified: cfe/trunk/lib/Analysis/PrintfFormatString.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/PrintfFormatString.cpp?rev=314470&r1=314469&r2=314470&view=diff
==
--- cfe/trunk/lib/Analysis/PrintfFormatString.cpp (original)
+++ cfe/trunk/lib/Analysis/PrintfFormatString.cpp Thu Sep 28 16:11:31 2017
@@ -505,9 +505,7 @@ ArgType PrintfSpecifier::getArgType(ASTC
? ArgType(Ctx.UnsignedLongLongTy, "unsigned __int64")
: ArgType(Ctx.UnsignedIntTy, "unsigned __int32");
   case LengthModifier::AsPtrDiff:
-// FIXME: How to get the corresponding unsigned
-// version of ptrdiff_t?
-return ArgType();
+return ArgType(Ctx.getUnsignedPointerDiffType(), "unsigned ptrdiff_t");
   case LengthModifier::AsAllocate:
   case LengthModifier::AsMAllocate:
   case LengthModifier::AsWide:

Modified: cfe/trunk/lib/Analysis/ScanfFormatString.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/ScanfFormatString.cpp?rev=3144

r314141 - [analyzer] Fix crash on modeling of pointer arithmetic

2017-09-25 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Sep 25 12:32:33 2017
New Revision: 314141

URL: http://llvm.org/viewvc/llvm-project?rev=314141&view=rev
Log:
[analyzer] Fix crash on modeling of pointer arithmetic

This patch fixes analyzer's crash on the newly added test case 
(see also https://bugs.llvm.org/show_bug.cgi?id=34374).
Pointers subtraction appears to be modeled incorrectly 
in the following example:
  char* p;
  auto n = p - reinterpret_cast((unsigned long)1);
In this case the analyzer (built without this patch) 
tries to create a symbolic value for the difference 
treating reinterpret_cast((unsigned long)1) 
as an integer, that is not correct.

Differential revision: https://reviews.llvm.org/D38214

Test plan: make check-all

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
cfe/trunk/test/Analysis/ptr-arith.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp?rev=314141&r1=314140&r2=314141&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp Mon Sep 25 12:32:33 
2017
@@ -726,9 +726,11 @@ SVal SimpleSValBuilder::evalBinOpLL(Prog
 if (Optional rInt = rhs.getAs()) {
   // If one of the operands is a symbol and the other is a constant,
   // build an expression for use by the constraint manager.
-  if (SymbolRef lSym = lhs.getAsLocSymbol(true))
-return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
-
+  if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
+if (BinaryOperator::isComparisonOp(op))
+  return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
+return UnknownVal();
+  }
   // Special case comparisons to NULL.
   // This must come after the test if the LHS is a symbol, which is used to
   // build constraints. The address of any non-symbolic region is 
guaranteed

Modified: cfe/trunk/test/Analysis/ptr-arith.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ptr-arith.cpp?rev=314141&r1=314140&r2=314141&view=diff
==
--- cfe/trunk/test/Analysis/ptr-arith.cpp (original)
+++ cfe/trunk/test/Analysis/ptr-arith.cpp Mon Sep 25 12:32:33 2017
@@ -111,3 +111,9 @@ bool ptrAsIntegerSubtractionNoCrash(__UI
   __UINTPTR_TYPE__ y = (__UINTPTR_TYPE__)p - 1;
   return y == x;
 }
+
+// Bug 34374
+bool integerAsPtrSubtractionNoCrash(char *p, __UINTPTR_TYPE__ m) {
+  auto n = p - reinterpret_cast((__UINTPTR_TYPE__)1);
+  return n == m;
+}


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


r314022 - [clang] Fix isExternC matcher docs

2017-09-22 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Sep 22 12:29:38 2017
New Revision: 314022

URL: http://llvm.org/viewvc/llvm-project?rev=314022&view=rev
Log:
[clang] Fix isExternC matcher docs

The wording in the documentation for the matcher isExternC 
appears to be misleading since this matcher 
is applicable to functions and variables as well. 
This diff changes the comment and regenerates the html file.

Differential revision: https://reviews.llvm.org/D38151

Modified:
cfe/trunk/docs/LibASTMatchersReference.html
cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h

Modified: cfe/trunk/docs/LibASTMatchersReference.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LibASTMatchersReference.html?rev=314022&r1=314021&r2=314022&view=diff
==
--- cfe/trunk/docs/LibASTMatchersReference.html (original)
+++ cfe/trunk/docs/LibASTMatchersReference.html Fri Sep 22 12:29:38 2017
@@ -2741,19 +2741,22 @@ functionDecl(isExplicitTemplateSpecializ
 Usable as: MatcherFunctionDecl>,
 MatcherVarDecl>,
 MatcherCXXRecordDecl>
 
 
-
 MatcherFunctionDecl>isExternC
-Matches extern "C" 
function declarations.
+Matches extern "C" 
function or variable declarations.
 
 Given:
   extern "C" void f() {}
   extern "C" { void g() {} }
   void h() {}
+  extern "C" int x = 1;
+  extern "C" int y = 2;
+  int z = 3;
 functionDecl(isExternC())
-  matches the declaration of f and g, but not the declaration h
+  matches the declaration of f and g, but not the declaration of h.
+varDecl(isExternC())
+  matches the declaration of x and y, but not the declaration of z.
 
 
-
 MatcherFunctionDecl>isInline
 Matches function and 
namespace declarations that are marked with
 the inline keyword.
@@ -3680,19 +3683,22 @@ functionDecl(isExplicitTemplateSpecializ
 Usable as: MatcherFunctionDecl>,
 MatcherVarDecl>,
 MatcherCXXRecordDecl>
 
 
-
 MatcherVarDecl>isExternC
-Matches extern "C" 
function declarations.
+Matches extern "C" 
function or variable declarations.
 
 Given:
   extern "C" void f() {}
   extern "C" { void g() {} }
   void h() {}
+  extern "C" int x = 1;
+  extern "C" int y = 2;
+  int z = 3;
 functionDecl(isExternC())
-  matches the declaration of f and g, but not the declaration h
+  matches the declaration of f and g, but not the declaration of h.
+varDecl(isExternC())
+  matches the declaration of x and y, but not the declaration of z.
 
 
-
 MatcherVarDecl>isStaticStorageClass
 Matches 
variablefunction declarations that have "static" storage
 class specifier ("static" keyword) written in the source.

Modified: cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h?rev=314022&r1=314021&r2=314022&view=diff
==
--- cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h (original)
+++ cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h Fri Sep 22 12:29:38 2017
@@ -3533,16 +3533,21 @@ AST_MATCHER_P(FunctionDecl, returns,
   return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
 }
 
-/// \brief Matches extern "C" function declarations.
+/// \brief Matches extern "C" function or variable declarations.
 ///
 /// Given:
 /// \code
 ///   extern "C" void f() {}
 ///   extern "C" { void g() {} }
 ///   void h() {}
+///   extern "C" int x = 1;
+///   extern "C" int y = 2;
+///   int z = 3;
 /// \endcode
 /// functionDecl(isExternC())
-///   matches the declaration of f and g, but not the declaration h
+///   matches the declaration of f and g, but not the declaration of h.
+/// varDecl(isExternC())
+///   matches the declaration of x and y, but not the declaration of z.
 AST_POLYMORPHIC_MATCHER(isExternC, 
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
VarDecl)) {
   return Node.isExternC();


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


r314011 - [clang] Fix printf fixit for objc specific types

2017-09-22 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Sep 22 11:36:06 2017
New Revision: 314011

URL: http://llvm.org/viewvc/llvm-project?rev=314011&view=rev
Log:
[clang] Fix printf fixit for objc specific types

For the triple thumbv7-apple-ios8.0.0 ssize_t is long and size_t is unsigned 
long,
while NSInteger is int and NSUinteger is unsigned int. Following 
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
Clang catches it and insert a cast to long, for example
 printf("%zd", getNSInteger())
will be replaced with 
 printf("%zd", (long)getNSInteger())
but since the underlying type of ssize_t is long the specifier "%zd" is not 
getting replaced.
This diff changes this behavior to enable replacing the specifier "%zd" with 
the correct one.

Differential revision: https://reviews.llvm.org/D38159

Test plan: make check-all

Added:
cfe/trunk/test/FixIt/fixit-format-ios.m
Modified:
cfe/trunk/lib/Sema/SemaChecking.cpp

Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=314011&r1=314010&r2=314011&view=diff
==
--- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
+++ cfe/trunk/lib/Sema/SemaChecking.cpp Fri Sep 22 11:36:06 2017
@@ -6346,7 +6346,7 @@ CheckPrintfHandler::checkFormatExpr(cons
   CastFix << ")";
 
   SmallVector Hints;
-  if (!AT.matchesType(S.Context, IntendedTy))
+  if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 
 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
 
   if (const CStyleCastExpr *CCast = dyn_cast(E)) {

Added: cfe/trunk/test/FixIt/fixit-format-ios.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/FixIt/fixit-format-ios.m?rev=314011&view=auto
==
--- cfe/trunk/test/FixIt/fixit-format-ios.m (added)
+++ cfe/trunk/test/FixIt/fixit-format-ios.m Fri Sep 22 11:36:06 2017
@@ -0,0 +1,26 @@
+// RUN: cp %s %t
+// RUN: %clang_cc1 -triple thumbv7-apple-ios8.0.0 -fsyntax-only -Wformat 
-fixit %t
+// RUN: grep -v CHECK %t | FileCheck %s
+
+int printf(const char * restrict, ...);
+typedef unsigned int NSUInteger;
+typedef int NSInteger;
+NSUInteger getNSUInteger();
+NSInteger getNSInteger();
+
+void test() {
+  // For thumbv7-apple-ios8.0.0 the underlying type of ssize_t is long
+  // and the underlying type of size_t is unsigned long.
+
+  printf("test 1: %zu", getNSUInteger()); 
+  // CHECK: printf("test 1: %lu", (unsigned long)getNSUInteger());
+
+  printf("test 2: %zu %zu", getNSUInteger(), getNSUInteger());
+  // CHECK: printf("test 2: %lu %lu", (unsigned long)getNSUInteger(), 
(unsigned long)getNSUInteger());
+
+  printf("test 3: %zd", getNSInteger()); 
+  // CHECK: printf("test 3: %ld", (long)getNSInteger());
+
+  printf("test 4: %zd %zd", getNSInteger(), getNSInteger());
+  // CHECK: printf("test 4: %ld %ld", (long)getNSInteger(), 
(long)getNSInteger());
+}


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


r311947 - [analyzer] Adjust ptr arithmetic test

2017-08-28 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Aug 28 15:58:54 2017
New Revision: 311947

URL: http://llvm.org/viewvc/llvm-project?rev=311947&view=rev
Log:
[analyzer] Adjust ptr arithmetic test

Replace "long" with __UINTPTR_TYPE__
to make the test added in rL311935 Windows-friendly.
Caught by the buildbot llvm-clang-x86_64-expensive-checks-win.

Modified:
cfe/trunk/test/Analysis/ptr-arith.cpp

Modified: cfe/trunk/test/Analysis/ptr-arith.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ptr-arith.cpp?rev=311947&r1=311946&r2=311947&view=diff
==
--- cfe/trunk/test/Analysis/ptr-arith.cpp (original)
+++ cfe/trunk/test/Analysis/ptr-arith.cpp Mon Aug 28 15:58:54 2017
@@ -107,7 +107,7 @@ unsigned ptrSubtractionNoCrash(char *Beg
 }
 
 // Bug 34309
-bool ptrAsIntegerSubtractionNoCrash(long x, char *p) {
-  long y = (long)p - 1;
+bool ptrAsIntegerSubtractionNoCrash(__UINTPTR_TYPE__ x, char *p) {
+  __UINTPTR_TYPE__ y = (__UINTPTR_TYPE__)p - 1;
   return y == x;
 }


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


r311935 - [analyzer] Fix crash in modeling arithmetic

2017-08-28 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Aug 28 14:15:21 2017
New Revision: 311935

URL: http://llvm.org/viewvc/llvm-project?rev=311935&view=rev
Log:
[analyzer] Fix crash in modeling arithmetic

This diff fixes modeling of arithmetic 
expressions where pointers are treated as integers 
(i.e. via C-style / reinterpret casts).
For now we return UnknownVal unless the operation is a comparison.

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D37120

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
cfe/trunk/test/Analysis/ptr-arith.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp?rev=311935&r1=311934&r2=311935&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp Mon Aug 28 14:15:21 
2017
@@ -360,10 +360,18 @@ SVal SimpleSValBuilder::evalBinOpNN(Prog
   Loc lhsL = lhs.castAs().getLoc();
   switch (rhs.getSubKind()) {
 case nonloc::LocAsIntegerKind:
+  // FIXME: at the moment the implementation 
+  // of modeling "pointers as integers" is not complete.
+  if (!BinaryOperator::isComparisonOp(op))
+return UnknownVal(); 
   return evalBinOpLL(state, op, lhsL,
  rhs.castAs().getLoc(),
  resultTy);
 case nonloc::ConcreteIntKind: {
+  // FIXME: at the moment the implementation 
+  // of modeling "pointers as integers" is not complete.
+  if (!BinaryOperator::isComparisonOp(op))
+return UnknownVal();
   // Transform the integer into a location and compare.
   // FIXME: This only makes sense for comparisons. If we want to, say,
   // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,

Modified: cfe/trunk/test/Analysis/ptr-arith.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ptr-arith.cpp?rev=311935&r1=311934&r2=311935&view=diff
==
--- cfe/trunk/test/Analysis/ptr-arith.cpp (original)
+++ cfe/trunk/test/Analysis/ptr-arith.cpp Mon Aug 28 14:15:21 2017
@@ -105,3 +105,9 @@ unsigned ptrSubtractionNoCrash(char *Beg
 return 0;
   return N;
 }
+
+// Bug 34309
+bool ptrAsIntegerSubtractionNoCrash(long x, char *p) {
+  long y = (long)p - 1;
+  return y == x;
+}


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


Re: r311182 - [analyzer] Fix modeling of constructors

2017-08-21 Thread Alexander Shaposhnikov via cfe-commits
Thanks!

On Mon, Aug 21, 2017 at 1:28 PM, Hans Wennborg via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Merged in r311378.
>
> Thanks,
> Hans
>
> On Mon, Aug 21, 2017 at 1:12 PM, Anna Zaks  wrote:
> > I approve.Thanks Hans!
> > Anna
> >> On Aug 21, 2017, at 1:05 PM, Hans Wennborg  wrote:
> >>
> >> I'm ok with it if Anna approves.
> >>
> >> On Mon, Aug 21, 2017 at 9:06 AM, Artem Dergachev 
> wrote:
> >>> Hello,
> >>>
> >>> Do we have time to merge this change into release 5.0.0? It's an
> assertion
> >>> failure fix, which shows up on C++ code involving double-inheritance
> with
> >>> empty base classes.
> >>>
> >>> Artem.
> >>>
> >>>
> >>> On 8/18/17 9:20 PM, Alexander Shaposhnikov via cfe-commits wrote:
> >>>>
> >>>> Author: alexshap
> >>>> Date: Fri Aug 18 11:20:43 2017
> >>>> New Revision: 311182
> >>>>
> >>>> URL:http://llvm.org/viewvc/llvm-project?rev=311182&view=rev
> >>>> Log:
> >>>> [analyzer] Fix modeling of constructors
> >>>>
> >>>> This diff fixes analyzer's crash (triggered assert) on the newly added
> >>>> test case.
> >>>> The assert being discussed is assert(!B.lookup(R, BindingKey::Direct))
> >>>> in lib/StaticAnalyzer/Core/RegionStore.cpp, however the root cause is
> >>>> different.
> >>>> For classes with empty bases the offsets might be tricky.
> >>>> For example, let's assume we have
> >>>>  struct S: NonEmptyBase, EmptyBase {
> >>>>  ...
> >>>>  };
> >>>> In this case Clang applies empty base class optimization and
> >>>> the offset of EmptyBase will be 0, it can be verified via
> >>>> clang -cc1 -x c++ -v -fdump-record-layouts main.cpp -emit-llvm -o
> >>>> /dev/null.
> >>>> When the analyzer tries to perform zero initialization of EmptyBase
> >>>> it will hit the assert because that region
> >>>> has already been "written" by the constructor of NonEmptyBase.
> >>>>
> >>>> Test plan:
> >>>> make check-all
> >>>>
> >>>> Differential revision:https://reviews.llvm.org/D36851
> >>>>
> >>>> Modified:
> >>>> cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
> >>>> cfe/trunk/test/Analysis/ctor.mm
> >>>>
> >>>> Modified: cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
> >>>>
> >>>> URL:http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/
> StaticAnalyzer/Core/RegionStore.cpp?rev=311182&r1=
> 311181&r2=311182&view=diff
> >>>>
> >>>> 
> ==
> >>>> --- cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp (original)
> >>>> +++ cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp Fri Aug 18
> 11:20:43
> >>>> 2017
> >>>> @@ -409,6 +409,19 @@ public: // Part of public interface to c
> >>>>  // BindDefault is only used to initialize a region with a default
> >>>> value.
> >>>>StoreRef BindDefault(Store store, const MemRegion *R, SVal V)
> override
> >>>> {
> >>>> +// FIXME: The offsets of empty bases can be tricky because of
> >>>> +// of the so called "empty base class optimization".
> >>>> +// If a base class has been optimized out
> >>>> +// we should not try to create a binding, otherwise we should.
> >>>> +// Unfortunately, at the moment ASTRecordLayout doesn't expose
> >>>> +// the actual sizes of the empty bases
> >>>> +// and trying to infer them from offsets/alignments
> >>>> +// seems to be error-prone and non-trivial because of the
> trailing
> >>>> padding.
> >>>> +// As a temporary mitigation we don't create bindings for empty
> >>>> bases.
> >>>> +if (R->getKind() == MemRegion::CXXBaseObjectRegionKind &&
> >>>> +cast(R)->getDecl()->isEmpty())
> >>>> +  return StoreRef(store, *this);
> >>>> +
> >>>>  RegionBindingsRef B = getRegionBindings(store);
> >>>>

r311182 - [analyzer] Fix modeling of constructors

2017-08-18 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Aug 18 11:20:43 2017
New Revision: 311182

URL: http://llvm.org/viewvc/llvm-project?rev=311182&view=rev
Log:
[analyzer] Fix modeling of constructors

This diff fixes analyzer's crash (triggered assert) on the newly added test 
case.
The assert being discussed is assert(!B.lookup(R, BindingKey::Direct))
in lib/StaticAnalyzer/Core/RegionStore.cpp, however the root cause is different.
For classes with empty bases the offsets might be tricky.
For example, let's assume we have
 struct S: NonEmptyBase, EmptyBase {
 ...
 };
In this case Clang applies empty base class optimization and 
the offset of EmptyBase will be 0, it can be verified via
clang -cc1 -x c++ -v -fdump-record-layouts main.cpp -emit-llvm -o /dev/null.
When the analyzer tries to perform zero initialization of EmptyBase
it will hit the assert because that region
has already been "written" by the constructor of NonEmptyBase.

Test plan:
make check-all

Differential revision: https://reviews.llvm.org/D36851

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
cfe/trunk/test/Analysis/ctor.mm

Modified: cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp?rev=311182&r1=311181&r2=311182&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp Fri Aug 18 11:20:43 2017
@@ -409,6 +409,19 @@ public: // Part of public interface to c
 
   // BindDefault is only used to initialize a region with a default value.
   StoreRef BindDefault(Store store, const MemRegion *R, SVal V) override {
+// FIXME: The offsets of empty bases can be tricky because of
+// of the so called "empty base class optimization".
+// If a base class has been optimized out
+// we should not try to create a binding, otherwise we should.
+// Unfortunately, at the moment ASTRecordLayout doesn't expose
+// the actual sizes of the empty bases
+// and trying to infer them from offsets/alignments
+// seems to be error-prone and non-trivial because of the trailing padding.
+// As a temporary mitigation we don't create bindings for empty bases.
+if (R->getKind() == MemRegion::CXXBaseObjectRegionKind &&
+cast(R)->getDecl()->isEmpty())
+  return StoreRef(store, *this);
+
 RegionBindingsRef B = getRegionBindings(store);
 assert(!B.lookup(R, BindingKey::Direct));
 

Modified: cfe/trunk/test/Analysis/ctor.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ctor.mm?rev=311182&r1=311181&r2=311182&view=diff
==
--- cfe/trunk/test/Analysis/ctor.mm (original)
+++ cfe/trunk/test/Analysis/ctor.mm Fri Aug 18 11:20:43 2017
@@ -704,3 +704,20 @@ namespace PR19579 {
 };
   }
 }
+
+namespace NoCrashOnEmptyBaseOptimization {
+  struct NonEmptyBase {
+int X;
+explicit NonEmptyBase(int X) : X(X) {}
+  };
+
+  struct EmptyBase {};
+
+  struct S : NonEmptyBase, EmptyBase {
+S() : NonEmptyBase(0), EmptyBase() {}
+  };
+
+  void testSCtorNoCrash() {
+S s;
+  }
+}


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


r310948 - [clang] Code cleanup in clang/tooling

2017-08-15 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Tue Aug 15 12:23:54 2017
New Revision: 310948

URL: http://llvm.org/viewvc/llvm-project?rev=310948&view=rev
Log:
[clang] Code cleanup in clang/tooling

1. Add missing explicit for SymbolName constructor.
2. Add missing std::move in createRenameReplacements.

Differential revision: https://reviews.llvm.org/D36715

Modified:
cfe/trunk/include/clang/Tooling/Refactoring/Rename/SymbolName.h
cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp

Modified: cfe/trunk/include/clang/Tooling/Refactoring/Rename/SymbolName.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Refactoring/Rename/SymbolName.h?rev=310948&r1=310947&r2=310948&view=diff
==
--- cfe/trunk/include/clang/Tooling/Refactoring/Rename/SymbolName.h (original)
+++ cfe/trunk/include/clang/Tooling/Refactoring/Rename/SymbolName.h Tue Aug 15 
12:23:54 2017
@@ -29,7 +29,7 @@ namespace tooling {
 /// \endcode
 class SymbolName {
 public:
-  SymbolName(StringRef Name) {
+  explicit SymbolName(StringRef Name) {
 // While empty symbol names are valid (Objective-C selectors can have empty
 // name pieces), occurrences Objective-C selectors are created using an
 // array of strings instead of just one string.

Modified: cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp?rev=310948&r1=310947&r2=310948&view=diff
==
--- cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp (original)
+++ cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp Tue Aug 15 
12:23:54 2017
@@ -53,7 +53,7 @@ createRenameReplacements(const SymbolOcc
 }
 Changes.push_back(std::move(Change));
   }
-  return Changes;
+  return std::move(Changes);
 }
 
 /// Takes each atomic change and inserts its replacements into the set of


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


r310887 - [analyzer] Fix SimpleSValBuilder::simplifySVal

2017-08-14 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Aug 14 14:23:08 2017
New Revision: 310887

URL: http://llvm.org/viewvc/llvm-project?rev=310887&view=rev
Log:
[analyzer] Fix SimpleSValBuilder::simplifySVal

This diff fixes a crash (triggered assert) on the newly added test case.
In the method Simplifier::VisitSymbolData we check the type of S and return
Loc/NonLoc accordingly.

Differential revision: https://reviews.llvm.org/D36564

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
cfe/trunk/test/Analysis/ptr-arith.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp?rev=310887&r1=310886&r2=310887&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp Mon Aug 14 14:23:08 
2017
@@ -1016,7 +1016,8 @@ SVal SimpleSValBuilder::simplifySVal(Pro
   SVB.getKnownValue(State, nonloc::SymbolVal(S)))
 return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
 : (SVal)SVB.makeIntVal(*I);
-  return nonloc::SymbolVal(S);
+  return Loc::isLocType(S->getType()) ? (SVal)SVB.makeLoc(S) 
+  : nonloc::SymbolVal(S);
 }
 
 // TODO: Support SymbolCast. Support IntSymExpr when/if we actually

Modified: cfe/trunk/test/Analysis/ptr-arith.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ptr-arith.cpp?rev=310887&r1=310886&r2=310887&view=diff
==
--- cfe/trunk/test/Analysis/ptr-arith.cpp (original)
+++ cfe/trunk/test/Analysis/ptr-arith.cpp Mon Aug 14 14:23:08 2017
@@ -98,3 +98,10 @@ void checkMultiDimansionalArray() {
   int a[5][5];
*(*(a+1)+2) = 2;
 }
+
+unsigned ptrSubtractionNoCrash(char *Begin, char *End) {
+  auto N = End - Begin;
+  if (Begin)
+return 0;
+  return N;
+}


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


[clang-tools-extra] r309505 - [clang-reorder-fields] Emit warning when reordering breaks member init list dependencies

2017-07-29 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Sat Jul 29 23:43:03 2017
New Revision: 309505

URL: http://llvm.org/viewvc/llvm-project?rev=309505&view=rev
Log:
[clang-reorder-fields] Emit warning when reordering breaks member init list 
dependencies

This diff adds a warning emitted by clang-reorder-fields 
when reordering breaks dependencies in the initializer list.

Patch by Sam Conrad!

Differential revision: https://reviews.llvm.org/D35972

Added:
clang-tools-extra/trunk/test/clang-reorder-fields/ClassDerived.cpp
clang-tools-extra/trunk/test/clang-reorder-fields/FieldDependencyWarning.cpp

clang-tools-extra/trunk/test/clang-reorder-fields/FieldDependencyWarningDerived.cpp
Modified:
clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp

Modified: clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp?rev=309505&r1=309504&r2=309505&view=diff
==
--- clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp 
(original)
+++ clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp Sat 
Jul 29 23:43:03 2017
@@ -22,21 +22,23 @@
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Refactoring.h"
+#include "llvm/ADT/SetVector.h"
 #include 
 #include 
 
 namespace clang {
 namespace reorder_fields {
 using namespace clang::ast_matchers;
+using llvm::SmallSetVector;
 
 /// \brief Finds the definition of a record by name.
 ///
 /// \returns nullptr if the name is ambiguous or not found.
 static const RecordDecl *findDefinition(StringRef RecordName,
 ASTContext &Context) {
-  auto Results = match(
-  recordDecl(hasName(RecordName), isDefinition()).bind("recordDecl"),
-  Context);
+  auto Results =
+  match(recordDecl(hasName(RecordName), isDefinition()).bind("recordDecl"),
+Context);
   if (Results.empty()) {
 llvm::errs() << "Definition of " << RecordName << "  not found\n";
 return nullptr;
@@ -91,6 +93,28 @@ addReplacement(SourceRange Old, SourceRa
   consumeError(Replacements[R.getFilePath()].add(R));
 }
 
+/// \brief Find all member fields used in the given init-list initializer expr
+/// that belong to the same record
+///
+/// \returns a set of field declarations, empty if none were present
+static SmallSetVector
+findMembersUsedInInitExpr(const CXXCtorInitializer *Initializer,
+  ASTContext &Context) {
+  SmallSetVector Results;
+  // Note that this does not pick up member fields of base classes since
+  // for those accesses Sema::PerformObjectMemberConversion always inserts an
+  // UncheckedDerivedToBase ImplicitCastExpr between the this expr and the
+  // object expression
+  auto FoundExprs =
+  match(findAll(memberExpr(hasObjectExpression(cxxThisExpr())).bind("ME")),
+*Initializer->getInit(), Context);
+  for (BoundNodes &BN : FoundExprs)
+if (auto *MemExpr = BN.getNodeAs("ME"))
+  if (auto *FD = dyn_cast(MemExpr->getMemberDecl()))
+Results.insert(FD);
+  return Results;
+}
+
 /// \brief Reorders fields in the definition of a struct/class.
 ///
 /// At the moment reodering of fields with
@@ -129,11 +153,12 @@ static bool reorderFieldsInDefinition(
 
 /// \brief Reorders initializers in a C++ struct/class constructor.
 ///
-/// A constructor can have initializers for an arbitrary subset of the class's 
fields.
-/// Thus, we need to ensure that we reorder just the initializers that are 
present.
+/// A constructor can have initializers for an arbitrary subset of the class's
+/// fields. Thus, we need to ensure that we reorder just the initializers that
+/// are present.
 static void reorderFieldsInConstructor(
 const CXXConstructorDecl *CtorDecl, ArrayRef NewFieldsOrder,
-const ASTContext &Context,
+ASTContext &Context,
 std::map &Replacements) {
   assert(CtorDecl && "Constructor declaration is null");
   if (CtorDecl->isImplicit() || CtorDecl->getNumCtorInitializers() <= 1)
@@ -151,8 +176,26 @@ static void reorderFieldsInConstructor(
   SmallVector OldWrittenInitializersOrder;
   SmallVector NewWrittenInitializersOrder;
   for (const auto *Initializer : CtorDecl->inits()) {
-if (!Initializer->isWritten())
+if (!Initializer->isMemberInitializer() || !Initializer->isWritten())
   continue;
+
+// Warn if this reordering violates initialization expr dependencies.
+const FieldDecl *ThisM = Initializer->getMember();
+const auto UsedMembers = findMembersUsedInInitExpr(Initializer, Context);
+for (const FieldDecl *UM : UsedMembers) {
+  if (NewFieldsPositions[UM->getFieldIndex()] >
+  NewFieldsPositions[ThisM->getFieldIndex()]) {
+DiagnosticsEngine &DiagEngine = Context.getDiagnostics();
+auto Description = ("reordering field " + UM->getNa

Re: [PATCH] D35961: [llvm] Update MachOObjectFile::exports interface

2017-07-28 Thread Alexander Shaposhnikov via cfe-commits
Hi,
many thanks for looking at the diff.
(i started working on this because this interface change broke some
out-of-tree code, but that's expected and not a big issue, i just wanted to
clean it up a bit).

I assume I might be missing smth,
however my diff doesn't change the static method
/// For use examining a trie not in a MachOObjectFile.
static iterator_range exports(Error &Err,
 ArrayRef Trie,
 const MachOObjectFile *O =

nullptr);

It changes only the regular method
/// For use iterating over all exported symbols.
iterator_range exports(Error &Err, const MachOObjectFile *O)
const;
because I didn't like syntax Obj->exports(Err, Obj).
LLD builds successfully with my patch - so I am wondering if this change
looks reasonable/safe to you.

Thanks,
Alex Shaposhnikov



On Fri, Jul 28, 2017 at 10:30 AM, David Blaikie  wrote:

>
>
> On Fri, Jul 28, 2017 at 10:24 AM Kevin Enderby  wrote:
>
>> On Jul 27, 2017, at 9:50 PM, Saleem Abdulrasool via Phabricator <
>> revi...@reviews.llvm.org> wrote:
>>
>> compnerd added a comment.
>>
>> Does anyone use the overload with the `O` for `exports` with `nullptr`
>> instead of `this`?  If not, we could just inline `this` throughout.
>>
>>
>> This will break lld as it needs the default nullptr.  See r308691.
>>
>> The reason that O was added was so that this check from r308690 could be
>> added.
>>
>
> When O is specified is it always == this, though? That seems to be implied
> by the original post.
>
> If that's the case, then the ability to pass null is really only passing
> the on/off state for the diagnostic? Is that necessary, or would it be good
> to just always produce the Error, even in lld?
>
>
>>
>> +  if (O != nullptr) {
>> +if (State.Other > O->getLibraryCount()) {
>> +  *E = malformedError("bad library ordinal: " +
>> Twine((int)State.Other)
>> +   + " (max " + Twine((int)O->getLibraryCount()) + ") in
>> export "
>> +   "trie data at node: 0x" + utohexstr(offset));
>> +  moveToEnd();
>> +  return;
>> +}
>>
>> This is needed for the test case:
>>
>> +RUN: not llvm-objdump -macho -exports-trie 
>> %p/Inputs/macho-trie-bad-library-ordinal
>> 2>&1 | FileCheck -check-prefix BAD_LIBRARY_ORDINAL %s
>> +BAD_LIBRARY_ORDINAL: macho-trie-bad-library-ordinal': truncated or
>> malformed object (bad library ordinal: 69 (max 3) in export trie data at
>> node: 0x33)
>>
>>
>>
>>
>> 
>> Comment at: tools/llvm-nm/llvm-nm.cpp:1230
>>   Error Err = Error::success();
>> -  for (const llvm::object::ExportEntry &Entry : MachO->exports(Err,
>> -   MachO))
>> {
>> +  for (const llvm::object::ExportEntry &Entry : MachO->exports(Err))
>> {
>> bool found = false;
>> 
>> I think that using `auto` here instead of `llvm::object:ExportEntry` is
>> better for readability.
>>
>>
>> 
>> Comment at: tools/llvm-objdump/MachODump.cpp:9406
>>   Error Err = Error::success();
>> -  for (const llvm::object::ExportEntry &Entry : Obj->exports(Err, Obj)) {
>> +  for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
>> uint64_t Flags = Entry.flags();
>> 
>> Similar.
>>
>>
>> Repository:
>>  rL LLVM
>>
>> https://reviews.llvm.org/D35961
>>
>>
>>
>>
>>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] Add warning to clang-reorder-fields when dependencies of init-list exprs are violated

2017-07-22 Thread Alexander Shaposhnikov via cfe-commits
Hi, Sam,
many thanks for the patch,
I'm sorry I didn't notice it earlier.
Do you mind uploading your patch to Phabricator, see
https://llvm.org/docs/Phabricator.html for instructions,
so it would be easier to review / discuss the changes.
Kind regards,
Alexander Shaposhnikov

On Sun, Jul 9, 2017 at 2:11 PM, Sam Conrad via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> This adds a warning emitted by clang-reorder-fields when the reordering
> fields breaks dependencies in the initializer list (such that
> -Wuninitialized would warn).  For example, given:
> Foo::Foo(int x)
>   : a(x)
>   , b(a) {}
>
> Reordering fields to [b,a] gives:
> Foo::Foo(int x)
>   : b(a)
>   , a(x) {}
>
> Emits the warning:
> 2: Warning: reordering field a after b makes a uninitialized when used in
> init expression.
>
> The patch also reformats a few lines that were over 80 columns wide.
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r308678 - [clang-tools-extra] Add support for plain C structs in clang-reorder-fields

2017-07-20 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Thu Jul 20 14:41:20 2017
New Revision: 308678

URL: http://llvm.org/viewvc/llvm-project?rev=308678&view=rev
Log:
[clang-tools-extra] Add support for plain C structs in clang-reorder-fields

This diff updates the tool clang-reorder-fields
to enable reordering of fields of plain C structs.

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D35329

Added:
clang-tools-extra/trunk/test/clang-reorder-fields/PlainCStructFieldsOrder.c
Modified:
clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp

Modified: clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp?rev=308678&r1=308677&r2=308678&view=diff
==
--- clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp 
(original)
+++ clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp Thu 
Jul 20 14:41:20 2017
@@ -32,10 +32,10 @@ using namespace clang::ast_matchers;
 /// \brief Finds the definition of a record by name.
 ///
 /// \returns nullptr if the name is ambiguous or not found.
-static const CXXRecordDecl *findDefinition(StringRef RecordName,
-   ASTContext &Context) {
+static const RecordDecl *findDefinition(StringRef RecordName,
+ASTContext &Context) {
   auto Results = match(
-  recordDecl(hasName(RecordName), isDefinition()).bind("cxxRecordDecl"),
+  recordDecl(hasName(RecordName), isDefinition()).bind("recordDecl"),
   Context);
   if (Results.empty()) {
 llvm::errs() << "Definition of " << RecordName << "  not found\n";
@@ -46,14 +46,14 @@ static const CXXRecordDecl *findDefiniti
  << " is ambiguous, several definitions found\n";
 return nullptr;
   }
-  return selectFirst("cxxRecordDecl", Results);
+  return selectFirst("recordDecl", Results);
 }
 
 /// \brief Calculates the new order of fields.
 ///
 /// \returns empty vector if the list of fields doesn't match the definition.
 static SmallVector
-getNewFieldsOrder(const CXXRecordDecl *Definition,
+getNewFieldsOrder(const RecordDecl *Definition,
   ArrayRef DesiredFieldsOrder) {
   assert(Definition && "Definition is null");
 
@@ -97,7 +97,7 @@ addReplacement(SourceRange Old, SourceRa
 /// different accesses (public/protected/private) is not supported.
 /// \returns true on success.
 static bool reorderFieldsInDefinition(
-const CXXRecordDecl *Definition, ArrayRef NewFieldsOrder,
+const RecordDecl *Definition, ArrayRef NewFieldsOrder,
 const ASTContext &Context,
 std::map &Replacements) {
   assert(Definition && "Definition is null");
@@ -223,7 +223,7 @@ public:
   ReorderingConsumer &operator=(const ReorderingConsumer &) = delete;
 
   void HandleTranslationUnit(ASTContext &Context) override {
-const CXXRecordDecl *RD = findDefinition(RecordName, Context);
+const RecordDecl *RD = findDefinition(RecordName, Context);
 if (!RD)
   return;
 SmallVector NewFieldsOrder =
@@ -232,16 +232,21 @@ public:
   return;
 if (!reorderFieldsInDefinition(RD, NewFieldsOrder, Context, Replacements))
   return;
-for (const auto *C : RD->ctors())
-  if (const auto *D = dyn_cast(C->getDefinition()))
-reorderFieldsInConstructor(cast(D),
-   NewFieldsOrder, Context, Replacements);
 
-// We only need to reorder init list expressions for aggregate types.
+// CXXRD will be nullptr if C code (not C++) is being processed.
+const CXXRecordDecl *CXXRD = dyn_cast(RD);
+if (CXXRD)
+  for (const auto *C : CXXRD->ctors())
+if (const auto *D = dyn_cast(C->getDefinition()))
+  reorderFieldsInConstructor(cast(D),
+  NewFieldsOrder, Context, Replacements);
+
+// We only need to reorder init list expressions for 
+// plain C structs or C++ aggregate types.
 // For other types the order of constructor parameters is used,
 // which we don't change at the moment.
 // Now (v0) partial initialization is not supported.
-if (RD->isAggregate())
+if (!CXXRD || CXXRD->isAggregate())
   for (auto Result :
match(initListExpr(hasType(equalsNode(RD))).bind("initListExpr"),
  Context))

Added: 
clang-tools-extra/trunk/test/clang-reorder-fields/PlainCStructFieldsOrder.c
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-reorder-fields/PlainCStructFieldsOrder.c?rev=308678&view=auto
==
--- clang-tools-extra/trunk/test/clang-reorder-fields/PlainCStructFieldsOrder.c 
(added)
+++ clang-tools-extra/trunk/test/clang-reorder-fields/PlainCStructFieldsOrder.c 
Thu Jul 20 14:41:20 2017
@@ -0,0 +1,14 @@
+// RUN: clang-re

r308662 - [clang] Fix handling of "%zd" in scanf

2017-07-20 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Thu Jul 20 13:11:47 2017
New Revision: 308662

URL: http://llvm.org/viewvc/llvm-project?rev=308662&view=rev
Log:
[clang] Fix handling of "%zd" in scanf

This diff addresses FIXMEs in lib/Analysis/ScanfFormatString.cpp 
for the case of ssize_t format specifier and adds tests.
In particular, this change enables Clang to emit a warning 
on incorrect using of "%zd"/"%zn".

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D35652

Modified:
cfe/trunk/lib/Analysis/ScanfFormatString.cpp
cfe/trunk/test/Sema/format-strings-fixit-ssize_t.c
cfe/trunk/test/Sema/format-strings-scanf.c

Modified: cfe/trunk/lib/Analysis/ScanfFormatString.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/ScanfFormatString.cpp?rev=308662&r1=308661&r2=308662&view=diff
==
--- cfe/trunk/lib/Analysis/ScanfFormatString.cpp (original)
+++ cfe/trunk/lib/Analysis/ScanfFormatString.cpp Thu Jul 20 13:11:47 2017
@@ -251,8 +251,7 @@ ArgType ScanfSpecifier::getArgType(ASTCo
 case LengthModifier::AsIntMax:
   return ArgType::PtrTo(ArgType(Ctx.getIntMaxType(), "intmax_t"));
 case LengthModifier::AsSizeT:
-  // FIXME: ssize_t.
-  return ArgType();
+  return ArgType::PtrTo(ArgType(Ctx.getSignedSizeType(), "ssize_t"));
 case LengthModifier::AsPtrDiff:
   return ArgType::PtrTo(ArgType(Ctx.getPointerDiffType(), 
"ptrdiff_t"));
 case LengthModifier::AsLongDouble:
@@ -386,7 +385,7 @@ ArgType ScanfSpecifier::getArgType(ASTCo
 case LengthModifier::AsIntMax:
   return ArgType::PtrTo(ArgType(Ctx.getIntMaxType(), "intmax_t"));
 case LengthModifier::AsSizeT:
-  return ArgType(); // FIXME: ssize_t
+  return ArgType::PtrTo(ArgType(Ctx.getSignedSizeType(), "ssize_t"));
 case LengthModifier::AsPtrDiff:
   return ArgType::PtrTo(ArgType(Ctx.getPointerDiffType(), 
"ptrdiff_t"));
 case LengthModifier::AsLongDouble:

Modified: cfe/trunk/test/Sema/format-strings-fixit-ssize_t.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/format-strings-fixit-ssize_t.c?rev=308662&r1=308661&r2=308662&view=diff
==
--- cfe/trunk/test/Sema/format-strings-fixit-ssize_t.c (original)
+++ cfe/trunk/test/Sema/format-strings-fixit-ssize_t.c Thu Jul 20 13:11:47 2017
@@ -1,7 +1,7 @@
 // RUN: cp %s %t
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -pedantic -Wall -fixit %t
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fsyntax-only -pedantic -Wall 
-Werror %t
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -E -o - %t | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c99 -pedantic -Wall 
-fixit %t
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c99 -fsyntax-only 
-pedantic -Wall -Werror %t
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -std=c99 -E -o - %t | 
FileCheck %s
 
 /* This is a test of the various code modification hints that are
provided as part of warning or extension diagnostics. All of the
@@ -9,10 +9,14 @@
compile cleanly with -Werror -pedantic. */
 
 int printf(char const *, ...);
+int scanf(const char *, ...);
 
 void test() {
   typedef signed long int ssize_t;
   printf("%f", (ssize_t) 42);
+  ssize_t s;
+  scanf("%f",  &s);
 }
 
 // CHECK: printf("%zd", (ssize_t) 42);
+// CHECK: scanf("%zd", &s)

Modified: cfe/trunk/test/Sema/format-strings-scanf.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/format-strings-scanf.c?rev=308662&r1=308661&r2=308662&view=diff
==
--- cfe/trunk/test/Sema/format-strings-scanf.c (original)
+++ cfe/trunk/test/Sema/format-strings-scanf.c Thu Jul 20 13:11:47 2017
@@ -1,10 +1,18 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -Wformat-nonliteral %s
+// RUN: %clang_cc1 -std=c11 -fsyntax-only -verify -Wformat-nonliteral %s
 
 // Test that -Wformat=0 works:
-// RUN: %clang_cc1 -fsyntax-only -Werror -Wformat=0 %s
+// RUN: %clang_cc1 -std=c11 -fsyntax-only -Werror -Wformat=0 %s
 
 #include 
-typedef __typeof(sizeof(int)) size_t;
+typedef __SIZE_TYPE__ size_t;
+#define __SSIZE_TYPE__ 
\
+  __typeof__(_Generic((__SIZE_TYPE__)0,
\
+  unsigned long long int : (long long int)0,   
\
+  unsigned long int : (long int)0, 
\
+  unsigned int : (int)0,   
\
+  unsigned short : (short)0,   
\
+  unsigned char : (signed char)0))
+typedef __SSIZE_TYPE__ ssize_t; 
 typedef struct _FILE FILE;
 typedef __WCHAR_TYPE__ wchar_t;
 
@@ -172,6 +180,26 @@ void test_qualifier

r308073 - [clang] Fix format test

2017-07-14 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Jul 14 18:06:59 2017
New Revision: 308073

URL: http://llvm.org/viewvc/llvm-project?rev=308073&view=rev
Log:
[clang] Fix format test 

This diff makes the test FixIt/format.m more robust.
The issue was caught by the build bot clang-cmake-thumbv7-a15.

Test plan: make check-all

Modified:
cfe/trunk/test/FixIt/format.m

Modified: cfe/trunk/test/FixIt/format.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/FixIt/format.m?rev=308073&r1=308072&r2=308073&view=diff
==
--- cfe/trunk/test/FixIt/format.m (original)
+++ cfe/trunk/test/FixIt/format.m Fri Jul 14 18:06:59 2017
@@ -230,14 +230,14 @@ void testSignedness(long i, unsigned lon
 }
 
 void testSizeTypes() {
-  printf("%zu", 0.f); // expected-warning{{format specifies type 'size_t' (aka 
'unsigned long') but the argument has type 'float'}}
+  printf("%zu", 0.f); // expected-warning-re{{format specifies type 'size_t' 
(aka '{{.+}}') but the argument has type 'float'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:14}:"%f"
 
-  printf("%zd", 0.f); // expected-warning{{format specifies type 'ssize_t' 
(aka 'long') but the argument has type 'float'}}
+  printf("%zd", 0.f); // expected-warning-re{{format specifies type 'ssize_t' 
(aka '{{.+}}') but the argument has type 'float'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:14}:"%f"
   
   int x;
-  printf("%zn", &x); // expected-warning{{format specifies type 'ssize_t *' 
(aka 'long *') but the argument has type 'int *'}}
+  printf("%zn", &x); // expected-warning-re{{format specifies type 'ssize_t *' 
(aka '{{.+}}') but the argument has type 'int *'}}
   // PrintfSpecifier::fixType doesn't handle %n, so a fix-it is not emitted, 
   // see the comment in PrintfSpecifier::fixType in PrintfFormatString.cpp.
 }


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


r308067 - [clang] Fix handling of "%zd" format specifier

2017-07-14 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Jul 14 15:57:00 2017
New Revision: 308067

URL: http://llvm.org/viewvc/llvm-project?rev=308067&view=rev
Log:
[clang] Fix handling of "%zd" format specifier

This diff addresses FIXME in lib/Analysis/PrintfFormatString.cpp
and makes PrintfSpecifier::getArgType return the correct type. 
In particular, this change enables Clang to emit a warning on 
incorrect using of "%zd"/"%zn" format specifiers.

Differential revision: https://reviews.llvm.org/D35427

Test plan: make check-all

Modified:
cfe/trunk/lib/Analysis/PrintfFormatString.cpp
cfe/trunk/test/FixIt/format.m

Modified: cfe/trunk/lib/Analysis/PrintfFormatString.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/PrintfFormatString.cpp?rev=308067&r1=308066&r2=308067&view=diff
==
--- cfe/trunk/lib/Analysis/PrintfFormatString.cpp (original)
+++ cfe/trunk/lib/Analysis/PrintfFormatString.cpp Fri Jul 14 15:57:00 2017
@@ -466,8 +466,7 @@ ArgType PrintfSpecifier::getArgType(ASTC
   case LengthModifier::AsIntMax:
 return ArgType(Ctx.getIntMaxType(), "intmax_t");
   case LengthModifier::AsSizeT:
-// FIXME: How to get the corresponding signed version of size_t?
-return ArgType();
+return ArgType(Ctx.getSignedSizeType(), "ssize_t");
   case LengthModifier::AsInt3264:
 return Ctx.getTargetInfo().getTriple().isArch64Bit()
? ArgType(Ctx.LongLongTy, "__int64")
@@ -537,7 +536,7 @@ ArgType PrintfSpecifier::getArgType(ASTC
   case LengthModifier::AsIntMax:
 return ArgType::PtrTo(ArgType(Ctx.getIntMaxType(), "intmax_t"));
   case LengthModifier::AsSizeT:
-return ArgType(); // FIXME: ssize_t
+return ArgType::PtrTo(ArgType(Ctx.getSignedSizeType(), "ssize_t"));
   case LengthModifier::AsPtrDiff:
 return ArgType::PtrTo(ArgType(Ctx.getPointerDiffType(), "ptrdiff_t"));
   case LengthModifier::AsLongDouble:

Modified: cfe/trunk/test/FixIt/format.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/FixIt/format.m?rev=308067&r1=308066&r2=308067&view=diff
==
--- cfe/trunk/test/FixIt/format.m (original)
+++ cfe/trunk/test/FixIt/format.m Fri Jul 14 15:57:00 2017
@@ -229,6 +229,19 @@ void testSignedness(long i, unsigned lon
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:11-[[@LINE-2]]:14}:"%+ld"
 }
 
+void testSizeTypes() {
+  printf("%zu", 0.f); // expected-warning{{format specifies type 'size_t' (aka 
'unsigned long') but the argument has type 'float'}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:14}:"%f"
+
+  printf("%zd", 0.f); // expected-warning{{format specifies type 'ssize_t' 
(aka 'long') but the argument has type 'float'}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:14}:"%f"
+  
+  int x;
+  printf("%zn", &x); // expected-warning{{format specifies type 'ssize_t *' 
(aka 'long *') but the argument has type 'int *'}}
+  // PrintfSpecifier::fixType doesn't handle %n, so a fix-it is not emitted, 
+  // see the comment in PrintfSpecifier::fixType in PrintfFormatString.cpp.
+}
+
 void testEnum() {
   typedef enum {
 ImplicitA = 1,


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


r308037 - [clang] Add getSignedSizeType method

2017-07-14 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Jul 14 10:30:14 2017
New Revision: 308037

URL: http://llvm.org/viewvc/llvm-project?rev=308037&view=rev
Log:
[clang] Add getSignedSizeType method

C11 standard refers to the signed counterpart of the type size_t in
the paragraph 7.21.6.1 where it defines d, i, o, u, x, or x conversion 
specifiers
(in printf format string).
In Clang there is a FIXME (in lib/Analysis/PrintfFormatString.cpp) for this case
(which is not handled correctly at the moment).
This diff adds getSignedSizeType method to TargetInfo and exposes it 
in ASTContext similarly to how it is done for getSizeType.
lib/Analysis/PrintfFormatString.cpp will be changed in a separate commit.

Differential revision: https://reviews.llvm.org/D35378

Test plan: make check-all

Modified:
cfe/trunk/include/clang/AST/ASTContext.h
cfe/trunk/include/clang/Basic/TargetInfo.h
cfe/trunk/lib/AST/ASTContext.cpp

Modified: cfe/trunk/include/clang/AST/ASTContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTContext.h?rev=308037&r1=308036&r2=308037&view=diff
==
--- cfe/trunk/include/clang/AST/ASTContext.h (original)
+++ cfe/trunk/include/clang/AST/ASTContext.h Fri Jul 14 10:30:14 2017
@@ -1441,6 +1441,10 @@ public:
   /// The sizeof operator requires this (C99 6.5.3.4p4).
   CanQualType getSizeType() const;
 
+  /// \brief Return the unique signed counterpart of 
+  /// the integer type corresponding to size_t.
+  CanQualType getSignedSizeType() const;
+
   /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
   /// .
   CanQualType getIntMaxType() const;

Modified: cfe/trunk/include/clang/Basic/TargetInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/TargetInfo.h?rev=308037&r1=308036&r2=308037&view=diff
==
--- cfe/trunk/include/clang/Basic/TargetInfo.h (original)
+++ cfe/trunk/include/clang/Basic/TargetInfo.h Fri Jul 14 10:30:14 2017
@@ -226,6 +226,20 @@ protected:
 
 public:
   IntType getSizeType() const { return SizeType; }
+  IntType getSignedSizeType() const {
+switch (SizeType) {
+case UnsignedShort:
+  return SignedShort;
+case UnsignedInt:
+  return SignedInt;
+case UnsignedLong:
+  return SignedLong;
+case UnsignedLongLong:
+  return SignedLongLong;
+default:
+  llvm_unreachable("Invalid SizeType");
+}
+  }
   IntType getIntMaxType() const { return IntMaxType; }
   IntType getUIntMaxType() const {
 return getCorrespondingUnsignedType(IntMaxType);

Modified: cfe/trunk/lib/AST/ASTContext.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTContext.cpp?rev=308037&r1=308036&r2=308037&view=diff
==
--- cfe/trunk/lib/AST/ASTContext.cpp (original)
+++ cfe/trunk/lib/AST/ASTContext.cpp Fri Jul 14 10:30:14 2017
@@ -4525,6 +4525,12 @@ CanQualType ASTContext::getSizeType() co
   return getFromTargetType(Target->getSizeType());
 }
 
+/// Return the unique signed counterpart of the integer type 
+/// corresponding to size_t.
+CanQualType ASTContext::getSignedSizeType() const {
+  return getFromTargetType(Target->getSignedSizeType());
+}
+
 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
 CanQualType ASTContext::getIntMaxType() const {
   return getFromTargetType(Target->getIntMaxType());


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


r307604 - [analyzer] Start fixing modeling of bool based types

2017-07-10 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Jul 10 17:30:14 2017
New Revision: 307604

URL: http://llvm.org/viewvc/llvm-project?rev=307604&view=rev
Log:
[analyzer] Start fixing modeling of bool based types

This is a follow up for one of 
the previous diffs https://reviews.llvm.org/D32328.
getTypeSize and with getIntWidth are not equivalent for bool 
(see https://clang.llvm.org/doxygen/ASTContext_8cpp_source.html#l08444),
this causes a number of issues
(for instance, if APint X representing a bool is created 
with the wrong bit width then X is not comparable against Min/Max
(because of the different bit width), that results in crashes 
(triggered asserts) inside assume* methods), 
for examples see the newly added test cases.

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D35041

Modified:

cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
cfe/trunk/test/Analysis/enum.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h?rev=307604&r1=307603&r2=307604&view=diff
==
--- 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h 
(original)
+++ 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h 
Mon Jul 10 17:30:14 2017
@@ -124,7 +124,7 @@ public:
   /// Returns the type of the APSInt used to store values of the given 
QualType.
   APSIntType getAPSIntType(QualType T) const {
 assert(T->isIntegralOrEnumerationType() || Loc::isLocType(T));
-return APSIntType(Ctx.getTypeSize(T),
+return APSIntType(Ctx.getIntWidth(T),
   !T->isSignedIntegerOrEnumerationType());
   }
 

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp?rev=307604&r1=307603&r2=307604&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp Mon Jul 10 17:30:14 
2017
@@ -71,18 +71,15 @@ SVal SimpleSValBuilder::dispatchCast(SVa
 }
 
 SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
-
   bool isLocType = Loc::isLocType(castTy);
-
   if (val.getAs())
 return val;
 
   if (Optional LI = val.getAs()) {
 if (isLocType)
   return LI->getLoc();
-
 // FIXME: Correctly support promotions/truncations.
-unsigned castSize = Context.getTypeSize(castTy);
+unsigned castSize = Context.getIntWidth(castTy);
 if (castSize == LI->getNumBits())
   return val;
 return makeLocAsInteger(LI->getLoc(), castSize);
@@ -173,7 +170,7 @@ SVal SimpleSValBuilder::evalCastFromLoc(
   }
 
   if (castTy->isIntegralOrEnumerationType()) {
-unsigned BitWidth = Context.getTypeSize(castTy);
+unsigned BitWidth = Context.getIntWidth(castTy);
 
 if (!val.getAs())
   return makeLocAsInteger(val, BitWidth);

Modified: cfe/trunk/test/Analysis/enum.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/enum.cpp?rev=307604&r1=307603&r2=307604&view=diff
==
--- cfe/trunk/test/Analysis/enum.cpp (original)
+++ cfe/trunk/test/Analysis/enum.cpp Mon Jul 10 17:30:14 2017
@@ -37,3 +37,33 @@ bool testNoCrashOnSwitchEnumBool(EnumBoo
   }
   return true;
 }
+
+bool testNoCrashOnSwitchEnumBoolConstant() {
+  EnumBool E = EnumBool::F;
+  switch (E) {
+case EnumBool::F:
+  return false; 
+  }
+  return true; 
+}
+
+typedef __INTPTR_TYPE__ intptr_t;
+bool testNoCrashOnSwitchEnumBoolConstantCastedFromNullptr() {
+  EnumBool E = static_cast((intptr_t)nullptr);
+  switch (E) {
+  case EnumBool::F:
+return false;
+  }
+  return true;
+}
+
+bool testNoCrashOnSwitchEnumBoolConstantCastedFromPtr() {
+  int X;
+  intptr_t P = (intptr_t)&X;
+  EnumBool E = static_cast(P);
+  switch (E) {
+  case EnumBool::F:
+return false;
+  }
+  return true;
+}


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


r306343 - [clang] Enable printf check for CFIndex

2017-06-26 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Jun 26 16:02:27 2017
New Revision: 306343

URL: http://llvm.org/viewvc/llvm-project?rev=306343&view=rev
Log:
[clang] Enable printf check for CFIndex

According to 
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
CFIndex and NSInteger should be treated the same way (see the section Platform 
Dependencies).
This diff changes the function shouldNotPrintDirectly in SemaChecking.cpp 
accordingly 
and adds tests for the "fixit" and the warning.

Differential revision: https://reviews.llvm.org/D34496

Test plan: make check-all

Modified:
cfe/trunk/lib/Sema/SemaChecking.cpp
cfe/trunk/test/FixIt/fixit-format-darwin.m
cfe/trunk/test/FixIt/format-darwin.m

Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=306343&r1=306342&r2=306343&view=diff
==
--- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
+++ cfe/trunk/lib/Sema/SemaChecking.cpp Mon Jun 26 16:02:27 2017
@@ -6000,6 +6000,7 @@ shouldNotPrintDirectly(const ASTContext
   while (const TypedefType *UserTy = TyTy->getAs()) {
 StringRef Name = UserTy->getDecl()->getName();
 QualType CastTy = llvm::StringSwitch(Name)
+  .Case("CFIndex", Context.LongTy)
   .Case("NSInteger", Context.LongTy)
   .Case("NSUInteger", Context.UnsignedLongTy)
   .Case("SInt32", Context.IntTy)

Modified: cfe/trunk/test/FixIt/fixit-format-darwin.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/FixIt/fixit-format-darwin.m?rev=306343&r1=306342&r2=306343&view=diff
==
--- cfe/trunk/test/FixIt/fixit-format-darwin.m (original)
+++ cfe/trunk/test/FixIt/fixit-format-darwin.m Mon Jun 26 16:02:27 2017
@@ -8,12 +8,15 @@
 int printf(const char * restrict, ...);
 
 #if __LP64__
+typedef long CFIndex;
 typedef long NSInteger;
 typedef unsigned long NSUInteger;
 #else
+typedef int CFIndex;
 typedef int NSInteger;
 typedef unsigned int NSUInteger;
 #endif
+CFIndex getCFIndex();
 NSInteger getNSInteger();
 NSUInteger getNSUInteger();
 
@@ -74,3 +77,10 @@ void bug33447() {
   Outer2("test 9: %s %s", getNSInteger(), getNSInteger());
   // CHECK: Outer2("test 9: %ld %ld", (long)getNSInteger(), 
(long)getNSInteger());
 }
+
+void testCFIndex() {
+  printf("test 10: %s", getCFIndex()); 
+  // CHECK: printf("test 10: %ld", (long)getCFIndex());
+  printf("test 11: %s %s", getCFIndex(), getCFIndex());
+  // CHECK: printf("test 11: %ld %ld", (long)getCFIndex(), (long)getCFIndex());
+}

Modified: cfe/trunk/test/FixIt/format-darwin.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/FixIt/format-darwin.m?rev=306343&r1=306342&r2=306343&view=diff
==
--- cfe/trunk/test/FixIt/format-darwin.m (original)
+++ cfe/trunk/test/FixIt/format-darwin.m Mon Jun 26 16:02:27 2017
@@ -7,13 +7,14 @@
 int printf(const char * restrict, ...);
 
 #if __LP64__
+typedef long CFIndex;
 typedef long NSInteger;
 typedef unsigned long NSUInteger;
 typedef int SInt32;
 typedef unsigned int UInt32;
 
 #else
-
+typedef int CFIndex;
 typedef int NSInteger;
 typedef unsigned int NSUInteger;
 typedef long SInt32;
@@ -27,6 +28,7 @@ typedef enum NSIntegerEnum : NSInteger {
   EnumValueB
 } NSIntegerEnum;
 
+CFIndex getCFIndex();
 NSInteger getNSInteger();
 NSUInteger getNSUInteger();
 SInt32 getSInt32();
@@ -55,6 +57,11 @@ void testCorrectionInAllCases() {
 
   // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:11-[[@LINE-2]]:13}:"%ld"
   // CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:16-[[@LINE-3]]:16}:"(long)"
+
+  printf("%s", getCFIndex()); // expected-warning{{values of type 'CFIndex' 
should not be used as format arguments; add an explicit cast to 'long' instead}}
+
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:11-[[@LINE-2]]:13}:"%ld"
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:16-[[@LINE-3]]:16}:"(long)"
 }
 
 @interface Foo {
@@ -120,6 +127,11 @@ void testWarn() {
 
   // CHECK-64: fix-it:"{{.*}}":{[[@LINE-2]]:11-[[@LINE-2]]:13}:"%ld"
   // CHECK-64: fix-it:"{{.*}}":{[[@LINE-3]]:16-[[@LINE-3]]:16}:"(long)"
+
+  printf("%d", getCFIndex()); // expected-warning{{values of type 'CFIndex' 
should not be used as format arguments; add an explicit cast to 'long' instead}}
+
+  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-2]]:11-[[@LINE-2]]:13}:"%ld"
+  // CHECK-64: fix-it:"{{.*}}":{[[@LINE-3]]:16-[[@LINE-3]]:16}:"(long)"
 }
 
 void testPreserveHex() {
@@ -167,6 +179,10 @@ void testWarn() {
   printf("%ld", getNSIntegerEnum()); // expected-warning{{enum values with 
underlying type 'NSInteger' should not be used as format arguments; add an 
explicit cast to 'long' instead}}
 
   // CHECK-32: fix-it:"{{.*}}":{[[@LINE-2]]:17-[[@LINE-2]]:17}:"(long)"
+
+  printf("%ld", getCFIndex()); // expected-warning{{values of type 'CFIndex' 
should not be used as f

r305845 - [clang] Fix format specifiers fixits for nested macros

2017-06-20 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Tue Jun 20 15:46:58 2017
New Revision: 305845

URL: http://llvm.org/viewvc/llvm-project?rev=305845&view=rev
Log:
[clang] Fix format specifiers fixits for nested macros

ExpansionLoc was previously calculated incorrectly in the case of 
nested macros expansions. In this diff we build the stack of expansions 
where the last one is the actual expansion which should be used 
for grouping together the edits. 
The definition of MacroArgUse is adjusted accordingly.

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D34268

Modified:
cfe/trunk/include/clang/Edit/EditedSource.h
cfe/trunk/lib/Edit/EditedSource.cpp
cfe/trunk/test/FixIt/fixit-format-darwin.m

Modified: cfe/trunk/include/clang/Edit/EditedSource.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Edit/EditedSource.h?rev=305845&r1=305844&r2=305845&view=diff
==
--- cfe/trunk/include/clang/Edit/EditedSource.h (original)
+++ cfe/trunk/include/clang/Edit/EditedSource.h Tue Jun 20 15:46:58 2017
@@ -17,6 +17,7 @@
 #include "llvm/ADT/TinyPtrVector.h"
 #include "llvm/Support/Allocator.h"
 #include 
+#include 
 
 namespace clang {
   class LangOptions;
@@ -41,10 +42,20 @@ class EditedSource {
   typedef std::map FileEditsTy;
   FileEditsTy FileEdits;
 
-  // Location of argument use inside the macro body 
-  typedef std::pair MacroArgUse;
-  llvm::DenseMap>
-ExpansionToArgMap;
+  struct MacroArgUse {
+IdentifierInfo *Identifier;
+SourceLocation ImmediateExpansionLoc;
+// Location of argument use inside the top-level macro
+SourceLocation UseLoc;
+
+bool operator==(const MacroArgUse &Other) const {
+  return std::tie(Identifier, ImmediateExpansionLoc, UseLoc) ==
+ std::tie(Other.Identifier, Other.ImmediateExpansionLoc,
+  Other.UseLoc);
+}
+  };
+
+  llvm::DenseMap> ExpansionToArgMap;
   SmallVector, 2>
 CurrCommitMacroArgExps;
 

Modified: cfe/trunk/lib/Edit/EditedSource.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Edit/EditedSource.cpp?rev=305845&r1=305844&r2=305845&view=diff
==
--- cfe/trunk/lib/Edit/EditedSource.cpp (original)
+++ cfe/trunk/lib/Edit/EditedSource.cpp Tue Jun 20 15:46:58 2017
@@ -28,13 +28,18 @@ void EditedSource::deconstructMacroArgLo
   MacroArgUse &ArgUse) {
   assert(SourceMgr.isMacroArgExpansion(Loc));
   SourceLocation DefArgLoc = SourceMgr.getImmediateExpansionRange(Loc).first;
-  ExpansionLoc = SourceMgr.getImmediateExpansionRange(DefArgLoc).first;
+  SourceLocation ImmediateExpansionLoc =
+  SourceMgr.getImmediateExpansionRange(DefArgLoc).first;
+  ExpansionLoc = ImmediateExpansionLoc;
+  while (SourceMgr.isMacroBodyExpansion(ExpansionLoc))
+ExpansionLoc = SourceMgr.getImmediateExpansionRange(ExpansionLoc).first;
   SmallString<20> Buf;
   StringRef ArgName = Lexer::getSpelling(SourceMgr.getSpellingLoc(DefArgLoc),
  Buf, SourceMgr, LangOpts);
-  ArgUse = {nullptr, SourceLocation()};
+  ArgUse = MacroArgUse{nullptr, SourceLocation(), SourceLocation()};
   if (!ArgName.empty())
-ArgUse = {&IdentTable.get(ArgName), SourceMgr.getSpellingLoc(DefArgLoc)};
+ArgUse = {&IdentTable.get(ArgName), ImmediateExpansionLoc,
+  SourceMgr.getSpellingLoc(DefArgLoc)};
 }
 
 void EditedSource::startingCommit() {}
@@ -69,10 +74,11 @@ bool EditedSource::canInsertInOffset(Sou
 deconstructMacroArgLoc(OrigLoc, ExpLoc, ArgUse);
 auto I = ExpansionToArgMap.find(ExpLoc.getRawEncoding());
 if (I != ExpansionToArgMap.end() &&
-std::find_if(
-I->second.begin(), I->second.end(), [&](const MacroArgUse &U) {
-  return ArgUse.first == U.first && ArgUse.second != U.second;
-}) != I->second.end()) {
+find_if(I->second, [&](const MacroArgUse &U) {
+  return ArgUse.Identifier == U.Identifier &&
+ std::tie(ArgUse.ImmediateExpansionLoc, ArgUse.UseLoc) !=
+ std::tie(U.ImmediateExpansionLoc, U.UseLoc);
+}) != I->second.end()) {
   // Trying to write in a macro argument input that has already been
   // written by a previous commit for another expansion of the same macro
   // argument name. For example:
@@ -89,7 +95,6 @@ bool EditedSource::canInsertInOffset(Sou
   return false;
 }
   }
-
   return true;
 }
 
@@ -102,13 +107,13 @@ bool EditedSource::commitInsert(SourceLo
 return true;
 
   if (SourceMgr.isMacroArgExpansion(OrigLoc)) {
-SourceLocation ExpLoc;
 MacroArgUse ArgUse;
+SourceLocation ExpLoc;
 deconstructMacroArgLoc(OrigLoc, ExpLoc, ArgUse);
-if (ArgUse.first)
+if (ArgUse.Identifier)
   CurrCommitMacroArgExps.emplace_back(ExpLoc, ArgUse);
   }
-  
+
   FileEdit &FA = FileEdits[Offs];
   if (FA.T

r305124 - [clang] Cleanup fixit.c

2017-06-09 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Jun  9 17:20:52 2017
New Revision: 305124

URL: http://llvm.org/viewvc/llvm-project?rev=305124&view=rev
Log:
[clang] Cleanup fixit.c

This diff removes temporary file t2 in fixit.c and updates the test command 
accordingly.
NFC.

Test plan:
make check-all

Differential revision: https://reviews.llvm.org/D34066

Modified:
cfe/trunk/test/FixIt/fixit.c

Modified: cfe/trunk/test/FixIt/fixit.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/FixIt/fixit.c?rev=305124&r1=305123&r2=305124&view=diff
==
--- cfe/trunk/test/FixIt/fixit.c (original)
+++ cfe/trunk/test/FixIt/fixit.c Fri Jun  9 17:20:52 2017
@@ -1,9 +1,8 @@
 // RUN: %clang_cc1 -pedantic -Wunused-label -verify -x c %s
 // RUN: cp %s %t
 // RUN: not %clang_cc1 -pedantic -Wunused-label -fixit -x c %t
-// RUN: grep -v CHECK %t > %t2
 // RUN: %clang_cc1 -pedantic -Wunused-label -Werror -x c %t
-// RUN: FileCheck -input-file=%t2 %t
+// RUN: grep -v CHECK %t | FileCheck %t
 
 /* This is a test of the various code modification hints that are
provided as part of warning or extension diagnostics. All of the


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


  1   2   3   >