[clang] [Clang][CodeGen] Optimised LLVM IR for atomic increments/decrements on floats (PR #89362)
https://github.com/Krishna-13-cyber updated https://github.com/llvm/llvm-project/pull/89362 >From 4e649d105a2af038e6dbd0e93b457eebea2e543a Mon Sep 17 00:00:00 2001 From: Krishna-13-cyber Date: Fri, 19 Apr 2024 15:09:26 +0530 Subject: [PATCH 1/3] Add optimised LLVM IR for atomic increments/decrements on floats --- clang/lib/CodeGen/CGExprScalar.cpp| 13 + clang/test/CodeGen/X86/x86-atomic-float.c | 97 +++ .../test/CodeGen/X86/x86-atomic-long_double.c | 609 +- 3 files changed, 410 insertions(+), 309 deletions(-) create mode 100644 clang/test/CodeGen/X86/x86-atomic-float.c diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp index 1f18e0d5ba409a..e97bb5c7e9dd16 100644 --- a/clang/lib/CodeGen/CGExprScalar.cpp +++ b/clang/lib/CodeGen/CGExprScalar.cpp @@ -2792,6 +2792,19 @@ ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, llvm::AtomicOrdering::SequentiallyConsistent); return isPre ? Builder.CreateBinOp(op, old, amt) : old; } +// Special case for atomic increment/decrement on floats +if (type->isFloatingType()) { + llvm::AtomicRMWInst::BinOp aop = + isInc ? llvm::AtomicRMWInst::FAdd : llvm::AtomicRMWInst::FSub; + llvm::Instruction::BinaryOps op = + isInc ? llvm::Instruction::FAdd : llvm::Instruction::FSub; + llvm::Value *amt = llvm::ConstantFP::get( + VMContext, llvm::APFloat(static_cast(amount))); + llvm::Value *old = + Builder.CreateAtomicRMW(aop, LV.getAddress(CGF), amt, + llvm::AtomicOrdering::SequentiallyConsistent); + return isPre ? Builder.CreateBinOp(op, old, amt) : old; +} value = EmitLoadOfLValue(LV, E->getExprLoc()); input = value; // For every other atomic operation, we need to emit a load-op-cmpxchg loop diff --git a/clang/test/CodeGen/X86/x86-atomic-float.c b/clang/test/CodeGen/X86/x86-atomic-float.c new file mode 100644 index 00..89a2605ed44461 --- /dev/null +++ b/clang/test/CodeGen/X86/x86-atomic-float.c @@ -0,0 +1,97 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --version 4 +// RUN: %clang_cc1 -triple x86_64-linux-gnu -target-cpu core2 %s -S -emit-llvm -o - | FileCheck %s +// RUN: %clang_cc1 -triple i686-linux-gnu -target-cpu core2 %s -S -emit-llvm -o - | FileCheck -check-prefix=CHECK32 %s + +// CHECK-LABEL: define dso_local i32 @test_int_inc( +// CHECK-SAME: ) #[[ATTR0:[0-9]+]] { +// CHECK-NEXT: entry: +// CHECK-NEXT:[[TMP0:%.*]] = atomicrmw add ptr @test_int_inc.n, i32 1 seq_cst, align 4 +// CHECK-NEXT:ret i32 [[TMP0]] +// +// CHECK32-LABEL: define dso_local i32 @test_int_inc( +// CHECK32-SAME: ) #[[ATTR0:[0-9]+]] { +// CHECK32-NEXT: entry: +// CHECK32-NEXT:[[TMP0:%.*]] = atomicrmw add ptr @test_int_inc.n, i32 1 seq_cst, align 4 +// CHECK32-NEXT:ret i32 [[TMP0]] +// +int test_int_inc() +{ +static _Atomic int n; +return n++; +} + +// CHECK-LABEL: define dso_local float @test_float_post_inc( +// CHECK-SAME: ) #[[ATTR0]] { +// CHECK-NEXT: entry: +// CHECK-NEXT:[[TMP0:%.*]] = atomicrmw fadd ptr @test_float_post_inc.n, float 1.00e+00 seq_cst, align 4 +// CHECK-NEXT:ret float [[TMP0]] +// +// CHECK32-LABEL: define dso_local float @test_float_post_inc( +// CHECK32-SAME: ) #[[ATTR0]] { +// CHECK32-NEXT: entry: +// CHECK32-NEXT:[[TMP0:%.*]] = atomicrmw fadd ptr @test_float_post_inc.n, float 1.00e+00 seq_cst, align 4 +// CHECK32-NEXT:ret float [[TMP0]] +// +float test_float_post_inc() +{ +static _Atomic float n; +return n++; +} + +// CHECK-LABEL: define dso_local float @test_float_post_dc( +// CHECK-SAME: ) #[[ATTR0]] { +// CHECK-NEXT: entry: +// CHECK-NEXT:[[TMP0:%.*]] = atomicrmw fsub ptr @test_float_post_dc.n, float -1.00e+00 seq_cst, align 4 +// CHECK-NEXT:ret float [[TMP0]] +// +// CHECK32-LABEL: define dso_local float @test_float_post_dc( +// CHECK32-SAME: ) #[[ATTR0]] { +// CHECK32-NEXT: entry: +// CHECK32-NEXT:[[TMP0:%.*]] = atomicrmw fsub ptr @test_float_post_dc.n, float -1.00e+00 seq_cst, align 4 +// CHECK32-NEXT:ret float [[TMP0]] +// +float test_float_post_dc() +{ +static _Atomic float n; +return n--; +} + +// CHECK-LABEL: define dso_local float @test_float_pre_dc( +// CHECK-SAME: ) #[[ATTR0]] { +// CHECK-NEXT: entry: +// CHECK-NEXT:[[TMP0:%.*]] = atomicrmw fsub ptr @test_float_pre_dc.n, float -1.00e+00 seq_cst, align 4 +// CHECK-NEXT:[[TMP1:%.*]] = fsub float [[TMP0]], -1.00e+00 +// CHECK-NEXT:ret float [[TMP1]] +// +// CHECK32-LABEL: define dso_local float @test_float_pre_dc( +// CHECK32-SAME: ) #[[ATTR0]] { +// CHECK32-NEXT: entry: +// CHECK32-NEXT:[[TMP0:%.*]] = atomicrmw fsub ptr @test_float_pre_dc.n, float -1.00e+00 seq_cst, align 4 +// CHECK32-NEXT:[[TMP1:%.*]] = fsub float [[TMP0]], -1.00e+00 +// CHECK32-NEXT:
[clang] [Clang][CodeGen] Optimised LLVM IR for atomic increments/decrements on floats (PR #89362)
@@ -0,0 +1,64 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --version 4 +// RUN: %clang_cc1 -triple x86_64-linux-gnu -target-cpu core2 %s -S -emit-llvm -o - | FileCheck %s Krishna-13-cyber wrote: Yes I added the test, I misinterpreted the earlier review. Thanks! https://github.com/llvm/llvm-project/pull/89362 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Support __typeof_unqual__ in all C modes (PR #87392)
@@ -665,28 +665,30 @@ KEYWORD(__kindof , KEYOBJC) // Alternate spelling for various tokens. There are GCC extensions in all // languages, but should not be disabled in strict conformance mode. -ALIAS("__alignof__" , __alignof , KEYALL) -ALIAS("__asm", asm, KEYALL) -ALIAS("__asm__" , asm, KEYALL) -ALIAS("__attribute__", __attribute, KEYALL) -ALIAS("__complex", _Complex , KEYALL) -ALIAS("__complex__" , _Complex , KEYALL) -ALIAS("__const" , const , KEYALL) -ALIAS("__const__", const , KEYALL) -ALIAS("__decltype" , decltype , KEYCXX) -ALIAS("__imag__" , __imag , KEYALL) -ALIAS("__inline" , inline , KEYALL) -ALIAS("__inline__" , inline , KEYALL) -ALIAS("__nullptr", nullptr, KEYCXX) -ALIAS("__real__" , __real , KEYALL) -ALIAS("__restrict" , restrict , KEYALL) -ALIAS("__restrict__" , restrict , KEYALL) -ALIAS("__signed" , signed , KEYALL) -ALIAS("__signed__" , signed , KEYALL) -ALIAS("__typeof" , typeof , KEYALL) -ALIAS("__typeof__" , typeof , KEYALL) -ALIAS("__volatile" , volatile , KEYALL) -ALIAS("__volatile__" , volatile , KEYALL) +ALIAS("__alignof__" , __alignof, KEYALL) +ALIAS("__asm", asm , KEYALL) +ALIAS("__asm__" , asm , KEYALL) +ALIAS("__attribute__", __attribute , KEYALL) +ALIAS("__complex", _Complex , KEYALL) +ALIAS("__complex__" , _Complex , KEYALL) +ALIAS("__const" , const, KEYALL) +ALIAS("__const__", const, KEYALL) +ALIAS("__decltype" , decltype , KEYCXX) +ALIAS("__imag__" , __imag , KEYALL) +ALIAS("__inline" , inline , KEYALL) +ALIAS("__inline__" , inline , KEYALL) +ALIAS("__nullptr", nullptr , KEYCXX) +ALIAS("__real__" , __real , KEYALL) +ALIAS("__restrict" , restrict , KEYALL) +ALIAS("__restrict__" , restrict , KEYALL) +ALIAS("__signed" , signed , KEYALL) +ALIAS("__signed__" , signed , KEYALL) +ALIAS("__typeof" , typeof , KEYALL) +ALIAS("__typeof__" , typeof , KEYALL) +ALIAS("__typeof_unqual" , typeof_unqual, KEYNOCXX) +ALIAS("__typeof_unqual__", typeof_unqual, KEYNOCXX) h-vetinari wrote: The C++ rejection should be questioned IMO. To my understanding, once upon a time C++ went with `decltype` to not steal `typeof` from C, waiting for WG14 to standardize it (and once that happened - admittedly decades later -, it was [explicitly](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2930.pdf) made more compatible with C++ during that process). Now that it's finally there, clang could reasonably expose this in all C/C++ modes, also without the leading underscores. https://github.com/llvm/llvm-project/pull/87392 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Support __typeof_unqual__ in all C modes (PR #87392)
tru wrote: The final decision is Toms, but I don't think it qualifies since we are so late in the current process and that 19 will start in just a few months. https://github.com/llvm/llvm-project/pull/87392 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Align -ffp-model=fast denormal handling with -ffast-math (PR #89477)
h-vetinari wrote: This effort is highly desirable, c.f. this [blog post](https://moyix.blogspot.com/2022/09/someones-been-messing-with-my-subnormals.html), so thanks for that! https://github.com/llvm/llvm-project/pull/89477 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix -fno-unsafe-math-optimizations behavior (PR #89473)
https://github.com/arsenm edited https://github.com/llvm/llvm-project/pull/89473 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Parser] Don't always destroy template annotations at the end of a declaration (PR #89494)
https://github.com/zyn0217 created https://github.com/llvm/llvm-project/pull/89494 Since [6163aa9](https://github.com/llvm/llvm-project/commit/6163aa96799cbad7f2f58e02c5bebee9647056a5#diff-3a7ef0bff7d2b73b4100de636f09ea68b72eda191b39c8091a6a1765d917c1a2), we have introduced an optimization that almost always destroys TemplateIdAnnotations at the end of a function declaration. This doesn't always work properly: a lambda within a default template argument could also result in such deallocation and hence a use-after-free bug while building a type constraint on the template parameter. Note the test doesn't always trigger a conspicuous bug/crash even with a debug build. But a sanitizer build can detect them, I believe. Fixes https://github.com/llvm/llvm-project/issues/67235 Fixes https://github.com/llvm/llvm-project/issues/89127 >From e78b183748e52f4709db7f32d663a0a5c03c5af5 Mon Sep 17 00:00:00 2001 From: Younan Zhang Date: Sat, 20 Apr 2024 02:52:16 +0800 Subject: [PATCH] [Clang][Parser] Don't always destroy template annotations at the end of a declaration Since 6163aa9, we have introduced an optimization that almost always destroys TemplateIdAnnotations at the end of a function declaration. This doesn't always work properly: a lambda within a default template argument could also result in such deallocation and hence a use-after-free bug while building a type constraint on the template parameter. Fixes https://github.com/llvm/llvm-project/issues/67235 Fixes https://github.com/llvm/llvm-project/issues/89127 --- clang/docs/ReleaseNotes.rst | 1 + clang/include/clang/Parse/Parser.h| 24 +++ clang/lib/Parse/ParseTemplate.cpp | 5 .../cxx2a-constrained-template-param.cpp | 20 +++- 4 files changed, 49 insertions(+), 1 deletion(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index efc32212f300cf..0cf81a59493faf 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -535,6 +535,7 @@ Bug Fixes to C++ Support - Fix a crash when deducing ``auto`` from an invalid dereference (#GH88329). - Fix a crash in requires expression with templated base class member function. Fixes (#GH84020). - Placement new initializes typedef array with correct size (#GH41441) +- Fixed a use-after-free bug in parsing of type constraints with default arguments that involve lambdas. (#GH67235) Bug Fixes to AST Handling ^ diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h index 23b268126de4e0..2a08b3d56e0cd1 100644 --- a/clang/include/clang/Parse/Parser.h +++ b/clang/include/clang/Parse/Parser.h @@ -313,7 +313,15 @@ class Parser : public CodeCompletionHandler { /// top-level declaration is finished. SmallVector TemplateIds; + /// Don't destroy template annotations in MaybeDestroyTemplateIds even if + /// we're at the end of a declaration. Instead, we defer the destruction until + /// after a top-level declaration. + /// Use DelayTemplateIdDestructionRAII rather than setting it directly. + bool DelayTemplateIdDestruction = false; + void MaybeDestroyTemplateIds() { +if (DelayTemplateIdDestruction) + return; if (!TemplateIds.empty() && (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens())) DestroyTemplateIds(); @@ -329,6 +337,22 @@ class Parser : public CodeCompletionHandler { ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); } }; + struct DelayTemplateIdDestructionRAII { +Parser &Self; +bool PrevDelayTemplateIdDestruction; + +DelayTemplateIdDestructionRAII(Parser &Self, + bool DelayTemplateIdDestruction) noexcept +: Self(Self), + PrevDelayTemplateIdDestruction(Self.DelayTemplateIdDestruction) { + Self.DelayTemplateIdDestruction = DelayTemplateIdDestruction; +} + +~DelayTemplateIdDestructionRAII() noexcept { + Self.DelayTemplateIdDestruction = PrevDelayTemplateIdDestruction; +} + }; + /// Identifiers which have been declared within a tentative parse. SmallVector TentativelyDeclaredIdentifiers; diff --git a/clang/lib/Parse/ParseTemplate.cpp b/clang/lib/Parse/ParseTemplate.cpp index b07ce451e878eb..917690d42ad960 100644 --- a/clang/lib/Parse/ParseTemplate.cpp +++ b/clang/lib/Parse/ParseTemplate.cpp @@ -733,7 +733,12 @@ NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) { // we introduce the type parameter into the local scope. SourceLocation EqualLoc; ParsedType DefaultArg; + std::optional DontDestructTemplateIds; if (TryConsumeToken(tok::equal, EqualLoc)) { +// The default argument might contain a lambda declaration; avoid destroying +// parsed template ids at the end of that declaration because they can be +// used in a type constraint later. +DontDestructTemplateIds.emplace(*this, false); // The defau
[clang] [Clang][Parser] Don't always destroy template annotations at the end of a declaration (PR #89494)
https://github.com/zyn0217 updated https://github.com/llvm/llvm-project/pull/89494 >From ba2e2a4bd2f7442003d6aa21f3d848cfef5061f6 Mon Sep 17 00:00:00 2001 From: Younan Zhang Date: Sat, 20 Apr 2024 02:52:16 +0800 Subject: [PATCH] [Clang][Parser] Don't always destroy template annotations at the end of a declaration Since 6163aa9, we have introduced an optimization that almost always destroys TemplateIdAnnotations at the end of a function declaration. This doesn't always work properly: a lambda within a default template argument could also result in such deallocation and hence a use-after-free bug while building a type constraint on the template parameter. Fixes https://github.com/llvm/llvm-project/issues/67235 Fixes https://github.com/llvm/llvm-project/issues/89127 --- clang/docs/ReleaseNotes.rst | 1 + clang/include/clang/Parse/Parser.h| 24 +++ clang/lib/Parse/ParseTemplate.cpp | 5 .../cxx2a-constrained-template-param.cpp | 20 +++- 4 files changed, 49 insertions(+), 1 deletion(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index efc32212f300cf..0cf81a59493faf 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -535,6 +535,7 @@ Bug Fixes to C++ Support - Fix a crash when deducing ``auto`` from an invalid dereference (#GH88329). - Fix a crash in requires expression with templated base class member function. Fixes (#GH84020). - Placement new initializes typedef array with correct size (#GH41441) +- Fixed a use-after-free bug in parsing of type constraints with default arguments that involve lambdas. (#GH67235) Bug Fixes to AST Handling ^ diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h index 23b268126de4e0..2a08b3d56e0cd1 100644 --- a/clang/include/clang/Parse/Parser.h +++ b/clang/include/clang/Parse/Parser.h @@ -313,7 +313,15 @@ class Parser : public CodeCompletionHandler { /// top-level declaration is finished. SmallVector TemplateIds; + /// Don't destroy template annotations in MaybeDestroyTemplateIds even if + /// we're at the end of a declaration. Instead, we defer the destruction until + /// after a top-level declaration. + /// Use DelayTemplateIdDestructionRAII rather than setting it directly. + bool DelayTemplateIdDestruction = false; + void MaybeDestroyTemplateIds() { +if (DelayTemplateIdDestruction) + return; if (!TemplateIds.empty() && (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens())) DestroyTemplateIds(); @@ -329,6 +337,22 @@ class Parser : public CodeCompletionHandler { ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); } }; + struct DelayTemplateIdDestructionRAII { +Parser &Self; +bool PrevDelayTemplateIdDestruction; + +DelayTemplateIdDestructionRAII(Parser &Self, + bool DelayTemplateIdDestruction) noexcept +: Self(Self), + PrevDelayTemplateIdDestruction(Self.DelayTemplateIdDestruction) { + Self.DelayTemplateIdDestruction = DelayTemplateIdDestruction; +} + +~DelayTemplateIdDestructionRAII() noexcept { + Self.DelayTemplateIdDestruction = PrevDelayTemplateIdDestruction; +} + }; + /// Identifiers which have been declared within a tentative parse. SmallVector TentativelyDeclaredIdentifiers; diff --git a/clang/lib/Parse/ParseTemplate.cpp b/clang/lib/Parse/ParseTemplate.cpp index b07ce451e878eb..665253a6674d27 100644 --- a/clang/lib/Parse/ParseTemplate.cpp +++ b/clang/lib/Parse/ParseTemplate.cpp @@ -733,7 +733,12 @@ NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) { // we introduce the type parameter into the local scope. SourceLocation EqualLoc; ParsedType DefaultArg; + std::optional DontDestructTemplateIds; if (TryConsumeToken(tok::equal, EqualLoc)) { +// The default argument might contain a lambda declaration; avoid destroying +// parsed template ids at the end of that declaration because they can be +// used in a type constraint later. +DontDestructTemplateIds.emplace(*this, /*DelayTemplateIdDestruction=*/true); // The default argument may declare template parameters, notably // if it contains a generic lambda, so we need to increase // the template depth as these parameters would not be instantiated diff --git a/clang/test/Parser/cxx2a-constrained-template-param.cpp b/clang/test/Parser/cxx2a-constrained-template-param.cpp index 6f14b66419c498..5afa99ea50cf91 100644 --- a/clang/test/Parser/cxx2a-constrained-template-param.cpp +++ b/clang/test/Parser/cxx2a-constrained-template-param.cpp @@ -49,4 +49,22 @@ namespace temp template // expected-error{{use of class template 'test1' requires template arguments}} // expected-error@-1 2{{concept named in type constraint is not a type concept}} using A = TT; // expected-error{{exp
[clang] Fix -fno-unsafe-math-optimizations behavior (PR #89473)
@@ -318,12 +320,12 @@ // RUN: %clang -### -fassociative-math -freciprocal-math -fno-signed-zeros \ // RUN: -fno-trapping-math -ftrapping-math -c %s 2>&1 \ -// RUN: | FileCheck --check-prefix=CHECK-NO-REASSOC-NO-UNSAFE-MATH %s +// RUN: | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s // CHECK-NO-REASSOC-NO-UNSAFE-MATH: "-cc1" -// CHECK-NO-REASSOC-NO_UNSAFE-MATH-NOT: "-funsafe-math-optimizations" -// CHECK-NO-REASSOC-NO_UNSAFE-MATH-NOT: "-mreassociate" -// CHECK-NO-REASSOC-NO_UNSAFE-MATH-NOT: "-funsafe-math-optimizations" +// CHECK-NO-REASSOC-NO-UNSAFE-MATH-NOT: "-funsafe-math-optimizations" +// CHECK-NO-REASSOC-NO-UNSAFE-MATH-NOT: "-mreassociate" +// CHECK-NO-REASSOC-NO-UNSAFE-MATH-NOT: "-funsafe-math-optimizations" arsenm wrote: I don't think this testing technique works. All of these flags would be printed on the same line as cc1. You would need to use CHECK-SAME-NOT, but I'm not sure you can actually compose -SAME and -NOT checks -NOT checks are hazardous this way, can we positively check for the flags that are emitted. https://github.com/llvm/llvm-project/pull/89473 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix -fno-unsafe-math-optimizations behavior (PR #89473)
@@ -271,30 +271,32 @@ // RUN: 2>&1 | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s // RUN: %clang -### -funsafe-math-optimizations -fno-reciprocal-math -c %s \ -// RUN: 2>&1 | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s +// RUN: 2>&1 | FileCheck --check-prefix=CHECK-REASSOC-NO-UNSAFE-MATH %s // RUN: %clang -### -funsafe-math-optimizations -fsigned-zeros -c %s 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s // RUN: %clang -### -funsafe-math-optimizations -ftrapping-math -c %s 2>&1 \ -// RUN: | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s +// RUN: | FileCheck --check-prefix=CHECK-TRAPPING-NO-UNSAFE-MATH %s // RUN: %clang -### -funsafe-math-optimizations -fno-unsafe-math-optimizations \ // RUN: -c %s 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s // RUN: %clang -### -ffast-math -fno-associative-math -c %s 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s // RUN: %clang -### -ffast-math -fno-reciprocal-math -c %s 2>&1 \ -// RUN: | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s +// RUN: | FileCheck --check-prefix=CHECK-REASSOC-NO-UNSAFE-MATH %s // RUN: %clang -### -ffast-math -fsigned-zeros -c %s 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s // RUN: %clang -### -ffast-math -ftrapping-math -c %s 2>&1 \ -// RUN: | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s +// RUN: | FileCheck --check-prefix=CHECK-TRAPPING-NO-UNSAFE-MATH %s // RUN: %clang -### -ffast-math -fno-unsafe-math-optimizations -c %s 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s // CHECK-NO-UNSAFE-MATH: "-cc1" // CHECK-NO-UNSAFE-MATH-NOT: "-funsafe-math-optimizations" -// CHECK-NO_UNSAFE-MATH-NOT: "-mreassociate" arsenm wrote: So this test was full of broken test checks? https://github.com/llvm/llvm-project/pull/89473 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Parser] Don't always destroy template annotations at the end of a declaration (PR #89494)
https://github.com/zyn0217 ready_for_review https://github.com/llvm/llvm-project/pull/89494 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Parser] Don't always destroy template annotations at the end of a declaration (PR #89494)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Younan Zhang (zyn0217) Changes Since [6163aa9](https://github.com/llvm/llvm-project/commit/6163aa96799cbad7f2f58e02c5bebee9647056a5#diff-3a7ef0bff7d2b73b4100de636f09ea68b72eda191b39c8091a6a1765d917c1a2), we have introduced an optimization that almost always destroys TemplateIdAnnotations at the end of a function declaration. This doesn't always work properly: a lambda within a default template argument could also result in such deallocation and hence a use-after-free bug while building a type constraint on the template parameter. Note the test doesn't always trigger a conspicuous bug/crash even with a debug build. But a sanitizer build can detect them, I believe. Fixes https://github.com/llvm/llvm-project/issues/67235 Fixes https://github.com/llvm/llvm-project/issues/89127 --- Full diff: https://github.com/llvm/llvm-project/pull/89494.diff 4 Files Affected: - (modified) clang/docs/ReleaseNotes.rst (+1) - (modified) clang/include/clang/Parse/Parser.h (+24) - (modified) clang/lib/Parse/ParseTemplate.cpp (+5) - (modified) clang/test/Parser/cxx2a-constrained-template-param.cpp (+19-1) ``diff diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index efc32212f300cf..0cf81a59493faf 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -535,6 +535,7 @@ Bug Fixes to C++ Support - Fix a crash when deducing ``auto`` from an invalid dereference (#GH88329). - Fix a crash in requires expression with templated base class member function. Fixes (#GH84020). - Placement new initializes typedef array with correct size (#GH41441) +- Fixed a use-after-free bug in parsing of type constraints with default arguments that involve lambdas. (#GH67235) Bug Fixes to AST Handling ^ diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h index 23b268126de4e0..2a08b3d56e0cd1 100644 --- a/clang/include/clang/Parse/Parser.h +++ b/clang/include/clang/Parse/Parser.h @@ -313,7 +313,15 @@ class Parser : public CodeCompletionHandler { /// top-level declaration is finished. SmallVector TemplateIds; + /// Don't destroy template annotations in MaybeDestroyTemplateIds even if + /// we're at the end of a declaration. Instead, we defer the destruction until + /// after a top-level declaration. + /// Use DelayTemplateIdDestructionRAII rather than setting it directly. + bool DelayTemplateIdDestruction = false; + void MaybeDestroyTemplateIds() { +if (DelayTemplateIdDestruction) + return; if (!TemplateIds.empty() && (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens())) DestroyTemplateIds(); @@ -329,6 +337,22 @@ class Parser : public CodeCompletionHandler { ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); } }; + struct DelayTemplateIdDestructionRAII { +Parser &Self; +bool PrevDelayTemplateIdDestruction; + +DelayTemplateIdDestructionRAII(Parser &Self, + bool DelayTemplateIdDestruction) noexcept +: Self(Self), + PrevDelayTemplateIdDestruction(Self.DelayTemplateIdDestruction) { + Self.DelayTemplateIdDestruction = DelayTemplateIdDestruction; +} + +~DelayTemplateIdDestructionRAII() noexcept { + Self.DelayTemplateIdDestruction = PrevDelayTemplateIdDestruction; +} + }; + /// Identifiers which have been declared within a tentative parse. SmallVector TentativelyDeclaredIdentifiers; diff --git a/clang/lib/Parse/ParseTemplate.cpp b/clang/lib/Parse/ParseTemplate.cpp index b07ce451e878eb..665253a6674d27 100644 --- a/clang/lib/Parse/ParseTemplate.cpp +++ b/clang/lib/Parse/ParseTemplate.cpp @@ -733,7 +733,12 @@ NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) { // we introduce the type parameter into the local scope. SourceLocation EqualLoc; ParsedType DefaultArg; + std::optional DontDestructTemplateIds; if (TryConsumeToken(tok::equal, EqualLoc)) { +// The default argument might contain a lambda declaration; avoid destroying +// parsed template ids at the end of that declaration because they can be +// used in a type constraint later. +DontDestructTemplateIds.emplace(*this, /*DelayTemplateIdDestruction=*/true); // The default argument may declare template parameters, notably // if it contains a generic lambda, so we need to increase // the template depth as these parameters would not be instantiated diff --git a/clang/test/Parser/cxx2a-constrained-template-param.cpp b/clang/test/Parser/cxx2a-constrained-template-param.cpp index 6f14b66419c498..5afa99ea50cf91 100644 --- a/clang/test/Parser/cxx2a-constrained-template-param.cpp +++ b/clang/test/Parser/cxx2a-constrained-template-param.cpp @@ -49,4 +49,22 @@ namespace temp template // expected-error{{use of class template 'test1' requires template arguments}} // expected-error@
[clang] [llvm] [ARM] Armv8-R does not require fp64 or neon. (PR #88287)
https://github.com/chrisnc updated https://github.com/llvm/llvm-project/pull/88287 >From 65e44d63a0939a4b91d084a2405f8a091329e311 Mon Sep 17 00:00:00 2001 From: Chris Copeland Date: Fri, 5 Apr 2024 22:40:46 -0700 Subject: [PATCH] [ARM] Armv8-R does not require fp64 or neon. --- clang/test/Preprocessor/arm-target-features.c | 4 ++-- llvm/include/llvm/TargetParser/ARMTargetParser.def | 2 +- llvm/lib/Target/ARM/ARM.td | 6 +++--- llvm/test/Analysis/CostModel/ARM/arith.ll | 2 +- llvm/test/Analysis/CostModel/ARM/cast.ll | 4 ++-- llvm/test/Analysis/CostModel/ARM/cast_ldst.ll | 4 ++-- llvm/test/Analysis/CostModel/ARM/cmps.ll | 4 ++-- llvm/test/Analysis/CostModel/ARM/divrem.ll | 2 +- llvm/test/CodeGen/ARM/cortex-a57-misched-basic.ll | 2 +- llvm/test/CodeGen/ARM/fpconv.ll| 4 ++-- llvm/test/CodeGen/ARM/half.ll | 4 ++-- llvm/test/CodeGen/ARM/misched-fp-basic.ll | 2 +- llvm/test/CodeGen/ARM/useaa.ll | 2 +- llvm/unittests/TargetParser/TargetParserTest.cpp | 4 ++-- 14 files changed, 23 insertions(+), 23 deletions(-) diff --git a/clang/test/Preprocessor/arm-target-features.c b/clang/test/Preprocessor/arm-target-features.c index 236c9f2479b705..2d65bfd4f43995 100644 --- a/clang/test/Preprocessor/arm-target-features.c +++ b/clang/test/Preprocessor/arm-target-features.c @@ -88,8 +88,8 @@ // CHECK-V8R: #define __ARM_FEATURE_NUMERIC_MAXMIN 1 // CHECK-V8R-NOT: #define __ARM_FP 0x -// RUN: %clang -target armv8r-none-linux-gnueabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V8R-ALLOW-FP-INSTR %s -// RUN: %clang -target armv8r-none-linux-gnueabihf -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V8R-ALLOW-FP-INSTR %s +// RUN: %clang -target armv8r-none-linux-gnueabi -mcpu=cortex-r52 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V8R-ALLOW-FP-INSTR %s +// RUN: %clang -target armv8r-none-linux-gnueabihf -mcpu=cortex-r52 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V8R-ALLOW-FP-INSTR %s // CHECK-V8R-ALLOW-FP-INSTR: #define __ARMEL__ 1 // CHECK-V8R-ALLOW-FP-INSTR: #define __ARM_ARCH 8 // CHECK-V8R-ALLOW-FP-INSTR: #define __ARM_ARCH_8R__ 1 diff --git a/llvm/include/llvm/TargetParser/ARMTargetParser.def b/llvm/include/llvm/TargetParser/ARMTargetParser.def index b821d224d7a82c..d787d988fbf69f 100644 --- a/llvm/include/llvm/TargetParser/ARMTargetParser.def +++ b/llvm/include/llvm/TargetParser/ARMTargetParser.def @@ -329,7 +329,7 @@ ARM_CPU_NAME("cortex-r7", ARMV7R, FK_VFPV3_D16_FP16, false, (ARM::AEK_MP | ARM::AEK_HWDIVARM)) ARM_CPU_NAME("cortex-r8", ARMV7R, FK_VFPV3_D16_FP16, false, (ARM::AEK_MP | ARM::AEK_HWDIVARM)) -ARM_CPU_NAME("cortex-r52", ARMV8R, FK_NEON_FP_ARMV8, true, ARM::AEK_NONE) +ARM_CPU_NAME("cortex-r52", ARMV8R, FK_NEON_FP_ARMV8, false, ARM::AEK_NONE) ARM_CPU_NAME("sc300", ARMV7M, FK_NONE, false, ARM::AEK_NONE) ARM_CPU_NAME("cortex-m3", ARMV7M, FK_NONE, true, ARM::AEK_NONE) ARM_CPU_NAME("cortex-m4", ARMV7EM, FK_FPV4_SP_D16, true, ARM::AEK_NONE) diff --git a/llvm/lib/Target/ARM/ARM.td b/llvm/lib/Target/ARM/ARM.td index 66596dbda83c95..dc40a7b56821d1 100644 --- a/llvm/lib/Target/ARM/ARM.td +++ b/llvm/lib/Target/ARM/ARM.td @@ -1167,9 +1167,7 @@ def ARMv8r: Architecture<"armv8-r", "ARMv8r", [HasV8Ops, FeatureDSP, FeatureCRC, FeatureMP, - FeatureVirtualization, - FeatureFPARMv8, - FeatureNEON]>; + FeatureVirtualization]>; def ARMv8mBaseline : Architecture<"armv8-m.base", "ARMv8mBaseline", [HasV8MBaselineOps, @@ -1726,6 +1724,8 @@ def : ProcNoItin<"kryo", [ARMv8a, ProcKryo, FeatureCRC]>; def : ProcessorModel<"cortex-r52", CortexR52Model, [ARMv8r, ProcR52, + FeatureFPARMv8, + FeatureNEON, FeatureUseMISched, FeatureFPAO]>; diff --git a/llvm/test/Analysis/CostModel/ARM/arith.ll b/llvm/test/Analysis/CostModel/ARM/arith.ll index 3a137a5af36664..8f173596c3b9a0 100644 --- a/llvm/test/Analysis/CostModel/ARM/arith.ll +++ b/llvm/test/Analysis/CostModel/ARM/arith.ll @@ -4,7 +4,7 @@ ; RUN: opt -passes="print" 2>&1 -disable-output -mtriple=thumbv8.1m.main-none-eabi -mattr
[clang] 32623a3 - [clang] Marshallers.h - use move semantics for 'NodeKinds' and update possible callers to use it (#87273)
Author: Amila Senadheera Date: 2024-04-20T10:47:57+01:00 New Revision: 32623a3fc09a87867df495ab8c059706f24a126c URL: https://github.com/llvm/llvm-project/commit/32623a3fc09a87867df495ab8c059706f24a126c DIFF: https://github.com/llvm/llvm-project/commit/32623a3fc09a87867df495ab8c059706f24a126c.diff LOG: [clang] Marshallers.h - use move semantics for 'NodeKinds' and update possible callers to use it (#87273) Fixes: https://github.com/llvm/llvm-project/issues/87248 Signed-off-by: amila Added: Modified: clang/lib/ASTMatchers/Dynamic/Marshallers.h Removed: diff --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.h b/clang/lib/ASTMatchers/Dynamic/Marshallers.h index c76ddf17b719d4..0e640cbada7268 100644 --- a/clang/lib/ASTMatchers/Dynamic/Marshallers.h +++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.h @@ -937,7 +937,7 @@ class MapAnyOfMatcherDescriptor : public MatcherDescriptor { public: MapAnyOfMatcherDescriptor(ASTNodeKind CladeNodeKind, std::vector NodeKinds) - : CladeNodeKind(CladeNodeKind), NodeKinds(NodeKinds) {} + : CladeNodeKind(CladeNodeKind), NodeKinds(std::move(NodeKinds)) {} VariantMatcher create(SourceRange NameRange, ArrayRef Args, Diagnostics *Error) const override { @@ -1026,7 +1026,7 @@ class MapAnyOfBuilderDescriptor : public MatcherDescriptor { } return std::make_unique(CladeNodeKind, - NodeKinds); + std::move(NodeKinds)); } bool isVariadic() const override { return true; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] cppcheck: use move semantics for 'NodeKinds' and update possible callers to use it (PR #87273)
https://github.com/RKSimon closed https://github.com/llvm/llvm-project/pull/87273 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] cppcheck: use move semantics for 'NodeKinds' and update possible callers to use it (PR #87273)
github-actions[bot] wrote: @Amila-Rukshan Congratulations on having your first Pull Request (PR) merged into the LLVM Project! Your changes will be combined with recent changes from other authors, then tested by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with a build, you may receive a report in an email or a comment on this PR. Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues. How to do this, and the rest of the post-merge process, is covered in detail [here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr). If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of [LLVM development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy). You can fix your changes and open a new PR to merge them again. If you don't get any reports, no action is required from you. Your changes are working as expected, well done! https://github.com/llvm/llvm-project/pull/87273 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Constexpr for __builtin_shufflevector and __builtin_convertvector (PR #76615)
Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= Message-ID: In-Reply-To: @@ -10895,6 +10899,132 @@ bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { return Success(APValue(ResultElements.data(), ResultElements.size()), E); } +static bool EvaluateVectorOrLValue(APValue &Result, EvalInfo &Info, + const Expr *E, const QualType &Type) { + if (!Evaluate(Result, Info, E)) +return false; + + if (Result.isLValue()) { +// Source of the data is an lvalue; Manually handle the lvalue as if +// it was an rvalue to get the current APValue. +LValue LValueFound; +LValueFound.setFrom(Info.Ctx, Result); +if (!handleLValueToRValueConversion(Info, E, Type, LValueFound, Result)) + return false; + } + + return Result.isVector(); +} + +static bool handleVectorConversion(EvalInfo &Info, const FPOptions FPO, + const Expr *E, QualType SourceTy, + QualType DestTy, APValue const &Original, + APValue &Result) { + if (SourceTy->isIntegerType()) { +if (DestTy->isRealFloatingType()) { + Result = APValue(APFloat(0.0)); + return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(), + DestTy, Result.getFloat()); +} +if (DestTy->isIntegerType()) { + Result = APValue( + HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt())); + return true; +} + } else if (SourceTy->isRealFloatingType()) { +if (DestTy->isRealFloatingType()) { + Result = Original; + return HandleFloatToFloatCast(Info, E, SourceTy, DestTy, +Result.getFloat()); +} +if (DestTy->isIntegerType()) { + Result = APValue(APSInt()); + return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(), + DestTy, Result.getInt()); +} + } + return false; Destroyerrrocket wrote: I agree that adding a diagnostic here, even if unreachable, is more than just desired, I'm well convinced on the future-proofing argument. I will not add a test because I simply don't have a way to reach this, I believe. https://github.com/llvm/llvm-project/pull/76615 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
https://github.com/HerrCai0907 created https://github.com/llvm/llvm-project/pull/89497 Detects the function which returns the const reference from parameter which causes potential use after free if the caller uses xvalue as argument. In c++, const reference parameter can accept xvalue which will be destructed after the call. When the function returns this parameter also as const reference, then the returned reference can be used after the object it refers to has been destroyed. Fixes: #85253 >From 91915f68902ade86c0bf8eba643428017ae8bb3c Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Sat, 20 Apr 2024 17:58:19 +0800 Subject: [PATCH] [tidy] add new check bugprone-return-const-ref-from-parameter Detects the function which returns the const reference from parameter which causes potential use after free if the caller uses xvalue as argument. In c++, const reference parameter can accept xvalue which will be destructed after the call. When the function returns this parameter also as const reference, then the returned reference can be used after the object it refers to has been destroyed. Fixes: #85253 --- .../bugprone/BugproneTidyModule.cpp | 3 ++ .../clang-tidy/bugprone/CMakeLists.txt| 1 + .../ReturnConstRefFromParameterCheck.cpp | 41 +++ .../ReturnConstRefFromParameterCheck.h| 35 clang-tools-extra/docs/ReleaseNotes.rst | 6 +++ .../return-const-ref-from-parameter.rst | 30 ++ .../docs/clang-tidy/checks/list.rst | 9 ++-- .../return-const-ref-from-parameter.cpp | 31 ++ 8 files changed, 152 insertions(+), 4 deletions(-) create mode 100644 clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/bugprone/return-const-ref-from-parameter.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/bugprone/return-const-ref-from-parameter.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp index 2931325d8b5798..1b92d2e60cc173 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp @@ -54,6 +54,7 @@ #include "PosixReturnCheck.h" #include "RedundantBranchConditionCheck.h" #include "ReservedIdentifierCheck.h" +#include "ReturnConstRefFromParameterCheck.h" #include "SharedPtrArrayMismatchCheck.h" #include "SignalHandlerCheck.h" #include "SignedCharMisuseCheck.h" @@ -137,6 +138,8 @@ class BugproneModule : public ClangTidyModule { "bugprone-inaccurate-erase"); CheckFactories.registerCheck( "bugprone-incorrect-enable-if"); +CheckFactories.registerCheck( +"bugprone-return-const-ref-from-parameter"); CheckFactories.registerCheck( "bugprone-switch-missing-default-case"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt index 081ba67efe1538..2d303191f88650 100644 --- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt @@ -26,6 +26,7 @@ add_clang_library(clangTidyBugproneModule ImplicitWideningOfMultiplicationResultCheck.cpp InaccurateEraseCheck.cpp IncorrectEnableIfCheck.cpp + ReturnConstRefFromParameterCheck.cpp SuspiciousStringviewDataUsageCheck.cpp SwitchMissingDefaultCaseCheck.cpp IncDecInConditionsCheck.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp new file mode 100644 index 00..87fc663231496e --- /dev/null +++ b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp @@ -0,0 +1,41 @@ +//===--- ReturnConstRefFromParameterCheck.cpp - clang-tidy ===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ReturnConstRefFromParameterCheck.h" +#include "../utils/Matchers.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +std::optional +ReturnConstRefFromParameterCheck::getCheckTraversalKind() const { + // Use 'AsIs' to make sure the return type is exactly the same as the + // parameter type. + return TK_AsIs; +} + +void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + returnStmt(hasReturnValue(declRefExpr
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
llvmbot wrote: @llvm/pr-subscribers-clang-tidy Author: Congcong Cai (HerrCai0907) Changes Detects the function which returns the const reference from parameter which causes potential use after free if the caller uses xvalue as argument. In c++, const reference parameter can accept xvalue which will be destructed after the call. When the function returns this parameter also as const reference, then the returned reference can be used after the object it refers to has been destroyed. Fixes: #85253 --- Full diff: https://github.com/llvm/llvm-project/pull/89497.diff 8 Files Affected: - (modified) clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp (+3) - (modified) clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt (+1) - (added) clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp (+41) - (added) clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.h (+35) - (modified) clang-tools-extra/docs/ReleaseNotes.rst (+6) - (added) clang-tools-extra/docs/clang-tidy/checks/bugprone/return-const-ref-from-parameter.rst (+30) - (modified) clang-tools-extra/docs/clang-tidy/checks/list.rst (+5-4) - (added) clang-tools-extra/test/clang-tidy/checkers/bugprone/return-const-ref-from-parameter.cpp (+31) ``diff diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp index 2931325d8b5798..1b92d2e60cc173 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp @@ -54,6 +54,7 @@ #include "PosixReturnCheck.h" #include "RedundantBranchConditionCheck.h" #include "ReservedIdentifierCheck.h" +#include "ReturnConstRefFromParameterCheck.h" #include "SharedPtrArrayMismatchCheck.h" #include "SignalHandlerCheck.h" #include "SignedCharMisuseCheck.h" @@ -137,6 +138,8 @@ class BugproneModule : public ClangTidyModule { "bugprone-inaccurate-erase"); CheckFactories.registerCheck( "bugprone-incorrect-enable-if"); +CheckFactories.registerCheck( +"bugprone-return-const-ref-from-parameter"); CheckFactories.registerCheck( "bugprone-switch-missing-default-case"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt index 081ba67efe1538..2d303191f88650 100644 --- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt @@ -26,6 +26,7 @@ add_clang_library(clangTidyBugproneModule ImplicitWideningOfMultiplicationResultCheck.cpp InaccurateEraseCheck.cpp IncorrectEnableIfCheck.cpp + ReturnConstRefFromParameterCheck.cpp SuspiciousStringviewDataUsageCheck.cpp SwitchMissingDefaultCaseCheck.cpp IncDecInConditionsCheck.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp new file mode 100644 index 00..87fc663231496e --- /dev/null +++ b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp @@ -0,0 +1,41 @@ +//===--- ReturnConstRefFromParameterCheck.cpp - clang-tidy ===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ReturnConstRefFromParameterCheck.h" +#include "../utils/Matchers.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +std::optional +ReturnConstRefFromParameterCheck::getCheckTraversalKind() const { + // Use 'AsIs' to make sure the return type is exactly the same as the + // parameter type. + return TK_AsIs; +} + +void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + returnStmt(hasReturnValue(declRefExpr(to(parmVarDecl(hasType( + hasCanonicalType(matchers::isReferenceToConst( + .bind("ret"), + this); +} + +void ReturnConstRefFromParameterCheck::check( +const MatchFinder::MatchResult &Result) { + const auto *R = Result.Nodes.getNodeAs("ret"); + diag(R->getRetValue()->getBeginLoc(), + "return const reference parameter cause potential use-after-free " + "when function accepts immediately constructed value."); +} + +} // namespace clang::tidy::bugprone diff --git a/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.h b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.h new file mode 100644 index 00..96d02aa2563edf --- /dev/null +++ b/clang-tools-extra/clang-tidy/bug
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
https://github.com/HerrCai0907 edited https://github.com/llvm/llvm-project/pull/89497 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Constexpr for __builtin_shufflevector and __builtin_convertvector (PR #76615)
Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= Message-ID: In-Reply-To: @@ -10961,6 +10968,118 @@ bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { return Success(APValue(ResultElements.data(), ResultElements.size()), E); } +static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, +const Expr *E, QualType SourceTy, +QualType DestTy, APValue const &Original, +APValue &Result) { + if (SourceTy->isIntegerType()) { +if (DestTy->isRealFloatingType()) { + Result = APValue(APFloat(0.0)); + return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(), + DestTy, Result.getFloat()); +} +if (DestTy->isIntegerType()) { + Result = APValue( + HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt())); + return true; +} + } else if (SourceTy->isRealFloatingType()) { +if (DestTy->isRealFloatingType()) { + Result = Original; + return HandleFloatToFloatCast(Info, E, SourceTy, DestTy, +Result.getFloat()); +} +if (DestTy->isIntegerType()) { + Result = APValue(APSInt()); + return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(), + DestTy, Result.getInt()); +} + } + return false; +} + +bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) { + APValue Source; + QualType SourceVecType = E->getSrcExpr()->getType(); + if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source)) +return false; + + QualType DestTy = E->getType()->castAs()->getElementType(); + QualType SourceTy = SourceVecType->castAs()->getElementType(); + + const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); + + auto SourceLen = Source.getVectorLength(); + SmallVector ResultElements; + ResultElements.reserve(SourceLen); + for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) { +APValue Elt; +if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy, + Source.getVectorElt(EltNum), Elt)) + return false; +ResultElements.push_back(std::move(Elt)); + } + + return Success(APValue(ResultElements.data(), ResultElements.size()), E); +} + +static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, +QualType ElemType, APValue const &VecVal1, +APValue const &VecVal2, unsigned EltNum, +APValue &Result) { + unsigned const TotalElementsInInputVector = VecVal1.getVectorLength(); + + APSInt IndexVal = E->getShuffleMaskIdx(Info.Ctx, EltNum); + int64_t index = IndexVal.getExtValue(); + // The spec says that -1 should be treated as undef for optimizations, + // but in constexpr we need to choose a value. We'll choose 0. + if (index == -1) { +Info.FFDiag( +E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr) +<< EltNum; +return false; + } + + if (index < 0 || index >= TotalElementsInInputVector * 2) +llvm_unreachable("Out of bounds shuffle index"); + + if (index >= TotalElementsInInputVector) +Result = VecVal2.getVectorElt(index - TotalElementsInInputVector); + else +Result = VecVal1.getVectorElt(index); + return true; +} + +bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) { + APValue VecVal1; + const Expr *Vec1 = E->getExpr(0); + if (!EvaluateAsRValue(Info, Vec1, VecVal1)) +return false; + APValue VecVal2; + const Expr *Vec2 = E->getExpr(1); + if (!EvaluateAsRValue(Info, Vec2, VecVal2)) +return false; + + VectorType const *DestVecTy = E->getType()->castAs(); + if (!DestVecTy) +return false; + + QualType DestElTy = DestVecTy->getElementType(); Destroyerrrocket wrote: That's good to know indeed :) https://github.com/llvm/llvm-project/pull/76615 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Sema] Remove invalid ctor (NFC) (PR #82161)
Smertig wrote: Ping? @cor3ntin https://github.com/llvm/llvm-project/pull/82161 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 55ed4e3 - [Clang][Sema] Remove invalid ctor (NFC) (#82161)
Author: Alexander Date: 2024-04-20T12:11:24+02:00 New Revision: 55ed4e314fb6f2c3e66113931088c36e6bcfca74 URL: https://github.com/llvm/llvm-project/commit/55ed4e314fb6f2c3e66113931088c36e6bcfca74 DIFF: https://github.com/llvm/llvm-project/commit/55ed4e314fb6f2c3e66113931088c36e6bcfca74.diff LOG: [Clang][Sema] Remove invalid ctor (NFC) (#82161) `TemplateArgumentLocInventIterator` default constructor should not exists https://github.com/llvm/llvm-project/blob/3496927edcd0685807351ba88a7e2cfb006e1c0d/clang/lib/Sema/TreeTransform.h#L4742 because it doesn't and couldn't initialize `Self` member that is reference: https://github.com/llvm/llvm-project/blob/3496927edcd0685807351ba88a7e2cfb006e1c0d/clang/lib/Sema/TreeTransform.h#L4721-L4723 Instantiation of this constructor is always a compile-time error. Please note, that I didn't run any tests, because cannot imagine situation where this constructor can be properly used. There are no new tests for this fix for the same reason. Added: Modified: clang/lib/Sema/TreeTransform.h Removed: diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index ade33ec65038fd..180574f1cab819 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -4759,8 +4759,6 @@ class TemplateArgumentLocInventIterator { const TemplateArgumentLoc *operator->() const { return &Arg; } }; - TemplateArgumentLocInventIterator() { } - explicit TemplateArgumentLocInventIterator(TreeTransform &Self, InputIterator Iter) : Self(Self), Iter(Iter) { } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Sema] Remove invalid ctor (NFC) (PR #82161)
https://github.com/cor3ntin closed https://github.com/llvm/llvm-project/pull/82161 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Sema] Remove invalid ctor (NFC) (PR #82161)
github-actions[bot] wrote: @Smertig Congratulations on having your first Pull Request (PR) merged into the LLVM Project! Your changes will be combined with recent changes from other authors, then tested by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with a build, you may receive a report in an email or a comment on this PR. Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues. How to do this, and the rest of the post-merge process, is covered in detail [here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr). If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of [LLVM development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy). You can fix your changes and open a new PR to merge them again. If you don't get any reports, no action is required from you. Your changes are working as expected, well done! https://github.com/llvm/llvm-project/pull/82161 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Constexpr for __builtin_shufflevector and __builtin_convertvector (PR #76615)
Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= Message-ID: In-Reply-To: https://github.com/Destroyerrrocket updated https://github.com/llvm/llvm-project/pull/76615 >From 7447038a5006ff5fe5fdeead865287930843d8f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pol=20Marcet=20Sard=C3=A0?= Date: Sat, 30 Dec 2023 13:59:00 +0100 Subject: [PATCH 1/5] [clang] Constexpr for __builtin_shufflevector and __builtin_convertvector Summary: This patch adds constexpr support for __builtin_shufflevector and __builtin_convertvector. A small oddity encountered was that the arg to the intrinsics may be an lvalue without any sort of implicit cast of any kind. I solved this through the EvaluateVectorOrLValue function, which treats the lvalue as if it was in an rvalue cast, which gets me the desired vector. --- clang/docs/LanguageExtensions.rst | 5 +- clang/docs/ReleaseNotes.rst | 3 + clang/lib/AST/ExprConstant.cpp| 138 +- clang/test/Sema/constant-builtins-2.c | 61 4 files changed, 204 insertions(+), 3 deletions(-) diff --git a/clang/docs/LanguageExtensions.rst b/clang/docs/LanguageExtensions.rst index 7b23e4d1c2f30c..485e4af69b3e02 100644 --- a/clang/docs/LanguageExtensions.rst +++ b/clang/docs/LanguageExtensions.rst @@ -2925,7 +2925,7 @@ Query for this feature with ``__has_builtin(__builtin_dump_struct)`` ``__builtin_shufflevector`` is used to express generic vector permutation/shuffle/swizzle operations. This builtin is also very important for the implementation of various target-specific header files like -. +. This builtin can be used within constant expressions. **Syntax**: @@ -2979,7 +2979,8 @@ Query for this feature with ``__has_builtin(__builtin_shufflevector)``. ``__builtin_convertvector`` is used to express generic vector type-conversion operations. The input vector and the output vector -type must have the same number of elements. +type must have the same number of elements. This builtin can be used within +constant expressions. **Syntax**: diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 76eaf0bf11c303..a3c96e44eef4dd 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -193,6 +193,9 @@ Non-comprehensive list of changes in this release with support for any unsigned integer type. Like the previous builtins, these new builtins are constexpr and may be used in constant expressions. +- Builtins ``__builtin_shufflevector()`` and ``__builtin_convertvector()`` may + now be used within constant expressions. + New Compiler Flags -- diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index dae8f32fc02951..6b43b6a1638fbc 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -2706,7 +2706,8 @@ static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result) { - assert(isa(E) || isa(E)); + assert(isa(E) || isa(E) || + isa(E)); llvm::RoundingMode RM = getActiveRoundingMode(Info, E); APFloat::opStatus St; APFloat Value = Result; @@ -10709,6 +10710,9 @@ namespace { bool VisitUnaryImag(const UnaryOperator *E); bool VisitBinaryOperator(const BinaryOperator *E); bool VisitUnaryOperator(const UnaryOperator *E); +bool VisitConvertVectorExpr(const ConvertVectorExpr *E); +bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E); + // FIXME: Missing: conditional operator (for GNU // conditional select), shufflevector, ExtVectorElementExpr }; @@ -10961,6 +10965,138 @@ bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { return Success(APValue(ResultElements.data(), ResultElements.size()), E); } +static bool EvaluateVectorOrLValue(APValue &Result, EvalInfo &Info, + const Expr *E, const QualType &Type) { + if (!Evaluate(Result, Info, E)) +return false; + + if (Result.isLValue()) { +// Source of the data is an lvalue; Manually handle the lvalue as if +// it was an rvalue to get the current APValue. +LValue LValueFound; +LValueFound.setFrom(Info.Ctx, Result); +if (!handleLValueToRValueConversion(Info, E, Type, LValueFound, Result)) { + return false; +} + } + + if (!Result.isVector()) { +return false; + } + return true; +} + +static bool handleVectorConversion(EvalInfo &Info, const FPOptions FPO, + const Expr *E, QualType SourceTy, + QualType DestTy, APValue const &Original, + APValue &Result) { + if (SourceTy->isIntegerType()) { +if (DestTy->isRealFloatingType()) { +
[clang] [clang] Allow relational comparisons between unequal pointers to `void` in constant expressions (PR #89449)
cor3ntin wrote: @Endilll The issues do not supersede one another , despite concerning the same note. The tests for CWG2526 are in [clang/test/CXX/expr/expr.const/p2-0x.cpp](https://github.com/llvm/llvm-project/pull/89449/files#diff-a7dde1a012f85b943dcb6e0f8086cf28d27a48987a27c118459525ab9632cf82), so we should make that as fixed by copying these tests in dr25xx.cpp Why do you think this should not apply to C++14 @offsetof ? https://github.com/llvm/llvm-project/pull/89449 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 31480b0 - [test] Avoid writing to a potentially write-protected dir (#89242)
Author: Karl-Johan Karlsson Date: 2024-04-20T12:26:58+02:00 New Revision: 31480b0cc8fe2bb1e080ffd38e38780ba7e8dec6 URL: https://github.com/llvm/llvm-project/commit/31480b0cc8fe2bb1e080ffd38e38780ba7e8dec6 DIFF: https://github.com/llvm/llvm-project/commit/31480b0cc8fe2bb1e080ffd38e38780ba7e8dec6.diff LOG: [test] Avoid writing to a potentially write-protected dir (#89242) These tests just don't check the output written to the current directory. The current directory may be write protected e.g. in a sandboxed environment. The Testcases that use -emit-llvm and -verify only care about stdout/stderr and are in this patch changed to use -emit-llvm-only to avoid writing to an output file. The verify-inlineasmbr.mir testcase that also only care about stdout/stderr is in this patch changed to throw away the output file and just write to /dev/null. Added: Modified: clang/test/CodeGen/PowerPC/builtins-ppc-htm.c clang/test/CodeGen/PowerPC/builtins-ppc-vec-ins-error.c clang/test/CodeGen/RISCV/riscv-func-attr-target-err.c clang/test/Sema/ppc-attr-target-inline.c clang/test/SemaHLSL/BuiltIns/any-errors.hlsl clang/test/SemaHLSL/BuiltIns/clamp-errors.hlsl clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl clang/test/SemaHLSL/BuiltIns/exp-errors.hlsl clang/test/SemaHLSL/BuiltIns/frac-errors.hlsl clang/test/SemaHLSL/BuiltIns/half-float-only-errors.hlsl clang/test/SemaHLSL/BuiltIns/isinf-errors.hlsl clang/test/SemaHLSL/BuiltIns/lerp-errors.hlsl clang/test/SemaHLSL/BuiltIns/mad-errors.hlsl clang/test/SemaHLSL/BuiltIns/pow-errors.hlsl clang/test/SemaHLSL/BuiltIns/rcp-errors.hlsl clang/test/SemaHLSL/BuiltIns/reversebits-errors.hlsl clang/test/SemaHLSL/BuiltIns/round-errors.hlsl clang/test/SemaHLSL/BuiltIns/rsqrt-errors.hlsl llvm/test/MachineVerifier/verify-inlineasmbr.mir Removed: diff --git a/clang/test/CodeGen/PowerPC/builtins-ppc-htm.c b/clang/test/CodeGen/PowerPC/builtins-ppc-htm.c index 51585f27e0bc70..eeb13b097819cd 100644 --- a/clang/test/CodeGen/PowerPC/builtins-ppc-htm.c +++ b/clang/test/CodeGen/PowerPC/builtins-ppc-htm.c @@ -1,6 +1,6 @@ // REQUIRES: powerpc-registered-target // RUN: %clang_cc1 -target-feature +altivec -target-feature +htm -triple powerpc64-unknown-unknown -emit-llvm %s -o - | FileCheck %s -// RUN: not %clang_cc1 -target-feature +altivec -target-feature -htm -triple powerpc64-unknown-unknown -emit-llvm %s 2>&1 | FileCheck %s --check-prefix=ERROR +// RUN: not %clang_cc1 -target-feature +altivec -target-feature -htm -triple powerpc64-unknown-unknown -emit-llvm-only %s 2>&1 | FileCheck %s --check-prefix=ERROR void test1(long int *r, int code, long int *a, long int *b) { // CHECK-LABEL: define{{.*}} void @test1 diff --git a/clang/test/CodeGen/PowerPC/builtins-ppc-vec-ins-error.c b/clang/test/CodeGen/PowerPC/builtins-ppc-vec-ins-error.c index f5149bf4ce8fda..485ef84df086b7 100644 --- a/clang/test/CodeGen/PowerPC/builtins-ppc-vec-ins-error.c +++ b/clang/test/CodeGen/PowerPC/builtins-ppc-vec-ins-error.c @@ -1,17 +1,17 @@ // REQUIRES: powerpc-registered-target // RUN: %clang_cc1 -flax-vector-conversions=none -target-feature +vsx -target-cpu pwr10 -fsyntax-only \ -// RUN: -triple powerpc64le-unknown-unknown -emit-llvm -ferror-limit 10 %s -verify -D __TEST_ELT_SI +// RUN: -triple powerpc64le-unknown-unknown -emit-llvm-only -ferror-limit 10 %s -verify -D __TEST_ELT_SI // RUN: %clang_cc1 -flax-vector-conversions=none -target-feature +vsx -target-cpu pwr10 -fsyntax-only \ -// RUN: -triple powerpc64-unknown-unknown -emit-llvm -ferror-limit 10 %s -verify -D __TEST_ELT_F +// RUN: -triple powerpc64-unknown-unknown -emit-llvm-only -ferror-limit 10 %s -verify -D __TEST_ELT_F // RUN: %clang_cc1 -flax-vector-conversions=none -target-feature +vsx -target-cpu pwr10 -fsyntax-only \ -// RUN: -triple powerpc64le-unknown-unknown -emit-llvm -ferror-limit 10 %s -verify -D __TEST_ELT_SLL +// RUN: -triple powerpc64le-unknown-unknown -emit-llvm-only -ferror-limit 10 %s -verify -D __TEST_ELT_SLL // RUN: %clang_cc1 -flax-vector-conversions=none -target-feature +vsx -target-cpu pwr10 -fsyntax-only \ -// RUN: -triple powerpc64-unknown-unknown -emit-llvm -ferror-limit 10 %s -verify -D __TEST_ELT_D +// RUN: -triple powerpc64-unknown-unknown -emit-llvm-only -ferror-limit 10 %s -verify -D __TEST_ELT_D // RUN: %clang_cc1 -flax-vector-conversions=none -target-feature +vsx -target-cpu pwr10 -fsyntax-only \ -// RUN: -triple powerpc64le-unknown-unknown -emit-llvm -ferror-limit 10 %s -verify -D __TEST_UNALIGNED_UI +// RUN: -triple powerpc64le-unknown-unknown -emit-llvm-only -ferror-limit 10 %s -verify -D __TEST_UNALIGNED_UI // RUN: %clang_cc1 -flax-vector-conversions=none -target-feature +vsx -target-cpu pwr10 -fsyntax-only \ -// RUN: -triple powerpc64-unknown-unknown -emit-llvm -ferror-limit 10 %s -verify +// RUN:
[clang] [llvm] [test] Avoid writing to a potentially write-protected dir (PR #89242)
https://github.com/karka228 closed https://github.com/llvm/llvm-project/pull/89242 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Constexpr for __builtin_shufflevector and __builtin_convertvector (PR #76615)
Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= Message-ID: In-Reply-To: https://github.com/Destroyerrrocket updated https://github.com/llvm/llvm-project/pull/76615 >From c14783de45687c754253c0cbf8a7834c7f986d80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pol=20Marcet=20Sard=C3=A0?= Date: Sat, 30 Dec 2023 13:59:00 +0100 Subject: [PATCH 1/5] [clang] Constexpr for __builtin_shufflevector and __builtin_convertvector Summary: This patch adds constexpr support for __builtin_shufflevector and __builtin_convertvector. A small oddity encountered was that the arg to the intrinsics may be an lvalue without any sort of implicit cast of any kind. I solved this through the EvaluateVectorOrLValue function, which treats the lvalue as if it was in an rvalue cast, which gets me the desired vector. --- clang/docs/LanguageExtensions.rst | 5 +- clang/docs/ReleaseNotes.rst | 3 + clang/lib/AST/ExprConstant.cpp| 138 +- clang/test/Sema/constant-builtins-2.c | 61 4 files changed, 204 insertions(+), 3 deletions(-) diff --git a/clang/docs/LanguageExtensions.rst b/clang/docs/LanguageExtensions.rst index 3bead159c8f946..3204e950f92429 100644 --- a/clang/docs/LanguageExtensions.rst +++ b/clang/docs/LanguageExtensions.rst @@ -2927,7 +2927,7 @@ Query for this feature with ``__has_builtin(__builtin_dump_struct)`` ``__builtin_shufflevector`` is used to express generic vector permutation/shuffle/swizzle operations. This builtin is also very important for the implementation of various target-specific header files like -. +. This builtin can be used within constant expressions. **Syntax**: @@ -2981,7 +2981,8 @@ Query for this feature with ``__has_builtin(__builtin_shufflevector)``. ``__builtin_convertvector`` is used to express generic vector type-conversion operations. The input vector and the output vector -type must have the same number of elements. +type must have the same number of elements. This builtin can be used within +constant expressions. **Syntax**: diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index c44f238e33846b..071a8f4cff9db9 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -203,6 +203,9 @@ Non-comprehensive list of changes in this release - ``__typeof_unqual__`` is available in all C modes as an extension, which behaves like ``typeof_unqual`` from C23, similar to ``__typeof__`` and ``typeof``. +- Builtins ``__builtin_shufflevector()`` and ``__builtin_convertvector()`` may + now be used within constant expressions. + New Compiler Flags -- - ``-fsanitize=implicit-bitfield-conversion`` checks implicit truncation and diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index 73ae8d8efb23a2..aafea66359d23b 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -2706,7 +2706,8 @@ static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result) { - assert(isa(E) || isa(E)); + assert(isa(E) || isa(E) || + isa(E)); llvm::RoundingMode RM = getActiveRoundingMode(Info, E); APFloat::opStatus St; APFloat Value = Result; @@ -10709,6 +10710,9 @@ namespace { bool VisitUnaryImag(const UnaryOperator *E); bool VisitBinaryOperator(const BinaryOperator *E); bool VisitUnaryOperator(const UnaryOperator *E); +bool VisitConvertVectorExpr(const ConvertVectorExpr *E); +bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E); + // FIXME: Missing: conditional operator (for GNU // conditional select), shufflevector, ExtVectorElementExpr }; @@ -10961,6 +10965,138 @@ bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { return Success(APValue(ResultElements.data(), ResultElements.size()), E); } +static bool EvaluateVectorOrLValue(APValue &Result, EvalInfo &Info, + const Expr *E, const QualType &Type) { + if (!Evaluate(Result, Info, E)) +return false; + + if (Result.isLValue()) { +// Source of the data is an lvalue; Manually handle the lvalue as if +// it was an rvalue to get the current APValue. +LValue LValueFound; +LValueFound.setFrom(Info.Ctx, Result); +if (!handleLValueToRValueConversion(Info, E, Type, LValueFound, Result)) { + return false; +} + } + + if (!Result.isVector()) { +return false; + } + return true; +} + +static bool handleVectorConversion(EvalInfo &Info, const FPOptions FPO, + const Expr *E, QualType SourceTy, + QualType DestTy, APValue const &Original, + APValue &Resu
[clang] [C++17] Support __GCC_[CON|DE]STRUCTIVE_SIZE (PR #89446)
cor3ntin wrote: @AaronBallman Did you read https://discourse.llvm.org/t/rfc-c-17-hardware-constructive-destructive-interference-size/48674/42 ? I want to make sure we do abide by it and it's unclear a consensus was ever formed or called https://github.com/llvm/llvm-project/pull/89446 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Constexpr for __builtin_shufflevector and __builtin_convertvector (PR #76615)
Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= , Pol Marcet =?utf-8?q?Sardà?= Message-ID: In-Reply-To: Destroyerrrocket wrote: Addressed the comments; I don't really like the expanded macro code, it generates 600 lines of really repetitive code, so I left the macros as a source of truth that I'd use to generate the cases in the future. https://github.com/llvm/llvm-project/pull/76615 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Allow constexpr cast from `void*` in more cases (PR #89484)
https://github.com/cor3ntin approved this pull request. LGTM, thanks! https://github.com/llvm/llvm-project/pull/89484 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Add config option to allow detection of unused system headers (PR #87208)
vvd170501 wrote: @HighCommander4 Ping. Could you review this PR or suggest other reviewers, please? https://github.com/llvm/llvm-project/pull/87208 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][CWG1815] Support lifetime extension of temporary created by aggregate initialization using a default member initializer (PR #87933)
yronglin wrote: Friendly ping~ @zygoloid @hubert-reinterpretcast https://github.com/llvm/llvm-project/pull/87933 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
@@ -0,0 +1,30 @@ +.. title:: clang-tidy - bugprone-return-const-ref-from-parameter + +bugprone-return-const-ref-from-parameter + + +Detects the function which returns the const reference from parameter which +causes potential use after free if the caller uses xvalue as argument. + +In c++, const reference parameter can accept xvalue which will be destructed EugeneZelenko wrote: ```suggestion In C++, const reference parameter can accept xvalue which will be destructed ``` https://github.com/llvm/llvm-project/pull/89497 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
@@ -0,0 +1,35 @@ +//===--- ReturnConstRefFromParameterCheck.h - clang-tidy *- 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 +// +//===--===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_RETURNCONSTREFFROMPARAMETERCHECK_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_RETURNCONSTREFFROMPARAMETERCHECK_H + +#include "../ClangTidyCheck.h" + +namespace clang::tidy::bugprone { + +/// Detects the function which returns the const reference from parameter which +/// causes potential use after free if the caller uses xvalue as argument. SimplyDanny wrote: ```suggestion /// Detects statements that return constant reference parameters as constant /// references. This might cause potential use after free errors if the caller /// uses xvalues as arguments. ``` https://github.com/llvm/llvm-project/pull/89497 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
@@ -0,0 +1,30 @@ +.. title:: clang-tidy - bugprone-return-const-ref-from-parameter + +bugprone-return-const-ref-from-parameter + + +Detects the function which returns the const reference from parameter which +causes potential use after free if the caller uses xvalue as argument. + +In c++, const reference parameter can accept xvalue which will be destructed +after the call. When the function returns this parameter also as const reference, +then the returned reference can be used after the object it refers to has been +destroyed. SimplyDanny wrote: ```suggestion In C++, constant reference parameters can accept xvalues which will be destructed after the call. When the function returns such a parameter also as constant reference, then the returned reference can be used after the object it refers to has been destroyed. ``` https://github.com/llvm/llvm-project/pull/89497 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
@@ -0,0 +1,41 @@ +//===--- ReturnConstRefFromParameterCheck.cpp - clang-tidy ===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ReturnConstRefFromParameterCheck.h" +#include "../utils/Matchers.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +std::optional +ReturnConstRefFromParameterCheck::getCheckTraversalKind() const { SimplyDanny wrote: I always wonder where these little methods are supposed to be implemented. Wondering because the implementation for `isLanguageVersionSupported` is also in the header file. https://github.com/llvm/llvm-project/pull/89497 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
@@ -0,0 +1,41 @@ +//===--- ReturnConstRefFromParameterCheck.cpp - clang-tidy ===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ReturnConstRefFromParameterCheck.h" +#include "../utils/Matchers.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +std::optional +ReturnConstRefFromParameterCheck::getCheckTraversalKind() const { + // Use 'AsIs' to make sure the return type is exactly the same as the + // parameter type. + return TK_AsIs; +} + +void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + returnStmt(hasReturnValue(declRefExpr(to(parmVarDecl(hasType( + hasCanonicalType(matchers::isReferenceToConst( + .bind("ret"), + this); +} + +void ReturnConstRefFromParameterCheck::check( +const MatchFinder::MatchResult &Result) { + const auto *R = Result.Nodes.getNodeAs("ret"); + diag(R->getRetValue()->getBeginLoc(), SimplyDanny wrote: Is it safe to assume that `R` is valid and not `nullptr`? https://github.com/llvm/llvm-project/pull/89497 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
@@ -341,9 +342,9 @@ Clang-Tidy Checks :doc:`portability-std-allocator-const `, :doc:`readability-avoid-const-params-in-decls `, "Yes" :doc:`readability-avoid-nested-conditional-operator `, - :doc:`readability-avoid-return-with-void-value `, + :doc:`readability-avoid-return-with-void-value `, "Yes" :doc:`readability-avoid-unconditional-preprocessor-if `, - :doc:`readability-braces-around-statements `, "Yes" SimplyDanny wrote: This should be separate changes. https://github.com/llvm/llvm-project/pull/89497 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lldb] Revert "NFC: Make clang resource headers an interface library (#88317)" (PR #89266)
ayermolo wrote: Fixed our internal foobar yesterday. Can close this. https://github.com/llvm/llvm-project/pull/89266 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 5a1a522 - [SPIRV][HLSL] Add mad intrinsic lowering for spirv (#89130)
Author: Farzon Lotfi Date: 2024-04-20T11:13:53-04:00 New Revision: 5a1a5226b578ec7f123f67efd4e24e39fecd11d7 URL: https://github.com/llvm/llvm-project/commit/5a1a5226b578ec7f123f67efd4e24e39fecd11d7 DIFF: https://github.com/llvm/llvm-project/commit/5a1a5226b578ec7f123f67efd4e24e39fecd11d7.diff LOG: [SPIRV][HLSL] Add mad intrinsic lowering for spirv (#89130) - `clang/lib/CodeGen/CGBuiltin.cpp` - Add a generic mull add implementation. Make DXIL implementation tied to target. resolves #88944 Added: llvm/test/CodeGen/SPIRV/hlsl-intrinsics/imad.ll Modified: clang/lib/CodeGen/CGBuiltin.cpp clang/test/CodeGenHLSL/builtins/mad.hlsl llvm/test/CodeGen/DirectX/fmad.ll llvm/test/CodeGen/SPIRV/hlsl-intrinsics/fmad.ll Removed: diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 4ab844d206e48a..afe2de5d00ac5d 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -18296,20 +18296,28 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned BuiltinID, Value *M = EmitScalarExpr(E->getArg(0)); Value *A = EmitScalarExpr(E->getArg(1)); Value *B = EmitScalarExpr(E->getArg(2)); -if (E->getArg(0)->getType()->hasFloatingRepresentation()) { +if (E->getArg(0)->getType()->hasFloatingRepresentation()) return Builder.CreateIntrinsic( /*ReturnType*/ M->getType(), Intrinsic::fmuladd, - ArrayRef{M, A, B}, nullptr, "dx.fmad"); -} + ArrayRef{M, A, B}, nullptr, "hlsl.fmad"); + if (E->getArg(0)->getType()->hasSignedIntegerRepresentation()) { - return Builder.CreateIntrinsic( - /*ReturnType*/ M->getType(), Intrinsic::dx_imad, - ArrayRef{M, A, B}, nullptr, "dx.imad"); + if (CGM.getTarget().getTriple().getArch() == llvm::Triple::dxil) +return Builder.CreateIntrinsic( +/*ReturnType*/ M->getType(), Intrinsic::dx_imad, +ArrayRef{M, A, B}, nullptr, "dx.imad"); + + Value *Mul = Builder.CreateNSWMul(M, A); + return Builder.CreateNSWAdd(Mul, B); } assert(E->getArg(0)->getType()->hasUnsignedIntegerRepresentation()); -return Builder.CreateIntrinsic( -/*ReturnType=*/M->getType(), Intrinsic::dx_umad, -ArrayRef{M, A, B}, nullptr, "dx.umad"); +if (CGM.getTarget().getTriple().getArch() == llvm::Triple::dxil) + return Builder.CreateIntrinsic( + /*ReturnType=*/M->getType(), Intrinsic::dx_umad, + ArrayRef{M, A, B}, nullptr, "dx.umad"); + +Value *Mul = Builder.CreateNUWMul(M, A); +return Builder.CreateNUWAdd(Mul, B); } case Builtin::BI__builtin_hlsl_elementwise_rcp: { Value *Op0 = EmitScalarExpr(E->getArg(0)); diff --git a/clang/test/CodeGenHLSL/builtins/mad.hlsl b/clang/test/CodeGenHLSL/builtins/mad.hlsl index 749eac6d64736d..bd4f38067a5c59 100644 --- a/clang/test/CodeGenHLSL/builtins/mad.hlsl +++ b/clang/test/CodeGenHLSL/builtins/mad.hlsl @@ -1,182 +1,238 @@ // RUN: %clang_cc1 -finclude-default-header -x hlsl -triple \ // RUN: dxil-pc-shadermodel6.3-library %s -fnative-half-type \ // RUN: -emit-llvm -disable-llvm-passes -o - | FileCheck %s \ -// RUN: --check-prefixes=CHECK,NATIVE_HALF +// RUN: --check-prefixes=CHECK,DXIL_CHECK,DXIL_NATIVE_HALF,NATIVE_HALF // RUN: %clang_cc1 -finclude-default-header -x hlsl -triple \ // RUN: dxil-pc-shadermodel6.3-library %s -emit-llvm -disable-llvm-passes \ -// RUN: -o - | FileCheck %s --check-prefixes=CHECK,NO_HALF +// RUN: -o - | FileCheck %s --check-prefixes=CHECK,DXIL_CHECK,NO_HALF + +// RUN: %clang_cc1 -finclude-default-header -x hlsl -triple \ +// RUN: spirv-unknown-vulkan-compute %s -fnative-half-type \ +// RUN: -emit-llvm -disable-llvm-passes -o - | FileCheck %s \ +// RUN: --check-prefixes=CHECK,NATIVE_HALF,SPIR_NATIVE_HALF,SPIR_CHECK +// RUN: %clang_cc1 -finclude-default-header -x hlsl -triple \ +// RUN: spirv-unknown-vulkan-compute %s -emit-llvm -disable-llvm-passes \ +// RUN: -o - | FileCheck %s --check-prefixes=CHECK,NO_HALF,SPIR_CHECK #ifdef __HLSL_ENABLE_16_BIT -// NATIVE_HALF: %dx.umad = call i16 @llvm.dx.umad.i16(i16 %0, i16 %1, i16 %2) -// NATIVE_HALF: ret i16 %dx.umad +// DXIL_NATIVE_HALF: %dx.umad = call i16 @llvm.dx.umad.i16(i16 %0, i16 %1, i16 %2) +// DXIL_NATIVE_HALF: ret i16 %dx.umad +// SPIR_NATIVE_HALF: mul nuw i16 %{{.*}}, %{{.*}} +// SPIR_NATIVE_HALF: add nuw i16 %{{.*}}, %{{.*}} uint16_t test_mad_uint16_t(uint16_t p0, uint16_t p1, uint16_t p2) { return mad(p0, p1, p2); } -// NATIVE_HALF: %dx.umad = call <2 x i16> @llvm.dx.umad.v2i16(<2 x i16> %0, <2 x i16> %1, <2 x i16> %2) -// NATIVE_HALF: ret <2 x i16> %dx.umad +// DXIL_NATIVE_HALF: %dx.umad = call <2 x i16> @llvm.dx.umad.v2i16(<2 x i16> %0, <2 x i16> %1, <2 x i16> %2) +// DXIL_NATIVE_HALF: ret <2 x i16> %dx.umad +// SPIR_NATIVE_HALF: mul nuw <2 x i16> %{{.*}}, %{{.*}} +// SPIR_NATIVE_HALF: add nuw <2 x i16> %
[clang] [llvm] [SPIRV][HLSL] Add mad intrinsic lowering for spirv (PR #89130)
https://github.com/farzonl closed https://github.com/llvm/llvm-project/pull/89130 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-repl] Keep the first llvm::Module empty to avoid invalid memory access. (PR #89031)
https://github.com/vgvassilev updated https://github.com/llvm/llvm-project/pull/89031 >From 751a3da878733ed4731d6d73c8c7de88033da92a Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Fri, 19 Apr 2024 07:51:17 + Subject: [PATCH] [clang-repl] Keep the first llvm::Module empty to avoid invalid memory access. Clang's CodeGen is designed to work with a single llvm::Module. In many cases for convenience various CodeGen parts have a reference to the llvm::Module (TheModule or Module) which does not change when a new module is pushed. However, the execution engine wants to take ownership of the module which does not map well to CodeGen's design. To work this around we clone the module and pass it down. With some effort it is possible to teach CodeGen to ask the CodeGenModule for its current module and that would have an overall positive impact on CodeGen improving the encapsulation of various parts but that's not resilient to future regression. This patch takes a more conservative approach and keeps the first llvm::Module empty intentionally and does not pass it to the Jit. That's also not bullet proof because we have to guarantee that CodeGen does not write on the blueprint. However, we have inserted some assertions to catch accidental additions to that canary module. This change will fixes a long-standing invalid memory access reported by valgrind when we enable the TBAA optimization passes. It also unblock progress on llvm/llvm-project#84758. --- clang/lib/Interpreter/IncrementalParser.cpp | 25 - clang/lib/Interpreter/IncrementalParser.h | 5 + 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp index 5eec2a2fd6d1a6..c87972719b66b3 100644 --- a/clang/lib/Interpreter/IncrementalParser.cpp +++ b/clang/lib/Interpreter/IncrementalParser.cpp @@ -209,6 +209,10 @@ IncrementalParser::IncrementalParser(Interpreter &Interp, if (Err) return; CI->ExecuteAction(*Act); + + if (getCodeGen()) +CachedInCodeGenModule = std::move(GenModule()); + std::unique_ptr IncrConsumer = std::make_unique(Interp, CI->takeASTConsumer()); CI->setASTConsumer(std::move(IncrConsumer)); @@ -224,11 +228,8 @@ IncrementalParser::IncrementalParser(Interpreter &Interp, return; // PTU.takeError(); } - if (CodeGenerator *CG = getCodeGen()) { -std::unique_ptr M(CG->ReleaseModule()); -CG->StartModule("incr_module_" + std::to_string(PTUs.size()), -M->getContext()); -PTU->TheModule = std::move(M); + if (getCodeGen()) { +PTU->TheModule = std::move(GenModule()); assert(PTU->TheModule && "Failed to create initial PTU"); } } @@ -364,6 +365,20 @@ IncrementalParser::Parse(llvm::StringRef input) { std::unique_ptr IncrementalParser::GenModule() { static unsigned ID = 0; if (CodeGenerator *CG = getCodeGen()) { +// Clang's CodeGen is designed to work with a single llvm::Module. In many +// cases for convenience various CodeGen parts have a reference to the +// llvm::Module (TheModule or Module) which does not change when a new +// module is pushed. However, the execution engine wants to take ownership +// of the module which does not map well to CodeGen's design. To work this +// around we created an empty module to make CodeGen happy. We should make +// sure it always stays empty. +assert((!CachedInCodeGenModule || +(CachedInCodeGenModule->empty() && + CachedInCodeGenModule->global_empty() && + CachedInCodeGenModule->alias_empty() && + CachedInCodeGenModule->ifunc_empty() && + CachedInCodeGenModule->named_metadata_empty())) && + "CodeGen wrote to a readonly module"); std::unique_ptr M(CG->ReleaseModule()); CG->StartModule("incr_module_" + std::to_string(ID++), M->getContext()); return M; diff --git a/clang/lib/Interpreter/IncrementalParser.h b/clang/lib/Interpreter/IncrementalParser.h index e13b74c7f65948..f63bce50acd3b9 100644 --- a/clang/lib/Interpreter/IncrementalParser.h +++ b/clang/lib/Interpreter/IncrementalParser.h @@ -24,6 +24,7 @@ #include namespace llvm { class LLVMContext; +class Module; } // namespace llvm namespace clang { @@ -57,6 +58,10 @@ class IncrementalParser { /// of code. std::list PTUs; + /// When CodeGen is created the first llvm::Module gets cached in many places + /// and we must keep it alive. + std::unique_ptr CachedInCodeGenModule; + IncrementalParser(); public: ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [clang][MBD] set up module build daemon infrastructure (PR #67562)
@@ -0,0 +1,289 @@ +//===--- cc1modbuildd_main.cpp - Clang CC1 Module Build Daemon ===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "clang/Tooling/ModuleBuildDaemon/SocketSupport.h" +#include "clang/Tooling/ModuleBuildDaemon/Utils.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/Signals.h" +#include "llvm/Support/ThreadPool.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +using namespace llvm; +using namespace clang::tooling::cc1modbuildd; + +// Create unbuffered STDOUT stream so that any logging done by the module build +// daemon can be viewed without having to terminate the process +static raw_fd_ostream &unbuff_outs() { + static raw_fd_ostream S(fileno(stdout), false, true); + return S; +} + +static bool LogVerbose = false; +static void logVerbose(const llvm::Twine &message) { + if (LogVerbose) { +unbuff_outs() << message << '\n'; + } +} + +static void modifySignals(decltype(SIG_DFL) handler) { + + if (std::signal(SIGTERM, handler) == SIG_ERR) { +errs() << "failed to handle SIGTERM" << '\n'; +exit(EXIT_FAILURE); + } + + if (std::signal(SIGINT, handler) == SIG_ERR) { +errs() << "failed to handle SIGINT" << '\n'; +exit(EXIT_FAILURE); + } + +#ifdef SIGHUP + if (::signal(SIGHUP, SIG_IGN) == SIG_ERR) { +errs() << "failed to handle SIGHUP" << '\n'; +exit(EXIT_FAILURE); + } +#endif +} + +namespace { + +class ModuleBuildDaemonServer { +public: + SmallString<256> SocketPath; + SmallString<256> Stderr; // path to stderr + SmallString<256> Stdout; // path to stdout + + explicit ModuleBuildDaemonServer(StringRef Path) + : SocketPath(Path), Stderr(Path), Stdout(Path) { +llvm::sys::path::append(SocketPath, SocketFileName); +llvm::sys::path::append(Stdout, StdoutFileName); +llvm::sys::path::append(Stderr, StderrFileName); + } + + void setupDaemonEnv(); + void createDaemonSocket(); + void listenForClients(); + + static void handleConnection(std::shared_ptr Connection); + + // TODO: modify so when shutdownDaemon is called the daemon stops accepting + // new client connections and waits for all existing client connections to + // terminate before closing the file descriptor and exiting + void shutdownDaemon() { +RunServiceLoop = false; +if (ServerListener.has_value()) + ServerListener.value().shutdown(); + } + +private: + std::atomic RunServiceLoop = true; + std::optional ServerListener; cpsughrue wrote: What do you think about moving the signal handler's installation to after `ServerListener` is created? The signal handler's purpose is to shut down `ListeningSocket` and set `RunServiceLoop` to `false`, which isn't relevant until we begin listening for client connections. The `ListeningSocket` should be thread-safe, so I won't have to worry about synchronously calling member functions. I would move `modifySignals(handleSignal)` to the top of `ModuleBuildDaemonServer::listenForClients` https://github.com/llvm/llvm-project/pull/67562 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Add ignoring paren imp casts in has any argument (PR #89509)
https://github.com/komalverma04 created https://github.com/llvm/llvm-project/pull/89509 # Maintaining Consistency in `hasAnyArgument()` and `hasArgument()` Matchers in Clang AST Matchers The `hasArgument()` matcher already ignores implicit casts and parentheses, but the `hasAnyArgument()` matcher does not. To ensure consistency, we need to explicitly use `ignoringParenImpCasts()` to handle cases where there might be implicit casts or parentheses around the argument in the Clang AST match. The code changes made are as follows: ```diff - hasAnyArgument(hasType(asString("S *"))) + hasAnyArgument(ignoringParenImpCasts(hasType(asString("S *" ``` This change ensures that any implicit casts and parentheses around the argument type S * are ignored. Fixes #75754 >From f76df7d3aeba5b93bc5468711e82285754dc732c Mon Sep 17 00:00:00 2001 From: komalverma04 Date: Sat, 20 Apr 2024 21:48:27 +0530 Subject: [PATCH] add ignoringParenImpCasts in hasAnyArgument --- .../clang-tidy/abseil/StrCatAppendCheck.cpp | 15 --- .../MisplacedOperatorInStrlenInAllocCheck.cpp | 4 ++-- .../bugprone/MisplacedWideningCastCheck.cpp | 3 ++- .../bugprone/MultipleNewInOneExpressionCheck.cpp | 14 ++ .../bugprone/NotNullTerminatedResultCheck.cpp | 9 + .../StringLiteralWithEmbeddedNulCheck.cpp | 9 ++--- .../bugprone/StringviewNullptrCheck.cpp | 12 +++- .../SuspiciousStringviewDataUsageCheck.cpp| 3 ++- .../cppcoreguidelines/OwningMemoryCheck.cpp | 4 ++-- .../clang-tidy/modernize/UseEmplaceCheck.cpp | 14 +++--- .../InefficientStringConcatenationCheck.cpp | 4 ++-- 11 files changed, 49 insertions(+), 42 deletions(-) diff --git a/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp b/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp index ab6ed701e59fee..f6b64a2dc15ede 100644 --- a/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp @@ -34,23 +34,23 @@ AST_MATCHER_P(Stmt, IgnoringTemporaries, ast_matchers::internal::Matcher, return InnerMatcher.matches(*E, Finder, Builder); } -} // namespace +} // namespace // TODO: str += StrCat(...) // str.append(StrCat(...)) void StrCatAppendCheck::registerMatchers(MatchFinder *Finder) { const auto StrCat = functionDecl(hasName("::absl::StrCat")); - // The arguments of absl::StrCat are implicitly converted to AlphaNum. This - // matches to the arguments because of that behavior. + // The arguments of absl::StrCat are implicitly converted to AlphaNum. This + // matches to the arguments because of that behavior. const auto AlphaNum = IgnoringTemporaries(cxxConstructExpr( argumentCountIs(1), hasType(cxxRecordDecl(hasName("::absl::AlphaNum"))), hasArgument(0, ignoringImpCasts(declRefExpr(to(equalsBoundNode("LHS")), expr().bind("Arg0")); - const auto HasAnotherReferenceToLhs = - callExpr(hasAnyArgument(expr(hasDescendant(declRefExpr( - to(equalsBoundNode("LHS")), unless(equalsBoundNode("Arg0"))); + const auto HasAnotherReferenceToLhs = callExpr( + hasAnyArgument(ignoringParenImpCasts(expr(hasDescendant(declRefExpr( + to(equalsBoundNode("LHS")), unless(equalsBoundNode("Arg0"; // Now look for calls to operator= with an object on the LHS and a call to // StrCat on the RHS. The first argument of the StrCat call should be the same @@ -73,7 +73,8 @@ void StrCatAppendCheck::registerMatchers(MatchFinder *Finder) { void StrCatAppendCheck::check(const MatchFinder::MatchResult &Result) { const auto *Op = Result.Nodes.getNodeAs("Op"); const auto *Call = Result.Nodes.getNodeAs("Call"); - assert(Op != nullptr && Call != nullptr && "Matcher does not work as expected"); + assert(Op != nullptr && Call != nullptr && + "Matcher does not work as expected"); // Handles the case 'x = absl::StrCat(x)', which has no effect. if (Call->getNumArgs() == 1) { diff --git a/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp index 40e4ab6c8b12af..cf7f06e06b26a0 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp @@ -24,7 +24,7 @@ void MisplacedOperatorInStrlenInAllocCheck::registerMatchers( const auto BadUse = callExpr(callee(StrLenFunc), - hasAnyArgument(ignoringImpCasts( + hasAnyArgument(ignoringParenImpCasts( binaryOperator( hasOperatorName("+"), hasRHS(ignoringParenImpCasts(integerLiteral(equals(1) @@ -74,7 +74,7 @@ void MisplacedOperatorInStrlenInAllocCheck::check( if (!Alloc) All
[clang] 7f0bbbb - [clang][Interp] Change array index types in OffsetHelper
Author: Timm Bäder Date: 2024-04-20T19:31:41+02:00 New Revision: 7f019b4f13c2efb400db300817aa7ed589cc URL: https://github.com/llvm/llvm-project/commit/7f019b4f13c2efb400db300817aa7ed589cc DIFF: https://github.com/llvm/llvm-project/commit/7f019b4f13c2efb400db300817aa7ed589cc.diff LOG: [clang][Interp] Change array index types in OffsetHelper This is closer to that the current interpreter does. It also fixes diagnostics in a case I was looking into. Unfortunately, this is not possible to test right now since it requires a large array and we don't implement array fillers yet. Added: Modified: clang/lib/AST/Interp/Interp.h Removed: diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h index dd0bacd73acb10..cebedf59e0593f 100644 --- a/clang/lib/AST/Interp/Interp.h +++ b/clang/lib/AST/Interp/Interp.h @@ -1548,17 +1548,16 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T &Offset, if (!CheckArray(S, OpPC, Ptr)) return false; - // Get a version of the index comparable to the type. - T Index = T::from(Ptr.getIndex(), Offset.bitWidth()); - // Compute the largest index into the array. - T MaxIndex = T::from(Ptr.getNumElems(), Offset.bitWidth()); + uint64_t Index = Ptr.getIndex(); + uint64_t MaxIndex = static_cast(Ptr.getNumElems()); bool Invalid = false; // Helper to report an invalid offset, computed as APSInt. auto DiagInvalidOffset = [&]() -> void { const unsigned Bits = Offset.bitWidth(); -APSInt APOffset(Offset.toAPSInt().extend(Bits + 2), false); -APSInt APIndex(Index.toAPSInt().extend(Bits + 2), false); +APSInt APOffset(Offset.toAPSInt().extend(Bits + 2), /*IsUnsigend=*/false); +APSInt APIndex(APInt(Bits + 2, Index, /*IsSigned=*/true), + /*IsUnsigned=*/false); APSInt NewIndex = (Op == ArithOp::Add) ? (APIndex + APOffset) : (APIndex - APOffset); S.CCEDiag(S.Current->getSource(OpPC), diag::note_constexpr_array_index) @@ -1569,22 +1568,24 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T &Offset, }; if (Ptr.isBlockPointer()) { -T MaxOffset = T::from(MaxIndex - Index, Offset.bitWidth()); +uint64_t IOffset = static_cast(Offset); +uint64_t MaxOffset = MaxIndex - Index; + if constexpr (Op == ArithOp::Add) { // If the new offset would be negative, bail out. - if (Offset.isNegative() && (Offset.isMin() || -Offset > Index)) + if (Offset.isNegative() && (Offset.isMin() || -IOffset > Index)) DiagInvalidOffset(); // If the new offset would be out of bounds, bail out. - if (Offset.isPositive() && Offset > MaxOffset) + if (Offset.isPositive() && IOffset > MaxOffset) DiagInvalidOffset(); } else { // If the new offset would be negative, bail out. - if (Offset.isPositive() && Index < Offset) + if (Offset.isPositive() && Index < IOffset) DiagInvalidOffset(); // If the new offset would be out of bounds, bail out. - if (Offset.isNegative() && (Offset.isMin() || -Offset > MaxOffset)) + if (Offset.isNegative() && (Offset.isMin() || -IOffset > MaxOffset)) DiagInvalidOffset(); } } @@ -1601,7 +1602,7 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T &Offset, else Result = WideIndex - WideOffset; - S.Stk.push(Ptr.atIndex(static_cast(Result))); + S.Stk.push(Ptr.atIndex(static_cast(Result))); return true; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Add ignoring paren imp casts in has any argument (PR #89509)
llvmbot wrote: @llvm/pr-subscribers-clang-tidy Author: None (komalverma04) Changes # Maintaining Consistency in `hasAnyArgument()` and `hasArgument()` Matchers in Clang AST Matchers The `hasArgument()` matcher already ignores implicit casts and parentheses, but the `hasAnyArgument()` matcher does not. To ensure consistency, we need to explicitly use `ignoringParenImpCasts()` to handle cases where there might be implicit casts or parentheses around the argument in the Clang AST match. The code changes made are as follows: ```diff - hasAnyArgument(hasType(asString("S *"))) + hasAnyArgument(ignoringParenImpCasts(hasType(asString("S *" ``` This change ensures that any implicit casts and parentheses around the argument type S * are ignored. Fixes #75754 --- Full diff: https://github.com/llvm/llvm-project/pull/89509.diff 11 Files Affected: - (modified) clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp (+8-7) - (modified) clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp (+2-2) - (modified) clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp (+2-1) - (modified) clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp (+6-8) - (modified) clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp (+5-4) - (modified) clang-tools-extra/clang-tidy/bugprone/StringLiteralWithEmbeddedNulCheck.cpp (+6-3) - (modified) clang-tools-extra/clang-tidy/bugprone/StringviewNullptrCheck.cpp (+7-5) - (modified) clang-tools-extra/clang-tidy/bugprone/SuspiciousStringviewDataUsageCheck.cpp (+2-1) - (modified) clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp (+2-2) - (modified) clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp (+7-7) - (modified) clang-tools-extra/clang-tidy/performance/InefficientStringConcatenationCheck.cpp (+2-2) ``diff diff --git a/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp b/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp index ab6ed701e59fee..f6b64a2dc15ede 100644 --- a/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp @@ -34,23 +34,23 @@ AST_MATCHER_P(Stmt, IgnoringTemporaries, ast_matchers::internal::Matcher, return InnerMatcher.matches(*E, Finder, Builder); } -} // namespace +} // namespace // TODO: str += StrCat(...) // str.append(StrCat(...)) void StrCatAppendCheck::registerMatchers(MatchFinder *Finder) { const auto StrCat = functionDecl(hasName("::absl::StrCat")); - // The arguments of absl::StrCat are implicitly converted to AlphaNum. This - // matches to the arguments because of that behavior. + // The arguments of absl::StrCat are implicitly converted to AlphaNum. This + // matches to the arguments because of that behavior. const auto AlphaNum = IgnoringTemporaries(cxxConstructExpr( argumentCountIs(1), hasType(cxxRecordDecl(hasName("::absl::AlphaNum"))), hasArgument(0, ignoringImpCasts(declRefExpr(to(equalsBoundNode("LHS")), expr().bind("Arg0")); - const auto HasAnotherReferenceToLhs = - callExpr(hasAnyArgument(expr(hasDescendant(declRefExpr( - to(equalsBoundNode("LHS")), unless(equalsBoundNode("Arg0"))); + const auto HasAnotherReferenceToLhs = callExpr( + hasAnyArgument(ignoringParenImpCasts(expr(hasDescendant(declRefExpr( + to(equalsBoundNode("LHS")), unless(equalsBoundNode("Arg0"; // Now look for calls to operator= with an object on the LHS and a call to // StrCat on the RHS. The first argument of the StrCat call should be the same @@ -73,7 +73,8 @@ void StrCatAppendCheck::registerMatchers(MatchFinder *Finder) { void StrCatAppendCheck::check(const MatchFinder::MatchResult &Result) { const auto *Op = Result.Nodes.getNodeAs("Op"); const auto *Call = Result.Nodes.getNodeAs("Call"); - assert(Op != nullptr && Call != nullptr && "Matcher does not work as expected"); + assert(Op != nullptr && Call != nullptr && + "Matcher does not work as expected"); // Handles the case 'x = absl::StrCat(x)', which has no effect. if (Call->getNumArgs() == 1) { diff --git a/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp index 40e4ab6c8b12af..cf7f06e06b26a0 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp @@ -24,7 +24,7 @@ void MisplacedOperatorInStrlenInAllocCheck::registerMatchers( const auto BadUse = callExpr(callee(StrLenFunc), - hasAnyArgument(ignoringImpCasts( + hasAnyArgument(ignoringParenImpCasts( binaryOperator( hasOperatorName("+"),
[clang] [clang-repl] Keep the first llvm::Module empty to avoid invalid memory access. (PR #89031)
vgvassilev wrote: Looks like the windows builders have been dead since a day or two... https://github.com/llvm/llvm-project/pull/89031 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 1faf314 - [clang-repl] Keep the first llvm::Module empty to avoid invalid memory access. (#89031)
Author: Vassil Vassilev Date: 2024-04-20T20:54:55+03:00 New Revision: 1faf3148fdef34ce0d556ec6a4049e06cbde71b3 URL: https://github.com/llvm/llvm-project/commit/1faf3148fdef34ce0d556ec6a4049e06cbde71b3 DIFF: https://github.com/llvm/llvm-project/commit/1faf3148fdef34ce0d556ec6a4049e06cbde71b3.diff LOG: [clang-repl] Keep the first llvm::Module empty to avoid invalid memory access. (#89031) Clang's CodeGen is designed to work with a single llvm::Module. In many cases for convenience various CodeGen parts have a reference to the llvm::Module (TheModule or Module) which does not change when a new module is pushed. However, the execution engine wants to take ownership of the module which does not map well to CodeGen's design. To work this around we clone the module and pass it down. With some effort it is possible to teach CodeGen to ask the CodeGenModule for its current module and that would have an overall positive impact on CodeGen improving the encapsulation of various parts but that's not resilient to future regression. This patch takes a more conservative approach and keeps the first llvm::Module empty intentionally and does not pass it to the Jit. That's also not bullet proof because we have to guarantee that CodeGen does not write on the blueprint. However, we have inserted some assertions to catch accidental additions to that canary module. This change will fixes a long-standing invalid memory access reported by valgrind when we enable the TBAA optimization passes. It also unblock progress on https://github.com/llvm/llvm-project/pull/84758. Added: Modified: clang/lib/Interpreter/IncrementalParser.cpp clang/lib/Interpreter/IncrementalParser.h Removed: diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp index 5eec2a2fd6d1a6..c87972719b66b3 100644 --- a/clang/lib/Interpreter/IncrementalParser.cpp +++ b/clang/lib/Interpreter/IncrementalParser.cpp @@ -209,6 +209,10 @@ IncrementalParser::IncrementalParser(Interpreter &Interp, if (Err) return; CI->ExecuteAction(*Act); + + if (getCodeGen()) +CachedInCodeGenModule = std::move(GenModule()); + std::unique_ptr IncrConsumer = std::make_unique(Interp, CI->takeASTConsumer()); CI->setASTConsumer(std::move(IncrConsumer)); @@ -224,11 +228,8 @@ IncrementalParser::IncrementalParser(Interpreter &Interp, return; // PTU.takeError(); } - if (CodeGenerator *CG = getCodeGen()) { -std::unique_ptr M(CG->ReleaseModule()); -CG->StartModule("incr_module_" + std::to_string(PTUs.size()), -M->getContext()); -PTU->TheModule = std::move(M); + if (getCodeGen()) { +PTU->TheModule = std::move(GenModule()); assert(PTU->TheModule && "Failed to create initial PTU"); } } @@ -364,6 +365,20 @@ IncrementalParser::Parse(llvm::StringRef input) { std::unique_ptr IncrementalParser::GenModule() { static unsigned ID = 0; if (CodeGenerator *CG = getCodeGen()) { +// Clang's CodeGen is designed to work with a single llvm::Module. In many +// cases for convenience various CodeGen parts have a reference to the +// llvm::Module (TheModule or Module) which does not change when a new +// module is pushed. However, the execution engine wants to take ownership +// of the module which does not map well to CodeGen's design. To work this +// around we created an empty module to make CodeGen happy. We should make +// sure it always stays empty. +assert((!CachedInCodeGenModule || +(CachedInCodeGenModule->empty() && + CachedInCodeGenModule->global_empty() && + CachedInCodeGenModule->alias_empty() && + CachedInCodeGenModule->ifunc_empty() && + CachedInCodeGenModule->named_metadata_empty())) && + "CodeGen wrote to a readonly module"); std::unique_ptr M(CG->ReleaseModule()); CG->StartModule("incr_module_" + std::to_string(ID++), M->getContext()); return M; diff --git a/clang/lib/Interpreter/IncrementalParser.h b/clang/lib/Interpreter/IncrementalParser.h index e13b74c7f65948..f63bce50acd3b9 100644 --- a/clang/lib/Interpreter/IncrementalParser.h +++ b/clang/lib/Interpreter/IncrementalParser.h @@ -24,6 +24,7 @@ #include namespace llvm { class LLVMContext; +class Module; } // namespace llvm namespace clang { @@ -57,6 +58,10 @@ class IncrementalParser { /// of code. std::list PTUs; + /// When CodeGen is created the first llvm::Module gets cached in many places + /// and we must keep it alive. + std::unique_ptr CachedInCodeGenModule; + IncrementalParser(); public: ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-repl] Keep the first llvm::Module empty to avoid invalid memory access. (PR #89031)
https://github.com/vgvassilev closed https://github.com/llvm/llvm-project/pull/89031 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-repl] Set up executor implicitly to account for init PTUs (PR #84758)
Stefan =?utf-8?q?Gränitz?= Message-ID: In-Reply-To: https://github.com/vgvassilev updated https://github.com/llvm/llvm-project/pull/84758 >From 969ff9856fd5e039afd6d1987a1bf44a9d6900ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= Date: Sun, 10 Mar 2024 18:17:48 +0100 Subject: [PATCH 1/2] [clang-repl] Set up executor implicitly to account for init PTUs --- clang/lib/Interpreter/Interpreter.cpp | 32 +++ clang/test/Interpreter/execute.cpp| 4 ++-- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/clang/lib/Interpreter/Interpreter.cpp b/clang/lib/Interpreter/Interpreter.cpp index b20e6efcebfd10..7bd44f8e046c02 100644 --- a/clang/lib/Interpreter/Interpreter.cpp +++ b/clang/lib/Interpreter/Interpreter.cpp @@ -229,12 +229,30 @@ IncrementalCompilerBuilder::CreateCudaHost() { } Interpreter::Interpreter(std::unique_ptr CI, - llvm::Error &Err) { - llvm::ErrorAsOutParameter EAO(&Err); + llvm::Error &ErrOut) { + llvm::ErrorAsOutParameter EAO(&ErrOut); auto LLVMCtx = std::make_unique(); TSCtx = std::make_unique(std::move(LLVMCtx)); - IncrParser = std::make_unique(*this, std::move(CI), - *TSCtx->getContext(), Err); + IncrParser = std::make_unique( + *this, std::move(CI), *TSCtx->getContext(), ErrOut); + if (ErrOut) +return; + + // Not all frontends support code-generation, e.g. ast-dump actions don't + if (IncrParser->getCodeGen()) { +if (llvm::Error Err = CreateExecutor()) { + ErrOut = joinErrors(std::move(ErrOut), std::move(Err)); + return; +} + +// Process the PTUs that came from initialization. For example -include will +// give us a header that's processed at initialization of the preprocessor. +for (PartialTranslationUnit &PTU : IncrParser->getPTUs()) + if (llvm::Error Err = Execute(PTU)) { +ErrOut = joinErrors(std::move(ErrOut), std::move(Err)); +return; + } + } } Interpreter::~Interpreter() { @@ -395,10 +413,16 @@ llvm::Error Interpreter::CreateExecutor() { return llvm::make_error("Operation failed. " "Execution engine exists", std::error_code()); + if (!IncrParser->getCodeGen()) +return llvm::make_error("Operation failed. " + "No code generator available", + std::error_code()); + llvm::Expected> JB = CreateJITBuilder(*getCompilerInstance()); if (!JB) return JB.takeError(); + llvm::Error Err = llvm::Error::success(); auto Executor = std::make_unique(*TSCtx, **JB, Err); if (!Err) diff --git a/clang/test/Interpreter/execute.cpp b/clang/test/Interpreter/execute.cpp index 6e73ed3927e815..534a54ed94fba2 100644 --- a/clang/test/Interpreter/execute.cpp +++ b/clang/test/Interpreter/execute.cpp @@ -7,6 +7,8 @@ // RUN: cat %s | clang-repl | FileCheck %s // RUN: cat %s | clang-repl -Xcc -O2 | FileCheck %s +// RUN: clang-repl -Xcc -include -Xcc %s | FileCheck %s +// RUN: clang-repl -Xcc -fsyntax-only -Xcc -include -Xcc %s extern "C" int printf(const char *, ...); int i = 42; auto r1 = printf("i = %d\n", i); @@ -19,5 +21,3 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, reinterpret_castFrom d22301d540eecf6d09304dd994d71338b54970c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= Date: Mon, 11 Mar 2024 14:10:58 +0100 Subject: [PATCH 2/2] [tmp] Add crash note --- clang/test/Interpreter/inline-virtual.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/test/Interpreter/inline-virtual.cpp b/clang/test/Interpreter/inline-virtual.cpp index 79ab8ed337ffea..d862b3354f61fe 100644 --- a/clang/test/Interpreter/inline-virtual.cpp +++ b/clang/test/Interpreter/inline-virtual.cpp @@ -14,7 +14,7 @@ struct A { int a; A(int a) : a(a) {} virtual ~A(); }; // PartialTranslationUnit. inline A::~A() { printf("~A(%d)\n", a); } -// Create one instance with new and delete it. +// Create one instance with new and delete it. We crash here now: A *a1 = new A(1); delete a1; // CHECK: ~A(1) ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] ca09045 - [Interpreter] Fix warnings
Author: Kazu Hirata Date: 2024-04-20T11:10:49-07:00 New Revision: ca090452d64e229b539a66379a3be891c4e8f3d8 URL: https://github.com/llvm/llvm-project/commit/ca090452d64e229b539a66379a3be891c4e8f3d8 DIFF: https://github.com/llvm/llvm-project/commit/ca090452d64e229b539a66379a3be891c4e8f3d8.diff LOG: [Interpreter] Fix warnings This patch fixes: clang/lib/Interpreter/IncrementalParser.cpp:214:29: error: moving a temporary object prevents copy elision [-Werror,-Wpessimizing-move] clang/lib/Interpreter/IncrementalParser.cpp:232:22: error: moving a temporary object prevents copy elision [-Werror,-Wpessimizing-move] Added: Modified: clang/lib/Interpreter/IncrementalParser.cpp Removed: diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp index c87972719b66b3..b72005d58f8391 100644 --- a/clang/lib/Interpreter/IncrementalParser.cpp +++ b/clang/lib/Interpreter/IncrementalParser.cpp @@ -211,7 +211,7 @@ IncrementalParser::IncrementalParser(Interpreter &Interp, CI->ExecuteAction(*Act); if (getCodeGen()) -CachedInCodeGenModule = std::move(GenModule()); +CachedInCodeGenModule = GenModule(); std::unique_ptr IncrConsumer = std::make_unique(Interp, CI->takeASTConsumer()); @@ -229,7 +229,7 @@ IncrementalParser::IncrementalParser(Interpreter &Interp, } if (getCodeGen()) { -PTU->TheModule = std::move(GenModule()); +PTU->TheModule = GenModule(); assert(PTU->TheModule && "Failed to create initial PTU"); } } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] adc4f62 - Revert "[clang-repl] Keep the first llvm::Module empty to avoid invalid memory access. (#89031)"
Author: Vassil Vassilev Date: 2024-04-20T18:26:59Z New Revision: adc4f6233df734fbe3793118ecc89d3584e0c90f URL: https://github.com/llvm/llvm-project/commit/adc4f6233df734fbe3793118ecc89d3584e0c90f DIFF: https://github.com/llvm/llvm-project/commit/adc4f6233df734fbe3793118ecc89d3584e0c90f.diff LOG: Revert "[clang-repl] Keep the first llvm::Module empty to avoid invalid memory access. (#89031)" This reverts commit ca090452d64e229b539a66379a3be891c4e8f3d8 and 1faf3148fdef34ce0d556ec6a4049e06cbde71b3 because it broke a darwin bot. Added: Modified: clang/lib/Interpreter/IncrementalParser.cpp clang/lib/Interpreter/IncrementalParser.h Removed: diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp index b72005d58f8391..5eec2a2fd6d1a6 100644 --- a/clang/lib/Interpreter/IncrementalParser.cpp +++ b/clang/lib/Interpreter/IncrementalParser.cpp @@ -209,10 +209,6 @@ IncrementalParser::IncrementalParser(Interpreter &Interp, if (Err) return; CI->ExecuteAction(*Act); - - if (getCodeGen()) -CachedInCodeGenModule = GenModule(); - std::unique_ptr IncrConsumer = std::make_unique(Interp, CI->takeASTConsumer()); CI->setASTConsumer(std::move(IncrConsumer)); @@ -228,8 +224,11 @@ IncrementalParser::IncrementalParser(Interpreter &Interp, return; // PTU.takeError(); } - if (getCodeGen()) { -PTU->TheModule = GenModule(); + if (CodeGenerator *CG = getCodeGen()) { +std::unique_ptr M(CG->ReleaseModule()); +CG->StartModule("incr_module_" + std::to_string(PTUs.size()), +M->getContext()); +PTU->TheModule = std::move(M); assert(PTU->TheModule && "Failed to create initial PTU"); } } @@ -365,20 +364,6 @@ IncrementalParser::Parse(llvm::StringRef input) { std::unique_ptr IncrementalParser::GenModule() { static unsigned ID = 0; if (CodeGenerator *CG = getCodeGen()) { -// Clang's CodeGen is designed to work with a single llvm::Module. In many -// cases for convenience various CodeGen parts have a reference to the -// llvm::Module (TheModule or Module) which does not change when a new -// module is pushed. However, the execution engine wants to take ownership -// of the module which does not map well to CodeGen's design. To work this -// around we created an empty module to make CodeGen happy. We should make -// sure it always stays empty. -assert((!CachedInCodeGenModule || -(CachedInCodeGenModule->empty() && - CachedInCodeGenModule->global_empty() && - CachedInCodeGenModule->alias_empty() && - CachedInCodeGenModule->ifunc_empty() && - CachedInCodeGenModule->named_metadata_empty())) && - "CodeGen wrote to a readonly module"); std::unique_ptr M(CG->ReleaseModule()); CG->StartModule("incr_module_" + std::to_string(ID++), M->getContext()); return M; diff --git a/clang/lib/Interpreter/IncrementalParser.h b/clang/lib/Interpreter/IncrementalParser.h index f63bce50acd3b9..e13b74c7f65948 100644 --- a/clang/lib/Interpreter/IncrementalParser.h +++ b/clang/lib/Interpreter/IncrementalParser.h @@ -24,7 +24,6 @@ #include namespace llvm { class LLVMContext; -class Module; } // namespace llvm namespace clang { @@ -58,10 +57,6 @@ class IncrementalParser { /// of code. std::list PTUs; - /// When CodeGen is created the first llvm::Module gets cached in many places - /// and we must keep it alive. - std::unique_ptr CachedInCodeGenModule; - IncrementalParser(); public: ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] a3f07d3 - Reland "[clang-repl] Keep the first llvm::Module empty to avoid invalid memory access. (#89031)"
Author: Vassil Vassilev Date: 2024-04-20T18:55:56Z New Revision: a3f07d36cbc9e3a0d004609d140474c1d8a25bb6 URL: https://github.com/llvm/llvm-project/commit/a3f07d36cbc9e3a0d004609d140474c1d8a25bb6 DIFF: https://github.com/llvm/llvm-project/commit/a3f07d36cbc9e3a0d004609d140474c1d8a25bb6.diff LOG: Reland "[clang-repl] Keep the first llvm::Module empty to avoid invalid memory access. (#89031)" Original commit message: " Clang's CodeGen is designed to work with a single llvm::Module. In many cases for convenience various CodeGen parts have a reference to the llvm::Module (TheModule or Module) which does not change when a new module is pushed. However, the execution engine wants to take ownership of the module which does not map well to CodeGen's design. To work this around we clone the module and pass it down. With some effort it is possible to teach CodeGen to ask the CodeGenModule for its current module and that would have an overall positive impact on CodeGen improving the encapsulation of various parts but that's not resilient to future regression. This patch takes a more conservative approach and keeps the first llvm::Module empty intentionally and does not pass it to the Jit. That's also not bullet proof because we have to guarantee that CodeGen does not write on the blueprint. However, we have inserted some assertions to catch accidental additions to that canary module. This change will fixes a long-standing invalid memory access reported by valgrind when we enable the TBAA optimization passes. It also unblock progress on https://github.com/llvm/llvm-project/pull/84758. " This patch reverts adc4f6233df734fbe3793118ecc89d3584e0c90f and removes the check of `named_metadata_empty` of the first llvm::Module because on darwin clang inserts some harmless metadata which we can ignore. Added: Modified: clang/lib/Interpreter/IncrementalParser.cpp clang/lib/Interpreter/IncrementalParser.h Removed: diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp index 5eec2a2fd6d1a6..ef90fe9e6f5451 100644 --- a/clang/lib/Interpreter/IncrementalParser.cpp +++ b/clang/lib/Interpreter/IncrementalParser.cpp @@ -209,6 +209,10 @@ IncrementalParser::IncrementalParser(Interpreter &Interp, if (Err) return; CI->ExecuteAction(*Act); + + if (getCodeGen()) +CachedInCodeGenModule = GenModule(); + std::unique_ptr IncrConsumer = std::make_unique(Interp, CI->takeASTConsumer()); CI->setASTConsumer(std::move(IncrConsumer)); @@ -224,11 +228,8 @@ IncrementalParser::IncrementalParser(Interpreter &Interp, return; // PTU.takeError(); } - if (CodeGenerator *CG = getCodeGen()) { -std::unique_ptr M(CG->ReleaseModule()); -CG->StartModule("incr_module_" + std::to_string(PTUs.size()), -M->getContext()); -PTU->TheModule = std::move(M); + if (getCodeGen()) { +PTU->TheModule = GenModule(); assert(PTU->TheModule && "Failed to create initial PTU"); } } @@ -364,6 +365,19 @@ IncrementalParser::Parse(llvm::StringRef input) { std::unique_ptr IncrementalParser::GenModule() { static unsigned ID = 0; if (CodeGenerator *CG = getCodeGen()) { +// Clang's CodeGen is designed to work with a single llvm::Module. In many +// cases for convenience various CodeGen parts have a reference to the +// llvm::Module (TheModule or Module) which does not change when a new +// module is pushed. However, the execution engine wants to take ownership +// of the module which does not map well to CodeGen's design. To work this +// around we created an empty module to make CodeGen happy. We should make +// sure it always stays empty. +assert((!CachedInCodeGenModule || +(CachedInCodeGenModule->empty() && + CachedInCodeGenModule->global_empty() && + CachedInCodeGenModule->alias_empty() && + CachedInCodeGenModule->ifunc_empty())) && + "CodeGen wrote to a readonly module"); std::unique_ptr M(CG->ReleaseModule()); CG->StartModule("incr_module_" + std::to_string(ID++), M->getContext()); return M; diff --git a/clang/lib/Interpreter/IncrementalParser.h b/clang/lib/Interpreter/IncrementalParser.h index e13b74c7f65948..f63bce50acd3b9 100644 --- a/clang/lib/Interpreter/IncrementalParser.h +++ b/clang/lib/Interpreter/IncrementalParser.h @@ -24,6 +24,7 @@ #include namespace llvm { class LLVMContext; +class Module; } // namespace llvm namespace clang { @@ -57,6 +58,10 @@ class IncrementalParser { /// of code. std::list PTUs; + /// When CodeGen is created the first llvm::Module gets cached in many places + /// and we must keep it alive. + std::unique_ptr CachedInCodeGenModule; + IncrementalParser(); public: ___ cfe-commits mailing list cfe-co
[clang] Reapply "[Clang][Sema] placement new initializes typedef array with correct size (#83124)" (PR #89036)
mahtohappy wrote: Hi, the build is failing for windows but there's not test failures and no errors in the log. What should I do from here? https://github.com/llvm/llvm-project/pull/89036 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-repl] Set up executor implicitly to account for init PTUs (PR #84758)
Stefan =?utf-8?q?Gränitz?= Message-ID: In-Reply-To: https://github.com/vgvassilev updated https://github.com/llvm/llvm-project/pull/84758 >From 2fc401486c4c637829dceb534e2d2ec205448ba9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= Date: Sun, 10 Mar 2024 18:17:48 +0100 Subject: [PATCH 1/2] [clang-repl] Set up executor implicitly to account for init PTUs --- clang/lib/Interpreter/Interpreter.cpp | 32 +++ clang/test/Interpreter/execute.cpp| 4 ++-- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/clang/lib/Interpreter/Interpreter.cpp b/clang/lib/Interpreter/Interpreter.cpp index b20e6efcebfd10..7bd44f8e046c02 100644 --- a/clang/lib/Interpreter/Interpreter.cpp +++ b/clang/lib/Interpreter/Interpreter.cpp @@ -229,12 +229,30 @@ IncrementalCompilerBuilder::CreateCudaHost() { } Interpreter::Interpreter(std::unique_ptr CI, - llvm::Error &Err) { - llvm::ErrorAsOutParameter EAO(&Err); + llvm::Error &ErrOut) { + llvm::ErrorAsOutParameter EAO(&ErrOut); auto LLVMCtx = std::make_unique(); TSCtx = std::make_unique(std::move(LLVMCtx)); - IncrParser = std::make_unique(*this, std::move(CI), - *TSCtx->getContext(), Err); + IncrParser = std::make_unique( + *this, std::move(CI), *TSCtx->getContext(), ErrOut); + if (ErrOut) +return; + + // Not all frontends support code-generation, e.g. ast-dump actions don't + if (IncrParser->getCodeGen()) { +if (llvm::Error Err = CreateExecutor()) { + ErrOut = joinErrors(std::move(ErrOut), std::move(Err)); + return; +} + +// Process the PTUs that came from initialization. For example -include will +// give us a header that's processed at initialization of the preprocessor. +for (PartialTranslationUnit &PTU : IncrParser->getPTUs()) + if (llvm::Error Err = Execute(PTU)) { +ErrOut = joinErrors(std::move(ErrOut), std::move(Err)); +return; + } + } } Interpreter::~Interpreter() { @@ -395,10 +413,16 @@ llvm::Error Interpreter::CreateExecutor() { return llvm::make_error("Operation failed. " "Execution engine exists", std::error_code()); + if (!IncrParser->getCodeGen()) +return llvm::make_error("Operation failed. " + "No code generator available", + std::error_code()); + llvm::Expected> JB = CreateJITBuilder(*getCompilerInstance()); if (!JB) return JB.takeError(); + llvm::Error Err = llvm::Error::success(); auto Executor = std::make_unique(*TSCtx, **JB, Err); if (!Err) diff --git a/clang/test/Interpreter/execute.cpp b/clang/test/Interpreter/execute.cpp index 6e73ed3927e815..534a54ed94fba2 100644 --- a/clang/test/Interpreter/execute.cpp +++ b/clang/test/Interpreter/execute.cpp @@ -7,6 +7,8 @@ // RUN: cat %s | clang-repl | FileCheck %s // RUN: cat %s | clang-repl -Xcc -O2 | FileCheck %s +// RUN: clang-repl -Xcc -include -Xcc %s | FileCheck %s +// RUN: clang-repl -Xcc -fsyntax-only -Xcc -include -Xcc %s extern "C" int printf(const char *, ...); int i = 42; auto r1 = printf("i = %d\n", i); @@ -19,5 +21,3 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, reinterpret_castFrom b42376eb59ab2667778a41a065cda3a131e7f67c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= Date: Mon, 11 Mar 2024 14:10:58 +0100 Subject: [PATCH 2/2] [tmp] Add crash note --- clang/test/Interpreter/inline-virtual.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/test/Interpreter/inline-virtual.cpp b/clang/test/Interpreter/inline-virtual.cpp index 79ab8ed337ffea..d862b3354f61fe 100644 --- a/clang/test/Interpreter/inline-virtual.cpp +++ b/clang/test/Interpreter/inline-virtual.cpp @@ -14,7 +14,7 @@ struct A { int a; A(int a) : a(a) {} virtual ~A(); }; // PartialTranslationUnit. inline A::~A() { printf("~A(%d)\n", a); } -// Create one instance with new and delete it. +// Create one instance with new and delete it. We crash here now: A *a1 = new A(1); delete a1; // CHECK: ~A(1) ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [mlir] Fix warning about mismatches between function parameter and call-site args names (PR #89294)
https://github.com/Troy-Butler edited https://github.com/llvm/llvm-project/pull/89294 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [mlir] Fix mismatches between function parameter definitions and declarations (PR #89512)
https://github.com/Troy-Butler created https://github.com/llvm/llvm-project/pull/89512 Addresses issue #88716. >From f03466fa44a3c7210e7590e6305bc0c9f9aeb446 Mon Sep 17 00:00:00 2001 From: Troy-Butler Date: Sat, 20 Apr 2024 15:13:09 -0400 Subject: [PATCH] Fix Definition-Declaration Mismatches Signed-off-by: Troy-Butler --- .../include/clang/StaticAnalyzer/Core/PathSensitive/Store.h | 4 ++-- llvm/lib/Transforms/InstCombine/InstCombineInternal.h | 2 +- llvm/lib/Transforms/Vectorize/VPlan.h | 4 ++-- .../SparseTensor/Transforms/Utils/SparseTensorIterator.h| 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h index fac0c04ae2caab..e60a49f68b7a0d 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h @@ -227,12 +227,12 @@ class StoreManager { /// information will not be used. virtual StoreRef invalidateRegions(Store store, ArrayRef Values, - const Expr *E, unsigned Count, + const Expr *Ex, unsigned Count, const LocationContext *LCtx, const CallEvent *Call, InvalidatedSymbols &IS, RegionAndSymbolInvalidationTraits &ITraits, - InvalidatedRegions *InvalidatedTopLevel, + InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated) = 0; /// enterStackFrame - Let the StoreManager to do something when execution diff --git a/llvm/lib/Transforms/InstCombine/InstCombineInternal.h b/llvm/lib/Transforms/InstCombine/InstCombineInternal.h index 4479afbd09afde..4ec5f417998273 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineInternal.h +++ b/llvm/lib/Transforms/InstCombine/InstCombineInternal.h @@ -433,7 +433,7 @@ class LLVM_LIBRARY_VISIBILITY InstCombinerImpl final Value *foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI, bool IsAnd, bool IsLogical = false); - Value *matchSelectFromAndOr(Value *A, Value *B, Value *C, Value *D, + Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D, bool InvertFalseVal = false); Value *getSelectCondition(Value *A, Value *B, bool ABIsTheSame); diff --git a/llvm/lib/Transforms/Vectorize/VPlan.h b/llvm/lib/Transforms/Vectorize/VPlan.h index c74329a0bcc4ac..21b088cd238660 100644 --- a/llvm/lib/Transforms/Vectorize/VPlan.h +++ b/llvm/lib/Transforms/Vectorize/VPlan.h @@ -3278,8 +3278,8 @@ class VPlan { private: /// Add to the given dominator tree the header block and every new basic block /// that was created between it and the latch block, inclusive. - static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB, - BasicBlock *LoopPreHeaderBB, + static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB, + BasicBlock *LoopLatchBB, BasicBlock *LoopExitBB); }; diff --git a/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h b/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h index 9d69a233555986..38f8c8423fd16f 100644 --- a/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h +++ b/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h @@ -284,9 +284,9 @@ class SparseIterator { }; /// Helper function to create a TensorLevel object from given `tensor`. -std::unique_ptr makeSparseTensorLevel(OpBuilder &builder, - Location loc, Value t, - unsigned tid, Level l); +std::unique_ptr makeSparseTensorLevel(OpBuilder &b, + Location l, Value t, + unsigned tid, Level lvl); /// Helper function to create a simple SparseIterator object that iterate over /// the SparseTensorLevel. ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [mlir] Fix mismatches between function parameter definitions and declarations (PR #89512)
llvmbot wrote: @llvm/pr-subscribers-mlir @llvm/pr-subscribers-clang-static-analyzer-1 Author: Troy Butler (Troy-Butler) Changes Addresses issue #88716. --- Full diff: https://github.com/llvm/llvm-project/pull/89512.diff 4 Files Affected: - (modified) clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h (+2-2) - (modified) llvm/lib/Transforms/InstCombine/InstCombineInternal.h (+1-1) - (modified) llvm/lib/Transforms/Vectorize/VPlan.h (+2-2) - (modified) mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h (+3-3) ``diff diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h index fac0c04ae2caab..e60a49f68b7a0d 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h @@ -227,12 +227,12 @@ class StoreManager { /// information will not be used. virtual StoreRef invalidateRegions(Store store, ArrayRef Values, - const Expr *E, unsigned Count, + const Expr *Ex, unsigned Count, const LocationContext *LCtx, const CallEvent *Call, InvalidatedSymbols &IS, RegionAndSymbolInvalidationTraits &ITraits, - InvalidatedRegions *InvalidatedTopLevel, + InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated) = 0; /// enterStackFrame - Let the StoreManager to do something when execution diff --git a/llvm/lib/Transforms/InstCombine/InstCombineInternal.h b/llvm/lib/Transforms/InstCombine/InstCombineInternal.h index 4479afbd09afde..4ec5f417998273 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineInternal.h +++ b/llvm/lib/Transforms/InstCombine/InstCombineInternal.h @@ -433,7 +433,7 @@ class LLVM_LIBRARY_VISIBILITY InstCombinerImpl final Value *foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI, bool IsAnd, bool IsLogical = false); - Value *matchSelectFromAndOr(Value *A, Value *B, Value *C, Value *D, + Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D, bool InvertFalseVal = false); Value *getSelectCondition(Value *A, Value *B, bool ABIsTheSame); diff --git a/llvm/lib/Transforms/Vectorize/VPlan.h b/llvm/lib/Transforms/Vectorize/VPlan.h index c74329a0bcc4ac..21b088cd238660 100644 --- a/llvm/lib/Transforms/Vectorize/VPlan.h +++ b/llvm/lib/Transforms/Vectorize/VPlan.h @@ -3278,8 +3278,8 @@ class VPlan { private: /// Add to the given dominator tree the header block and every new basic block /// that was created between it and the latch block, inclusive. - static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB, - BasicBlock *LoopPreHeaderBB, + static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB, + BasicBlock *LoopLatchBB, BasicBlock *LoopExitBB); }; diff --git a/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h b/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h index 9d69a233555986..38f8c8423fd16f 100644 --- a/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h +++ b/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h @@ -284,9 +284,9 @@ class SparseIterator { }; /// Helper function to create a TensorLevel object from given `tensor`. -std::unique_ptr makeSparseTensorLevel(OpBuilder &builder, - Location loc, Value t, - unsigned tid, Level l); +std::unique_ptr makeSparseTensorLevel(OpBuilder &b, + Location l, Value t, + unsigned tid, Level lvl); /// Helper function to create a simple SparseIterator object that iterate over /// the SparseTensorLevel. `` https://github.com/llvm/llvm-project/pull/89512 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [mlir] Fix mismatches between function parameter definitions and declarations (PR #89512)
llvmbot wrote: @llvm/pr-subscribers-mlir-sparse Author: Troy Butler (Troy-Butler) Changes Addresses issue #88716. --- Full diff: https://github.com/llvm/llvm-project/pull/89512.diff 4 Files Affected: - (modified) clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h (+2-2) - (modified) llvm/lib/Transforms/InstCombine/InstCombineInternal.h (+1-1) - (modified) llvm/lib/Transforms/Vectorize/VPlan.h (+2-2) - (modified) mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h (+3-3) ``diff diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h index fac0c04ae2caab..e60a49f68b7a0d 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h @@ -227,12 +227,12 @@ class StoreManager { /// information will not be used. virtual StoreRef invalidateRegions(Store store, ArrayRef Values, - const Expr *E, unsigned Count, + const Expr *Ex, unsigned Count, const LocationContext *LCtx, const CallEvent *Call, InvalidatedSymbols &IS, RegionAndSymbolInvalidationTraits &ITraits, - InvalidatedRegions *InvalidatedTopLevel, + InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated) = 0; /// enterStackFrame - Let the StoreManager to do something when execution diff --git a/llvm/lib/Transforms/InstCombine/InstCombineInternal.h b/llvm/lib/Transforms/InstCombine/InstCombineInternal.h index 4479afbd09afde..4ec5f417998273 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineInternal.h +++ b/llvm/lib/Transforms/InstCombine/InstCombineInternal.h @@ -433,7 +433,7 @@ class LLVM_LIBRARY_VISIBILITY InstCombinerImpl final Value *foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI, bool IsAnd, bool IsLogical = false); - Value *matchSelectFromAndOr(Value *A, Value *B, Value *C, Value *D, + Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D, bool InvertFalseVal = false); Value *getSelectCondition(Value *A, Value *B, bool ABIsTheSame); diff --git a/llvm/lib/Transforms/Vectorize/VPlan.h b/llvm/lib/Transforms/Vectorize/VPlan.h index c74329a0bcc4ac..21b088cd238660 100644 --- a/llvm/lib/Transforms/Vectorize/VPlan.h +++ b/llvm/lib/Transforms/Vectorize/VPlan.h @@ -3278,8 +3278,8 @@ class VPlan { private: /// Add to the given dominator tree the header block and every new basic block /// that was created between it and the latch block, inclusive. - static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB, - BasicBlock *LoopPreHeaderBB, + static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB, + BasicBlock *LoopLatchBB, BasicBlock *LoopExitBB); }; diff --git a/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h b/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h index 9d69a233555986..38f8c8423fd16f 100644 --- a/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h +++ b/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h @@ -284,9 +284,9 @@ class SparseIterator { }; /// Helper function to create a TensorLevel object from given `tensor`. -std::unique_ptr makeSparseTensorLevel(OpBuilder &builder, - Location loc, Value t, - unsigned tid, Level l); +std::unique_ptr makeSparseTensorLevel(OpBuilder &b, + Location l, Value t, + unsigned tid, Level lvl); /// Helper function to create a simple SparseIterator object that iterate over /// the SparseTensorLevel. `` https://github.com/llvm/llvm-project/pull/89512 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [mlir] Fix mismatches between function parameter definitions and declarations (PR #89512)
github-actions[bot] wrote: :warning: C/C++ code formatter, clang-format found issues in your code. :warning: You can test this locally with the following command: ``bash git-clang-format --diff adc4f6233df734fbe3793118ecc89d3584e0c90f f03466fa44a3c7210e7590e6305bc0c9f9aeb446 -- clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h llvm/lib/Transforms/InstCombine/InstCombineInternal.h llvm/lib/Transforms/Vectorize/VPlan.h mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h `` View the diff from clang-format here. ``diff diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h index e60a49f68b..ef23b160a3 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h @@ -225,15 +225,11 @@ public: /// invalidated. This should include any regions explicitly invalidated /// even if they do not currently have bindings. Pass \c NULL if this /// information will not be used. - virtual StoreRef invalidateRegions(Store store, - ArrayRef Values, - const Expr *Ex, unsigned Count, - const LocationContext *LCtx, - const CallEvent *Call, - InvalidatedSymbols &IS, - RegionAndSymbolInvalidationTraits &ITraits, - InvalidatedRegions *TopLevelRegions, - InvalidatedRegions *Invalidated) = 0; + virtual StoreRef invalidateRegions( + Store store, ArrayRef Values, const Expr *Ex, unsigned Count, + const LocationContext *LCtx, const CallEvent *Call, + InvalidatedSymbols &IS, RegionAndSymbolInvalidationTraits &ITraits, + InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated) = 0; /// enterStackFrame - Let the StoreManager to do something when execution /// engine is about to execute into a callee. diff --git a/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h b/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h index 38f8c8423f..46b923250d 100644 --- a/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h +++ b/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h @@ -286,7 +286,8 @@ private: /// Helper function to create a TensorLevel object from given `tensor`. std::unique_ptr makeSparseTensorLevel(OpBuilder &b, Location l, Value t, - unsigned tid, Level lvl); + unsigned tid, + Level lvl); /// Helper function to create a simple SparseIterator object that iterate over /// the SparseTensorLevel. `` https://github.com/llvm/llvm-project/pull/89512 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [mlir] Fix mismatches between function parameter definitions and declarations (PR #89512)
https://github.com/Troy-Butler updated https://github.com/llvm/llvm-project/pull/89512 >From f03466fa44a3c7210e7590e6305bc0c9f9aeb446 Mon Sep 17 00:00:00 2001 From: Troy-Butler Date: Sat, 20 Apr 2024 15:13:09 -0400 Subject: [PATCH 1/2] Fix Definition-Declaration Mismatches Signed-off-by: Troy-Butler --- .../include/clang/StaticAnalyzer/Core/PathSensitive/Store.h | 4 ++-- llvm/lib/Transforms/InstCombine/InstCombineInternal.h | 2 +- llvm/lib/Transforms/Vectorize/VPlan.h | 4 ++-- .../SparseTensor/Transforms/Utils/SparseTensorIterator.h| 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h index fac0c04ae2caab..e60a49f68b7a0d 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h @@ -227,12 +227,12 @@ class StoreManager { /// information will not be used. virtual StoreRef invalidateRegions(Store store, ArrayRef Values, - const Expr *E, unsigned Count, + const Expr *Ex, unsigned Count, const LocationContext *LCtx, const CallEvent *Call, InvalidatedSymbols &IS, RegionAndSymbolInvalidationTraits &ITraits, - InvalidatedRegions *InvalidatedTopLevel, + InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated) = 0; /// enterStackFrame - Let the StoreManager to do something when execution diff --git a/llvm/lib/Transforms/InstCombine/InstCombineInternal.h b/llvm/lib/Transforms/InstCombine/InstCombineInternal.h index 4479afbd09afde..4ec5f417998273 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineInternal.h +++ b/llvm/lib/Transforms/InstCombine/InstCombineInternal.h @@ -433,7 +433,7 @@ class LLVM_LIBRARY_VISIBILITY InstCombinerImpl final Value *foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI, bool IsAnd, bool IsLogical = false); - Value *matchSelectFromAndOr(Value *A, Value *B, Value *C, Value *D, + Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D, bool InvertFalseVal = false); Value *getSelectCondition(Value *A, Value *B, bool ABIsTheSame); diff --git a/llvm/lib/Transforms/Vectorize/VPlan.h b/llvm/lib/Transforms/Vectorize/VPlan.h index c74329a0bcc4ac..21b088cd238660 100644 --- a/llvm/lib/Transforms/Vectorize/VPlan.h +++ b/llvm/lib/Transforms/Vectorize/VPlan.h @@ -3278,8 +3278,8 @@ class VPlan { private: /// Add to the given dominator tree the header block and every new basic block /// that was created between it and the latch block, inclusive. - static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB, - BasicBlock *LoopPreHeaderBB, + static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB, + BasicBlock *LoopLatchBB, BasicBlock *LoopExitBB); }; diff --git a/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h b/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h index 9d69a233555986..38f8c8423fd16f 100644 --- a/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h +++ b/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h @@ -284,9 +284,9 @@ class SparseIterator { }; /// Helper function to create a TensorLevel object from given `tensor`. -std::unique_ptr makeSparseTensorLevel(OpBuilder &builder, - Location loc, Value t, - unsigned tid, Level l); +std::unique_ptr makeSparseTensorLevel(OpBuilder &b, + Location l, Value t, + unsigned tid, Level lvl); /// Helper function to create a simple SparseIterator object that iterate over /// the SparseTensorLevel. >From 4fe63ddecc056bc521d439952fb2b7fc5d83d9b6 Mon Sep 17 00:00:00 2001 From: Troy-Butler Date: Sat, 20 Apr 2024 15:33:43 -0400 Subject: [PATCH 2/2] Fix Code Formatting Issues Signed-off-by: Troy-Butler --- .../StaticAnalyzer/Core/PathSensitive/Store.h | 14 +- .../Transforms/Utils/SparseTensorIterator.h| 3 ++- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h b/clang/include/clang/StaticAnalyzer/Core/PathSensiti
[clang] [llvm] [mlir] Fix mismatches between function parameter definitions and declarations (PR #89512)
https://github.com/Troy-Butler updated https://github.com/llvm/llvm-project/pull/89512 >From f03466fa44a3c7210e7590e6305bc0c9f9aeb446 Mon Sep 17 00:00:00 2001 From: Troy-Butler Date: Sat, 20 Apr 2024 15:13:09 -0400 Subject: [PATCH 1/3] Fix Definition-Declaration Mismatches Signed-off-by: Troy-Butler --- .../include/clang/StaticAnalyzer/Core/PathSensitive/Store.h | 4 ++-- llvm/lib/Transforms/InstCombine/InstCombineInternal.h | 2 +- llvm/lib/Transforms/Vectorize/VPlan.h | 4 ++-- .../SparseTensor/Transforms/Utils/SparseTensorIterator.h| 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h index fac0c04ae2caab..e60a49f68b7a0d 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h @@ -227,12 +227,12 @@ class StoreManager { /// information will not be used. virtual StoreRef invalidateRegions(Store store, ArrayRef Values, - const Expr *E, unsigned Count, + const Expr *Ex, unsigned Count, const LocationContext *LCtx, const CallEvent *Call, InvalidatedSymbols &IS, RegionAndSymbolInvalidationTraits &ITraits, - InvalidatedRegions *InvalidatedTopLevel, + InvalidatedRegions *TopLevelRegions, InvalidatedRegions *Invalidated) = 0; /// enterStackFrame - Let the StoreManager to do something when execution diff --git a/llvm/lib/Transforms/InstCombine/InstCombineInternal.h b/llvm/lib/Transforms/InstCombine/InstCombineInternal.h index 4479afbd09afde..4ec5f417998273 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineInternal.h +++ b/llvm/lib/Transforms/InstCombine/InstCombineInternal.h @@ -433,7 +433,7 @@ class LLVM_LIBRARY_VISIBILITY InstCombinerImpl final Value *foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI, bool IsAnd, bool IsLogical = false); - Value *matchSelectFromAndOr(Value *A, Value *B, Value *C, Value *D, + Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D, bool InvertFalseVal = false); Value *getSelectCondition(Value *A, Value *B, bool ABIsTheSame); diff --git a/llvm/lib/Transforms/Vectorize/VPlan.h b/llvm/lib/Transforms/Vectorize/VPlan.h index c74329a0bcc4ac..21b088cd238660 100644 --- a/llvm/lib/Transforms/Vectorize/VPlan.h +++ b/llvm/lib/Transforms/Vectorize/VPlan.h @@ -3278,8 +3278,8 @@ class VPlan { private: /// Add to the given dominator tree the header block and every new basic block /// that was created between it and the latch block, inclusive. - static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB, - BasicBlock *LoopPreHeaderBB, + static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB, + BasicBlock *LoopLatchBB, BasicBlock *LoopExitBB); }; diff --git a/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h b/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h index 9d69a233555986..38f8c8423fd16f 100644 --- a/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h +++ b/mlir/lib/Dialect/SparseTensor/Transforms/Utils/SparseTensorIterator.h @@ -284,9 +284,9 @@ class SparseIterator { }; /// Helper function to create a TensorLevel object from given `tensor`. -std::unique_ptr makeSparseTensorLevel(OpBuilder &builder, - Location loc, Value t, - unsigned tid, Level l); +std::unique_ptr makeSparseTensorLevel(OpBuilder &b, + Location l, Value t, + unsigned tid, Level lvl); /// Helper function to create a simple SparseIterator object that iterate over /// the SparseTensorLevel. >From 4fe63ddecc056bc521d439952fb2b7fc5d83d9b6 Mon Sep 17 00:00:00 2001 From: Troy-Butler Date: Sat, 20 Apr 2024 15:33:43 -0400 Subject: [PATCH 2/3] Fix Code Formatting Issues Signed-off-by: Troy-Butler --- .../StaticAnalyzer/Core/PathSensitive/Store.h | 14 +- .../Transforms/Utils/SparseTensorIterator.h| 3 ++- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h b/clang/include/clang/StaticAnalyzer/Core/PathSensiti
[clang] [llvm] [clang][MBD] set up module build daemon infrastructure (PR #67562)
@@ -0,0 +1,289 @@ +//===--- cc1modbuildd_main.cpp - Clang CC1 Module Build Daemon ===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "clang/Tooling/ModuleBuildDaemon/SocketSupport.h" +#include "clang/Tooling/ModuleBuildDaemon/Utils.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/Signals.h" +#include "llvm/Support/ThreadPool.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +using namespace llvm; +using namespace clang::tooling::cc1modbuildd; + +// Create unbuffered STDOUT stream so that any logging done by the module build +// daemon can be viewed without having to terminate the process +static raw_fd_ostream &unbuff_outs() { + static raw_fd_ostream S(fileno(stdout), false, true); + return S; +} + +static bool LogVerbose = false; +static void logVerbose(const llvm::Twine &message) { + if (LogVerbose) { +unbuff_outs() << message << '\n'; + } +} + +static void modifySignals(decltype(SIG_DFL) handler) { + + if (std::signal(SIGTERM, handler) == SIG_ERR) { +errs() << "failed to handle SIGTERM" << '\n'; +exit(EXIT_FAILURE); + } + + if (std::signal(SIGINT, handler) == SIG_ERR) { +errs() << "failed to handle SIGINT" << '\n'; +exit(EXIT_FAILURE); + } + +#ifdef SIGHUP + if (::signal(SIGHUP, SIG_IGN) == SIG_ERR) { +errs() << "failed to handle SIGHUP" << '\n'; +exit(EXIT_FAILURE); + } +#endif +} + +namespace { + +class ModuleBuildDaemonServer { +public: + SmallString<256> SocketPath; + SmallString<256> Stderr; // path to stderr + SmallString<256> Stdout; // path to stdout + + explicit ModuleBuildDaemonServer(StringRef Path) + : SocketPath(Path), Stderr(Path), Stdout(Path) { +llvm::sys::path::append(SocketPath, SocketFileName); +llvm::sys::path::append(Stdout, StdoutFileName); +llvm::sys::path::append(Stderr, StderrFileName); + } + + void setupDaemonEnv(); + void createDaemonSocket(); + void listenForClients(); + + static void handleConnection(std::shared_ptr Connection); + + // TODO: modify so when shutdownDaemon is called the daemon stops accepting + // new client connections and waits for all existing client connections to + // terminate before closing the file descriptor and exiting + void shutdownDaemon() { +RunServiceLoop = false; +if (ServerListener.has_value()) + ServerListener.value().shutdown(); + } + +private: + std::atomic RunServiceLoop = true; + std::optional ServerListener; +}; + +// Used to handle signals +ModuleBuildDaemonServer *DaemonPtr = nullptr; +void handleSignal(int) { DaemonPtr->shutdownDaemon(); } +} // namespace + +// Sets up file descriptors and signals for module build daemon +void ModuleBuildDaemonServer::setupDaemonEnv() { + +#ifdef _WIN32 + if (std::freopen("NUL", "r", stdin) == NULL) { +#else + if (std::freopen("/dev/null", "r", stdin) == NULL) { +#endif +llvm::errs() << "Failed to close stdin" << '\n'; +exit(EXIT_FAILURE); + } + + if (std::freopen(Stdout.c_str(), "a", stdout) == NULL) { +llvm::errs() << "Failed to redirect stdout to " << Stdout << '\n'; +exit(EXIT_FAILURE); + } + if (std::freopen(Stderr.c_str(), "a", stderr) == NULL) { +llvm::errs() << "Failed to redirect stderr to " << Stderr << '\n'; +exit(EXIT_FAILURE); + } + + modifySignals(handleSignal); +} + +// Creates unix socket for IPC with frontends +void ModuleBuildDaemonServer::createDaemonSocket() { + + while (true) { +Expected MaybeServerListener = +llvm::ListeningSocket::createUnix(SocketPath); + +if (llvm::Error Err = MaybeServerListener.takeError()) { + llvm::handleAllErrors(std::move(Err), [&](const llvm::StringError &SE) { +std::error_code EC = SE.convertToErrorCode(); + +// Exit successfully if the socket address is already in use. When +// TUs are compiled in parallel, until the socket file is created, all +// clang invocations will try to spawn a module build daemon. +#ifdef _WIN32 +if (EC.value() == WSAEADDRINUSE) { +#else +if (EC == std::errc::address_in_use) { +#endif + exit(EXIT_SUCCESS); +} else if (EC == std::errc::file_exists) { + if (std::remove(SocketPath.c_str()) != 0) { +llvm::errs() << "Failed to remove " << SocketPath << ": " + << strerror(errno) << '\n'; +exit(EXIT_FAILURE); + } + // If a previous module build daemon invocation crashes, the socket + // file will need to be removed before the address can be binded to + logVerbose("Removing ineligible file: " + SocketPath); +
[clang] [llvm] [ARM] Armv8-R does not require fp64 or neon. (PR #88287)
https://github.com/chrisnc updated https://github.com/llvm/llvm-project/pull/88287 >From a4a27e9db447fde7f38952618b877fc1ff741279 Mon Sep 17 00:00:00 2001 From: Chris Copeland Date: Fri, 5 Apr 2024 22:40:46 -0700 Subject: [PATCH] [ARM] Armv8-R does not require fp64 or neon. --- clang/test/Driver/arm-cortex-cpus-1.c | 8 clang/test/Driver/arm-features.c | 2 +- clang/test/Preprocessor/arm-target-features.c | 4 ++-- llvm/include/llvm/TargetParser/ARMTargetParser.def | 2 +- llvm/lib/Target/ARM/ARM.td | 6 +++--- llvm/test/Analysis/CostModel/ARM/arith.ll | 2 +- llvm/test/Analysis/CostModel/ARM/cast.ll | 4 ++-- llvm/test/Analysis/CostModel/ARM/cast_ldst.ll | 4 ++-- llvm/test/Analysis/CostModel/ARM/cmps.ll | 4 ++-- llvm/test/Analysis/CostModel/ARM/divrem.ll | 2 +- llvm/test/CodeGen/ARM/cortex-a57-misched-basic.ll | 2 +- llvm/test/CodeGen/ARM/fpconv.ll| 4 ++-- llvm/test/CodeGen/ARM/half.ll | 4 ++-- llvm/test/CodeGen/ARM/misched-fp-basic.ll | 2 +- llvm/test/CodeGen/ARM/useaa.ll | 2 +- llvm/unittests/TargetParser/TargetParserTest.cpp | 4 ++-- 16 files changed, 28 insertions(+), 28 deletions(-) diff --git a/clang/test/Driver/arm-cortex-cpus-1.c b/clang/test/Driver/arm-cortex-cpus-1.c index 25abbe1e3a8ad7..6f0b64910f9b07 100644 --- a/clang/test/Driver/arm-cortex-cpus-1.c +++ b/clang/test/Driver/arm-cortex-cpus-1.c @@ -153,23 +153,23 @@ // RUN: %clang -target armv8r-linux-gnueabi -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8R %s // RUN: %clang -target arm -march=armv8r -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8R %s // RUN: %clang -target arm -march=armv8-r -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8R %s -// CHECK-V8R: "-cc1"{{.*}} "-triple" "armv8r-{{.*}} "-target-cpu" "cortex-r52" +// CHECK-V8R: "-cc1"{{.*}} "-triple" "armv8r-{{.*}} "-target-cpu" "generic" // RUN: %clang -target armv8r-linux-gnueabi -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8R-BIG %s // RUN: %clang -target arm -march=armv8r -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8R-BIG %s // RUN: %clang -target arm -march=armv8-r -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8R-BIG %s -// CHECK-V8R-BIG: "-cc1"{{.*}} "-triple" "armebv8r-{{.*}} "-target-cpu" "cortex-r52" +// CHECK-V8R-BIG: "-cc1"{{.*}} "-triple" "armebv8r-{{.*}} "-target-cpu" "generic" // RUN: %clang -target armv8r-linux-gnueabi -mthumb -### -c %s 2>&1 | \ // RUN: FileCheck -check-prefix=CHECK-V8R-THUMB %s // RUN: %clang -target arm -march=armv8r -mthumb -### -c %s 2>&1 | \ // RUN: FileCheck -check-prefix=CHECK-V8R-THUMB %s -// CHECK-V8R-THUMB: "-cc1"{{.*}} "-triple" "thumbv8r-{{.*}} "-target-cpu" "cortex-r52" +// CHECK-V8R-THUMB: "-cc1"{{.*}} "-triple" "thumbv8r-{{.*}} "-target-cpu" "generic" // RUN: %clang -target armv8r-linux-gnueabi -mthumb -mbig-endian -### -c %s 2>&1 | \ // RUN: FileCheck -check-prefix=CHECK-V8R-THUMB-BIG %s // RUN: %clang -target arm -march=armv8r -mthumb -mbig-endian -### -c %s 2>&1 | \ // RUN: FileCheck -check-prefix=CHECK-V8R-THUMB-BIG %s -// CHECK-V8R-THUMB-BIG: "-cc1"{{.*}} "-triple" "thumbebv8r-{{.*}} "-target-cpu" "cortex-r52" +// CHECK-V8R-THUMB-BIG: "-cc1"{{.*}} "-triple" "thumbebv8r-{{.*}} "-target-cpu" "generic" // RUN: %clang -mcpu=generic -target armv8 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A-GENERIC %s // RUN: %clang -mcpu=generic -target arm -march=armv8 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A-GENERIC %s diff --git a/clang/test/Driver/arm-features.c b/clang/test/Driver/arm-features.c index e043244f18a61f..eb424f5f61116b 100644 --- a/clang/test/Driver/arm-features.c +++ b/clang/test/Driver/arm-features.c @@ -74,7 +74,7 @@ // Check +crypto for M and R profiles: // // RUN: %clang -target arm-arm-none-eabi -march=armv8-r+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CRYPTO-R %s -// CHECK-CRYPTO-R: "-cc1"{{.*}} "-target-cpu" "cortex-r52"{{.*}} "-target-feature" "+sha2" "-target-feature" "+aes" +// CHECK-CRYPTO-R: "-cc1"{{.*}} "-target-cpu" "generic"{{.*}} "-target-feature" "+sha2" "-target-feature" "+aes" // RUN: %clang -target arm-arm-none-eabi -march=armv8-m.base+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO5 %s // RUN: %clang -target arm-arm-none-eabi -march=armv8-m.main+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO5 %s // RUN: %clang -target arm-arm-none-eabi -mcpu=cortex-m23+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO5 %s diff --git a/clang/test/Preprocessor/arm-target-features.c b/clang/test/Preprocessor/arm-target-features.c index 236c9f2479b705..2d65bfd4f43995 100644 --- a/clang/test/Preprocessor/arm-target-features.c +++ b/clang/test/Preprocessor/arm-target-features.c @@ -88,8 +88,8 @@ // CHECK-V8R: #define __ARM_FEATURE_NUMER
[clang] [Clang] Allow the value of unroll count to be zero in `#pragma GCC unroll` and `#pragma unroll` (PR #88666)
alexfh wrote: After this patch clang doesn't accept integer template argument as a parameter of `#pragma unroll` (https://gcc.godbolt.org/z/Woc7zs3sK): ``` template void test(int *List, int Length) { int i = 0; #pragma unroll Unroll while (i + 1 < Length) { List[i] = i; } } ``` ``` :4:16: error: expression is not an integral constant expression 4 | #pragma unroll Unroll |^~ ``` Please fix soon or revert. Thanks! https://github.com/llvm/llvm-project/pull/88666 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CMake][Release] Add stage2-package target (PR #89517)
https://github.com/tstellar created https://github.com/llvm/llvm-project/pull/89517 This target will be used to generate the release binary package for uploading to GitHub. >From 79e4f21df778ede9238c66e06ca289d7599f9f5c Mon Sep 17 00:00:00 2001 From: Tom Stellard Date: Mon, 15 Apr 2024 12:03:33 -0700 Subject: [PATCH] [CMake][Release] Add stage2-package target This target will be used to generate the release binary package for uploading to GitHub. --- clang/cmake/caches/Release.cmake | 2 ++ 1 file changed, 2 insertions(+) diff --git a/clang/cmake/caches/Release.cmake b/clang/cmake/caches/Release.cmake index bd1f688d61a7ea..fa972636553f1f 100644 --- a/clang/cmake/caches/Release.cmake +++ b/clang/cmake/caches/Release.cmake @@ -14,6 +14,7 @@ if (LLVM_RELEASE_ENABLE_PGO) set(CLANG_BOOTSTRAP_TARGETS generate-profdata stage2 +stage2-package stage2-clang stage2-distribution stage2-install @@ -57,6 +58,7 @@ set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "") set(BOOTSTRAP_CLANG_ENABLE_BOOTSTRAP ON CACHE STRING "") set(BOOTSTRAP_CLANG_BOOTSTRAP_TARGETS clang + package check-all check-llvm check-clang CACHE STRING "") ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CMake][Release] Add stage2-package target (PR #89517)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Tom Stellard (tstellar) Changes This target will be used to generate the release binary package for uploading to GitHub. --- Full diff: https://github.com/llvm/llvm-project/pull/89517.diff 1 Files Affected: - (modified) clang/cmake/caches/Release.cmake (+2) ``diff diff --git a/clang/cmake/caches/Release.cmake b/clang/cmake/caches/Release.cmake index bd1f688d61a7ea..fa972636553f1f 100644 --- a/clang/cmake/caches/Release.cmake +++ b/clang/cmake/caches/Release.cmake @@ -14,6 +14,7 @@ if (LLVM_RELEASE_ENABLE_PGO) set(CLANG_BOOTSTRAP_TARGETS generate-profdata stage2 +stage2-package stage2-clang stage2-distribution stage2-install @@ -57,6 +58,7 @@ set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "") set(BOOTSTRAP_CLANG_ENABLE_BOOTSTRAP ON CACHE STRING "") set(BOOTSTRAP_CLANG_BOOTSTRAP_TARGETS clang + package check-all check-llvm check-clang CACHE STRING "") `` https://github.com/llvm/llvm-project/pull/89517 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Add config option to allow detection of unused system headers (PR #87208)
HighCommander4 wrote: > @HighCommander4 Ping. Could you review this PR or suggest other reviewers, > please? I'm not very familiar with include-cleaner, but I added some reviewers who are. https://github.com/llvm/llvm-project/pull/87208 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [cmake] Remove custom linker flag check function (PR #86602)
https://github.com/tstellar approved this pull request. LGTM. https://github.com/llvm/llvm-project/pull/86602 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
@@ -0,0 +1,41 @@ +//===--- ReturnConstRefFromParameterCheck.cpp - clang-tidy ===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ReturnConstRefFromParameterCheck.h" +#include "../utils/Matchers.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +std::optional +ReturnConstRefFromParameterCheck::getCheckTraversalKind() const { + // Use 'AsIs' to make sure the return type is exactly the same as the + // parameter type. + return TK_AsIs; +} + +void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + returnStmt(hasReturnValue(declRefExpr(to(parmVarDecl(hasType( + hasCanonicalType(matchers::isReferenceToConst( + .bind("ret"), + this); +} + +void ReturnConstRefFromParameterCheck::check( +const MatchFinder::MatchResult &Result) { + const auto *R = Result.Nodes.getNodeAs("ret"); + diag(R->getRetValue()->getBeginLoc(), HerrCai0907 wrote: Yes, "ret" is bind with ReturnStmt. So the cast should always success. https://github.com/llvm/llvm-project/pull/89497 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
@@ -0,0 +1,35 @@ +//===--- ReturnConstRefFromParameterCheck.h - clang-tidy *- 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 +// +//===--===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_RETURNCONSTREFFROMPARAMETERCHECK_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_RETURNCONSTREFFROMPARAMETERCHECK_H + +#include "../ClangTidyCheck.h" + +namespace clang::tidy::bugprone { + +/// Detects the function which returns the const reference from parameter which +/// causes potential use after free if the caller uses xvalue as argument. HerrCai0907 wrote: looks better. Could you explain more about why here should use constant reference. const reference can map to `const &` semantics directly. https://github.com/llvm/llvm-project/pull/89497 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
https://github.com/HerrCai0907 updated https://github.com/llvm/llvm-project/pull/89497 >From 91915f68902ade86c0bf8eba643428017ae8bb3c Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Sat, 20 Apr 2024 17:58:19 +0800 Subject: [PATCH 1/3] [tidy] add new check bugprone-return-const-ref-from-parameter Detects the function which returns the const reference from parameter which causes potential use after free if the caller uses xvalue as argument. In c++, const reference parameter can accept xvalue which will be destructed after the call. When the function returns this parameter also as const reference, then the returned reference can be used after the object it refers to has been destroyed. Fixes: #85253 --- .../bugprone/BugproneTidyModule.cpp | 3 ++ .../clang-tidy/bugprone/CMakeLists.txt| 1 + .../ReturnConstRefFromParameterCheck.cpp | 41 +++ .../ReturnConstRefFromParameterCheck.h| 35 clang-tools-extra/docs/ReleaseNotes.rst | 6 +++ .../return-const-ref-from-parameter.rst | 30 ++ .../docs/clang-tidy/checks/list.rst | 9 ++-- .../return-const-ref-from-parameter.cpp | 31 ++ 8 files changed, 152 insertions(+), 4 deletions(-) create mode 100644 clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/bugprone/return-const-ref-from-parameter.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/bugprone/return-const-ref-from-parameter.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp index 2931325d8b5798..1b92d2e60cc173 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp @@ -54,6 +54,7 @@ #include "PosixReturnCheck.h" #include "RedundantBranchConditionCheck.h" #include "ReservedIdentifierCheck.h" +#include "ReturnConstRefFromParameterCheck.h" #include "SharedPtrArrayMismatchCheck.h" #include "SignalHandlerCheck.h" #include "SignedCharMisuseCheck.h" @@ -137,6 +138,8 @@ class BugproneModule : public ClangTidyModule { "bugprone-inaccurate-erase"); CheckFactories.registerCheck( "bugprone-incorrect-enable-if"); +CheckFactories.registerCheck( +"bugprone-return-const-ref-from-parameter"); CheckFactories.registerCheck( "bugprone-switch-missing-default-case"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt index 081ba67efe1538..2d303191f88650 100644 --- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt @@ -26,6 +26,7 @@ add_clang_library(clangTidyBugproneModule ImplicitWideningOfMultiplicationResultCheck.cpp InaccurateEraseCheck.cpp IncorrectEnableIfCheck.cpp + ReturnConstRefFromParameterCheck.cpp SuspiciousStringviewDataUsageCheck.cpp SwitchMissingDefaultCaseCheck.cpp IncDecInConditionsCheck.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp new file mode 100644 index 00..87fc663231496e --- /dev/null +++ b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp @@ -0,0 +1,41 @@ +//===--- ReturnConstRefFromParameterCheck.cpp - clang-tidy ===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ReturnConstRefFromParameterCheck.h" +#include "../utils/Matchers.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +std::optional +ReturnConstRefFromParameterCheck::getCheckTraversalKind() const { + // Use 'AsIs' to make sure the return type is exactly the same as the + // parameter type. + return TK_AsIs; +} + +void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + returnStmt(hasReturnValue(declRefExpr(to(parmVarDecl(hasType( + hasCanonicalType(matchers::isReferenceToConst( + .bind("ret"), + this); +} + +void ReturnConstRefFromParameterCheck::check( +const MatchFinder::MatchResult &Result) { + const auto *R = Result.Nodes.getNodeAs("ret"); + diag(R->getRetValue()->getBeginLoc(), + "return const reference parameter cause potential use-after-free " +
[clang-tools-extra] 811ffc0 - [tidy] update check list [NFC]
Author: Congcong Cai Date: 2024-04-21T11:58:35+08:00 New Revision: 811ffc049ff914e15116c25ca8db7b8bd9a8e186 URL: https://github.com/llvm/llvm-project/commit/811ffc049ff914e15116c25ca8db7b8bd9a8e186 DIFF: https://github.com/llvm/llvm-project/commit/811ffc049ff914e15116c25ca8db7b8bd9a8e186.diff LOG: [tidy] update check list [NFC] Added: Modified: clang-tools-extra/docs/clang-tidy/checks/list.rst Removed: diff --git a/clang-tools-extra/docs/clang-tidy/checks/list.rst b/clang-tools-extra/docs/clang-tidy/checks/list.rst index 8bc46acad56c84..3a06d7c30c9b79 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/list.rst +++ b/clang-tools-extra/docs/clang-tidy/checks/list.rst @@ -341,9 +341,9 @@ Clang-Tidy Checks :doc:`portability-std-allocator-const `, :doc:`readability-avoid-const-params-in-decls `, "Yes" :doc:`readability-avoid-nested-conditional-operator `, - :doc:`readability-avoid-return-with-void-value `, + :doc:`readability-avoid-return-with-void-value `, "Yes" :doc:`readability-avoid-unconditional-preprocessor-if `, - :doc:`readability-braces-around-statements `, "Yes" + :doc:`readability-braces-around-statements `, :doc:`readability-const-return-type `, "Yes" :doc:`readability-container-contains `, "Yes" :doc:`readability-container-data-pointer `, "Yes" @@ -529,12 +529,12 @@ Clang-Tidy Checks :doc:`cppcoreguidelines-non-private-member-variables-in-classes `, :doc:`misc-non-private-member-variables-in-classes `, :doc:`cppcoreguidelines-use-default-member-init `, :doc:`modernize-use-default-member-init `, "Yes" :doc:`fuchsia-header-anon-namespaces `, :doc:`google-build-namespaces `, - :doc:`google-readability-braces-around-statements `, :doc:`readability-braces-around-statements `, "Yes" + :doc:`google-readability-braces-around-statements `, :doc:`readability-braces-around-statements `, :doc:`google-readability-function-size `, :doc:`readability-function-size `, :doc:`google-readability-namespace-comments `, :doc:`llvm-namespace-comment `, :doc:`hicpp-avoid-c-arrays `, :doc:`modernize-avoid-c-arrays `, :doc:`hicpp-avoid-goto `, :doc:`cppcoreguidelines-avoid-goto `, - :doc:`hicpp-braces-around-statements `, :doc:`readability-braces-around-statements `, "Yes" + :doc:`hicpp-braces-around-statements `, :doc:`readability-braces-around-statements `, :doc:`hicpp-deprecated-headers `, :doc:`modernize-deprecated-headers `, "Yes" :doc:`hicpp-explicit-conversions `, :doc:`google-explicit-constructor `, "Yes" :doc:`hicpp-function-size `, :doc:`readability-function-size `, ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)
@@ -341,9 +342,9 @@ Clang-Tidy Checks :doc:`portability-std-allocator-const `, :doc:`readability-avoid-const-params-in-decls `, "Yes" :doc:`readability-avoid-nested-conditional-operator `, - :doc:`readability-avoid-return-with-void-value `, + :doc:`readability-avoid-return-with-void-value `, "Yes" :doc:`readability-avoid-unconditional-preprocessor-if `, - :doc:`readability-braces-around-statements `, "Yes" HerrCai0907 wrote: Thanks. I split the change and commit in 811ffc049ff914e15116c25ca8db7b8bd9a8e186 https://github.com/llvm/llvm-project/pull/89497 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)
https://github.com/nicovank created https://github.com/llvm/llvm-project/pull/89530 Using `compare` is the next most common roundabout way to express `starts_with` before it was added to the standard. In this case, using `starts_with` is a readability improvement. Extend existing `modernize-use-starts-ends-with` to cover this case. ``` // The following will now be replaced by starts_with(). string.compare(0, strlen("prefix"), "prefix") == 0; string.compare(0, 6, "prefix") == 0; string.compare(0, prefix.length(), prefix) == 0; string.compare(0, prefix.size(), prefix) == 0; ``` There are no such instances in llvm-project, maybe more will surface when the C++ default is changed to 20 for `std::string`. Other build issues come up when trying to override it. Running this on llvm-project and dolphin: - https://github.com/llvm/llvm-project/pull/89140 (no additional instances) - https://github.com/dolphin-emu/dolphin/pull/12718 >From decc4b58c4d899e619ea63c50fa873c7bc605baf Mon Sep 17 00:00:00 2001 From: Nicolas van Kempen Date: Sun, 21 Apr 2024 05:17:19 + Subject: [PATCH] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() --- .../modernize/UseStartsEndsWithCheck.cpp | 92 --- .../modernize/UseStartsEndsWithCheck.h| 4 +- clang-tools-extra/docs/ReleaseNotes.rst | 4 + .../checks/modernize/use-starts-ends-with.rst | 6 +- .../clang-tidy/checkers/Inputs/Headers/string | 4 + .../checkers/Inputs/Headers/string.h | 1 + .../modernize/use-starts-ends-with.cpp| 45 + 7 files changed, 137 insertions(+), 19 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 062f6e9911dbed..38fe1984ac494e 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -16,6 +16,49 @@ using namespace clang::ast_matchers; namespace clang::tidy::modernize { +namespace { +// Given two argument indices X and Y, matches when a call expression has a +// string at index X with an expression representing that string's length at +// index Y. The string can be a string literal or a variable. The length can be +// matched via an integer literal or a call to strlen() in the case of a string +// literal, and by a call to size() or length() in the string variable case. +AST_POLYMORPHIC_MATCHER_P2(HasStringAndLengthArguments, + AST_POLYMORPHIC_SUPPORTED_TYPES( + CallExpr, CXXConstructExpr, + CXXUnresolvedConstructExpr, ObjCMessageExpr), + unsigned, StringArgIndex, unsigned, LengthArgIndex) { + if (StringArgIndex >= Node.getNumArgs() || + LengthArgIndex >= Node.getNumArgs()) { +return false; + } + + const Expr *StringArgExpr = + Node.getArg(StringArgIndex)->IgnoreParenImpCasts(); + const Expr *LengthArgExpr = + Node.getArg(LengthArgIndex)->IgnoreParenImpCasts(); + + if (const auto *StringArg = dyn_cast(StringArgExpr)) { +// Match an integer literal equal to the string length or a call to strlen. +const auto Matcher = expr(anyOf( +integerLiteral(equals(StringArg->getLength())), +callExpr( +callee(functionDecl(hasName("strlen"))), argumentCountIs(1), +hasArgument(0, stringLiteral(hasSize(StringArg->getLength())); +return Matcher.matches(*LengthArgExpr, Finder, Builder); + } + + if (const auto *StringArg = dyn_cast(StringArgExpr)) { +// Match a call to size() or length() on the same variable. +const auto Matcher = cxxMemberCallExpr( +on(declRefExpr(to(varDecl(equalsNode(StringArg->getDecl()), +callee(cxxMethodDecl(hasAnyName("size", "length"), isConst(), + parameterCountIs(0; +return Matcher.matches(*LengthArgExpr, Finder, Builder); + } + + return false; +} +} // namespace UseStartsEndsWithCheck::UseStartsEndsWithCheck(StringRef Name, ClangTidyContext *Context) @@ -43,7 +86,9 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { callee(cxxMethodDecl(hasName("find")).bind("find_fun")), // ... on a class with a starts_with function. on(hasType( - hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction); + hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction, + // Bind search expression. + hasArgument(0, expr().bind("search_expr"))); const auto RFindExpr = cxxMemberCallExpr( // A method call with a second argument of zero... @@ -52,15 +97,30 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { callee(cxxMethodDecl(hasName("rfind")).bind("find_fun")), // ... on a class with a starts_with function. on(hasTy
[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)
llvmbot wrote: @llvm/pr-subscribers-clang-tools-extra Author: Nicolas van Kempen (nicovank) Changes Using `compare` is the next most common roundabout way to express `starts_with` before it was added to the standard. In this case, using `starts_with` is a readability improvement. Extend existing `modernize-use-starts-ends-with` to cover this case. ``` // The following will now be replaced by starts_with(). string.compare(0, strlen("prefix"), "prefix") == 0; string.compare(0, 6, "prefix") == 0; string.compare(0, prefix.length(), prefix) == 0; string.compare(0, prefix.size(), prefix) == 0; ``` There are no such instances in llvm-project, maybe more will surface when the C++ default is changed to 20 for `std::string`. Other build issues come up when trying to override it. Running this on llvm-project and dolphin: - https://github.com/llvm/llvm-project/pull/89140 (no additional instances) - https://github.com/dolphin-emu/dolphin/pull/12718 --- Full diff: https://github.com/llvm/llvm-project/pull/89530.diff 7 Files Affected: - (modified) clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp (+77-15) - (modified) clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.h (+2-2) - (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) - (modified) clang-tools-extra/docs/clang-tidy/checks/modernize/use-starts-ends-with.rst (+4-2) - (modified) clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/string (+4) - (modified) clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/string.h (+1) - (modified) clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp (+45) ``diff diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 062f6e9911dbed..38fe1984ac494e 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -16,6 +16,49 @@ using namespace clang::ast_matchers; namespace clang::tidy::modernize { +namespace { +// Given two argument indices X and Y, matches when a call expression has a +// string at index X with an expression representing that string's length at +// index Y. The string can be a string literal or a variable. The length can be +// matched via an integer literal or a call to strlen() in the case of a string +// literal, and by a call to size() or length() in the string variable case. +AST_POLYMORPHIC_MATCHER_P2(HasStringAndLengthArguments, + AST_POLYMORPHIC_SUPPORTED_TYPES( + CallExpr, CXXConstructExpr, + CXXUnresolvedConstructExpr, ObjCMessageExpr), + unsigned, StringArgIndex, unsigned, LengthArgIndex) { + if (StringArgIndex >= Node.getNumArgs() || + LengthArgIndex >= Node.getNumArgs()) { +return false; + } + + const Expr *StringArgExpr = + Node.getArg(StringArgIndex)->IgnoreParenImpCasts(); + const Expr *LengthArgExpr = + Node.getArg(LengthArgIndex)->IgnoreParenImpCasts(); + + if (const auto *StringArg = dyn_cast(StringArgExpr)) { +// Match an integer literal equal to the string length or a call to strlen. +const auto Matcher = expr(anyOf( +integerLiteral(equals(StringArg->getLength())), +callExpr( +callee(functionDecl(hasName("strlen"))), argumentCountIs(1), +hasArgument(0, stringLiteral(hasSize(StringArg->getLength())); +return Matcher.matches(*LengthArgExpr, Finder, Builder); + } + + if (const auto *StringArg = dyn_cast(StringArgExpr)) { +// Match a call to size() or length() on the same variable. +const auto Matcher = cxxMemberCallExpr( +on(declRefExpr(to(varDecl(equalsNode(StringArg->getDecl()), +callee(cxxMethodDecl(hasAnyName("size", "length"), isConst(), + parameterCountIs(0; +return Matcher.matches(*LengthArgExpr, Finder, Builder); + } + + return false; +} +} // namespace UseStartsEndsWithCheck::UseStartsEndsWithCheck(StringRef Name, ClangTidyContext *Context) @@ -43,7 +86,9 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { callee(cxxMethodDecl(hasName("find")).bind("find_fun")), // ... on a class with a starts_with function. on(hasType( - hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction); + hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction, + // Bind search expression. + hasArgument(0, expr().bind("search_expr"))); const auto RFindExpr = cxxMemberCallExpr( // A method call with a second argument of zero... @@ -52,15 +97,30 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { callee(cxxMethodDecl(hasName("rfind")).bind("find_fun")), // ... on a class
[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)
llvmbot wrote: @llvm/pr-subscribers-clang-tidy Author: Nicolas van Kempen (nicovank) Changes Using `compare` is the next most common roundabout way to express `starts_with` before it was added to the standard. In this case, using `starts_with` is a readability improvement. Extend existing `modernize-use-starts-ends-with` to cover this case. ``` // The following will now be replaced by starts_with(). string.compare(0, strlen("prefix"), "prefix") == 0; string.compare(0, 6, "prefix") == 0; string.compare(0, prefix.length(), prefix) == 0; string.compare(0, prefix.size(), prefix) == 0; ``` There are no such instances in llvm-project, maybe more will surface when the C++ default is changed to 20 for `std::string`. Other build issues come up when trying to override it. Running this on llvm-project and dolphin: - https://github.com/llvm/llvm-project/pull/89140 (no additional instances) - https://github.com/dolphin-emu/dolphin/pull/12718 --- Full diff: https://github.com/llvm/llvm-project/pull/89530.diff 7 Files Affected: - (modified) clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp (+77-15) - (modified) clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.h (+2-2) - (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) - (modified) clang-tools-extra/docs/clang-tidy/checks/modernize/use-starts-ends-with.rst (+4-2) - (modified) clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/string (+4) - (modified) clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/string.h (+1) - (modified) clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp (+45) ``diff diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 062f6e9911dbed..38fe1984ac494e 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -16,6 +16,49 @@ using namespace clang::ast_matchers; namespace clang::tidy::modernize { +namespace { +// Given two argument indices X and Y, matches when a call expression has a +// string at index X with an expression representing that string's length at +// index Y. The string can be a string literal or a variable. The length can be +// matched via an integer literal or a call to strlen() in the case of a string +// literal, and by a call to size() or length() in the string variable case. +AST_POLYMORPHIC_MATCHER_P2(HasStringAndLengthArguments, + AST_POLYMORPHIC_SUPPORTED_TYPES( + CallExpr, CXXConstructExpr, + CXXUnresolvedConstructExpr, ObjCMessageExpr), + unsigned, StringArgIndex, unsigned, LengthArgIndex) { + if (StringArgIndex >= Node.getNumArgs() || + LengthArgIndex >= Node.getNumArgs()) { +return false; + } + + const Expr *StringArgExpr = + Node.getArg(StringArgIndex)->IgnoreParenImpCasts(); + const Expr *LengthArgExpr = + Node.getArg(LengthArgIndex)->IgnoreParenImpCasts(); + + if (const auto *StringArg = dyn_cast(StringArgExpr)) { +// Match an integer literal equal to the string length or a call to strlen. +const auto Matcher = expr(anyOf( +integerLiteral(equals(StringArg->getLength())), +callExpr( +callee(functionDecl(hasName("strlen"))), argumentCountIs(1), +hasArgument(0, stringLiteral(hasSize(StringArg->getLength())); +return Matcher.matches(*LengthArgExpr, Finder, Builder); + } + + if (const auto *StringArg = dyn_cast(StringArgExpr)) { +// Match a call to size() or length() on the same variable. +const auto Matcher = cxxMemberCallExpr( +on(declRefExpr(to(varDecl(equalsNode(StringArg->getDecl()), +callee(cxxMethodDecl(hasAnyName("size", "length"), isConst(), + parameterCountIs(0; +return Matcher.matches(*LengthArgExpr, Finder, Builder); + } + + return false; +} +} // namespace UseStartsEndsWithCheck::UseStartsEndsWithCheck(StringRef Name, ClangTidyContext *Context) @@ -43,7 +86,9 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { callee(cxxMethodDecl(hasName("find")).bind("find_fun")), // ... on a class with a starts_with function. on(hasType( - hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction); + hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction, + // Bind search expression. + hasArgument(0, expr().bind("search_expr"))); const auto RFindExpr = cxxMemberCallExpr( // A method call with a second argument of zero... @@ -52,15 +97,30 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { callee(cxxMethodDecl(hasName("rfind")).bind("find_fun")), // ... on a class with a
[clang] [lldb] Revert "NFC: Make clang resource headers an interface library (#88317)" (PR #89266)
etcwilde wrote: Great, glad to hear that you figured out what was happening. I wasn't sure how the target would end up in the clang-export list and not be defined since the bit of code that adds it to the clang-export list isn't conditionalized any differently than the creation of the target itself. https://github.com/llvm/llvm-project/pull/89266 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lldb] Revert "NFC: Make clang resource headers an interface library (#88317)" (PR #89266)
https://github.com/etcwilde closed https://github.com/llvm/llvm-project/pull/89266 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)
https://github.com/nicovank updated https://github.com/llvm/llvm-project/pull/89530 >From 5f20627f74103d3b2b5adf484c902b85228006dd Mon Sep 17 00:00:00 2001 From: Nicolas van Kempen Date: Sun, 21 Apr 2024 05:17:19 + Subject: [PATCH] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() --- .../modernize/UseStartsEndsWithCheck.cpp | 92 --- .../modernize/UseStartsEndsWithCheck.h| 4 +- clang-tools-extra/docs/ReleaseNotes.rst | 4 + .../checks/modernize/use-starts-ends-with.rst | 6 +- .../clang-tidy/checkers/Inputs/Headers/string | 4 + .../checkers/Inputs/Headers/string.h | 1 + .../modernize/use-starts-ends-with.cpp| 45 + 7 files changed, 137 insertions(+), 19 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 062f6e9911dbed..38fe1984ac494e 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -16,6 +16,49 @@ using namespace clang::ast_matchers; namespace clang::tidy::modernize { +namespace { +// Given two argument indices X and Y, matches when a call expression has a +// string at index X with an expression representing that string's length at +// index Y. The string can be a string literal or a variable. The length can be +// matched via an integer literal or a call to strlen() in the case of a string +// literal, and by a call to size() or length() in the string variable case. +AST_POLYMORPHIC_MATCHER_P2(HasStringAndLengthArguments, + AST_POLYMORPHIC_SUPPORTED_TYPES( + CallExpr, CXXConstructExpr, + CXXUnresolvedConstructExpr, ObjCMessageExpr), + unsigned, StringArgIndex, unsigned, LengthArgIndex) { + if (StringArgIndex >= Node.getNumArgs() || + LengthArgIndex >= Node.getNumArgs()) { +return false; + } + + const Expr *StringArgExpr = + Node.getArg(StringArgIndex)->IgnoreParenImpCasts(); + const Expr *LengthArgExpr = + Node.getArg(LengthArgIndex)->IgnoreParenImpCasts(); + + if (const auto *StringArg = dyn_cast(StringArgExpr)) { +// Match an integer literal equal to the string length or a call to strlen. +const auto Matcher = expr(anyOf( +integerLiteral(equals(StringArg->getLength())), +callExpr( +callee(functionDecl(hasName("strlen"))), argumentCountIs(1), +hasArgument(0, stringLiteral(hasSize(StringArg->getLength())); +return Matcher.matches(*LengthArgExpr, Finder, Builder); + } + + if (const auto *StringArg = dyn_cast(StringArgExpr)) { +// Match a call to size() or length() on the same variable. +const auto Matcher = cxxMemberCallExpr( +on(declRefExpr(to(varDecl(equalsNode(StringArg->getDecl()), +callee(cxxMethodDecl(hasAnyName("size", "length"), isConst(), + parameterCountIs(0; +return Matcher.matches(*LengthArgExpr, Finder, Builder); + } + + return false; +} +} // namespace UseStartsEndsWithCheck::UseStartsEndsWithCheck(StringRef Name, ClangTidyContext *Context) @@ -43,7 +86,9 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { callee(cxxMethodDecl(hasName("find")).bind("find_fun")), // ... on a class with a starts_with function. on(hasType( - hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction); + hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction, + // Bind search expression. + hasArgument(0, expr().bind("search_expr"))); const auto RFindExpr = cxxMemberCallExpr( // A method call with a second argument of zero... @@ -52,15 +97,30 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { callee(cxxMethodDecl(hasName("rfind")).bind("find_fun")), // ... on a class with a starts_with function. on(hasType( - hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction); - - const auto FindOrRFindExpr = - cxxMemberCallExpr(anyOf(FindExpr, RFindExpr)).bind("find_expr"); + hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction, + // Bind search expression. + hasArgument(0, expr().bind("search_expr"))); + + const auto CompareExpr = cxxMemberCallExpr( + // A method call with a first argument of zero... + hasArgument(0, ZeroLiteral), + // ... named compare... + callee(cxxMethodDecl(hasName("compare")).bind("find_fun")), + // ... on a class with a starts_with function... + on(hasType( + hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction, + // ... where the third argument is some string and the second its length. + HasStringAndLengthArguments(2, 1),
[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)
https://github.com/nicovank updated https://github.com/llvm/llvm-project/pull/89530 >From 7a2ff84f113959bc89f50b6eef7ee9762e6f5d2f Mon Sep 17 00:00:00 2001 From: Nicolas van Kempen Date: Sun, 21 Apr 2024 05:17:19 + Subject: [PATCH] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() --- .../modernize/UseStartsEndsWithCheck.cpp | 92 --- .../modernize/UseStartsEndsWithCheck.h| 4 +- clang-tools-extra/docs/ReleaseNotes.rst | 4 + .../checks/modernize/use-starts-ends-with.rst | 6 +- .../clang-tidy/checkers/Inputs/Headers/string | 4 + .../checkers/Inputs/Headers/string.h | 1 + .../abseil/redundant-strcat-calls.cpp | 2 - .../modernize/use-starts-ends-with.cpp| 45 + 8 files changed, 137 insertions(+), 21 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 062f6e9911dbed..38fe1984ac494e 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -16,6 +16,49 @@ using namespace clang::ast_matchers; namespace clang::tidy::modernize { +namespace { +// Given two argument indices X and Y, matches when a call expression has a +// string at index X with an expression representing that string's length at +// index Y. The string can be a string literal or a variable. The length can be +// matched via an integer literal or a call to strlen() in the case of a string +// literal, and by a call to size() or length() in the string variable case. +AST_POLYMORPHIC_MATCHER_P2(HasStringAndLengthArguments, + AST_POLYMORPHIC_SUPPORTED_TYPES( + CallExpr, CXXConstructExpr, + CXXUnresolvedConstructExpr, ObjCMessageExpr), + unsigned, StringArgIndex, unsigned, LengthArgIndex) { + if (StringArgIndex >= Node.getNumArgs() || + LengthArgIndex >= Node.getNumArgs()) { +return false; + } + + const Expr *StringArgExpr = + Node.getArg(StringArgIndex)->IgnoreParenImpCasts(); + const Expr *LengthArgExpr = + Node.getArg(LengthArgIndex)->IgnoreParenImpCasts(); + + if (const auto *StringArg = dyn_cast(StringArgExpr)) { +// Match an integer literal equal to the string length or a call to strlen. +const auto Matcher = expr(anyOf( +integerLiteral(equals(StringArg->getLength())), +callExpr( +callee(functionDecl(hasName("strlen"))), argumentCountIs(1), +hasArgument(0, stringLiteral(hasSize(StringArg->getLength())); +return Matcher.matches(*LengthArgExpr, Finder, Builder); + } + + if (const auto *StringArg = dyn_cast(StringArgExpr)) { +// Match a call to size() or length() on the same variable. +const auto Matcher = cxxMemberCallExpr( +on(declRefExpr(to(varDecl(equalsNode(StringArg->getDecl()), +callee(cxxMethodDecl(hasAnyName("size", "length"), isConst(), + parameterCountIs(0; +return Matcher.matches(*LengthArgExpr, Finder, Builder); + } + + return false; +} +} // namespace UseStartsEndsWithCheck::UseStartsEndsWithCheck(StringRef Name, ClangTidyContext *Context) @@ -43,7 +86,9 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { callee(cxxMethodDecl(hasName("find")).bind("find_fun")), // ... on a class with a starts_with function. on(hasType( - hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction); + hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction, + // Bind search expression. + hasArgument(0, expr().bind("search_expr"))); const auto RFindExpr = cxxMemberCallExpr( // A method call with a second argument of zero... @@ -52,15 +97,30 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { callee(cxxMethodDecl(hasName("rfind")).bind("find_fun")), // ... on a class with a starts_with function. on(hasType( - hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction); - - const auto FindOrRFindExpr = - cxxMemberCallExpr(anyOf(FindExpr, RFindExpr)).bind("find_expr"); + hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction, + // Bind search expression. + hasArgument(0, expr().bind("search_expr"))); + + const auto CompareExpr = cxxMemberCallExpr( + // A method call with a first argument of zero... + hasArgument(0, ZeroLiteral), + // ... named compare... + callee(cxxMethodDecl(hasName("compare")).bind("find_fun")), + // ... on a class with a starts_with function... + on(hasType( + hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction, + // ... where the third argument is some string and the second
[clang] fa01d04 - [clang][Interp][NFC] Change pointer offset to uint64
Author: Timm Bäder Date: 2024-04-21T08:30:58+02:00 New Revision: fa01d04c9b9a3c8454194a36a0e64daf43cddaf2 URL: https://github.com/llvm/llvm-project/commit/fa01d04c9b9a3c8454194a36a0e64daf43cddaf2 DIFF: https://github.com/llvm/llvm-project/commit/fa01d04c9b9a3c8454194a36a0e64daf43cddaf2.diff LOG: [clang][Interp][NFC] Change pointer offset to uint64 To accomodate for recent changes in array index calculations. Added: Modified: clang/lib/AST/Interp/Pointer.cpp clang/lib/AST/Interp/Pointer.h Removed: diff --git a/clang/lib/AST/Interp/Pointer.cpp b/clang/lib/AST/Interp/Pointer.cpp index e163e658d462b2..5ef31671ae7be5 100644 --- a/clang/lib/AST/Interp/Pointer.cpp +++ b/clang/lib/AST/Interp/Pointer.cpp @@ -23,7 +23,7 @@ Pointer::Pointer(Block *Pointee) : Pointer(Pointee, Pointee->getDescriptor()->getMetadataSize(), Pointee->getDescriptor()->getMetadataSize()) {} -Pointer::Pointer(Block *Pointee, unsigned BaseAndOffset) +Pointer::Pointer(Block *Pointee, uint64_t BaseAndOffset) : Pointer(Pointee, BaseAndOffset, BaseAndOffset) {} Pointer::Pointer(const Pointer &P) @@ -34,7 +34,7 @@ Pointer::Pointer(const Pointer &P) PointeeStorage.BS.Pointee->addPointer(this); } -Pointer::Pointer(Block *Pointee, unsigned Base, unsigned Offset) +Pointer::Pointer(Block *Pointee, unsigned Base, uint64_t Offset) : Offset(Offset), StorageKind(Storage::Block) { assert((Base == RootPtrMark || Base % alignof(void *) == 0) && "wrong base"); diff --git a/clang/lib/AST/Interp/Pointer.h b/clang/lib/AST/Interp/Pointer.h index b4475577b74625..c4d701bc71b7bf 100644 --- a/clang/lib/AST/Interp/Pointer.h +++ b/clang/lib/AST/Interp/Pointer.h @@ -89,10 +89,10 @@ class Pointer { PointeeStorage.Int.Desc = nullptr; } Pointer(Block *B); - Pointer(Block *B, unsigned BaseAndOffset); + Pointer(Block *B, uint64_t BaseAndOffset); Pointer(const Pointer &P); Pointer(Pointer &&P); - Pointer(uint64_t Address, const Descriptor *Desc, unsigned Offset = 0) + Pointer(uint64_t Address, const Descriptor *Desc, uint64_t Offset = 0) : Offset(Offset), StorageKind(Storage::Int) { PointeeStorage.Int.Value = Address; PointeeStorage.Int.Desc = Desc; @@ -134,14 +134,14 @@ class Pointer { std::optional toRValue(const Context &Ctx) const; /// Offsets a pointer inside an array. - [[nodiscard]] Pointer atIndex(unsigned Idx) const { + [[nodiscard]] Pointer atIndex(uint64_t Idx) const { if (isIntegralPointer()) return Pointer(asIntPointer().Value, asIntPointer().Desc, Idx); if (asBlockPointer().Base == RootPtrMark) return Pointer(asBlockPointer().Pointee, RootPtrMark, getDeclDesc()->getSize()); -unsigned Off = Idx * elemSize(); +uint64_t Off = Idx * elemSize(); if (getFieldDesc()->ElemDesc) Off += sizeof(InlineDescriptor); else @@ -630,7 +630,7 @@ class Pointer { friend class DeadBlock; friend struct InitMap; - Pointer(Block *Pointee, unsigned Base, unsigned Offset); + Pointer(Block *Pointee, unsigned Base, uint64_t Offset); /// Returns the embedded descriptor preceding a field. InlineDescriptor *getInlineDesc() const { @@ -656,7 +656,7 @@ class Pointer { } /// Offset into the storage. - unsigned Offset = 0; + uint64_t Offset = 0; /// Previous link in the pointer chain. Pointer *Prev = nullptr; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits