[clang] [Sema] Fixed faulty shift count warning (PR #69521)

2023-10-24 Thread Karl-Johan Karlsson via cfe-commits

https://github.com/karka228 updated 
https://github.com/llvm/llvm-project/pull/69521

>From db4a254b721eddacf592a647d3de4fd10a8032e0 Mon Sep 17 00:00:00 2001
From: Karl-Johan Karlsson 
Date: Wed, 18 Oct 2023 16:40:53 +0200
Subject: [PATCH] [Sema] Fixed faulty shift count warning

Constant values of _BitInt have the bitwith to exactly fit the constant
number. This patch fix a problem in Sema when building an APInt where the
supplied bitwidth can become too small and simply truncate the value leading to
a faulty warning.
---
 clang/docs/ReleaseNotes.rst  |  3 +++
 clang/lib/Sema/SemaExpr.cpp  |  7 +++
 clang/test/Sema/c2x-expr-range.c | 12 
 3 files changed, 18 insertions(+), 4 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a063733e96cb74c..4cc148905d4e130 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -488,6 +488,9 @@ Bug Fixes in This Version
 - Clang no longer permits using the `_BitInt` types as an underlying type for 
an
   enumeration as specified in the C23 Standard.
   Fixes (`#69619 `_)
+- Fixed an issue when a shift count specified by a small constant 
``_BitInt()``,
+  in a left shift operation, could result in a faulty warnings about
+  ``shift count >= width of type``.
 - Clang now accepts anonymous members initialized with designated initializers
   inside templates.
   Fixes (`#65143 `_)
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 895b22805860d98..c2772bfb71c77e9 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -12143,8 +12143,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
   }
-  llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
-  if (Right.uge(LeftBits)) {
+  if (Right.uge(LeftSize)) {
 S.DiagRuntimeBehavior(Loc, RHS.get(),
   S.PDiag(diag::warn_shift_gt_typewidth)
 << RHS.get()->getSourceRange());
@@ -12186,7 +12185,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
 
   llvm::APInt ResultBits =
   static_cast(Right) + Left.getSignificantBits();
-  if (LeftBits.uge(ResultBits))
+  if (ResultBits.ule(LeftSize))
 return;
   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
   Result = Result.shl(Right);
@@ -12200,7 +12199,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   // bugs -- if the result is cast back to an unsigned type, it will have the
   // expected value. Thus we place this behind a different warning that can be
   // turned off separately if needed.
-  if (LeftBits == ResultBits - 1) {
+  if (ResultBits - 1 == LeftSize) {
 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
 << HexResult << LHSType
 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
diff --git a/clang/test/Sema/c2x-expr-range.c b/clang/test/Sema/c2x-expr-range.c
index 73683e6bfe684aa..eff0b7cd4d9f546 100644
--- a/clang/test/Sema/c2x-expr-range.c
+++ b/clang/test/Sema/c2x-expr-range.c
@@ -12,3 +12,15 @@ void test1(int *a) {
 void test2(__uint128_t *a) {
   (void)(*a >> ((__uint128_t)__UINT64_MAX__ + 1) <= 0); // expected-warning 
{{shift count >= width of type}}
 }
+
+// Regression test for bug where a faulty warning was given. We don't expect to
+// see any warning in this case.
+_BitInt(128) test3(_BitInt(128) a) {
+  return a << 12wb;
+}
+
+// Similar to test3 above, but with a too large shift count. We expect to see a
+// warning in this case.
+_BitInt(128) test4(_BitInt(128) a) {
+  return a << 129wb; // expected-warning {{shift count >= width of type}}
+}

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


[clang] [RISCV] Run mem2reg to simplify Zbc tests (PR #70169)

2023-10-24 Thread Alex Bradbury via cfe-commits

https://github.com/asb approved this pull request.

LGTM.

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


[clang] [RISCV] Run mem2reg to simplify Zbc tests (PR #70169)

2023-10-24 Thread Wang Pengcheng via cfe-commits

https://github.com/wangpc-pp created 
https://github.com/llvm/llvm-project/pull/70169

None

>From c5500404b5885e7038b0360d7d8bfbb317d6a1b5 Mon Sep 17 00:00:00 2001
From: wangpc 
Date: Wed, 25 Oct 2023 14:36:09 +0800
Subject: [PATCH] [RISCV] Run mem2reg to simplify Zbc tests

---
 clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c | 72 +--
 1 file changed, 16 insertions(+), 56 deletions(-)

diff --git a/clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c 
b/clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c
index aa5bebe38dd6b2d..ae9153eff155e19 100644
--- a/clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c
+++ b/clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c
@@ -1,7 +1,9 @@
 // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
 // RUN: %clang_cc1 -triple riscv32 -target-feature +zbc -emit-llvm %s -o - \
+// RUN: -disable-O0-optnone | opt -S -passes=mem2reg \
 // RUN: | FileCheck %s  -check-prefix=RV32ZBC
 // RUN: %clang_cc1 -triple riscv64 -target-feature +zbc -emit-llvm %s -o - \
+// RUN: -disable-O0-optnone | opt -S -passes=mem2reg \
 // RUN: | FileCheck %s  -check-prefix=RV64ZBC
 
 #include 
@@ -9,14 +11,8 @@
 #if __riscv_xlen == 64
 // RV64ZBC-LABEL: @clmul_64(
 // RV64ZBC-NEXT:  entry:
-// RV64ZBC-NEXT:[[A_ADDR:%.*]] = alloca i64, align 8
-// RV64ZBC-NEXT:[[B_ADDR:%.*]] = alloca i64, align 8
-// RV64ZBC-NEXT:store i64 [[A:%.*]], ptr [[A_ADDR]], align 8
-// RV64ZBC-NEXT:store i64 [[B:%.*]], ptr [[B_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP0:%.*]] = load i64, ptr [[A_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP1:%.*]] = load i64, ptr [[B_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP2:%.*]] = call i64 @llvm.riscv.clmul.i64(i64 
[[TMP0]], i64 [[TMP1]])
-// RV64ZBC-NEXT:ret i64 [[TMP2]]
+// RV64ZBC-NEXT:[[TMP0:%.*]] = call i64 @llvm.riscv.clmul.i64(i64 
[[A:%.*]], i64 [[B:%.*]])
+// RV64ZBC-NEXT:ret i64 [[TMP0]]
 //
 uint64_t clmul_64(uint64_t a, uint64_t b) {
   return __builtin_riscv_clmul_64(a, b);
@@ -24,14 +20,8 @@ uint64_t clmul_64(uint64_t a, uint64_t b) {
 
 // RV64ZBC-LABEL: @clmulh_64(
 // RV64ZBC-NEXT:  entry:
-// RV64ZBC-NEXT:[[A_ADDR:%.*]] = alloca i64, align 8
-// RV64ZBC-NEXT:[[B_ADDR:%.*]] = alloca i64, align 8
-// RV64ZBC-NEXT:store i64 [[A:%.*]], ptr [[A_ADDR]], align 8
-// RV64ZBC-NEXT:store i64 [[B:%.*]], ptr [[B_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP0:%.*]] = load i64, ptr [[A_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP1:%.*]] = load i64, ptr [[B_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP2:%.*]] = call i64 @llvm.riscv.clmulh.i64(i64 
[[TMP0]], i64 [[TMP1]])
-// RV64ZBC-NEXT:ret i64 [[TMP2]]
+// RV64ZBC-NEXT:[[TMP0:%.*]] = call i64 @llvm.riscv.clmulh.i64(i64 
[[A:%.*]], i64 [[B:%.*]])
+// RV64ZBC-NEXT:ret i64 [[TMP0]]
 //
 uint64_t clmulh_64(uint64_t a, uint64_t b) {
   return __builtin_riscv_clmulh_64(a, b);
@@ -39,14 +29,8 @@ uint64_t clmulh_64(uint64_t a, uint64_t b) {
 
 // RV64ZBC-LABEL: @clmulr_64(
 // RV64ZBC-NEXT:  entry:
-// RV64ZBC-NEXT:[[A_ADDR:%.*]] = alloca i64, align 8
-// RV64ZBC-NEXT:[[B_ADDR:%.*]] = alloca i64, align 8
-// RV64ZBC-NEXT:store i64 [[A:%.*]], ptr [[A_ADDR]], align 8
-// RV64ZBC-NEXT:store i64 [[B:%.*]], ptr [[B_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP0:%.*]] = load i64, ptr [[A_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP1:%.*]] = load i64, ptr [[B_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP2:%.*]] = call i64 @llvm.riscv.clmulr.i64(i64 
[[TMP0]], i64 [[TMP1]])
-// RV64ZBC-NEXT:ret i64 [[TMP2]]
+// RV64ZBC-NEXT:[[TMP0:%.*]] = call i64 @llvm.riscv.clmulr.i64(i64 
[[A:%.*]], i64 [[B:%.*]])
+// RV64ZBC-NEXT:ret i64 [[TMP0]]
 //
 uint64_t clmulr_64(uint64_t a, uint64_t b) {
   return __builtin_riscv_clmulr_64(a, b);
@@ -55,25 +39,13 @@ uint64_t clmulr_64(uint64_t a, uint64_t b) {
 
 // RV32ZBC-LABEL: @clmul_32(
 // RV32ZBC-NEXT:  entry:
-// RV32ZBC-NEXT:[[A_ADDR:%.*]] = alloca i32, align 4
-// RV32ZBC-NEXT:[[B_ADDR:%.*]] = alloca i32, align 4
-// RV32ZBC-NEXT:store i32 [[A:%.*]], ptr [[A_ADDR]], align 4
-// RV32ZBC-NEXT:store i32 [[B:%.*]], ptr [[B_ADDR]], align 4
-// RV32ZBC-NEXT:[[TMP0:%.*]] = load i32, ptr [[A_ADDR]], align 4
-// RV32ZBC-NEXT:[[TMP1:%.*]] = load i32, ptr [[B_ADDR]], align 4
-// RV32ZBC-NEXT:[[TMP2:%.*]] = call i32 @llvm.riscv.clmul.i32(i32 
[[TMP0]], i32 [[TMP1]])
-// RV32ZBC-NEXT:ret i32 [[TMP2]]
+// RV32ZBC-NEXT:[[TMP0:%.*]] = call i32 @llvm.riscv.clmul.i32(i32 
[[A:%.*]], i32 [[B:%.*]])
+// RV32ZBC-NEXT:ret i32 [[TMP0]]
 //
 // RV64ZBC-LABEL: @clmul_32(
 // RV64ZBC-NEXT:  entry:
-// RV64ZBC-NEXT:[[A_ADDR:%.*]] = alloca i32, align 4
-// RV64ZBC-NEXT:[[B_ADDR:%.*]] = alloca i32, align 4
-// RV64ZBC-NEXT:store i32 [[A:%.*]], ptr [[A_ADDR]], align 4
-// RV64ZBC-NEXT:store i32 [[B:%.*]], ptr [[B_ADDR]], align 4
-// RV64ZBC-NEXT:[[TMP0:%.*]] = load i32, ptr [[A_ADDR]], align 4
-// RV64ZBC-NEXT:[[TMP1:%.*]] = load i32, ptr [[B_ADDR]], align 4
-// RV64ZBC-NEXT:[

[clang] [clang][dataflow] Add `Environment::allows()`. (PR #70046)

2023-10-24 Thread via cfe-commits


@@ -184,6 +192,12 @@ class DataflowAnalysisContext {
   addTransitiveFlowConditionConstraints(Atom Token,
 llvm::SetVector &Out);
 
+  /// Returns true if the solver is able to prove that there is a satisfying
+  /// assignment for `Constraints`

martinboehme wrote:

Done.

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


[clang] [clang][dataflow] Add `Environment::allows()`. (PR #70046)

2023-10-24 Thread via cfe-commits


@@ -546,12 +546,29 @@ class Environment {
   Atom getFlowConditionToken() const { return FlowConditionToken; }
 
   /// Record a fact that must be true if this point in the program is reached.
-  void addToFlowCondition(const Formula &);
+  void assume(const Formula &);
+
+  /// Deprecated synonym for `assume()`.
+  void addToFlowCondition(const Formula &F) { assume(F); }
 
   /// Returns true if the formula is always true when this point is reached.
-  /// Returns false if the formula may be false, or if the flow condition isn't
-  /// sufficiently precise to prove that it is true.
-  bool flowConditionImplies(const Formula &) const;
+  /// Returns false if the formula may be false (or the flow condition isn't
+  /// sufficiently precise to prove that it is true) or if the solver times 
out.
+  ///
+  /// Note that there is an asymmetry between this function and `allows()` in
+  /// that they both return false if the solver times out. The assumption is
+  /// that if `proves()` or `allows() ` returns true, this will result in a

martinboehme wrote:

Done.

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


[clang] [clang][dataflow] Add `Environment::allows()`. (PR #70046)

2023-10-24 Thread via cfe-commits


@@ -129,9 +129,17 @@ class DataflowAnalysisContext {
   /// token.
   Atom joinFlowConditions(Atom FirstToken, Atom SecondToken);
 
-  /// Returns true if and only if the constraints of the flow condition
-  /// identified by `Token` imply that `Val` is true.
-  bool flowConditionImplies(Atom Token, const Formula &);
+  /// Returns true if the constraints of the flow condition identified by
+  /// `Token` imply that `F` is true.
+  /// Returns false the flow condition does not imply `F` or if the solver 
times

martinboehme wrote:

Done.

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


[clang] [clang][dataflow] Add `Environment::allows()`. (PR #70046)

2023-10-24 Thread via cfe-commits

https://github.com/martinboehme updated 
https://github.com/llvm/llvm-project/pull/70046

>From 8d1119c97581fe5bf9d44330ce2a58b2be18e8b7 Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Tue, 24 Oct 2023 14:13:44 +
Subject: [PATCH 1/2] [clang][dataflow] Add `Environment::allows()`.

This allows querying whether, given the flow condition, a certain formula still
has a solution (though it is not necessarily implied by the flow condition, as
`flowConditionImplies()` would check).

This can be checked today, but only with a double negation, i.e. to check
whether, given the flow condition, a formula F has a solution, you can check
`!Env.flowConditionImplies(Arena.makeNot(F))`. The double negation makes this
hard to reason about, and it would be nicer to have a way of directly checking
this.

For consistency, this patch also renames `flowConditionImplies()` to `proves()`;
the old name is kept around for compatibility but deprecated.
---
 .../FlowSensitive/DataflowAnalysisContext.h   | 20 ---
 .../FlowSensitive/DataflowEnvironment.h   | 25 ---
 .../FlowSensitive/DataflowAnalysisContext.cpp | 17 ++---
 .../FlowSensitive/DataflowEnvironment.cpp | 12 ++---
 .../FlowSensitive/DataflowEnvironmentTest.cpp | 17 -
 5 files changed, 70 insertions(+), 21 deletions(-)

diff --git 
a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
index a792c3f911b1dd0..3ae5ac3cf501e39 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
@@ -129,9 +129,17 @@ class DataflowAnalysisContext {
   /// token.
   Atom joinFlowConditions(Atom FirstToken, Atom SecondToken);
 
-  /// Returns true if and only if the constraints of the flow condition
-  /// identified by `Token` imply that `Val` is true.
-  bool flowConditionImplies(Atom Token, const Formula &);
+  /// Returns true if the constraints of the flow condition identified by
+  /// `Token` imply that `F` is true.
+  /// Returns false the flow condition does not imply `F` or if the solver 
times
+  /// out.
+  bool flowConditionImplies(Atom Token, const Formula &F);
+
+  /// Returns true if the constraints of the flow condition identified by
+  /// `Token` still allow `F` to be true.
+  /// Returns false if the flow condition implies that `F` is false or if the
+  /// solver times out.
+  bool flowConditionAllows(Atom Token, const Formula &F);
 
   /// Returns true if `Val1` is equivalent to `Val2`.
   /// Note: This function doesn't take into account constraints on `Val1` and
@@ -184,6 +192,12 @@ class DataflowAnalysisContext {
   addTransitiveFlowConditionConstraints(Atom Token,
 llvm::SetVector &Out);
 
+  /// Returns true if the solver is able to prove that there is a satisfying
+  /// assignment for `Constraints`
+  bool isSatisfiable(llvm::SetVector Constraints) {
+return querySolver(std::move(Constraints)).getStatus() ==
+   Solver::Result::Status::Satisfiable;
+  }
 
   /// Returns true if the solver is able to prove that there is no satisfying
   /// assignment for `Constraints`
diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 9ac2cb90ccc4d4a..a815a3f2d263d70 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -546,12 +546,29 @@ class Environment {
   Atom getFlowConditionToken() const { return FlowConditionToken; }
 
   /// Record a fact that must be true if this point in the program is reached.
-  void addToFlowCondition(const Formula &);
+  void assume(const Formula &);
+
+  /// Deprecated synonym for `assume()`.
+  void addToFlowCondition(const Formula &F) { assume(F); }
 
   /// Returns true if the formula is always true when this point is reached.
-  /// Returns false if the formula may be false, or if the flow condition isn't
-  /// sufficiently precise to prove that it is true.
-  bool flowConditionImplies(const Formula &) const;
+  /// Returns false if the formula may be false (or the flow condition isn't
+  /// sufficiently precise to prove that it is true) or if the solver times 
out.
+  ///
+  /// Note that there is an asymmetry between this function and `allows()` in
+  /// that they both return false if the solver times out. The assumption is
+  /// that if `proves()` or `allows() ` returns true, this will result in a
+  /// diagnostic, and we want to bias towards false negatives in the case where
+  /// the solver times out.
+  bool proves(const Formula &) const;
+
+  /// Returns true if the formula may be true when this point is reached.
+  /// Returns false if the formula is always false when this point is reached
+  /// (or the flow condition is overly cons

[clang] [Sema] Fixed faulty shift count warning (PR #69521)

2023-10-24 Thread Karl-Johan Karlsson via cfe-commits

https://github.com/karka228 updated 
https://github.com/llvm/llvm-project/pull/69521

>From a4a9fb73de9319acd26290ef31d1e17b127c0c3b Mon Sep 17 00:00:00 2001
From: Karl-Johan Karlsson 
Date: Wed, 18 Oct 2023 16:40:53 +0200
Subject: [PATCH] [Sema] Fixed faulty shift count warning

Constant values of _BitInt have the bitwith to exactly fit the constant
number. This patch fix a problem in Sema when building an APInt where the
supplied bitwidth can become too small and simply truncate the value leading to
a faulty warning.
---
 clang/docs/ReleaseNotes.rst  |  3 +++
 clang/lib/Sema/SemaExpr.cpp  |  7 +++
 clang/test/Sema/c2x-expr-range.c | 12 
 3 files changed, 18 insertions(+), 4 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cdef43f2011bc98..05bb069fe709700 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -403,6 +403,9 @@ Bug Fixes in This Version
   operator in C. No longer issuing a confusing diagnostic along the lines of
   "incompatible operand types ('foo' and 'foo')" with extensions such as matrix
   types. Fixes (`#69008 `_)
+- Fixed an issue when a shift count specified by a small constant 
``_BitInt()``,
+  in a left shift operation, could result in a faulty warnings about
+  ``shift count >= width of type``.
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index aa30a3a03887558..c00178ee1835e00 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -12120,8 +12120,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
   }
-  llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
-  if (Right.uge(LeftBits)) {
+  if (Right.uge(LeftSize)) {
 S.DiagRuntimeBehavior(Loc, RHS.get(),
   S.PDiag(diag::warn_shift_gt_typewidth)
 << RHS.get()->getSourceRange());
@@ -12163,7 +12162,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
 
   llvm::APInt ResultBits =
   static_cast(Right) + Left.getSignificantBits();
-  if (LeftBits.uge(ResultBits))
+  if (ResultBits.ule(LeftSize))
 return;
   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
   Result = Result.shl(Right);
@@ -12177,7 +12176,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   // bugs -- if the result is cast back to an unsigned type, it will have the
   // expected value. Thus we place this behind a different warning that can be
   // turned off separately if needed.
-  if (LeftBits == ResultBits - 1) {
+  if (ResultBits - 1 == LeftSize) {
 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
 << HexResult << LHSType
 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
diff --git a/clang/test/Sema/c2x-expr-range.c b/clang/test/Sema/c2x-expr-range.c
index 73683e6bfe684aa..eff0b7cd4d9f546 100644
--- a/clang/test/Sema/c2x-expr-range.c
+++ b/clang/test/Sema/c2x-expr-range.c
@@ -12,3 +12,15 @@ void test1(int *a) {
 void test2(__uint128_t *a) {
   (void)(*a >> ((__uint128_t)__UINT64_MAX__ + 1) <= 0); // expected-warning 
{{shift count >= width of type}}
 }
+
+// Regression test for bug where a faulty warning was given. We don't expect to
+// see any warning in this case.
+_BitInt(128) test3(_BitInt(128) a) {
+  return a << 12wb;
+}
+
+// Similar to test3 above, but with a too large shift count. We expect to see a
+// warning in this case.
+_BitInt(128) test4(_BitInt(128) a) {
+  return a << 129wb; // expected-warning {{shift count >= width of type}}
+}

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


[clang] [clang][dataflow] Add `Environment::allows()`. (PR #70046)

2023-10-24 Thread via cfe-commits

martinboehme wrote:

CI failures look unrelated

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


[clang] [ADT] Rename llvm::erase_value to llvm::erase (NFC) (PR #70156)

2023-10-24 Thread Kazu Hirata via cfe-commits

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


[clang] [ADT] Rename llvm::erase_value to llvm::erase (NFC) (PR #70156)

2023-10-24 Thread Kazu Hirata via cfe-commits

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


[clang] [Clang] Ensure zero-init is not overridden when initializing a base class in a constant expression context (PR #70150)

2023-10-24 Thread Richard Smith via cfe-commits

https://github.com/zygoloid approved this pull request.


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


[clang] [ADT] Rename llvm::erase_value to llvm::erase (NFC) (PR #70156)

2023-10-24 Thread Kazu Hirata via cfe-commits

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


[clang] [ADT] Rename llvm::erase_value to llvm::erase (NFC) (PR #70156)

2023-10-24 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay approved this pull request.


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


[clang] [WIP] For Asan instrumented global, emit two symbols, one with actual size and other with instrumented size. (PR #70166)

2023-10-24 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

Would it be possible to create an issue, or RFC explain in one place what it 
the problem you are trying to solve and how?

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


[clang] [WIP] For Asan instrumented global, emit two symbols, one with actual size and other with instrumented size. (PR #70166)

2023-10-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Chaitanya (skc7)


Changes

This PR has dependency on #68865

---
Full diff: https://github.com/llvm/llvm-project/pull/70166.diff


3 Files Affected:

- (added) clang/test/CodeGen/asan_globals_symbols.cpp (+15) 
- (modified) llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp (+27-1) 
- (modified) llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp (+3) 


``diff
diff --git a/clang/test/CodeGen/asan_globals_symbols.cpp 
b/clang/test/CodeGen/asan_globals_symbols.cpp
new file mode 100644
index 000..09e35506bd8e186
--- /dev/null
+++ b/clang/test/CodeGen/asan_globals_symbols.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -S -x c++ -std=c++11 -triple x86_64-linux \
+// RUN:   -fsanitize=address -o %t.out %s
+// RUN: FileCheck %s --input-file=%t.out --check-prefix=CHECK-A
+
+// CHECK-A: myGlobal:
+// CHECK-A: .size   myGlobal, 4
+// CHECK-A: myGlobal__asan_instrumented:
+// CHECK-A  .size   myGlobal__asan_instrumented, 32
+
+int myGlobal;
+
+int main() {
+myGlobal = 0;
+return 0;
+}
diff --git a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp 
b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
index 072c55f79caa9dc..d71ee82ce6ca628 100644
--- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
@@ -758,6 +758,19 @@ void AsmPrinter::emitGlobalVariable(const GlobalVariable 
*GV) {
   // sections and expected to be contiguous (e.g. ObjC metadata).
   const Align Alignment = getGVAlignment(GV, DL);
 
+  // Identify globals with "asan_instrumented" attribute and extract
+  // the actual global variable size.
+  uint64_t ActualSize = 0;
+  if (GV->hasAttribute(Attribute::SanitizeAddress)) {
+StructType *ST = dyn_cast(GV->getValueType());
+if (ST && ST->getNumElements() == 2) {
+  auto *ET0 = ST->getElementType(0);
+  if (ET0 && isa(ST->getElementType(1))) {
+ActualSize = DL.getTypeAllocSize(ET0);
+  }
+}
+  }
+
   for (const HandlerInfo &HI : Handlers) {
 NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
HI.TimerGroupName, HI.TimerGroupDescription,
@@ -868,6 +881,18 @@ void AsmPrinter::emitGlobalVariable(const GlobalVariable 
*GV) {
 
   MCSymbol *EmittedInitSym = GVSym;
 
+  if (GV->hasAttribute(Attribute::SanitizeAddress)) {
+OutStreamer->switchSection(TheSection);
+emitLinkage(GV, EmittedInitSym);
+OutStreamer->emitLabel(EmittedInitSym);
+if (MAI->hasDotTypeDotSizeDirective())
+  OutStreamer->emitELFSize(EmittedInitSym,
+   MCConstantExpr::create(ActualSize, OutContext));
+EmittedInitSym = OutContext.getOrCreateSymbol(GVSym->getName() +
+  
Twine("__asan_instrumented"));
+emitVisibility(EmittedInitSym, GV->getVisibility(), !GV->isDeclaration());
+  }
+
   OutStreamer->switchSection(TheSection);
 
   emitLinkage(GV, EmittedInitSym);
@@ -875,7 +900,8 @@ void AsmPrinter::emitGlobalVariable(const GlobalVariable 
*GV) {
 
   OutStreamer->emitLabel(EmittedInitSym);
   MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
-  if (LocalAlias != EmittedInitSym)
+  if ((LocalAlias != EmittedInitSym) &&
+  !GV->hasAttribute(Attribute::SanitizeAddress))
 OutStreamer->emitLabel(LocalAlias);
 
   emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index e80ee1953de6b21..c5ef705d8ca9e30 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -2441,6 +2441,9 @@ void 
ModuleAddressSanitizer::instrumentGlobals(IRBuilder<> &IRB, Module &M,
 // zero so we can copy the metadata over as is.
 NewGlobal->copyMetadata(G, 0);
 
+// Attach "asan_instrumented" attribute to the new global.
+NewGlobal->addAttribute(Attribute::SanitizeAddress);
+
 Value *Indices2[2];
 Indices2[0] = IRB.getInt32(0);
 Indices2[1] = IRB.getInt32(0);

``




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


[clang] [WIP] For Asan instrumented global, emit two symbols, one with actual size and other with instrumented size. (PR #70166)

2023-10-24 Thread via cfe-commits

https://github.com/skc7 created https://github.com/llvm/llvm-project/pull/70166

This PR has dependency on #68865

>From d6f66a73e6ae7684411c246cb3e82a4ab214c0d1 Mon Sep 17 00:00:00 2001
From: skc7 
Date: Wed, 25 Oct 2023 10:46:10 +0530
Subject: [PATCH] [ASAN] For Asan instrumented globals, emit two symbols, with
 actual size and instrumented size.

---
 clang/test/CodeGen/asan_globals_symbols.cpp   | 15 ++
 llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp| 28 ++-
 .../Instrumentation/AddressSanitizer.cpp  |  3 ++
 3 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGen/asan_globals_symbols.cpp

diff --git a/clang/test/CodeGen/asan_globals_symbols.cpp 
b/clang/test/CodeGen/asan_globals_symbols.cpp
new file mode 100644
index 000..09e35506bd8e186
--- /dev/null
+++ b/clang/test/CodeGen/asan_globals_symbols.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -S -x c++ -std=c++11 -triple x86_64-linux \
+// RUN:   -fsanitize=address -o %t.out %s
+// RUN: FileCheck %s --input-file=%t.out --check-prefix=CHECK-A
+
+// CHECK-A: myGlobal:
+// CHECK-A: .size   myGlobal, 4
+// CHECK-A: myGlobal__asan_instrumented:
+// CHECK-A  .size   myGlobal__asan_instrumented, 32
+
+int myGlobal;
+
+int main() {
+myGlobal = 0;
+return 0;
+}
diff --git a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp 
b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
index 072c55f79caa9dc..d71ee82ce6ca628 100644
--- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
@@ -758,6 +758,19 @@ void AsmPrinter::emitGlobalVariable(const GlobalVariable 
*GV) {
   // sections and expected to be contiguous (e.g. ObjC metadata).
   const Align Alignment = getGVAlignment(GV, DL);
 
+  // Identify globals with "asan_instrumented" attribute and extract
+  // the actual global variable size.
+  uint64_t ActualSize = 0;
+  if (GV->hasAttribute(Attribute::SanitizeAddress)) {
+StructType *ST = dyn_cast(GV->getValueType());
+if (ST && ST->getNumElements() == 2) {
+  auto *ET0 = ST->getElementType(0);
+  if (ET0 && isa(ST->getElementType(1))) {
+ActualSize = DL.getTypeAllocSize(ET0);
+  }
+}
+  }
+
   for (const HandlerInfo &HI : Handlers) {
 NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
HI.TimerGroupName, HI.TimerGroupDescription,
@@ -868,6 +881,18 @@ void AsmPrinter::emitGlobalVariable(const GlobalVariable 
*GV) {
 
   MCSymbol *EmittedInitSym = GVSym;
 
+  if (GV->hasAttribute(Attribute::SanitizeAddress)) {
+OutStreamer->switchSection(TheSection);
+emitLinkage(GV, EmittedInitSym);
+OutStreamer->emitLabel(EmittedInitSym);
+if (MAI->hasDotTypeDotSizeDirective())
+  OutStreamer->emitELFSize(EmittedInitSym,
+   MCConstantExpr::create(ActualSize, OutContext));
+EmittedInitSym = OutContext.getOrCreateSymbol(GVSym->getName() +
+  
Twine("__asan_instrumented"));
+emitVisibility(EmittedInitSym, GV->getVisibility(), !GV->isDeclaration());
+  }
+
   OutStreamer->switchSection(TheSection);
 
   emitLinkage(GV, EmittedInitSym);
@@ -875,7 +900,8 @@ void AsmPrinter::emitGlobalVariable(const GlobalVariable 
*GV) {
 
   OutStreamer->emitLabel(EmittedInitSym);
   MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
-  if (LocalAlias != EmittedInitSym)
+  if ((LocalAlias != EmittedInitSym) &&
+  !GV->hasAttribute(Attribute::SanitizeAddress))
 OutStreamer->emitLabel(LocalAlias);
 
   emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index e80ee1953de6b21..c5ef705d8ca9e30 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -2441,6 +2441,9 @@ void 
ModuleAddressSanitizer::instrumentGlobals(IRBuilder<> &IRB, Module &M,
 // zero so we can copy the metadata over as is.
 NewGlobal->copyMetadata(G, 0);
 
+// Attach "asan_instrumented" attribute to the new global.
+NewGlobal->addAttribute(Attribute::SanitizeAddress);
+
 Value *Indices2[2];
 Indices2[0] = IRB.getInt32(0);
 Indices2[1] = IRB.getInt32(0);

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


[clang] [Clang] Ensure zero-init is not overridden when initializing a base class in a constant expression context (PR #70150)

2023-10-24 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik updated 
https://github.com/llvm/llvm-project/pull/70150

>From 1e7ec004102349a67519966bb7111838668ab2b4 Mon Sep 17 00:00:00 2001
From: Shafik Yaghmour 
Date: Tue, 24 Oct 2023 16:21:30 -0700
Subject: [PATCH] [Clang] Ensure zero-init is not overridden when intializing a
 base class in a constant expression context

During constant evaluation when value-initializing a class if the base class
was default-initialized it would undue the previously zero-initialized class
members. This fixes the way we handle default initialzation to avoid
initializing over an already initialized member to an indeterminate value.

Fixes: https://github.com/llvm/llvm-project/issues/69890
---
 clang/docs/ReleaseNotes.rst   |  4 +++
 clang/lib/AST/ExprConstant.cpp| 33 +++
 clang/test/AST/Interp/records.cpp |  7 ++--
 .../dcl.init/dcl.init.general/p16-cxx20.cpp   | 18 ++
 4 files changed, 44 insertions(+), 18 deletions(-)
 create mode 100644 
clang/test/CXX/dcl.decl/dcl.init/dcl.init.general/p16-cxx20.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a063733e96cb74c..ae2f082ad323a78 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -622,6 +622,10 @@ Bug Fixes to C++ Support
   (`#46200 `_)
   (`#57812 `_)
 
+- Fix bug where we were overriding zero-initialization of class members when
+  default initializing a base class in a constant expression context. Fixes:
+  (`#69890 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 6b47b8a1256477d..eea0827d6f7a8a1 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4872,8 +4872,13 @@ static bool HandleBaseToDerivedCast(EvalInfo &Info, 
const CastExpr *E,
 
 /// Get the value to use for a default-initialized object of type T.
 /// Return false if it encounters something invalid.
-static bool getDefaultInitValue(QualType T, APValue &Result) {
+static bool handleDefaultInitValue(QualType T, APValue &Result) {
   bool Success = true;
+
+  // If there is already a value present don't overwrite it.
+  if (!Result.isAbsent())
+return true;
+
   if (auto *RD = T->getAsCXXRecordDecl()) {
 if (RD->isInvalidDecl()) {
   Result = APValue();
@@ -4890,13 +4895,14 @@ static bool getDefaultInitValue(QualType T, APValue 
&Result) {
 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
   End = RD->bases_end();
  I != End; ++I, ++Index)
-  Success &= getDefaultInitValue(I->getType(), 
Result.getStructBase(Index));
+  Success &=
+  handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
 
 for (const auto *I : RD->fields()) {
   if (I->isUnnamedBitfield())
 continue;
-  Success &= getDefaultInitValue(I->getType(),
- 
Result.getStructField(I->getFieldIndex()));
+  Success &= handleDefaultInitValue(
+  I->getType(), Result.getStructField(I->getFieldIndex()));
 }
 return Success;
   }
@@ -4906,7 +4912,7 @@ static bool getDefaultInitValue(QualType T, APValue 
&Result) {
 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
 if (Result.hasArrayFiller())
   Success &=
-  getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
+  handleDefaultInitValue(AT->getElementType(), 
Result.getArrayFiller());
 
 return Success;
   }
@@ -4947,7 +4953,7 @@ static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl 
*VD) {
   if (!InitE) {
 if (VD->getType()->isDependentType())
   return Info.noteSideEffect();
-return getDefaultInitValue(VD->getType(), Val);
+return handleDefaultInitValue(VD->getType(), Val);
   }
   if (InitE->isValueDependent())
 return false;
@@ -6049,7 +6055,7 @@ struct StartLifetimeOfUnionMemberHandler {
   return false;
 }
 APValue Result;
-Failed = !getDefaultInitValue(Field->getType(), Result);
+Failed = !handleDefaultInitValue(Field->getType(), Result);
 Subobj.setUnion(Field, Result);
 return true;
   }
@@ -6401,7 +6407,7 @@ static bool HandleConstructorCall(const Expr *E, const 
LValue &This,
 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
   assert(FieldIt != RD->field_end() && "missing field?");
   if (!FieldIt->isUnnamedBitfield())
-Success &= getDefaultInitValue(
+Success &= handleDefaultInitValue(
 FieldIt->getType(),
 Result.getStructField(FieldIt->getFieldIndex()));
 }
@@ -6458,7 +6464,8 @@ static bool HandleConstructorCall(const Expr *E, const 
LVa

[clang] [ADT] Rename llvm::erase_value to llvm::erase (NFC) (PR #70156)

2023-10-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-mlir-core

Author: Kazu Hirata (kazutakahirata)


Changes

C++20 comes with std::erase to erase a value from std::vector.  This
patch renames llvm::erase_value to llvm::erase for consistency with
C++20.

We could make llvm::erase more similar to std::erase by having it
return the number of elements removed, but I'm not doing that for now
because nobody seems to care about that in our code base.

Since there are only 50 occurrences of erase_value in our code base,
this patch replaces all of them with llvm::erase and deprecates
llvm::erase_value.


---

Patch is 28.05 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/70156.diff


42 Files Affected:

- (modified) bolt/lib/Passes/HFSortPlus.cpp (+1-1) 
- (modified) bolt/lib/Passes/IndirectCallPromotion.cpp (+1-1) 
- (modified) clang-tools-extra/clangd/FindTarget.cpp (+1-1) 
- (modified) clang-tools-extra/clangd/SystemIncludeExtractor.cpp (+1-1) 
- (modified) clang/include/clang/Analysis/Analyses/Dominators.h (+1-1) 
- (modified) clang/include/clang/Basic/JsonSupport.h (+1-1) 
- (modified) clang/include/clang/Sema/ScopeInfo.h (+1-1) 
- (modified) clang/lib/AST/ASTContext.cpp (+1-1) 
- (modified) clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp 
(+1-1) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+1-1) 
- (modified) llvm/include/llvm/ADT/STLExtras.h (+7-1) 
- (modified) llvm/include/llvm/Analysis/IntervalIterator.h (+1-1) 
- (modified) llvm/include/llvm/Support/CFGDiff.h (+2-2) 
- (modified) llvm/include/llvm/Support/GenericDomTreeConstruction.h (+1-1) 
- (modified) llvm/include/llvm/TableGen/DirectiveEmitter.h (+1-1) 
- (modified) llvm/lib/Analysis/AssumptionCache.cpp (+1-1) 
- (modified) llvm/lib/Analysis/LoopPass.cpp (+1-1) 
- (modified) llvm/lib/Analysis/ScalarEvolution.cpp (+2-2) 
- (modified) llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/LiveIntervals.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/MachineBlockPlacement.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/MachinePipeliner.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/MachineRegisterInfo.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/TwoAddressInstructionPass.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/WinEHPrepare.cpp (+2-2) 
- (modified) llvm/lib/DebugInfo/LogicalView/Core/LVScope.cpp (+1-1) 
- (modified) llvm/lib/TableGen/TGParser.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Utils/CodeLayout.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Utils/LoopUnroll.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Utils/SimplifyCFG.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp (+2-2) 
- (modified) llvm/lib/Transforms/Vectorize/VPlanValue.h (+1-1) 
- (modified) llvm/tools/llvm-dwarfdump/Statistics.cpp (+3-3) 
- (modified) 
llvm/tools/llvm-yaml-numeric-parser-fuzzer/yaml-numeric-parser-fuzzer.cpp 
(+1-1) 
- (modified) llvm/tools/llvm-yaml-parser-fuzzer/yaml-parser-fuzzer.cpp (+1-1) 
- (modified) 
mlir/lib/Dialect/Bufferization/IR/BufferDeallocationOpInterface.cpp (+1-1) 
- (modified) mlir/lib/Dialect/Transform/IR/TransformInterfaces.cpp (+2-2) 
- (modified) mlir/lib/Reducer/ReductionNode.cpp (+1-1) 
- (modified) mlir/lib/TableGen/Dialect.cpp (+1-1) 
- (modified) polly/lib/Analysis/ScopInfo.cpp (+3-3) 


``diff
diff --git a/bolt/lib/Passes/HFSortPlus.cpp b/bolt/lib/Passes/HFSortPlus.cpp
index 70b9a4d51e6ee58..0a481b5418dd259 100644
--- a/bolt/lib/Passes/HFSortPlus.cpp
+++ b/bolt/lib/Passes/HFSortPlus.cpp
@@ -567,7 +567,7 @@ class HFSortPlus {
 Into->Score = score(Into);
 
 // Remove chain From From the list of active chains
-llvm::erase_value(HotChains, From);
+llvm::erase(HotChains, From);
   }
 
 private:
diff --git a/bolt/lib/Passes/IndirectCallPromotion.cpp 
b/bolt/lib/Passes/IndirectCallPromotion.cpp
index ea8019431cf52f9..457997d35323d8b 100644
--- a/bolt/lib/Passes/IndirectCallPromotion.cpp
+++ b/bolt/lib/Passes/IndirectCallPromotion.cpp
@@ -591,7 +591,7 @@ 
IndirectCallPromotion::findCallTargetSymbols(std::vector &Targets,
 
   NewTargets.push_back(Target);
   std::vector({JTIndex}).swap(NewTargets.back().JTIndices);
-  llvm::erase_value(Target.JTIndices, JTIndex);
+  llvm::erase(Target.JTIndices, JTIndex);
 
   // Keep fixCFG counts sane if more indices use this same target later
   assert(IndicesPerTarget[Target.To.Sym] > 0 && "wrong map");
diff --git a/clang-tools-extra/clangd/FindTarget.cpp 
b/clang-tools-extra/clangd/FindTarget.cpp
index a766122ad3deee9..839cf6332fe8b07 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -1131,7 +1131,7 @@ class ExplicitReferenceCollector
   void reportReference(ReferenceLoc &&Ref, DynTypedNode N) {
 // Strip null targets that can arise from invalid code.
 // (This avoids having to 

[clang-tools-extra] [ADT] Rename llvm::erase_value to llvm::erase (NFC) (PR #70156)

2023-10-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-mlir-core

Author: Kazu Hirata (kazutakahirata)


Changes

C++20 comes with std::erase to erase a value from std::vector.  This
patch renames llvm::erase_value to llvm::erase for consistency with
C++20.

We could make llvm::erase more similar to std::erase by having it
return the number of elements removed, but I'm not doing that for now
because nobody seems to care about that in our code base.

Since there are only 50 occurrences of erase_value in our code base,
this patch replaces all of them with llvm::erase and deprecates
llvm::erase_value.


---

Patch is 28.05 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/70156.diff


42 Files Affected:

- (modified) bolt/lib/Passes/HFSortPlus.cpp (+1-1) 
- (modified) bolt/lib/Passes/IndirectCallPromotion.cpp (+1-1) 
- (modified) clang-tools-extra/clangd/FindTarget.cpp (+1-1) 
- (modified) clang-tools-extra/clangd/SystemIncludeExtractor.cpp (+1-1) 
- (modified) clang/include/clang/Analysis/Analyses/Dominators.h (+1-1) 
- (modified) clang/include/clang/Basic/JsonSupport.h (+1-1) 
- (modified) clang/include/clang/Sema/ScopeInfo.h (+1-1) 
- (modified) clang/lib/AST/ASTContext.cpp (+1-1) 
- (modified) clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp 
(+1-1) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+1-1) 
- (modified) llvm/include/llvm/ADT/STLExtras.h (+7-1) 
- (modified) llvm/include/llvm/Analysis/IntervalIterator.h (+1-1) 
- (modified) llvm/include/llvm/Support/CFGDiff.h (+2-2) 
- (modified) llvm/include/llvm/Support/GenericDomTreeConstruction.h (+1-1) 
- (modified) llvm/include/llvm/TableGen/DirectiveEmitter.h (+1-1) 
- (modified) llvm/lib/Analysis/AssumptionCache.cpp (+1-1) 
- (modified) llvm/lib/Analysis/LoopPass.cpp (+1-1) 
- (modified) llvm/lib/Analysis/ScalarEvolution.cpp (+2-2) 
- (modified) llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/LiveIntervals.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/MachineBlockPlacement.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/MachinePipeliner.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/MachineRegisterInfo.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/TwoAddressInstructionPass.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/WinEHPrepare.cpp (+2-2) 
- (modified) llvm/lib/DebugInfo/LogicalView/Core/LVScope.cpp (+1-1) 
- (modified) llvm/lib/TableGen/TGParser.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Utils/CodeLayout.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Utils/LoopUnroll.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Utils/SimplifyCFG.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp (+2-2) 
- (modified) llvm/lib/Transforms/Vectorize/VPlanValue.h (+1-1) 
- (modified) llvm/tools/llvm-dwarfdump/Statistics.cpp (+3-3) 
- (modified) 
llvm/tools/llvm-yaml-numeric-parser-fuzzer/yaml-numeric-parser-fuzzer.cpp 
(+1-1) 
- (modified) llvm/tools/llvm-yaml-parser-fuzzer/yaml-parser-fuzzer.cpp (+1-1) 
- (modified) 
mlir/lib/Dialect/Bufferization/IR/BufferDeallocationOpInterface.cpp (+1-1) 
- (modified) mlir/lib/Dialect/Transform/IR/TransformInterfaces.cpp (+2-2) 
- (modified) mlir/lib/Reducer/ReductionNode.cpp (+1-1) 
- (modified) mlir/lib/TableGen/Dialect.cpp (+1-1) 
- (modified) polly/lib/Analysis/ScopInfo.cpp (+3-3) 


``diff
diff --git a/bolt/lib/Passes/HFSortPlus.cpp b/bolt/lib/Passes/HFSortPlus.cpp
index 70b9a4d51e6ee58..0a481b5418dd259 100644
--- a/bolt/lib/Passes/HFSortPlus.cpp
+++ b/bolt/lib/Passes/HFSortPlus.cpp
@@ -567,7 +567,7 @@ class HFSortPlus {
 Into->Score = score(Into);
 
 // Remove chain From From the list of active chains
-llvm::erase_value(HotChains, From);
+llvm::erase(HotChains, From);
   }
 
 private:
diff --git a/bolt/lib/Passes/IndirectCallPromotion.cpp 
b/bolt/lib/Passes/IndirectCallPromotion.cpp
index ea8019431cf52f9..457997d35323d8b 100644
--- a/bolt/lib/Passes/IndirectCallPromotion.cpp
+++ b/bolt/lib/Passes/IndirectCallPromotion.cpp
@@ -591,7 +591,7 @@ 
IndirectCallPromotion::findCallTargetSymbols(std::vector &Targets,
 
   NewTargets.push_back(Target);
   std::vector({JTIndex}).swap(NewTargets.back().JTIndices);
-  llvm::erase_value(Target.JTIndices, JTIndex);
+  llvm::erase(Target.JTIndices, JTIndex);
 
   // Keep fixCFG counts sane if more indices use this same target later
   assert(IndicesPerTarget[Target.To.Sym] > 0 && "wrong map");
diff --git a/clang-tools-extra/clangd/FindTarget.cpp 
b/clang-tools-extra/clangd/FindTarget.cpp
index a766122ad3deee9..839cf6332fe8b07 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -1131,7 +1131,7 @@ class ExplicitReferenceCollector
   void reportReference(ReferenceLoc &&Ref, DynTypedNode N) {
 // Strip null targets that can arise from invalid code.
 // (This avoids having to 

[clang] [NFC] [Serializer] Pack information in serializer (PR #69287)

2023-10-24 Thread Chuanqi Xu via cfe-commits


@@ -617,24 +617,27 @@ void ASTDeclReader::VisitDecl(Decl *D) {
Reader.getContext());
   }
   D->setLocation(ThisDeclLoc);
-  D->InvalidDecl = Record.readInt();
-  if (Record.readInt()) { // hasAttrs
+
+  uint64_t DeclBits = Record.readInt();
+  D->InvalidDecl = DeclBits & 0x1;
+  D->setImplicit(DeclBits & (1 << 2));
+  D->Used = (DeclBits >> 3) & 0x1;
+  IsDeclMarkedUsed |= D->Used;
+  D->setReferenced(DeclBits & (1 << 4));
+  D->setTopLevelDeclInObjCContainer(DeclBits & (1 << 5));
+  D->setAccess((AccessSpecifier)((DeclBits >> 6) & 0x3));
+  D->FromASTFile = true;
+  auto ModuleOwnership = (Decl::ModuleOwnershipKind)((DeclBits >> 8) & 0x7);

ChuanqiXu9 wrote:

What I had in mind is to introduce a BitPacker, but it can't avoid magic 
constants completely. e.g, we have to know that the width of `AccessSpecifier ` 
should be 2 and the width of `ModuleOwnershipKind` should be 3.

Then we can refactor the above section to:

```
BitPacker Bits = Record.readInt();
D->InvalidDecl = Bits.getNextBit();
D->setImplicit(Bits.getNextBit());
D->Used = Bits.getNextBit();
IsDeclMarkedUsed |= D->Used;
D->setReferenced(Bits.getNextBit());
D->setTopLevelDeclInObjCContainer(Bits.getNextBit());
D->setAccess((AccessSpecifier)Bits.getNextBit()); // Still we 
can't avoid the magic constants completely.
D->FromASTFile = true;
auto ModuleOwnership = (Decl::ModuleOwnershipKind)Bits.getNextBit());
```

Would you be happy about the above form?

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


[clang-tools-extra] [clang-tidy] Ignore deleted functions in cppcoreguidelines-rvalue-reference-param-not-moved (PR #69514)

2023-10-24 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 approved this pull request.


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


[clang-tools-extra] [clang-tidy] Improve bugprone-unused-return-value check (PR #66573)

2023-10-24 Thread Congcong Cai via cfe-commits


@@ -130,26 +130,35 @@ 
UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
 "::std::error_condition;"
 "::std::errc;"
 "::std::expected;"
-"::boost::system::error_code"))) {}
+"::boost::system::error_code"))),
+  AllowCastToVoid(Options.get("AllowCastToVoid", false)) {}
 
 void UnusedReturnValueCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "CheckedFunctions", CheckedFunctions);
   Options.store(Opts, "CheckedReturnTypes",
 utils::options::serializeStringList(CheckedReturnTypes));
+  Options.store(Opts, "AllowCastToVoid", AllowCastToVoid);
 }
 
 void UnusedReturnValueCheck::registerMatchers(MatchFinder *Finder) {
   auto FunVec = utils::options::parseStringList(CheckedFunctions);
 
-  auto MatchedCallExpr = expr(ignoringImplicit(ignoringParenImpCasts(
-  callExpr(callee(functionDecl(
-   // Don't match void overloads of checked functions.
-   unless(returns(voidType())),
-   anyOf(isInstantiatedFrom(hasAnyName(FunVec)),
- returns(hasCanonicalType(hasDeclaration(
- namedDecl(matchers::matchesAnyListedName(
- CheckedReturnTypes)
-  .bind("match";
+  auto MatchedDirectCallExpr =
+  expr(callExpr(callee(functionDecl(
+// Don't match void overloads of checked functions.
+unless(returns(voidType())),
+anyOf(isInstantiatedFrom(hasAnyName(FunVec)),
+  returns(hasCanonicalType(hasDeclaration(
+  namedDecl(matchers::matchesAnyListedName(
+  CheckedReturnTypes)
+   .bind("match"));
+
+  auto CheckCastToVoid =
+  AllowCastToVoid ? castExpr(unless(hasCastKind(CK_ToVoid))) : castExpr();
+  auto MatchedCallExpr = expr(
+  anyOf(MatchedDirectCallExpr,
+explicitCastExpr(unless(cxxFunctionalCastExpr()), CheckCastToVoid,

HerrCai0907 wrote:

I am not pretty sure about this part. If we ignore other part and unfold it, it 
looks like
```c++
expr(
  explicitCastExpr(
castExpr(
  unless(hasCastKind(CK_ToVoid))
)
  )
)
```
Should it be
```c++
  explicitCastExpr(
  unless(hasCastKind(CK_ToVoid))
  )
```

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


[clang] [OpenMP 5.2] Deprecate old syntax of linear clause (PR #70152)

2023-10-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Fazlay Rabbi (mdfazlay)


Changes

The syntax of the linear clause that specifies its argument and linear-modifier 
as linear-modifier(list) was deprecated since OpenMP 5.2 and the step modifier 
was added for specifying the linear step.

Reference: OpenMP 5.2 Spec, Page 627, Line 15

---
Full diff: https://github.com/llvm/llvm-project/pull/70152.diff


3 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticParseKinds.td (+2) 
- (modified) clang/lib/Parse/ParseOpenMP.cpp (+4) 
- (modified) clang/test/OpenMP/for_linear_messages.cpp (+2) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index d6652e6a610c1be..0621a61c2edb6a4 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1350,6 +1350,8 @@ def warn_omp_extra_tokens_at_eol : Warning<
   InGroup;
 def err_omp_multiple_step_or_linear_modifier : Error<
   "multiple %select{'step size'|'linear modifier'}0 found in linear clause">; 
+def err_omp_deprecate_old_syntax : Error<
+  "old syntax '%0' on '%1' clause was deprecated, use new syntax '%2'">; 
 def warn_pragma_expected_colon_r_paren : Warning<
   "missing ':' or ')' after %0 - ignoring">, InGroup;
 def err_omp_unknown_directive : Error<
diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp
index 4f3b8a28ee47ef3..3e7d8274aeefc52 100644
--- a/clang/lib/Parse/ParseOpenMP.cpp
+++ b/clang/lib/Parse/ParseOpenMP.cpp
@@ -4573,6 +4573,10 @@ bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind 
DKind,
   Data.ExtraModifierLoc = ConsumeToken();
   LinearT.consumeOpen();
   NeedRParenForLinear = true;
+  if (getLangOpts().OpenMP >= 52)
+Diag(Data.ExtraModifierLoc, diag::err_omp_deprecate_old_syntax)
+<< "linear-modifier(list)" << getOpenMPClauseName(Kind)
+<< "linear(list: [linear-modifier,] step(step-size))";
 }
   } else if (Kind == OMPC_lastprivate) {
 // Try to parse modifier if any.
diff --git a/clang/test/OpenMP/for_linear_messages.cpp 
b/clang/test/OpenMP/for_linear_messages.cpp
index 03c5c763d7b5c1d..d8d3391c0c27150 100644
--- a/clang/test/OpenMP/for_linear_messages.cpp
+++ b/clang/test/OpenMP/for_linear_messages.cpp
@@ -215,6 +215,8 @@ int main(int argc, char **argv) {
 int i;
 #pragma omp for linear(i)
 for (int k = 0; k < argc; ++k) ++k;
+#pragma omp for linear(val(i)) // omp52-error {{old syntax 
'linear-modifier(list)' on 'linear' clause was deprecated, use new syntax 
'linear(list: [linear-modifier,] step(step-size))'}}
+for (int k = 0; k < argc; ++k) ++k;
 #ifdef OMP52
 #pragma omp for linear(i : step(4))
 #else

``




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


[clang] [OpenMP 5.2] Deprecate old syntax of linear clause (PR #70152)

2023-10-24 Thread Fazlay Rabbi via cfe-commits

mdfazlay wrote:

@alexey-bataev, I'll add more tests as soon as we finalize the proper error 
message.

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


[clang] [OpenMP 5.2] Deprecate old syntax of linear clause (PR #70152)

2023-10-24 Thread Fazlay Rabbi via cfe-commits

https://github.com/mdfazlay created 
https://github.com/llvm/llvm-project/pull/70152

The syntax of the linear clause that specifies its argument and linear-modifier 
as linear-modifier(list) was deprecated since OpenMP 5.2 and the step modifier 
was added for specifying the linear step.

Reference: OpenMP 5.2 Spec, Page 627, Line 15

>From c470a9bb86f31ec7de01d4efad72ff785dc4124e Mon Sep 17 00:00:00 2001
From: Fazlay Rabbi 
Date: Tue, 24 Oct 2023 18:36:53 -0700
Subject: [PATCH] [OpenMP 5.2] Deprecate old syntax of linear clause

The syntax of the linear clause that specifies its argument and linear-modifier
as linear-modifier(list) was deprecated since OpenMP 5.2 and the step modifier
was added for specifying the linear step.

Reference: OpenMP 5.2 Spec, Page 627, Line 15
---
 clang/include/clang/Basic/DiagnosticParseKinds.td | 2 ++
 clang/lib/Parse/ParseOpenMP.cpp   | 4 
 clang/test/OpenMP/for_linear_messages.cpp | 2 ++
 3 files changed, 8 insertions(+)

diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index d6652e6a610c1be..0621a61c2edb6a4 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1350,6 +1350,8 @@ def warn_omp_extra_tokens_at_eol : Warning<
   InGroup;
 def err_omp_multiple_step_or_linear_modifier : Error<
   "multiple %select{'step size'|'linear modifier'}0 found in linear clause">; 
+def err_omp_deprecate_old_syntax : Error<
+  "old syntax '%0' on '%1' clause was deprecated, use new syntax '%2'">; 
 def warn_pragma_expected_colon_r_paren : Warning<
   "missing ':' or ')' after %0 - ignoring">, InGroup;
 def err_omp_unknown_directive : Error<
diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp
index 4f3b8a28ee47ef3..3e7d8274aeefc52 100644
--- a/clang/lib/Parse/ParseOpenMP.cpp
+++ b/clang/lib/Parse/ParseOpenMP.cpp
@@ -4573,6 +4573,10 @@ bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind 
DKind,
   Data.ExtraModifierLoc = ConsumeToken();
   LinearT.consumeOpen();
   NeedRParenForLinear = true;
+  if (getLangOpts().OpenMP >= 52)
+Diag(Data.ExtraModifierLoc, diag::err_omp_deprecate_old_syntax)
+<< "linear-modifier(list)" << getOpenMPClauseName(Kind)
+<< "linear(list: [linear-modifier,] step(step-size))";
 }
   } else if (Kind == OMPC_lastprivate) {
 // Try to parse modifier if any.
diff --git a/clang/test/OpenMP/for_linear_messages.cpp 
b/clang/test/OpenMP/for_linear_messages.cpp
index 03c5c763d7b5c1d..d8d3391c0c27150 100644
--- a/clang/test/OpenMP/for_linear_messages.cpp
+++ b/clang/test/OpenMP/for_linear_messages.cpp
@@ -215,6 +215,8 @@ int main(int argc, char **argv) {
 int i;
 #pragma omp for linear(i)
 for (int k = 0; k < argc; ++k) ++k;
+#pragma omp for linear(val(i)) // omp52-error {{old syntax 
'linear-modifier(list)' on 'linear' clause was deprecated, use new syntax 
'linear(list: [linear-modifier,] step(step-size))'}}
+for (int k = 0; k < argc; ++k) ++k;
 #ifdef OMP52
 #pragma omp for linear(i : step(4))
 #else

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


[clang] [libc++] Implement ranges::iota (PR #68494)

2023-10-24 Thread James E T Smith via cfe-commits

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


[clang-tools-extra] [libc++] Implement ranges::iota (PR #68494)

2023-10-24 Thread James E T Smith via cfe-commits

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


[clang] [libc++] Implement ranges::iota (PR #68494)

2023-10-24 Thread James E T Smith via cfe-commits

https://github.com/jamesETsmith updated 
https://github.com/llvm/llvm-project/pull/68494

>From c4a3ccfbad090ad8314aa8ad53092edc8d5432bc Mon Sep 17 00:00:00 2001
From: James Smith 
Date: Thu, 28 Sep 2023 10:11:15 -0400
Subject: [PATCH 1/7] [libc++] Implement ranges::iota and
 ranges::out_value_result

---
 libcxx/include/CMakeLists.txt |   2 +
 libcxx/include/__algorithm/out_value_result.h |  52 +
 libcxx/include/__numeric/ranges_iota.h|  53 +
 libcxx/include/algorithm  |   4 +
 libcxx/include/numeric|   1 +
 libcxx/include/version|   2 +-
 .../out_value_result.pass.cpp | 102 ++
 .../numeric.iota/ranges.iota.pass.cpp |  52 +
 8 files changed, 267 insertions(+), 1 deletion(-)
 create mode 100644 libcxx/include/__algorithm/out_value_result.h
 create mode 100644 libcxx/include/__numeric/ranges_iota.h
 create mode 100644 
libcxx/test/std/algorithms/algorithms.results/out_value_result.pass.cpp
 create mode 100644 
libcxx/test/std/numerics/numeric.ops/numeric.iota/ranges.iota.pass.cpp

diff --git a/libcxx/include/CMakeLists.txt b/libcxx/include/CMakeLists.txt
index 2ec755236dbaee2..c6eb03f1d68e984 100644
--- a/libcxx/include/CMakeLists.txt
+++ b/libcxx/include/CMakeLists.txt
@@ -63,6 +63,7 @@ set(files
   __algorithm/next_permutation.h
   __algorithm/none_of.h
   __algorithm/nth_element.h
+  __algorithm/out_value_result.h
   __algorithm/partial_sort.h
   __algorithm/partial_sort_copy.h
   __algorithm/partition.h
@@ -561,6 +562,7 @@ set(files
   __numeric/partial_sum.h
   __numeric/pstl_reduce.h
   __numeric/pstl_transform_reduce.h
+  __numeric/ranges_iota.h
   __numeric/reduce.h
   __numeric/transform_exclusive_scan.h
   __numeric/transform_inclusive_scan.h
diff --git a/libcxx/include/__algorithm/out_value_result.h 
b/libcxx/include/__algorithm/out_value_result.h
new file mode 100644
index 000..8baffec7b9ef4da
--- /dev/null
+++ b/libcxx/include/__algorithm/out_value_result.h
@@ -0,0 +1,52 @@
+// -*- 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 _LIBCPP___ALGORITHM_OUT_VALUE_RESULT_H
+#define _LIBCPP___ALGORITHM_OUT_VALUE_RESULT_H
+
+#include <__concepts/convertible_to.h>
+#include <__config>
+#include <__utility/move.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 23
+
+namespace ranges {
+
+template 
+struct out_value_result {
+  _LIBCPP_NO_UNIQUE_ADDRESS _OutIter1 out;
+  _LIBCPP_NO_UNIQUE_ADDRESS _ValType1 value;
+
+  template 
+requires convertible_to && 
convertible_to
+  constexpr operator out_value_result<_OutIter2, _ValType2>() const& { return 
{out, value}; }
+
+  template 
+requires convertible_to<_OutIter1, _OutIter2> && convertible_to<_ValType1, 
_ValType2>
+  constexpr operator out_value_result<_OutIter2, _ValType2>() && { return 
{std::move(out), std::move(value)}; }
+};
+
+} // namespace ranges
+
+#endif // _LIBCPP_STD_VER >= 23
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_OUT_VALUE_RESULT_H
diff --git a/libcxx/include/__numeric/ranges_iota.h 
b/libcxx/include/__numeric/ranges_iota.h
new file mode 100644
index 000..20311a68c2a348c
--- /dev/null
+++ b/libcxx/include/__numeric/ranges_iota.h
@@ -0,0 +1,53 @@
+// -*- 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 _LIBCPP___NUMERIC_RANGES_IOTA_H
+#define _LIBCPP___NUMERIC_RANGES_IOTA_H
+
+#include <__algorithm/out_value_result.h>
+#include <__config>
+#include <__ranges/concepts.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 23
+namespace ranges {
+template 
+using iota_result = ranges::out_value_result<_Out, _Tp>;
+
+struct __iota_fn {
+  template  _Sent, 
weakly_incrementable _Tp>
+requires indirectly_writable<_Out, const _Tp&>
+  constexpr iota_result<_Out, _Tp> operator()(_Out __first, _Sent __last, _Tp 
__value) const {
+while (__first != __last) {
+  *__first = static_cast(__value);
+  ++__first;
+  ++__value;
+}
+return {std::move(__first), std::move(__value)

[clang-tools-extra] [libc++] Implement ranges::iota (PR #68494)

2023-10-24 Thread James E T Smith via cfe-commits

https://github.com/jamesETsmith updated 
https://github.com/llvm/llvm-project/pull/68494

>From c4a3ccfbad090ad8314aa8ad53092edc8d5432bc Mon Sep 17 00:00:00 2001
From: James Smith 
Date: Thu, 28 Sep 2023 10:11:15 -0400
Subject: [PATCH 1/7] [libc++] Implement ranges::iota and
 ranges::out_value_result

---
 libcxx/include/CMakeLists.txt |   2 +
 libcxx/include/__algorithm/out_value_result.h |  52 +
 libcxx/include/__numeric/ranges_iota.h|  53 +
 libcxx/include/algorithm  |   4 +
 libcxx/include/numeric|   1 +
 libcxx/include/version|   2 +-
 .../out_value_result.pass.cpp | 102 ++
 .../numeric.iota/ranges.iota.pass.cpp |  52 +
 8 files changed, 267 insertions(+), 1 deletion(-)
 create mode 100644 libcxx/include/__algorithm/out_value_result.h
 create mode 100644 libcxx/include/__numeric/ranges_iota.h
 create mode 100644 
libcxx/test/std/algorithms/algorithms.results/out_value_result.pass.cpp
 create mode 100644 
libcxx/test/std/numerics/numeric.ops/numeric.iota/ranges.iota.pass.cpp

diff --git a/libcxx/include/CMakeLists.txt b/libcxx/include/CMakeLists.txt
index 2ec755236dbaee2..c6eb03f1d68e984 100644
--- a/libcxx/include/CMakeLists.txt
+++ b/libcxx/include/CMakeLists.txt
@@ -63,6 +63,7 @@ set(files
   __algorithm/next_permutation.h
   __algorithm/none_of.h
   __algorithm/nth_element.h
+  __algorithm/out_value_result.h
   __algorithm/partial_sort.h
   __algorithm/partial_sort_copy.h
   __algorithm/partition.h
@@ -561,6 +562,7 @@ set(files
   __numeric/partial_sum.h
   __numeric/pstl_reduce.h
   __numeric/pstl_transform_reduce.h
+  __numeric/ranges_iota.h
   __numeric/reduce.h
   __numeric/transform_exclusive_scan.h
   __numeric/transform_inclusive_scan.h
diff --git a/libcxx/include/__algorithm/out_value_result.h 
b/libcxx/include/__algorithm/out_value_result.h
new file mode 100644
index 000..8baffec7b9ef4da
--- /dev/null
+++ b/libcxx/include/__algorithm/out_value_result.h
@@ -0,0 +1,52 @@
+// -*- 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 _LIBCPP___ALGORITHM_OUT_VALUE_RESULT_H
+#define _LIBCPP___ALGORITHM_OUT_VALUE_RESULT_H
+
+#include <__concepts/convertible_to.h>
+#include <__config>
+#include <__utility/move.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 23
+
+namespace ranges {
+
+template 
+struct out_value_result {
+  _LIBCPP_NO_UNIQUE_ADDRESS _OutIter1 out;
+  _LIBCPP_NO_UNIQUE_ADDRESS _ValType1 value;
+
+  template 
+requires convertible_to && 
convertible_to
+  constexpr operator out_value_result<_OutIter2, _ValType2>() const& { return 
{out, value}; }
+
+  template 
+requires convertible_to<_OutIter1, _OutIter2> && convertible_to<_ValType1, 
_ValType2>
+  constexpr operator out_value_result<_OutIter2, _ValType2>() && { return 
{std::move(out), std::move(value)}; }
+};
+
+} // namespace ranges
+
+#endif // _LIBCPP_STD_VER >= 23
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_OUT_VALUE_RESULT_H
diff --git a/libcxx/include/__numeric/ranges_iota.h 
b/libcxx/include/__numeric/ranges_iota.h
new file mode 100644
index 000..20311a68c2a348c
--- /dev/null
+++ b/libcxx/include/__numeric/ranges_iota.h
@@ -0,0 +1,53 @@
+// -*- 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 _LIBCPP___NUMERIC_RANGES_IOTA_H
+#define _LIBCPP___NUMERIC_RANGES_IOTA_H
+
+#include <__algorithm/out_value_result.h>
+#include <__config>
+#include <__ranges/concepts.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 23
+namespace ranges {
+template 
+using iota_result = ranges::out_value_result<_Out, _Tp>;
+
+struct __iota_fn {
+  template  _Sent, 
weakly_incrementable _Tp>
+requires indirectly_writable<_Out, const _Tp&>
+  constexpr iota_result<_Out, _Tp> operator()(_Out __first, _Sent __last, _Tp 
__value) const {
+while (__first != __last) {
+  *__first = static_cast(__value);
+  ++__first;
+  ++__value;
+}
+return {std::move(__first), std::move(__value)

[clang-tools-extra] [InstCombine] Convert or concat to fshl if opposite or concat exists (PR #68502)

2023-10-24 Thread via cfe-commits

HaohaiWen wrote:

> > See most recent comments about missing tests. That being said code looks 
> > functionally correct to me. Still not 100% sure this is a desirable change. 
> > Will defer to @nikic about that.
> 
> I'm also skeptical about accepting this optimization. Looking at the 
> motivating case in [#68502 
> (comment)](https://github.com/llvm/llvm-project/pull/68502#discussion_r1351618002),
>  this seems like a bad approach to the problem: It means that in order to 
> fold the pattern to `bitreverse(%xy)`, we must just so happen to have the 
> right `%xy` lying around in the IR, even though it doesn't have any relation 
> to the main pattern (it's not used inside it, just injected via an extra 
> use). It sounds to me like the better way to handle that case would be to 
> support matching a variant of plain bitreverse in the form of 
> `bitreverse(rot(%yx))`.
> 
> Replacing the `rot(%yx)` by `%xy` is then an extra optimization opportunity, 
> but it's no longer a precondition to performing the transform.

In fact, this is a real case.
Currently, there's no chance for matchBSwapOrBitReverse to match bitreverse 
pattern if we don't do this fshl optimization. Even if we teach it to recognize 
this pattern, this requires injecting a new rot(%yx) then look for %xy and it 
still requires to look for user chain.
Even if we don't have bitreverse pattern in the rest IR, there's still 
beneficial to do such fshl optimization. This removes an extra shl.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-10-24 Thread Aaron Puchert via cfe-commits


@@ -435,6 +435,86 @@ bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo 
&CI,
   return true;
 }
 
+// Warn if parent function does not have builtin function format attribute.
+void Sema::DiagnoseMissingFormatAttributes(NamedDecl *FDecl,
+   SourceLocation Loc) {
+  if (!FDecl)
+return;
+
+  auto *FD = dyn_cast_or_null(FDecl);
+  if (!FD)
+return;
+
+  unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
+  
+  // Function is not builtin if it's builtin ID is 0.
+  if (!BuiltinID)
+return;
+
+  // Check if function is one with format attribute.
+  switch (BuiltinID) {
+  case Builtin::BIprintf:
+  case Builtin::BIfprintf:
+  case Builtin::BIsprintf:
+  case Builtin::BIscanf:
+  case Builtin::BIfscanf:
+  case Builtin::BIsscanf:
+  case Builtin::BIvprintf:
+  case Builtin::BIvfprintf:
+  case Builtin::BIvsprintf:
+break;
+  default: {
+// In C99 mode check functions below.
+if (!getLangOpts().C99)
+  return;
+switch (BuiltinID) {
+case Builtin::BIsnprintf:
+case Builtin::BIvsnprintf:
+case Builtin::BIvscanf:
+case Builtin::BIvfscanf:
+case Builtin::BIvsscanf:
+  break;
+default:
+  return;
+}
+  }
+  }
+
+  Scope *ParentScope = getCurScope() ? getCurScope()->getFnParent() : nullptr;
+  if (!ParentScope)
+return;
+
+  DeclContext *ParentScopeEntity = ParentScope->getEntity();
+  if (!ParentScopeEntity)
+return;
+  if (ParentScopeEntity->getDeclKind() != Decl::Kind::Function)
+return;
+
+  FunctionDecl *ParentFuncDecl = static_cast(ParentScopeEntity);
+  if (!ParentFuncDecl)
+return;
+  if (!ParentFuncDecl->isVariadic())
+return;
+
+  // Iterate through builtin function format attributes. Then check
+  // if parent function has these attributes. If parent function does
+  // not have builtin function format attribut, emit warning.
+  for (const FormatAttr *Attr : FD->specific_attrs()) {
+bool hasFormatAttr = false;
+for (const FormatAttr *ParentAttr :
+ ParentFuncDecl->specific_attrs()) {
+  if (ParentAttr->getType() == Attr->getType()) {

aaronpuchert wrote:

We probably also want to check the other attribute arguments.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-10-24 Thread Aaron Puchert via cfe-commits


@@ -435,6 +435,86 @@ bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo 
&CI,
   return true;
 }
 
+// Warn if parent function does not have builtin function format attribute.
+void Sema::DiagnoseMissingFormatAttributes(NamedDecl *FDecl,
+   SourceLocation Loc) {
+  if (!FDecl)
+return;
+
+  auto *FD = dyn_cast_or_null(FDecl);
+  if (!FD)
+return;
+
+  unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
+  
+  // Function is not builtin if it's builtin ID is 0.
+  if (!BuiltinID)
+return;
+
+  // Check if function is one with format attribute.
+  switch (BuiltinID) {
+  case Builtin::BIprintf:
+  case Builtin::BIfprintf:
+  case Builtin::BIsprintf:
+  case Builtin::BIscanf:
+  case Builtin::BIfscanf:
+  case Builtin::BIsscanf:
+  case Builtin::BIvprintf:
+  case Builtin::BIvfprintf:
+  case Builtin::BIvsprintf:
+break;
+  default: {
+// In C99 mode check functions below.
+if (!getLangOpts().C99)
+  return;
+switch (BuiltinID) {
+case Builtin::BIsnprintf:
+case Builtin::BIvsnprintf:
+case Builtin::BIvscanf:
+case Builtin::BIvfscanf:
+case Builtin::BIvsscanf:
+  break;

aaronpuchert wrote:

Why don't we move them into the switch above? Presumably they can simply not be 
used prior to C99? If we need this at all.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-10-24 Thread Aaron Puchert via cfe-commits


@@ -435,6 +435,86 @@ bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo 
&CI,
   return true;
 }
 
+// Warn if parent function does not have builtin function format attribute.
+void Sema::DiagnoseMissingFormatAttributes(NamedDecl *FDecl,
+   SourceLocation Loc) {
+  if (!FDecl)
+return;
+
+  auto *FD = dyn_cast_or_null(FDecl);
+  if (!FD)
+return;
+
+  unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
+  
+  // Function is not builtin if it's builtin ID is 0.
+  if (!BuiltinID)
+return;
+
+  // Check if function is one with format attribute.
+  switch (BuiltinID) {
+  case Builtin::BIprintf:
+  case Builtin::BIfprintf:
+  case Builtin::BIsprintf:
+  case Builtin::BIscanf:
+  case Builtin::BIfscanf:
+  case Builtin::BIsscanf:
+  case Builtin::BIvprintf:
+  case Builtin::BIvfprintf:
+  case Builtin::BIvsprintf:
+break;
+  default: {
+// In C99 mode check functions below.
+if (!getLangOpts().C99)
+  return;
+switch (BuiltinID) {
+case Builtin::BIsnprintf:
+case Builtin::BIvsnprintf:
+case Builtin::BIvscanf:
+case Builtin::BIvfscanf:
+case Builtin::BIvsscanf:
+  break;
+default:
+  return;
+}
+  }
+  }
+
+  Scope *ParentScope = getCurScope() ? getCurScope()->getFnParent() : nullptr;
+  if (!ParentScope)
+return;
+
+  DeclContext *ParentScopeEntity = ParentScope->getEntity();
+  if (!ParentScopeEntity)
+return;
+  if (ParentScopeEntity->getDeclKind() != Decl::Kind::Function)
+return;
+
+  FunctionDecl *ParentFuncDecl = static_cast(ParentScopeEntity);
+  if (!ParentFuncDecl)
+return;
+  if (!ParentFuncDecl->isVariadic())
+return;
+
+  // Iterate through builtin function format attributes. Then check
+  // if parent function has these attributes. If parent function does
+  // not have builtin function format attribut, emit warning.

aaronpuchert wrote:

This seems to be missing an important ingredient, unless I'm overlooking it: we 
only want to diagnose if the format string and the var args are forwarded. 
Simply calling one of these functions does not mean that we need to propagate 
the attribute, e.g. if we're calling it with a string literal.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-10-24 Thread Aaron Puchert via cfe-commits


@@ -435,6 +435,86 @@ bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo 
&CI,
   return true;
 }
 
+// Warn if parent function does not have builtin function format attribute.
+void Sema::DiagnoseMissingFormatAttributes(NamedDecl *FDecl,
+   SourceLocation Loc) {
+  if (!FDecl)
+return;
+
+  auto *FD = dyn_cast_or_null(FDecl);
+  if (!FD)
+return;
+
+  unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
+  
+  // Function is not builtin if it's builtin ID is 0.
+  if (!BuiltinID)
+return;
+
+  // Check if function is one with format attribute.
+  switch (BuiltinID) {
+  case Builtin::BIprintf:
+  case Builtin::BIfprintf:
+  case Builtin::BIsprintf:
+  case Builtin::BIscanf:
+  case Builtin::BIfscanf:
+  case Builtin::BIsscanf:
+  case Builtin::BIvprintf:
+  case Builtin::BIvfprintf:
+  case Builtin::BIvsprintf:
+break;
+  default: {
+// In C99 mode check functions below.
+if (!getLangOpts().C99)
+  return;
+switch (BuiltinID) {
+case Builtin::BIsnprintf:
+case Builtin::BIvsnprintf:
+case Builtin::BIvscanf:
+case Builtin::BIvfscanf:
+case Builtin::BIvsscanf:
+  break;
+default:
+  return;
+}
+  }
+  }
+
+  Scope *ParentScope = getCurScope() ? getCurScope()->getFnParent() : nullptr;
+  if (!ParentScope)
+return;
+
+  DeclContext *ParentScopeEntity = ParentScope->getEntity();
+  if (!ParentScopeEntity)
+return;
+  if (ParentScopeEntity->getDeclKind() != Decl::Kind::Function)
+return;
+
+  FunctionDecl *ParentFuncDecl = static_cast(ParentScopeEntity);
+  if (!ParentFuncDecl)
+return;
+  if (!ParentFuncDecl->isVariadic())
+return;
+
+  // Iterate through builtin function format attributes. Then check
+  // if parent function has these attributes. If parent function does
+  // not have builtin function format attribut, emit warning.
+  for (const FormatAttr *Attr : FD->specific_attrs()) {
+bool hasFormatAttr = false;
+for (const FormatAttr *ParentAttr :
+ ParentFuncDecl->specific_attrs()) {
+  if (ParentAttr->getType() == Attr->getType()) {
+hasFormatAttr = true;
+break;
+  }
+}
+if (!hasFormatAttr) {
+  Diag(Loc, diag::warn_missing_format_attribute)
+  << ParentFuncDecl << Attr->getType();

aaronpuchert wrote:

Would be cool if we could add a fix-it. There are even ways to find macros that 
wrap the attribute, see the implementation for `-Wimplicit-fallthrough`.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-10-24 Thread Aaron Puchert via cfe-commits


@@ -435,6 +435,86 @@ bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo 
&CI,
   return true;
 }
 
+// Warn if parent function does not have builtin function format attribute.
+void Sema::DiagnoseMissingFormatAttributes(NamedDecl *FDecl,
+   SourceLocation Loc) {
+  if (!FDecl)
+return;
+
+  auto *FD = dyn_cast_or_null(FDecl);
+  if (!FD)
+return;
+
+  unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
+  
+  // Function is not builtin if it's builtin ID is 0.
+  if (!BuiltinID)
+return;
+
+  // Check if function is one with format attribute.
+  switch (BuiltinID) {
+  case Builtin::BIprintf:
+  case Builtin::BIfprintf:
+  case Builtin::BIsprintf:
+  case Builtin::BIscanf:
+  case Builtin::BIfscanf:
+  case Builtin::BIsscanf:
+  case Builtin::BIvprintf:
+  case Builtin::BIvfprintf:
+  case Builtin::BIvsprintf:
+break;
+  default: {
+// In C99 mode check functions below.
+if (!getLangOpts().C99)
+  return;
+switch (BuiltinID) {
+case Builtin::BIsnprintf:
+case Builtin::BIvsnprintf:
+case Builtin::BIvscanf:
+case Builtin::BIvfscanf:
+case Builtin::BIvsscanf:
+  break;
+default:
+  return;
+}
+  }
+  }
+
+  Scope *ParentScope = getCurScope() ? getCurScope()->getFnParent() : nullptr;
+  if (!ParentScope)
+return;
+
+  DeclContext *ParentScopeEntity = ParentScope->getEntity();
+  if (!ParentScopeEntity)
+return;
+  if (ParentScopeEntity->getDeclKind() != Decl::Kind::Function)
+return;
+
+  FunctionDecl *ParentFuncDecl = static_cast(ParentScopeEntity);
+  if (!ParentFuncDecl)
+return;
+  if (!ParentFuncDecl->isVariadic())
+return;
+
+  // Iterate through builtin function format attributes. Then check
+  // if parent function has these attributes. If parent function does
+  // not have builtin function format attribut, emit warning.
+  for (const FormatAttr *Attr : FD->specific_attrs()) {
+bool hasFormatAttr = false;
+for (const FormatAttr *ParentAttr :
+ ParentFuncDecl->specific_attrs()) {
+  if (ParentAttr->getType() == Attr->getType()) {
+hasFormatAttr = true;
+break;
+  }
+}

aaronpuchert wrote:

Seems like you could use `llvm::any_of`.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-10-24 Thread Aaron Puchert via cfe-commits


@@ -435,6 +435,86 @@ bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo 
&CI,
   return true;
 }
 
+// Warn if parent function does not have builtin function format attribute.
+void Sema::DiagnoseMissingFormatAttributes(NamedDecl *FDecl,
+   SourceLocation Loc) {
+  if (!FDecl)
+return;
+
+  auto *FD = dyn_cast_or_null(FDecl);
+  if (!FD)
+return;
+
+  unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
+  
+  // Function is not builtin if it's builtin ID is 0.
+  if (!BuiltinID)
+return;

aaronpuchert wrote:

What about calling a regular function that also has a `format` attribute? The 
GCC warning catches that as well.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-10-24 Thread Aaron Puchert via cfe-commits


@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wmissing-format-attribute %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c99 -Wmissing-format-attribute %s
+
+#include 
+#include 
+
+va_list args;

aaronpuchert wrote:

This should be in the function body together with `va_start`.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-10-24 Thread Aaron Puchert via cfe-commits


@@ -435,6 +435,86 @@ bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo 
&CI,
   return true;
 }
 
+// Warn if parent function does not have builtin function format attribute.
+void Sema::DiagnoseMissingFormatAttributes(NamedDecl *FDecl,
+   SourceLocation Loc) {
+  if (!FDecl)
+return;
+
+  auto *FD = dyn_cast_or_null(FDecl);
+  if (!FD)
+return;
+
+  unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
+  
+  // Function is not builtin if it's builtin ID is 0.
+  if (!BuiltinID)
+return;
+
+  // Check if function is one with format attribute.
+  switch (BuiltinID) {
+  case Builtin::BIprintf:
+  case Builtin::BIfprintf:
+  case Builtin::BIsprintf:
+  case Builtin::BIscanf:
+  case Builtin::BIfscanf:
+  case Builtin::BIsscanf:
+  case Builtin::BIvprintf:
+  case Builtin::BIvfprintf:
+  case Builtin::BIvsprintf:
+break;
+  default: {
+// In C99 mode check functions below.
+if (!getLangOpts().C99)
+  return;
+switch (BuiltinID) {
+case Builtin::BIsnprintf:
+case Builtin::BIvsnprintf:
+case Builtin::BIvscanf:
+case Builtin::BIvfscanf:
+case Builtin::BIvsscanf:
+  break;
+default:
+  return;
+}
+  }
+  }
+
+  Scope *ParentScope = getCurScope() ? getCurScope()->getFnParent() : nullptr;
+  if (!ParentScope)
+return;
+
+  DeclContext *ParentScopeEntity = ParentScope->getEntity();
+  if (!ParentScopeEntity)
+return;
+  if (ParentScopeEntity->getDeclKind() != Decl::Kind::Function)
+return;
+
+  FunctionDecl *ParentFuncDecl = static_cast(ParentScopeEntity);
+  if (!ParentFuncDecl)
+return;
+  if (!ParentFuncDecl->isVariadic())
+return;

aaronpuchert wrote:

Couldn't we use `getCurFunctionDecl`?

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-10-24 Thread Aaron Puchert via cfe-commits


@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wmissing-format-attribute %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c99 -Wmissing-format-attribute %s
+
+#include 
+#include 
+
+va_list args;
+
+__attribute__((__format__ (__scanf__, 1, 4)))
+void foo(char *out, const size_t len, const char *format, ... /* args */)
+{
+vsnprintf(out, len, format, args); // expected-warning {{Function 'foo' 
might be candidate for 'printf' format attribute}}

aaronpuchert wrote:

Add a test where we're calling the function with non-argument format string and 
variadic arguments. Then the warning should not be emitted. Not sure about 
mixing argument format string and non-argument variadic arguments and the other 
way around, but these should probably not warn either, since we can't propagate 
the attribute.

Also where we're taking a `va_list` as argument and forwarding that. This 
should also warn.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-10-24 Thread Aaron Puchert via cfe-commits

https://github.com/aaronpuchert commented:

I assume this is meant to imitate the GCC warning of the same name, which I 
found pretty useful. Would be nice to have the same in Clang!

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-10-24 Thread Aaron Puchert via cfe-commits


@@ -435,6 +435,86 @@ bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo 
&CI,
   return true;
 }
 
+// Warn if parent function does not have builtin function format attribute.
+void Sema::DiagnoseMissingFormatAttributes(NamedDecl *FDecl,
+   SourceLocation Loc) {
+  if (!FDecl)
+return;
+
+  auto *FD = dyn_cast_or_null(FDecl);
+  if (!FD)
+return;

aaronpuchert wrote:

Unless I'm missing something, the only caller is already passing a non-null 
`FunctionDecl`.
```suggestion
void Sema::DiagnoseMissingFormatAttributes(FunctionDecl *FD,
   SourceLocation Loc) {
```

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-10-24 Thread Aaron Puchert via cfe-commits

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


[clang] [libc++] Implement ranges::iota (PR #68494)

2023-10-24 Thread James E T Smith via cfe-commits

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


[clang-tools-extra] [libc++] Implement ranges::iota (PR #68494)

2023-10-24 Thread James E T Smith via cfe-commits

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


[clang] [libc++] Implement ranges::iota (PR #68494)

2023-10-24 Thread James E T Smith via cfe-commits


@@ -0,0 +1,54 @@
+// -*- 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 _LIBCPP___NUMERIC_RANGES_IOTA_H
+#define _LIBCPP___NUMERIC_RANGES_IOTA_H
+
+#include <__algorithm/out_value_result.h>
+#include <__config>
+#include <__ranges/concepts.h>
+#include <__utility/as_const.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 23
+namespace ranges {
+template 
+using iota_result = ranges::out_value_result<_Out, _Tp>;
+
+struct __iota_fn {
+  template  _Sent, 
weakly_incrementable _Tp>
+requires indirectly_writable<_Out, const _Tp&>
+  constexpr iota_result<_Out, _Tp> operator()(_Out __first, _Sent __last, _Tp 
__value) const {

jamesETsmith wrote:

@philnik777, I'm happy to make these changes, but could you explain why 
`static` is more appropriate than `const` here?

As an alternative, after I've added the helper function, I could make that 
static and leave the public functions as `const` like it says in the original 
paper. I stumbled on this strategy (it's used by `ranges::for_each` and 
`ranges::generate` at least) while looking at how other libcxx helper functions 
were structured.

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


[clang-tools-extra] [libc++] Implement ranges::iota (PR #68494)

2023-10-24 Thread James E T Smith via cfe-commits


@@ -0,0 +1,54 @@
+// -*- 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 _LIBCPP___NUMERIC_RANGES_IOTA_H
+#define _LIBCPP___NUMERIC_RANGES_IOTA_H
+
+#include <__algorithm/out_value_result.h>
+#include <__config>
+#include <__ranges/concepts.h>
+#include <__utility/as_const.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 23
+namespace ranges {
+template 
+using iota_result = ranges::out_value_result<_Out, _Tp>;
+
+struct __iota_fn {
+  template  _Sent, 
weakly_incrementable _Tp>
+requires indirectly_writable<_Out, const _Tp&>
+  constexpr iota_result<_Out, _Tp> operator()(_Out __first, _Sent __last, _Tp 
__value) const {

jamesETsmith wrote:

@philnik777, I'm happy to make these changes, but could you explain why 
`static` is more appropriate than `const` here?

As an alternative, after I've added the helper function, I could make that 
static and leave the public functions as `const` like it says in the original 
paper. I stumbled on this strategy (it's used by `ranges::for_each` and 
`ranges::generate` at least) while looking at how other libcxx helper functions 
were structured.

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


[clang] [AArch64] Stack probing for function prologues (PR #66524)

2023-10-24 Thread Oskar Wirga via cfe-commits

oskarwirga wrote:

> Upon function entry the caller guarantees that it has probed the stack (e.g. 
> performed a store) at some address [sp, #N], where0 <= N <= 1024.

I haven't been able to produce a minimal, sharable example as of yet, but I'm 
encountering a runtime error associated with an inlined function where stack 
probing is active. The error manifests as a null pointer dereference, 
originating from a stack value that is probed (and set to 0) before being 
subsequently dereferenced.

The IR contributing to this runtime issue is somewhat complex and challenging 
to interpret, but here's my observations:

- A value returned from `malloc(some_struct)` is stored in a stack variable.
- This stack variable is passed as an argument to a function.
- This function is later inlined, and within the inlined body, it attempts to 
set a value in the struct.
- At runtime, when setting the value we get a null pointer dereference.

I'm working to isolate this issue and will share a repro ASAP. In the meantime, 
any insights or suggestions based on this description would be greatly 
appreciated.

Also is it required to write to the value? Would reading the value be 
sufficient?

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


[clang] [Clang] Ensure zero-init is not overridden when initializing a base class in a constant expression context (PR #70150)

2023-10-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Shafik Yaghmour (shafik)


Changes

During constant evaluation when value-initializing a class if the base class 
was default-initialized it would undue the previously zero-initialized class 
members. This fixes the way we handle default initialization to avoid 
initializing over an already initialized member to an indeterminate value.

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

---
Full diff: https://github.com/llvm/llvm-project/pull/70150.diff


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+4) 
- (modified) clang/lib/AST/ExprConstant.cpp (+20-13) 
- (added) clang/test/CXX/dcl.decl/dcl.init/dcl.init.general/p16-cxx20.cpp (+18) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a063733e96cb74c..ae2f082ad323a78 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -622,6 +622,10 @@ Bug Fixes to C++ Support
   (`#46200 `_)
   (`#57812 `_)
 
+- Fix bug where we were overriding zero-initialization of class members when
+  default initializing a base class in a constant expression context. Fixes:
+  (`#69890 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 6b47b8a1256477d..eea0827d6f7a8a1 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4872,8 +4872,13 @@ static bool HandleBaseToDerivedCast(EvalInfo &Info, 
const CastExpr *E,
 
 /// Get the value to use for a default-initialized object of type T.
 /// Return false if it encounters something invalid.
-static bool getDefaultInitValue(QualType T, APValue &Result) {
+static bool handleDefaultInitValue(QualType T, APValue &Result) {
   bool Success = true;
+
+  // If there is already a value present don't overwrite it.
+  if (!Result.isAbsent())
+return true;
+
   if (auto *RD = T->getAsCXXRecordDecl()) {
 if (RD->isInvalidDecl()) {
   Result = APValue();
@@ -4890,13 +4895,14 @@ static bool getDefaultInitValue(QualType T, APValue 
&Result) {
 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
   End = RD->bases_end();
  I != End; ++I, ++Index)
-  Success &= getDefaultInitValue(I->getType(), 
Result.getStructBase(Index));
+  Success &=
+  handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
 
 for (const auto *I : RD->fields()) {
   if (I->isUnnamedBitfield())
 continue;
-  Success &= getDefaultInitValue(I->getType(),
- 
Result.getStructField(I->getFieldIndex()));
+  Success &= handleDefaultInitValue(
+  I->getType(), Result.getStructField(I->getFieldIndex()));
 }
 return Success;
   }
@@ -4906,7 +4912,7 @@ static bool getDefaultInitValue(QualType T, APValue 
&Result) {
 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
 if (Result.hasArrayFiller())
   Success &=
-  getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
+  handleDefaultInitValue(AT->getElementType(), 
Result.getArrayFiller());
 
 return Success;
   }
@@ -4947,7 +4953,7 @@ static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl 
*VD) {
   if (!InitE) {
 if (VD->getType()->isDependentType())
   return Info.noteSideEffect();
-return getDefaultInitValue(VD->getType(), Val);
+return handleDefaultInitValue(VD->getType(), Val);
   }
   if (InitE->isValueDependent())
 return false;
@@ -6049,7 +6055,7 @@ struct StartLifetimeOfUnionMemberHandler {
   return false;
 }
 APValue Result;
-Failed = !getDefaultInitValue(Field->getType(), Result);
+Failed = !handleDefaultInitValue(Field->getType(), Result);
 Subobj.setUnion(Field, Result);
 return true;
   }
@@ -6401,7 +6407,7 @@ static bool HandleConstructorCall(const Expr *E, const 
LValue &This,
 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
   assert(FieldIt != RD->field_end() && "missing field?");
   if (!FieldIt->isUnnamedBitfield())
-Success &= getDefaultInitValue(
+Success &= handleDefaultInitValue(
 FieldIt->getType(),
 Result.getStructField(FieldIt->getFieldIndex()));
 }
@@ -6458,7 +6464,8 @@ static bool HandleConstructorCall(const Expr *E, const 
LValue &This,
 // FIXME: This immediately starts the lifetime of all members of
 // an anonymous struct. It would be preferable to strictly start
 // member lifetime in initialization order.
-Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
+Success &=
+ha

[clang] [Clang] Ensure zero-init is not overridden when initializing a base class in a constant expression context (PR #70150)

2023-10-24 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik created 
https://github.com/llvm/llvm-project/pull/70150

During constant evaluation when value-initializing a class if the base class 
was default-initialized it would undue the previously zero-initialized class 
members. This fixes the way we handle default initialization to avoid 
initializing over an already initialized member to an indeterminate value.

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

>From 54190bf0805df23037bbe2929282c958d609375f Mon Sep 17 00:00:00 2001
From: Shafik Yaghmour 
Date: Tue, 24 Oct 2023 16:21:30 -0700
Subject: [PATCH] [Clang] Ensure zero-init is not overridden when intializing a
 base class in a constant expression context

During constant evaluation when value-initializing a class if the base class
was default-initialized it would undue the previously zero-initialized class
members. This fixes the way we handle default initialzation to avoid
initializing over an already initialized member to an indeterminate value.

Fixes: https://github.com/llvm/llvm-project/issues/69890
---
 clang/docs/ReleaseNotes.rst   |  4 +++
 clang/lib/AST/ExprConstant.cpp| 33 +++
 .../dcl.init/dcl.init.general/p16-cxx20.cpp   | 18 ++
 3 files changed, 42 insertions(+), 13 deletions(-)
 create mode 100644 
clang/test/CXX/dcl.decl/dcl.init/dcl.init.general/p16-cxx20.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a063733e96cb74c..ae2f082ad323a78 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -622,6 +622,10 @@ Bug Fixes to C++ Support
   (`#46200 `_)
   (`#57812 `_)
 
+- Fix bug where we were overriding zero-initialization of class members when
+  default initializing a base class in a constant expression context. Fixes:
+  (`#69890 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 6b47b8a1256477d..eea0827d6f7a8a1 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4872,8 +4872,13 @@ static bool HandleBaseToDerivedCast(EvalInfo &Info, 
const CastExpr *E,
 
 /// Get the value to use for a default-initialized object of type T.
 /// Return false if it encounters something invalid.
-static bool getDefaultInitValue(QualType T, APValue &Result) {
+static bool handleDefaultInitValue(QualType T, APValue &Result) {
   bool Success = true;
+
+  // If there is already a value present don't overwrite it.
+  if (!Result.isAbsent())
+return true;
+
   if (auto *RD = T->getAsCXXRecordDecl()) {
 if (RD->isInvalidDecl()) {
   Result = APValue();
@@ -4890,13 +4895,14 @@ static bool getDefaultInitValue(QualType T, APValue 
&Result) {
 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
   End = RD->bases_end();
  I != End; ++I, ++Index)
-  Success &= getDefaultInitValue(I->getType(), 
Result.getStructBase(Index));
+  Success &=
+  handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
 
 for (const auto *I : RD->fields()) {
   if (I->isUnnamedBitfield())
 continue;
-  Success &= getDefaultInitValue(I->getType(),
- 
Result.getStructField(I->getFieldIndex()));
+  Success &= handleDefaultInitValue(
+  I->getType(), Result.getStructField(I->getFieldIndex()));
 }
 return Success;
   }
@@ -4906,7 +4912,7 @@ static bool getDefaultInitValue(QualType T, APValue 
&Result) {
 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
 if (Result.hasArrayFiller())
   Success &=
-  getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
+  handleDefaultInitValue(AT->getElementType(), 
Result.getArrayFiller());
 
 return Success;
   }
@@ -4947,7 +4953,7 @@ static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl 
*VD) {
   if (!InitE) {
 if (VD->getType()->isDependentType())
   return Info.noteSideEffect();
-return getDefaultInitValue(VD->getType(), Val);
+return handleDefaultInitValue(VD->getType(), Val);
   }
   if (InitE->isValueDependent())
 return false;
@@ -6049,7 +6055,7 @@ struct StartLifetimeOfUnionMemberHandler {
   return false;
 }
 APValue Result;
-Failed = !getDefaultInitValue(Field->getType(), Result);
+Failed = !handleDefaultInitValue(Field->getType(), Result);
 Subobj.setUnion(Field, Result);
 return true;
   }
@@ -6401,7 +6407,7 @@ static bool HandleConstructorCall(const Expr *E, const 
LValue &This,
 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
   assert(FieldIt != RD->field_end() && "missing field?");
   

[clang] [clang][NFC] Assert not llvm_unreachable (PR #70149)

2023-10-24 Thread Nathan Sidwell via cfe-commits

https://github.com/urnathan created 
https://github.com/llvm/llvm-project/pull/70149

An assert is better here.

>From 1120a9bd5490dba672898f6902e60e461792b711 Mon Sep 17 00:00:00 2001
From: Nathan Sidwell 
Date: Tue, 24 Oct 2023 20:20:18 -0400
Subject: [PATCH] [clang][NFC] Assert not llvm_unreachable

An assert is better here.
---
 clang/lib/CodeGen/CGExprScalar.cpp | 9 -
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index c25ddeff9adc3a7..7633c6b17db88eb 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -2084,11 +2084,10 @@ Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
 Value *Src = Visit(const_cast(E));
 llvm::Type *SrcTy = Src->getType();
 llvm::Type *DstTy = ConvertType(DestTy);
-if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
-SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
-  llvm_unreachable("wrong cast for pointers in different address spaces"
-   "(must be an address space cast)!");
-}
+assert(
+(!SrcTy->isPtrOrPtrVectorTy() || !DstTy->isPtrOrPtrVectorTy() ||
+ SrcTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace()) &&
+"Address-space cast must be used to convert address spaces");
 
 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
   if (auto *PT = DestTy->getAs()) {

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


[clang] [clang][deps] Fix `__has_include` behavior with umbrella headers (PR #70144)

2023-10-24 Thread Ben Langmuir via cfe-commits

https://github.com/benlangmuir commented:

Can you clarify how this bug occurs in terms of what information about the 
header is stored that causes us to get the wrong module? It seems bad that 
passing `nullptr` to `LookupFile` could cause incorrect behaviour and makes me 
wonder if we need to always trigger module lookup or if there is another way to 
fix this that would make it safe to not do module lookup here.

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


[clang] [Offloading][NFC] Move creation of offloading entries from OpenMP (PR #70116)

2023-10-24 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

> Can this stuff really be generic?

Obviously flags are going to be target dependent, but the actual form, 
generation, and iteration of these can be generic. The idea is to put them all 
into a single section such that we can filter out the ones that apply to 
whatever runtime so they can all live in the same section and re-use all the 
same code.

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


[clang] [Offloading][NFC] Move creation of offloading entries from OpenMP (PR #70116)

2023-10-24 Thread Shilei Tian via cfe-commits

shiltian wrote:

Can this stuff really be generic?

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


[clang] [clang][deps] Fix `__has_include` behavior with umbrella headers (PR #70144)

2023-10-24 Thread Jan Svoboda via cfe-commits

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


[clang] [clang][deps] Fix `__has_include` behavior with umbrella headers (PR #70144)

2023-10-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Jan Svoboda (jansvoboda11)


Changes

Previously, Clang wouldn't try to resolve the module for the header being 
checked via `__has_include`. This meant that such header was considered textual 
(a.k.a. part of the module Clang is currently compiling).


---
Full diff: https://github.com/llvm/llvm-project/pull/70144.diff


2 Files Affected:

- (modified) clang/lib/Lex/PPMacroExpansion.cpp (+6-1) 
- (added) clang/test/ClangScanDeps/modules-has-include-umbrella-header.c (+99) 


``diff
diff --git a/clang/lib/Lex/PPMacroExpansion.cpp 
b/clang/lib/Lex/PPMacroExpansion.cpp
index b371f8cf7a9c072..30c4abdbad8aa44 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -1248,10 +1248,15 @@ static bool EvaluateHasIncludeCommon(Token &Tok, 
IdentifierInfo *II,
   if (Filename.empty())
 return false;
 
+  // Passing this to LookupFile forces header search to check whether the found
+  // file belongs to a module. Skipping that check could incorrectly mark
+  // modular header as textual, causing issues down the line.
+  ModuleMap::KnownHeader KH;
+
   // Search include directories.
   OptionalFileEntryRef File =
   PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, 
LookupFromFile,
-nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
+nullptr, nullptr, nullptr, &KH, nullptr, nullptr);
 
   if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
 SrcMgr::CharacteristicKind FileType = SrcMgr::C_User;
diff --git a/clang/test/ClangScanDeps/modules-has-include-umbrella-header.c 
b/clang/test/ClangScanDeps/modules-has-include-umbrella-header.c
new file mode 100644
index 000..45ff2bd3b9cd24e
--- /dev/null
+++ b/clang/test/ClangScanDeps/modules-has-include-umbrella-header.c
@@ -0,0 +1,99 @@
+// This test checks that __has_include() in a module does
+// not clobber #include  in importers of said module.
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+//--- cdb.json.template
+[{
+  "file": "DIR/tu.c",
+  "directory": "DIR",
+  "command": "clang DIR/tu.c -fmodules -fmodules-cache-path=DIR/cache -I 
DIR/modules -F DIR/frameworks -o DIR/tu.o"
+}]
+
+//--- frameworks/FW.framework/Modules/module.private.modulemap
+framework module FW_Private {
+  umbrella header "A.h"
+  module * { export * }
+}
+//--- frameworks/FW.framework/PrivateHeaders/A.h
+#include 
+//--- frameworks/FW.framework/PrivateHeaders/B.h
+struct B {};
+
+//--- modules/module.modulemap
+module Foo { header "foo.h" }
+//--- modules/foo.h
+#if __has_include()
+#define HAS_B 1
+#else
+#define HAS_B 0
+#endif
+
+//--- tu.c
+#include "foo.h"
+#include 
+
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full > %t/deps.json
+// RUN: cat %t/deps.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%t
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/frameworks/FW.framework/Modules/module.private.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: 
"[[PREFIX]]/frameworks/FW.framework/Modules/module.private.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/frameworks/FW.framework/PrivateHeaders/A.h",
+// CHECK-NEXT: "[[PREFIX]]/frameworks/FW.framework/PrivateHeaders/B.h"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "FW_Private"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/modules/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK:  
"-fmodule-map-file=[[PREFIX]]/frameworks/FW.framework/Modules/module.private.modulemap",
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// FIXME: The frameworks/FW.framework/PrivateHeaders/B.h header never makes it 
into SourceManager,
+//so we don't track it as a file dependency (even though we should).
+// CHECK-NEXT: 
"[[PREFIX]]/frameworks/FW.framework/Modules/module.private.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/modules/foo.h",
+// CHECK-NEXT: "[[PREFIX]]/modules/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "Foo"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "translation-units": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "commands": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-context-hash": "{{.*}}",
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "module-name": "FW_Private"
+// CHECK-NEXT: 

[clang] [clang][deps] Fix `__has_include` behavior with umbrella headers (PR #70144)

2023-10-24 Thread Jan Svoboda via cfe-commits

https://github.com/jansvoboda11 created 
https://github.com/llvm/llvm-project/pull/70144

Previously, Clang wouldn't try to resolve the module for the header being 
checked via `__has_include`. This meant that such header was considered textual 
(a.k.a. part of the module Clang is currently compiling).


>From 4199b80e5cb0a8873f63c356e4c4304833d6fffa Mon Sep 17 00:00:00 2001
From: Jan Svoboda 
Date: Tue, 24 Oct 2023 16:30:22 -0700
Subject: [PATCH] [clang][deps] Fix `__has_include` behavior with umbrella
 headers

Previously, Clang wouldn't try to resolve the module for the header being 
checked via `__has_include`. This meant that such header was considered textual 
(a.k.a. part of the module Clang is currently compiling).
---
 clang/lib/Lex/PPMacroExpansion.cpp|  7 +-
 .../modules-has-include-umbrella-header.c | 99 +++
 2 files changed, 105 insertions(+), 1 deletion(-)
 create mode 100644 
clang/test/ClangScanDeps/modules-has-include-umbrella-header.c

diff --git a/clang/lib/Lex/PPMacroExpansion.cpp 
b/clang/lib/Lex/PPMacroExpansion.cpp
index b371f8cf7a9c072..30c4abdbad8aa44 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -1248,10 +1248,15 @@ static bool EvaluateHasIncludeCommon(Token &Tok, 
IdentifierInfo *II,
   if (Filename.empty())
 return false;
 
+  // Passing this to LookupFile forces header search to check whether the found
+  // file belongs to a module. Skipping that check could incorrectly mark
+  // modular header as textual, causing issues down the line.
+  ModuleMap::KnownHeader KH;
+
   // Search include directories.
   OptionalFileEntryRef File =
   PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, 
LookupFromFile,
-nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
+nullptr, nullptr, nullptr, &KH, nullptr, nullptr);
 
   if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
 SrcMgr::CharacteristicKind FileType = SrcMgr::C_User;
diff --git a/clang/test/ClangScanDeps/modules-has-include-umbrella-header.c 
b/clang/test/ClangScanDeps/modules-has-include-umbrella-header.c
new file mode 100644
index 000..45ff2bd3b9cd24e
--- /dev/null
+++ b/clang/test/ClangScanDeps/modules-has-include-umbrella-header.c
@@ -0,0 +1,99 @@
+// This test checks that __has_include() in a module does
+// not clobber #include  in importers of said module.
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+//--- cdb.json.template
+[{
+  "file": "DIR/tu.c",
+  "directory": "DIR",
+  "command": "clang DIR/tu.c -fmodules -fmodules-cache-path=DIR/cache -I 
DIR/modules -F DIR/frameworks -o DIR/tu.o"
+}]
+
+//--- frameworks/FW.framework/Modules/module.private.modulemap
+framework module FW_Private {
+  umbrella header "A.h"
+  module * { export * }
+}
+//--- frameworks/FW.framework/PrivateHeaders/A.h
+#include 
+//--- frameworks/FW.framework/PrivateHeaders/B.h
+struct B {};
+
+//--- modules/module.modulemap
+module Foo { header "foo.h" }
+//--- modules/foo.h
+#if __has_include()
+#define HAS_B 1
+#else
+#define HAS_B 0
+#endif
+
+//--- tu.c
+#include "foo.h"
+#include 
+
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full > %t/deps.json
+// RUN: cat %t/deps.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%t
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/frameworks/FW.framework/Modules/module.private.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: 
"[[PREFIX]]/frameworks/FW.framework/Modules/module.private.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/frameworks/FW.framework/PrivateHeaders/A.h",
+// CHECK-NEXT: "[[PREFIX]]/frameworks/FW.framework/PrivateHeaders/B.h"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "FW_Private"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/modules/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK:  
"-fmodule-map-file=[[PREFIX]]/frameworks/FW.framework/Modules/module.private.modulemap",
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// FIXME: The frameworks/FW.framework/PrivateHeaders/B.h header never makes it 
into SourceManager,
+//so we don't track it as a file dependency (even though we should).
+// CHECK-NEXT: 
"[[PREFIX]]/frameworks/FW.framework/Modules/module.private.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/modules/foo.h",
+// CHECK-NEXT: "[[PREFIX]]/modules/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "Foo

[clang] [Offloading][NFC] Move creation of offloading entries from OpenMP (PR #70116)

2023-10-24 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/70116

>From 8add2113864618d310e01bdbb0cf16e1847eb9a8 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Tue, 24 Oct 2023 15:27:21 -0500
Subject: [PATCH] [Offloading][NFC] Move creation of offloading entries from
 OpenMP

Summary:
This patch is a first step to remove dependencies on the OpenMPIRBuilder
for creating generic offloading entires. This patch changes no
functionality and merely moves the code around. In the future the
interface will be changed to allow for more code re-use in the
registeration and creation of offloading entries as well as a more
generic interface for CUDA, HIP, OpenMP, and SYCL(?). Doing this as a
first step to reduce the noise involved in the functional changes.
---
 clang/lib/CodeGen/CGCUDANV.cpp| 28 +++
 clang/lib/CodeGen/CMakeLists.txt  |  1 +
 .../llvm/Frontend/Offloading/Utility.h| 37 +
 .../llvm/Frontend/OpenMP/OMPIRBuilder.h   | 21 -
 .../include/llvm/Frontend/OpenMP/OMPKinds.def |  2 -
 llvm/lib/Frontend/CMakeLists.txt  |  1 +
 llvm/lib/Frontend/Offloading/CMakeLists.txt   | 14 
 llvm/lib/Frontend/Offloading/Utility.cpp  | 78 +++
 llvm/lib/Frontend/OpenMP/CMakeLists.txt   |  1 +
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp | 43 +-
 10 files changed, 150 insertions(+), 76 deletions(-)
 create mode 100644 llvm/include/llvm/Frontend/Offloading/Utility.h
 create mode 100644 llvm/lib/Frontend/Offloading/CMakeLists.txt
 create mode 100644 llvm/lib/Frontend/Offloading/Utility.cpp

diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp
index 8a1212f2272e87a..2ef4dc236d091b0 100644
--- a/clang/lib/CodeGen/CGCUDANV.cpp
+++ b/clang/lib/CodeGen/CGCUDANV.cpp
@@ -19,6 +19,7 @@
 #include "clang/Basic/Cuda.h"
 #include "clang/CodeGen/CodeGenABITypes.h"
 #include "clang/CodeGen/ConstantInitBuilder.h"
+#include "llvm/Frontend/Offloading/Utility.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DerivedTypes.h"
@@ -1129,33 +1130,32 @@ void CGNVCUDARuntime::transformManagedVars() {
 // registered. The linker will provide a pointer to this section so we can
 // register the symbols with the linked device image.
 void CGNVCUDARuntime::createOffloadingEntries() {
-  llvm::OpenMPIRBuilder OMPBuilder(CGM.getModule());
-  OMPBuilder.initialize();
-
   StringRef Section = CGM.getLangOpts().HIP ? "hip_offloading_entries"
 : "cuda_offloading_entries";
+  llvm::Module &M = CGM.getModule();
   for (KernelInfo &I : EmittedKernels)
-OMPBuilder.emitOffloadingEntry(KernelHandles[I.Kernel->getName()],
-   getDeviceSideName(cast(I.D)), 0,
-   DeviceVarFlags::OffloadGlobalEntry, 
Section);
+llvm::offloading::emitOffloadingEntry(
+M, KernelHandles[I.Kernel->getName()],
+getDeviceSideName(cast(I.D)), 0,
+DeviceVarFlags::OffloadGlobalEntry, Section);
 
   for (VarInfo &I : DeviceVars) {
 uint64_t VarSize =
 CGM.getDataLayout().getTypeAllocSize(I.Var->getValueType());
 if (I.Flags.getKind() == DeviceVarFlags::Variable) {
-  OMPBuilder.emitOffloadingEntry(
-  I.Var, getDeviceSideName(I.D), VarSize,
+  llvm::offloading::emitOffloadingEntry(
+  M, I.Var, getDeviceSideName(I.D), VarSize,
   I.Flags.isManaged() ? DeviceVarFlags::OffloadGlobalManagedEntry
   : DeviceVarFlags::OffloadGlobalEntry,
   Section);
 } else if (I.Flags.getKind() == DeviceVarFlags::Surface) {
-  OMPBuilder.emitOffloadingEntry(I.Var, getDeviceSideName(I.D), VarSize,
- DeviceVarFlags::OffloadGlobalSurfaceEntry,
- Section);
+  llvm::offloading::emitOffloadingEntry(
+  M, I.Var, getDeviceSideName(I.D), VarSize,
+  DeviceVarFlags::OffloadGlobalSurfaceEntry, Section);
 } else if (I.Flags.getKind() == DeviceVarFlags::Texture) {
-  OMPBuilder.emitOffloadingEntry(I.Var, getDeviceSideName(I.D), VarSize,
- DeviceVarFlags::OffloadGlobalTextureEntry,
- Section);
+  llvm::offloading::emitOffloadingEntry(
+  M, I.Var, getDeviceSideName(I.D), VarSize,
+  DeviceVarFlags::OffloadGlobalTextureEntry, Section);
 }
   }
 }
diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt
index d67ce982d78acf3..da98848e3b44387 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -11,6 +11,7 @@ set(LLVM_LINK_COMPONENTS
   Extensions
   FrontendHLSL
   FrontendOpenMP
+  FrontendOffloading
   HIPStdPar
   IPO
   IRPrinter
diff --git a/llvm/include/llvm/Frontend/Offloading/Utility.h 
b/llvm/include/llvm/Frontend/Offloading/Utility.h
new file mode 100644
index 00

[clang] [Offloading][NFC] Move creation of offloading entries from OpenMP (PR #70116)

2023-10-24 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/70116

>From 2af5fc3dc871f0bc3bdfeff4ed2c08f6ccd089d5 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Tue, 24 Oct 2023 15:27:21 -0500
Subject: [PATCH] [Offloading][NFC] Move creation of offloading entries from
 OpenMP

Summary:
This patch is a first step to remove dependencies on the OpenMPIRBuilder
for creating generic offloading entires. This patch changes no
functionality and merely moves the code around. In the future the
interface will be changed to allow for more code re-use in the
registeration and creation of offloading entries as well as a more
generic interface for CUDA, HIP, OpenMP, and SYCL(?). Doing this as a
first step to reduce the noise involved in the functional changes.
---
 clang/lib/CodeGen/CGCUDANV.cpp| 28 +++
 clang/lib/CodeGen/CMakeLists.txt  |  1 +
 .../llvm/Frontend/Offloading/Utility.h| 37 +
 .../llvm/Frontend/OpenMP/OMPIRBuilder.h   | 21 -
 .../include/llvm/Frontend/OpenMP/OMPKinds.def |  2 -
 llvm/lib/Frontend/CMakeLists.txt  |  1 +
 llvm/lib/Frontend/Offloading/CMakeLists.txt   | 14 
 llvm/lib/Frontend/Offloading/Utility.cpp  | 76 +++
 llvm/lib/Frontend/OpenMP/CMakeLists.txt   |  1 +
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp | 43 +--
 10 files changed, 148 insertions(+), 76 deletions(-)
 create mode 100644 llvm/include/llvm/Frontend/Offloading/Utility.h
 create mode 100644 llvm/lib/Frontend/Offloading/CMakeLists.txt
 create mode 100644 llvm/lib/Frontend/Offloading/Utility.cpp

diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp
index 8a1212f2272e87a..2ef4dc236d091b0 100644
--- a/clang/lib/CodeGen/CGCUDANV.cpp
+++ b/clang/lib/CodeGen/CGCUDANV.cpp
@@ -19,6 +19,7 @@
 #include "clang/Basic/Cuda.h"
 #include "clang/CodeGen/CodeGenABITypes.h"
 #include "clang/CodeGen/ConstantInitBuilder.h"
+#include "llvm/Frontend/Offloading/Utility.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DerivedTypes.h"
@@ -1129,33 +1130,32 @@ void CGNVCUDARuntime::transformManagedVars() {
 // registered. The linker will provide a pointer to this section so we can
 // register the symbols with the linked device image.
 void CGNVCUDARuntime::createOffloadingEntries() {
-  llvm::OpenMPIRBuilder OMPBuilder(CGM.getModule());
-  OMPBuilder.initialize();
-
   StringRef Section = CGM.getLangOpts().HIP ? "hip_offloading_entries"
 : "cuda_offloading_entries";
+  llvm::Module &M = CGM.getModule();
   for (KernelInfo &I : EmittedKernels)
-OMPBuilder.emitOffloadingEntry(KernelHandles[I.Kernel->getName()],
-   getDeviceSideName(cast(I.D)), 0,
-   DeviceVarFlags::OffloadGlobalEntry, 
Section);
+llvm::offloading::emitOffloadingEntry(
+M, KernelHandles[I.Kernel->getName()],
+getDeviceSideName(cast(I.D)), 0,
+DeviceVarFlags::OffloadGlobalEntry, Section);
 
   for (VarInfo &I : DeviceVars) {
 uint64_t VarSize =
 CGM.getDataLayout().getTypeAllocSize(I.Var->getValueType());
 if (I.Flags.getKind() == DeviceVarFlags::Variable) {
-  OMPBuilder.emitOffloadingEntry(
-  I.Var, getDeviceSideName(I.D), VarSize,
+  llvm::offloading::emitOffloadingEntry(
+  M, I.Var, getDeviceSideName(I.D), VarSize,
   I.Flags.isManaged() ? DeviceVarFlags::OffloadGlobalManagedEntry
   : DeviceVarFlags::OffloadGlobalEntry,
   Section);
 } else if (I.Flags.getKind() == DeviceVarFlags::Surface) {
-  OMPBuilder.emitOffloadingEntry(I.Var, getDeviceSideName(I.D), VarSize,
- DeviceVarFlags::OffloadGlobalSurfaceEntry,
- Section);
+  llvm::offloading::emitOffloadingEntry(
+  M, I.Var, getDeviceSideName(I.D), VarSize,
+  DeviceVarFlags::OffloadGlobalSurfaceEntry, Section);
 } else if (I.Flags.getKind() == DeviceVarFlags::Texture) {
-  OMPBuilder.emitOffloadingEntry(I.Var, getDeviceSideName(I.D), VarSize,
- DeviceVarFlags::OffloadGlobalTextureEntry,
- Section);
+  llvm::offloading::emitOffloadingEntry(
+  M, I.Var, getDeviceSideName(I.D), VarSize,
+  DeviceVarFlags::OffloadGlobalTextureEntry, Section);
 }
   }
 }
diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt
index d67ce982d78acf3..da98848e3b44387 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -11,6 +11,7 @@ set(LLVM_LINK_COMPONENTS
   Extensions
   FrontendHLSL
   FrontendOpenMP
+  FrontendOffloading
   HIPStdPar
   IPO
   IRPrinter
diff --git a/llvm/include/llvm/Frontend/Offloading/Utility.h 
b/llvm/include/llvm/Frontend/Offloading/Utility.h
new file mode 100644
index 0

[clang] [libc++] Fix the behavior of throwing `operator new` under -fno-exceptions (PR #69498)

2023-10-24 Thread James Y Knight via cfe-commits

jyknight wrote:

I think we can check whether it's been overridden more easily using an asm 
alias like this (when libc++ is built under -fno-exceptions):
```
#include 
#include 

__attribute__((weak)) void* operator new(std::size_t size) {
  void* mem = malloc(size);
  if (!mem) abort();
  return mem;
}

// TODO: ifdef for MSVC mangling.
static void* original_operator_new(std::size_t size) 
__attribute__((alias(__USER_LABEL_PREFIX__ "_Znwm")));

__attribute__((weak)) void* operator new(std::size_t size, std::nothrow_t) 
noexcept {
  if (static_cast(&::operator new) != 
original_operator_new)
abort();
  return malloc(size);
}
```


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


[clang] [CodeLayout] Faster basic block reordering, ext-tsp (PR #68617)

2023-10-24 Thread via cfe-commits

https://github.com/spupyrev updated 
https://github.com/llvm/llvm-project/pull/68617

>From ca0e18230d9b61aa8d65113d2ad0292f3b61c8a0 Mon Sep 17 00:00:00 2001
From: spupyrev 
Date: Thu, 12 Oct 2023 17:32:36 -0700
Subject: [PATCH 1/4] review

---
 llvm/lib/Transforms/Utils/CodeLayout.cpp | 130 +--
 1 file changed, 76 insertions(+), 54 deletions(-)

diff --git a/llvm/lib/Transforms/Utils/CodeLayout.cpp 
b/llvm/lib/Transforms/Utils/CodeLayout.cpp
index dea91dcac21ae14..3f325eaa21a4863 100644
--- a/llvm/lib/Transforms/Utils/CodeLayout.cpp
+++ b/llvm/lib/Transforms/Utils/CodeLayout.cpp
@@ -101,8 +101,8 @@ static cl::opt BackwardDistance(
 // The maximum size of a chain created by the algorithm. The size is bounded
 // so that the algorithm can efficiently process extremely large instances.
 static cl::opt
-MaxChainSize("ext-tsp-max-chain-size", cl::ReallyHidden, cl::init(4096),
- cl::desc("The maximum size of a chain to create."));
+MaxChainSize("ext-tsp-max-chain-size", cl::ReallyHidden, cl::init(512),
+ cl::desc("The maximum size of a chain to create"));
 
 // The maximum size of a chain for splitting. Larger values of the threshold
 // may yield better quality at the cost of worsen run-time.
@@ -110,11 +110,10 @@ static cl::opt ChainSplitThreshold(
 "ext-tsp-chain-split-threshold", cl::ReallyHidden, cl::init(128),
 cl::desc("The maximum size of a chain to apply splitting"));
 
-// The option enables splitting (large) chains along in-coming and out-going
-// jumps. This typically results in a better quality.
-static cl::opt EnableChainSplitAlongJumps(
-"ext-tsp-enable-chain-split-along-jumps", cl::ReallyHidden, cl::init(true),
-cl::desc("The maximum size of a chain to apply splitting"));
+// The maximum ratio between densities of two chains for merging.
+static cl::opt MaxMergeDensityRatio(
+"ext-tsp-max-merge-density-ratio", cl::ReallyHidden, cl::init(100),
+cl::desc("The maximum ratio between densities of two chains for merging"));
 
 // Algorithm-specific options for CDS.
 static cl::opt CacheEntries("cds-cache-entries", cl::ReallyHidden,
@@ -222,6 +221,8 @@ struct NodeT {
 
   bool isEntry() const { return Index == 0; }
 
+  // Check if Other is a successor of the node.
+  bool isSuccessor(const NodeT *Other) const;
   // The total execution count of outgoing jumps.
   uint64_t outCount() const;
 
@@ -285,7 +286,7 @@ struct ChainT {
 
   size_t numBlocks() const { return Nodes.size(); }
 
-  double density() const { return static_cast(ExecutionCount) / Size; }
+  double density() const { return ExecutionCount / Size; }
 
   bool isEntry() const { return Nodes[0]->Index == 0; }
 
@@ -346,8 +347,9 @@ struct ChainT {
   uint64_t Id;
   // Cached ext-tsp score for the chain.
   double Score{0};
-  // The total execution count of the chain.
-  uint64_t ExecutionCount{0};
+  // The total execution count of the chain. Since the execution count of
+  // a basic block is uint64_t, using doubles here to avoid overflow.
+  double ExecutionCount{0};
   // The total size of the chain.
   uint64_t Size{0};
   // Nodes of the chain.
@@ -442,6 +444,14 @@ struct ChainEdge {
   bool CacheValidBackward{false};
 };
 
+bool NodeT::isSuccessor(const NodeT *Other) const {
+  for (JumpT *Jump : OutJumps) {
+if (Jump->Target == Other)
+  return true;
+  }
+  return false;
+}
+
 uint64_t NodeT::outCount() const {
   uint64_t Count = 0;
   for (JumpT *Jump : OutJumps)
@@ -507,8 +517,6 @@ struct MergedNodesT {
 
   const NodeT *getFirstNode() const { return *Begin1; }
 
-  bool empty() const { return Begin1 == End1; }
-
 private:
   NodeIter Begin1;
   NodeIter End1;
@@ -632,7 +640,8 @@ class ExtTSPImpl {
   }
 }
 for (JumpT &Jump : AllJumps) {
-  assert(OutDegree[Jump.Source->Index] > 0);
+  assert(OutDegree[Jump.Source->Index] > 0 &&
+ "incorrectly computed out-degree of the block");
   Jump.IsConditional = OutDegree[Jump.Source->Index] > 1;
 }
 
@@ -725,6 +734,7 @@ class ExtTSPImpl {
   return std::make_tuple(A1->Id, B1->Id) < std::make_tuple(A2->Id, B2->Id);
 };
 
+double PrevScore = 1e9;
 while (HotChains.size() > 1) {
   ChainT *BestChainPred = nullptr;
   ChainT *BestChainSucc = nullptr;
@@ -734,14 +744,25 @@ class ExtTSPImpl {
 // Get candidates for merging with the current chain.
 for (const auto &[ChainSucc, Edge] : ChainPred->Edges) {
   // Ignore loop edges.
-  if (ChainPred == ChainSucc)
+  if (Edge->isSelfEdge())
 continue;
-
   // Stop early if the combined chain violates the maximum allowed 
size.
   if (ChainPred->numBlocks() + ChainSucc->numBlocks() >= MaxChainSize)
 continue;
+  // Don't merge the chains if they have vastly different densities.
+  // We stop early if the ratio between the densities exceeds
+  // MaxMergeDensityRatio. Smaller values of the opt

[clang-tools-extra] [CodeLayout] Faster basic block reordering, ext-tsp (PR #68617)

2023-10-24 Thread via cfe-commits

https://github.com/spupyrev updated 
https://github.com/llvm/llvm-project/pull/68617

>From ca0e18230d9b61aa8d65113d2ad0292f3b61c8a0 Mon Sep 17 00:00:00 2001
From: spupyrev 
Date: Thu, 12 Oct 2023 17:32:36 -0700
Subject: [PATCH 1/4] review

---
 llvm/lib/Transforms/Utils/CodeLayout.cpp | 130 +--
 1 file changed, 76 insertions(+), 54 deletions(-)

diff --git a/llvm/lib/Transforms/Utils/CodeLayout.cpp 
b/llvm/lib/Transforms/Utils/CodeLayout.cpp
index dea91dcac21ae14..3f325eaa21a4863 100644
--- a/llvm/lib/Transforms/Utils/CodeLayout.cpp
+++ b/llvm/lib/Transforms/Utils/CodeLayout.cpp
@@ -101,8 +101,8 @@ static cl::opt BackwardDistance(
 // The maximum size of a chain created by the algorithm. The size is bounded
 // so that the algorithm can efficiently process extremely large instances.
 static cl::opt
-MaxChainSize("ext-tsp-max-chain-size", cl::ReallyHidden, cl::init(4096),
- cl::desc("The maximum size of a chain to create."));
+MaxChainSize("ext-tsp-max-chain-size", cl::ReallyHidden, cl::init(512),
+ cl::desc("The maximum size of a chain to create"));
 
 // The maximum size of a chain for splitting. Larger values of the threshold
 // may yield better quality at the cost of worsen run-time.
@@ -110,11 +110,10 @@ static cl::opt ChainSplitThreshold(
 "ext-tsp-chain-split-threshold", cl::ReallyHidden, cl::init(128),
 cl::desc("The maximum size of a chain to apply splitting"));
 
-// The option enables splitting (large) chains along in-coming and out-going
-// jumps. This typically results in a better quality.
-static cl::opt EnableChainSplitAlongJumps(
-"ext-tsp-enable-chain-split-along-jumps", cl::ReallyHidden, cl::init(true),
-cl::desc("The maximum size of a chain to apply splitting"));
+// The maximum ratio between densities of two chains for merging.
+static cl::opt MaxMergeDensityRatio(
+"ext-tsp-max-merge-density-ratio", cl::ReallyHidden, cl::init(100),
+cl::desc("The maximum ratio between densities of two chains for merging"));
 
 // Algorithm-specific options for CDS.
 static cl::opt CacheEntries("cds-cache-entries", cl::ReallyHidden,
@@ -222,6 +221,8 @@ struct NodeT {
 
   bool isEntry() const { return Index == 0; }
 
+  // Check if Other is a successor of the node.
+  bool isSuccessor(const NodeT *Other) const;
   // The total execution count of outgoing jumps.
   uint64_t outCount() const;
 
@@ -285,7 +286,7 @@ struct ChainT {
 
   size_t numBlocks() const { return Nodes.size(); }
 
-  double density() const { return static_cast(ExecutionCount) / Size; }
+  double density() const { return ExecutionCount / Size; }
 
   bool isEntry() const { return Nodes[0]->Index == 0; }
 
@@ -346,8 +347,9 @@ struct ChainT {
   uint64_t Id;
   // Cached ext-tsp score for the chain.
   double Score{0};
-  // The total execution count of the chain.
-  uint64_t ExecutionCount{0};
+  // The total execution count of the chain. Since the execution count of
+  // a basic block is uint64_t, using doubles here to avoid overflow.
+  double ExecutionCount{0};
   // The total size of the chain.
   uint64_t Size{0};
   // Nodes of the chain.
@@ -442,6 +444,14 @@ struct ChainEdge {
   bool CacheValidBackward{false};
 };
 
+bool NodeT::isSuccessor(const NodeT *Other) const {
+  for (JumpT *Jump : OutJumps) {
+if (Jump->Target == Other)
+  return true;
+  }
+  return false;
+}
+
 uint64_t NodeT::outCount() const {
   uint64_t Count = 0;
   for (JumpT *Jump : OutJumps)
@@ -507,8 +517,6 @@ struct MergedNodesT {
 
   const NodeT *getFirstNode() const { return *Begin1; }
 
-  bool empty() const { return Begin1 == End1; }
-
 private:
   NodeIter Begin1;
   NodeIter End1;
@@ -632,7 +640,8 @@ class ExtTSPImpl {
   }
 }
 for (JumpT &Jump : AllJumps) {
-  assert(OutDegree[Jump.Source->Index] > 0);
+  assert(OutDegree[Jump.Source->Index] > 0 &&
+ "incorrectly computed out-degree of the block");
   Jump.IsConditional = OutDegree[Jump.Source->Index] > 1;
 }
 
@@ -725,6 +734,7 @@ class ExtTSPImpl {
   return std::make_tuple(A1->Id, B1->Id) < std::make_tuple(A2->Id, B2->Id);
 };
 
+double PrevScore = 1e9;
 while (HotChains.size() > 1) {
   ChainT *BestChainPred = nullptr;
   ChainT *BestChainSucc = nullptr;
@@ -734,14 +744,25 @@ class ExtTSPImpl {
 // Get candidates for merging with the current chain.
 for (const auto &[ChainSucc, Edge] : ChainPred->Edges) {
   // Ignore loop edges.
-  if (ChainPred == ChainSucc)
+  if (Edge->isSelfEdge())
 continue;
-
   // Stop early if the combined chain violates the maximum allowed 
size.
   if (ChainPred->numBlocks() + ChainSucc->numBlocks() >= MaxChainSize)
 continue;
+  // Don't merge the chains if they have vastly different densities.
+  // We stop early if the ratio between the densities exceeds
+  // MaxMergeDensityRatio. Smaller values of the opt

[clang] [clang-format] unexpected break after binOp '<<' (PR #69859)

2023-10-24 Thread Tsarkov Maksim via cfe-commits

s1Sharp wrote:

yes, issue with breaking after << is gone. I want to get your point about 
functionality clang-format and implementing new option such as 
"BreakAfterStreamOperator". As i can see, @HazardyKnusperkeks you agree with 
"owenca" point?

May be i can do something with this feature

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


[clang] [Profile] Refactor profile correlation. (PR #69656)

2023-10-24 Thread Ellis Hoag via cfe-commits


@@ -55,6 +56,7 @@
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/TargetParser/SubtargetFeature.h"
 #include "llvm/TargetParser/Triple.h"
+#include "llvm/Transforms/HipStdPar/HipStdPar.h"

ellishg wrote:

Is this include used?

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


[clang] [Profile] Refactor profile correlation. (PR #69656)

2023-10-24 Thread Ellis Hoag via cfe-commits


@@ -24,15 +24,38 @@
 
 using namespace llvm;
 
-/// Get the __llvm_prf_cnts section.
-Expected getCountersSection(const object::ObjectFile &Obj) 
{
+namespace llvm {
+// Deprecated. Use -profile-correlate=debug-info.
+cl::opt DebugInfoCorrelate(
+"debug-info-correlate",
+cl::desc("Use debug info to correlate profiles (Deprecated). Use "
+ "-profile-correlate=debug-info instead."),
+cl::init(false));
+
+cl::opt ProfileCorrelate(
+"profile-correlate",
+cl::desc("Use debug info or binary file to correlate profiles."),
+cl::init(InstrProfCorrelator::NONE),
+cl::values(clEnumValN(InstrProfCorrelator::NONE, "",
+  "No profile correlation"),
+   clEnumValN(InstrProfCorrelator::DEBUG_INFO, "debug-info",
+  "Use debug info to correlate")));

ellishg wrote:

This patch moves these options from `InstrProfiling.cpp` to 
`InstrProfCorrelator.cpp`, but this file doesn't actually use these flags. Is 
there any reason why we can't keep the flags in `InstrProfiling.cpp`?

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


[clang] Dfpir types (PR #70127)

2023-10-24 Thread Zahira Ammarguellat via cfe-commits

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


[clang-tools-extra] `clangd`: support `-stdlib=` flags from `compile_commands.json`. (PR #69283)

2023-10-24 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] 3935a29 - [clangd] Support `-stdlib` flags in SystemIncludeExtractor. (#69283)

2023-10-24 Thread via cfe-commits

Author: Chris Carlon
Date: 2023-10-24T17:33:00-04:00
New Revision: 3935a29a3e8acf31bb1658265e8f9b977435f6bb

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

LOG: [clangd] Support `-stdlib` flags in SystemIncludeExtractor. (#69283)

The `--stdlib` flag can affect the system headers used by `clang` during
compilation. By default, `clang` will use the platform-installed C++
standard headers, but with `--stdlib=libc++`, `clang` can use headers
included in the distribution for its `libc++` implementation.

Prior to this patch, if `compile_commands.json` specified
`-stdlib=libc++` or an equivalent form and `--query-driver` took effect,
`clangd` would ignore `stdlib` and index based on the platform's
headers. When these mismatch, e.g. due to version differences,
`clangd`'s completions and the actual compilation can differ.

fixes clangd/clangd#1784

-

Co-authored-by: Chris Carlon 

Added: 


Modified: 
clang-tools-extra/clangd/SystemIncludeExtractor.cpp
clang-tools-extra/clangd/test/system-include-extractor.test

Removed: 




diff  --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp 
b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
index 68b80478e1bd969..ae7b268154d326c 100644
--- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -88,12 +88,14 @@ struct DriverArgs {
   std::string Sysroot;
   std::string ISysroot;
   std::string Target;
+  std::string Stdlib;
 
   bool operator==(const DriverArgs &RHS) const {
 return std::tie(Driver, StandardIncludes, StandardCXXIncludes, Lang,
-Sysroot, ISysroot, Target) ==
+Sysroot, ISysroot, Target, Stdlib) ==
std::tie(RHS.Driver, RHS.StandardIncludes, RHS.StandardCXXIncludes,
-RHS.Lang, RHS.Sysroot, RHS.ISysroot, RHS.Target);
+RHS.Lang, RHS.Sysroot, RHS.ISysroot, RHS.Target,
+RHS.Stdlib);
   }
 
   DriverArgs(const tooling::CompileCommand &Cmd, llvm::StringRef File) {
@@ -136,6 +138,13 @@ struct DriverArgs {
   } else if (Arg.consume_front("-target")) {
 if (Arg.empty() && I + 1 < E)
   Target = Cmd.CommandLine[I + 1];
+  } else if (Arg.consume_front("--stdlib")) {
+if (Arg.consume_front("="))
+  Stdlib = Arg.str();
+else if (Arg.empty() && I + 1 < E)
+  Stdlib = Cmd.CommandLine[I + 1];
+  } else if (Arg.consume_front("-stdlib=")) {
+Stdlib = Arg.str();
   }
 }
 
@@ -175,6 +184,8 @@ struct DriverArgs {
   Args.append({"-isysroot", ISysroot});
 if (!Target.empty())
   Args.append({"-target", Target});
+if (!Stdlib.empty())
+  Args.append({"--stdlib", Stdlib});
 return Args;
   }
 
@@ -206,6 +217,8 @@ template <> struct DenseMapInfo {
 Val.Lang,
 Val.Sysroot,
 Val.ISysroot,
+Val.Target,
+Val.Stdlib,
 });
   }
   static bool isEqual(const DriverArgs &LHS, const DriverArgs &RHS) {

diff  --git a/clang-tools-extra/clangd/test/system-include-extractor.test 
b/clang-tools-extra/clangd/test/system-include-extractor.test
index 66882e424bb9216..cbb3018b2fa7349 100644
--- a/clang-tools-extra/clangd/test/system-include-extractor.test
+++ b/clang-tools-extra/clangd/test/system-include-extractor.test
@@ -18,6 +18,7 @@
 # RUN: echo '[ -z "${args##*"--sysroot /my/sysroot/path"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo '[ -z "${args##*"-isysroot /isysroot"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo '[ -z "${args##*"-target arm-linux-gnueabihf"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
+# RUN: echo '[ -z "${args##*"--stdlib libc++"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'echo line to ignore >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "Target: arm-linux-gnueabihf\r\n" >&2' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'printf "#include <...> search starts here:\r\n" >&2' >> 
%t.dir/bin/my_driver.sh
@@ -37,7 +38,7 @@
 
 # Generate a compile_commands.json that will query the mock driver we've
 # created. Which should add a.h and b.h into include search path.
-# RUN: echo '[{"directory": "%/t.dir", "command": "my_driver.sh the-file.cpp 
--target=arm-linux-gnueabihf -nostdinc --sysroot /my/sysroot/path 
-isysroot/isysroot", "file": "the-file.cpp"}]' > %t.dir/compile_commands.json
+# RUN: echo '[{"directory": "%/t.dir", "command": "my_driver.sh the-file.cpp 
--target=arm-linux-gnueabihf -nostdinc --sysroot /my/sysroot/path 
-isysroot/isysroot -stdlib=libc++", "file": "the-file.cpp"}]' > 
%t.dir/compile_commands.json
 
 # RUN: sed -e "s|INPUT_DIR|%/t.dir|g" %s > %t.test.1
 # On Windows, we need the URI in didOpen to look like "uri":"file:///C:/..."
@@ -75,7 +76,7 @@
 {"jsonrpc":"2

[clang] Dfpir types (PR #70127)

2023-10-24 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam created 
https://github.com/llvm/llvm-project/pull/70127

None

>From 707f1625a626faae14b8e24f7e3cf10a2ed621ce Mon Sep 17 00:00:00 2001
From: Tom Honermann 
Date: Sun, 24 Sep 2023 22:38:01 -0400
Subject: [PATCH 1/4] [clang][DFP] Add basic builtin type representation for
 decimal floating point types.

This change adds basic type representation support for the decimal
floating point types defined by ISO/IEC TS 18661-2 and adopted for C23.
These types will also serve as the underlying native types for the
library types defined by ISO/IEC TR 24733 and as implemented in
libstdcxx. This change does not include representation support in
LLVM IR, in debugging information, or in C++ mangling for the MS ABI;
such support will be added in later patches.
---
 clang/include/clang/AST/ASTContext.h  |  2 ++
 clang/include/clang/AST/BuiltinTypes.def  | 17 
 clang/include/clang/Basic/TargetInfo.h| 17 
 clang/include/clang/Basic/TokenKinds.def  |  4 +++-
 .../include/clang/Serialization/ASTBitCodes.h |  9 +
 clang/lib/AST/ASTContext.cpp  | 20 +++
 clang/lib/AST/ExprConstant.cpp|  2 ++
 clang/lib/AST/ItaniumMangle.cpp   |  9 +
 clang/lib/AST/MicrosoftMangle.cpp |  6 ++
 clang/lib/AST/NSAPI.cpp   |  3 +++
 clang/lib/AST/PrintfFormatString.cpp  |  4 
 clang/lib/AST/Type.cpp|  7 +++
 clang/lib/AST/TypeLoc.cpp |  3 +++
 clang/lib/Basic/TargetInfo.cpp|  5 +
 clang/lib/CodeGen/CGDebugInfo.cpp |  7 +++
 clang/lib/CodeGen/CodeGenTypes.cpp|  8 
 clang/lib/CodeGen/ItaniumCXXABI.cpp   |  3 +++
 clang/lib/Index/USRGeneration.cpp |  6 ++
 clang/lib/Sema/SemaType.cpp   | 16 ++-
 clang/lib/Serialization/ASTCommon.cpp |  9 +
 clang/lib/Serialization/ASTReader.cpp |  9 +
 clang/test/Sema/types.c   |  4 +++-
 clang/tools/libclang/CIndex.cpp   |  1 +
 23 files changed, 168 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 4ee32c76a95d8e3..f862456797b5f92 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1098,6 +1098,8 @@ class ASTContext : public RefCountedBase {
   CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
   CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
   SatUnsignedLongFractTy;
+  // ISO/IEC TS 18661-2, ISO/IEC TR 24733, and C23 decimal floating-point.
+  CanQualType DecimalFloat32Ty, DecimalFloat64Ty, DecimalFloat128Ty;
   CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
   CanQualType BFloat16Ty;
   CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
diff --git a/clang/include/clang/AST/BuiltinTypes.def 
b/clang/include/clang/AST/BuiltinTypes.def
index c04f6f6f1271916..3a0f78fb6a33fa9 100644
--- a/clang/include/clang/AST/BuiltinTypes.def
+++ b/clang/include/clang/AST/BuiltinTypes.def
@@ -44,6 +44,10 @@
 #define FLOATING_TYPE(Id, SingletonId) BUILTIN_TYPE(Id, SingletonId)
 #endif
 
+#ifndef DECIMAL_FLOATING_TYPE
+#define DECIMAL_FLOATING_TYPE(Id, SingletonId) BUILTIN_TYPE(Id, SingletonId)
+#endif
+
 #ifndef PLACEHOLDER_TYPE
 #define PLACEHOLDER_TYPE(Id, SingletonId) BUILTIN_TYPE(Id, SingletonId)
 #endif
@@ -221,6 +225,18 @@ FLOATING_TYPE(Float128, Float128Ty)
 // '__ibm128'
 FLOATING_TYPE(Ibm128, Ibm128Ty)
 
+//===- Decimal floating point types 
---===//
+// ISO/IEC TS 18661-2, ISO/IEC TR 24733, and C23 decimal floating-point.
+
+// '_Decimal32'
+DECIMAL_FLOATING_TYPE(DecimalFloat32, DecimalFloat32Ty)
+
+// '_Decimal64'
+DECIMAL_FLOATING_TYPE(DecimalFloat64, DecimalFloat64Ty)
+
+// '_Decimal128'
+DECIMAL_FLOATING_TYPE(DecimalFloat128, DecimalFloat128Ty)
+
 //===- Language-specific types 
===//
 
 // This is the type of C++0x 'nullptr'.
@@ -336,6 +352,7 @@ LAST_BUILTIN_TYPE(OMPIterator)
 #undef SHARED_SINGLETON_TYPE
 #undef PLACEHOLDER_TYPE
 #undef FLOATING_TYPE
+#undef DECIMAL_FLOATING_TYPE
 #undef SIGNED_TYPE
 #undef UNSIGNED_TYPE
 #undef BUILTIN_TYPE
diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 61be52149341f01..ddf166c971fec95 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -95,6 +95,11 @@ struct TransferrableTargetInfo {
   unsigned char LongLongWidth, LongLongAlign;
   unsigned char Int128Align;
 
+  // Decimal floating-point bit widths and alignment.
+  unsigned char DecimalFloat32Width, DecimalFloat32Align;
+  unsigned char DecimalFloat64Width, DecimalFloat64Align;
+  unsigned char DecimalFloat128Width, DecimalFloat128Align;
+
   // Fixed point bit widths
   unsigned c

[clang-tools-extra] `clangd`: support `-stdlib=` flags from `compile_commands.json`. (PR #69283)

2023-10-24 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 approved this pull request.

LGTM

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


[clang-tools-extra] [clangd] Fix RawStringLiteral being available to C and C++ versions prior to C++11 (PR #69775)

2023-10-24 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] 2f3d4f6 - [clangd] Do not offer RawStringLiteral code action in C and C++98 (#69775)

2023-10-24 Thread via cfe-commits

Author: robozati
Date: 2023-10-24T17:29:43-04:00
New Revision: 2f3d4f6c9829bfc17a3e2d034286c03940d506ec

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

LOG: [clangd] Do not offer RawStringLiteral code action in C and C++98 (#69775)

Raw string literals are a C++ feature first added in C++11.

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

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
index f5021b820f38d7f..5613ceacdfe1bfc 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 #include "ParsedAST.h"
 #include "refactor/Tweak.h"
+#include "clang/AST/ASTContext.h"
 #include "clang/AST/Stmt.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
@@ -43,6 +44,12 @@ class RawStringLiteral : public Tweak {
 
 REGISTER_TWEAK(RawStringLiteral)
 
+static bool isFeatureAvailable(const ASTContext &Context) {
+  // Raw strings are available only for C++11 or later versions, and they are
+  // not available for C.
+  return Context.getLangOpts().CPlusPlus11;
+}
+
 static bool isNormalString(const StringLiteral &Str, SourceLocation Cursor,
   SourceManager &SM) {
   // All chunks must be normal ASCII strings, not u8"..." etc.
@@ -72,6 +79,9 @@ static bool canBeRaw(llvm::StringRef Content) {
 }
 
 bool RawStringLiteral::prepare(const Selection &Inputs) {
+  if (!isFeatureAvailable(Inputs.AST->getASTContext())) {
+return false;
+  }
   const SelectionTree::Node *N = Inputs.ASTSelection.commonAncestor();
   if (!N)
 return false;

diff  --git 
a/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
index 4bc304559705031..2681b8c815dbae3 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
@@ -36,6 +36,20 @@ literal)")cpp";
   EXPECT_EQ(apply(Input), Output);
 }
 
+TEST_F(RawStringLiteralTest, TestC) {
+  Context = File;
+  FileName = "TestTU.c";
+  ExtraArgs = {"-xc"}; // raw strings are unavailable in C
+  EXPECT_UNAVAILABLE(R"c(const char *a = ^"^f^o^o^\^n^";)c");
+}
+
+TEST_F(RawStringLiteralTest, TestCpp98) {
+  Context = File;
+  ExtraArgs = {"-std=c++98"}; // raw strings are unavailable
+  // in versions prior to C++11
+  EXPECT_UNAVAILABLE(R"cpp(const char *a = ^"^f^o^o^\^n^";)cpp");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang



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


[clang-tools-extra] [clangd] Fix RawStringLiteral being available to C and C++ versions prior to C++11 (PR #69775)

2023-10-24 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 approved this pull request.

LGTM, thanks!

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


[clang] [Offloading][NFC] Move creation of offloading entries from OpenMP (PR #70116)

2023-10-24 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/70116

>From 35347649fe160073e73c3bca96506b6fd96d8a31 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Tue, 24 Oct 2023 15:27:21 -0500
Subject: [PATCH] [Offloading][NFC] Move creation of offloading entries from
 OpenMP

Summary:
This patch is a first step to remove dependencies on the OpenMPIRBuilder
for creating generic offloading entires. This patch changes no
functionality and merely moves the code around. In the future the
interface will be changed to allow for more code re-use in the
registeration and creation of offloading entries as well as a more
generic interface for CUDA, HIP, OpenMP, and SYCL(?). Doing this as a
first step to reduce the noise involved in the functional changes.
---
 clang/lib/CodeGen/CGCUDANV.cpp| 28 +++
 clang/lib/CodeGen/CMakeLists.txt  |  1 +
 .../llvm/Frontend/Offloading/Utility.h| 37 +
 .../llvm/Frontend/OpenMP/OMPIRBuilder.h   | 21 -
 .../include/llvm/Frontend/OpenMP/OMPKinds.def |  2 -
 llvm/lib/Frontend/CMakeLists.txt  |  1 +
 llvm/lib/Frontend/Offloading/CMakeLists.txt   | 14 
 llvm/lib/Frontend/Offloading/Utility.cpp  | 76 +++
 llvm/lib/Frontend/OpenMP/CMakeLists.txt   |  1 +
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp | 43 +--
 10 files changed, 148 insertions(+), 76 deletions(-)
 create mode 100644 llvm/include/llvm/Frontend/Offloading/Utility.h
 create mode 100644 llvm/lib/Frontend/Offloading/CMakeLists.txt
 create mode 100644 llvm/lib/Frontend/Offloading/Utility.cpp

diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp
index 8a1212f2272e87a..2ef4dc236d091b0 100644
--- a/clang/lib/CodeGen/CGCUDANV.cpp
+++ b/clang/lib/CodeGen/CGCUDANV.cpp
@@ -19,6 +19,7 @@
 #include "clang/Basic/Cuda.h"
 #include "clang/CodeGen/CodeGenABITypes.h"
 #include "clang/CodeGen/ConstantInitBuilder.h"
+#include "llvm/Frontend/Offloading/Utility.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DerivedTypes.h"
@@ -1129,33 +1130,32 @@ void CGNVCUDARuntime::transformManagedVars() {
 // registered. The linker will provide a pointer to this section so we can
 // register the symbols with the linked device image.
 void CGNVCUDARuntime::createOffloadingEntries() {
-  llvm::OpenMPIRBuilder OMPBuilder(CGM.getModule());
-  OMPBuilder.initialize();
-
   StringRef Section = CGM.getLangOpts().HIP ? "hip_offloading_entries"
 : "cuda_offloading_entries";
+  llvm::Module &M = CGM.getModule();
   for (KernelInfo &I : EmittedKernels)
-OMPBuilder.emitOffloadingEntry(KernelHandles[I.Kernel->getName()],
-   getDeviceSideName(cast(I.D)), 0,
-   DeviceVarFlags::OffloadGlobalEntry, 
Section);
+llvm::offloading::emitOffloadingEntry(
+M, KernelHandles[I.Kernel->getName()],
+getDeviceSideName(cast(I.D)), 0,
+DeviceVarFlags::OffloadGlobalEntry, Section);
 
   for (VarInfo &I : DeviceVars) {
 uint64_t VarSize =
 CGM.getDataLayout().getTypeAllocSize(I.Var->getValueType());
 if (I.Flags.getKind() == DeviceVarFlags::Variable) {
-  OMPBuilder.emitOffloadingEntry(
-  I.Var, getDeviceSideName(I.D), VarSize,
+  llvm::offloading::emitOffloadingEntry(
+  M, I.Var, getDeviceSideName(I.D), VarSize,
   I.Flags.isManaged() ? DeviceVarFlags::OffloadGlobalManagedEntry
   : DeviceVarFlags::OffloadGlobalEntry,
   Section);
 } else if (I.Flags.getKind() == DeviceVarFlags::Surface) {
-  OMPBuilder.emitOffloadingEntry(I.Var, getDeviceSideName(I.D), VarSize,
- DeviceVarFlags::OffloadGlobalSurfaceEntry,
- Section);
+  llvm::offloading::emitOffloadingEntry(
+  M, I.Var, getDeviceSideName(I.D), VarSize,
+  DeviceVarFlags::OffloadGlobalSurfaceEntry, Section);
 } else if (I.Flags.getKind() == DeviceVarFlags::Texture) {
-  OMPBuilder.emitOffloadingEntry(I.Var, getDeviceSideName(I.D), VarSize,
- DeviceVarFlags::OffloadGlobalTextureEntry,
- Section);
+  llvm::offloading::emitOffloadingEntry(
+  M, I.Var, getDeviceSideName(I.D), VarSize,
+  DeviceVarFlags::OffloadGlobalTextureEntry, Section);
 }
   }
 }
diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt
index d67ce982d78acf3..da98848e3b44387 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -11,6 +11,7 @@ set(LLVM_LINK_COMPONENTS
   Extensions
   FrontendHLSL
   FrontendOpenMP
+  FrontendOffloading
   HIPStdPar
   IPO
   IRPrinter
diff --git a/llvm/include/llvm/Frontend/Offloading/Utility.h 
b/llvm/include/llvm/Frontend/Offloading/Utility.h
new file mode 100644
index 0

[clang] Add a new attribute value for suppressing WebKit's unsafe member variable warning (PR #70124)

2023-10-24 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa created https://github.com/llvm/llvm-project/pull/70124

None

>From 3b420fcb0a6d74dc034cfdf2d7b28e13e75f0e08 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Tue, 24 Oct 2023 13:51:50 -0700
Subject: [PATCH] Add a new attribute value for suppressing WebKit's unsafe
 member variable warning

---
 .../Checkers/WebKit/NoUncountedMembersChecker.cpp  | 7 +++
 clang/test/Analysis/Checkers/WebKit/uncounted-members.cpp  | 1 +
 2 files changed, 8 insertions(+)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/NoUncountedMembersChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/NoUncountedMembersChecker.cpp
index 66d8588e2531589..6f03e4ac27c4613 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/NoUncountedMembersChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/NoUncountedMembersChecker.cpp
@@ -75,6 +75,13 @@ class NoUncountedMemberChecker
   if (!MemberType)
 continue;
 
+  if (std::any_of(
+Member->specific_attr_begin(),
+Member->specific_attr_end(), [](const AnnotateAttr *Ann) 
{
+  return Ann->getAnnotation() == "webkit_uncountedmember_exception";
+}))
+  continue;
+
   if (auto *MemberCXXRD = MemberType->getPointeeCXXRecordDecl()) {
 // If we don't see the definition we just don't know.
 if (MemberCXXRD->hasDefinition()) {
diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-members.cpp 
b/clang/test/Analysis/Checkers/WebKit/uncounted-members.cpp
index a0ea61e0e2a13b1..b175f9491ab5b73 100644
--- a/clang/test/Analysis/Checkers/WebKit/uncounted-members.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/uncounted-members.cpp
@@ -16,6 +16,7 @@ namespace members {
 RefCountable& c = silenceWarningAboutInit;
 // expected-warning@-1{{Member variable 'c' in 'members::Foo' is a reference 
to ref-countable type 'RefCountable'}}
 Ref d;
+__attribute__((annotate("webkit_uncountedmember_exception"))) 
RefCountable* e;
   };
 
   template

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


[clang] [libc++] Implement ranges::iota (PR #68494)

2023-10-24 Thread James E T Smith via cfe-commits

jamesETsmith wrote:

Sorry for the delay, just circling back to this. @philnik777 should I update 
the `robust_against_*` tests in both `test/std/algorithms` and 
`test/libcxx/algorithms/`? 

Probably a simple follow-up question, but you're interested in adding 
`ranges::iota` to the `ranges_robust_against_*` right? Or should it be added to 
the `robust_against_*` tests?

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


[clang] [Offloading][NFC] Move creation of offloading entries from OpenMP (PR #70116)

2023-10-24 Thread via cfe-commits

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 c780352de961371949333c3eb0d9d55fda39bf7f 
93d72202bc5776483eddb9285ab384979caa85f4 -- 
llvm/include/llvm/Frontend/Offloading/Utility.h 
llvm/lib/Frontend/Offloading/Utility.cpp clang/lib/CodeGen/CGCUDANV.cpp 
llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h 
llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp
index a8b9c1325731..2ef4dc236d09 100644
--- a/clang/lib/CodeGen/CGCUDANV.cpp
+++ b/clang/lib/CodeGen/CGCUDANV.cpp
@@ -1134,27 +1134,28 @@ void CGNVCUDARuntime::createOffloadingEntries() {
 : "cuda_offloading_entries";
   llvm::Module &M = CGM.getModule();
   for (KernelInfo &I : EmittedKernels)
-llvm::offloading::emitOffloadingEntry(M, 
KernelHandles[I.Kernel->getName()],
-   getDeviceSideName(cast(I.D)), 0,
-   DeviceVarFlags::OffloadGlobalEntry, 
Section);
+llvm::offloading::emitOffloadingEntry(
+M, KernelHandles[I.Kernel->getName()],
+getDeviceSideName(cast(I.D)), 0,
+DeviceVarFlags::OffloadGlobalEntry, Section);
 
   for (VarInfo &I : DeviceVars) {
 uint64_t VarSize =
 CGM.getDataLayout().getTypeAllocSize(I.Var->getValueType());
 if (I.Flags.getKind() == DeviceVarFlags::Variable) {
-  llvm::offloading::emitOffloadingEntry(M, 
-  I.Var, getDeviceSideName(I.D), VarSize,
+  llvm::offloading::emitOffloadingEntry(
+  M, I.Var, getDeviceSideName(I.D), VarSize,
   I.Flags.isManaged() ? DeviceVarFlags::OffloadGlobalManagedEntry
   : DeviceVarFlags::OffloadGlobalEntry,
   Section);
 } else if (I.Flags.getKind() == DeviceVarFlags::Surface) {
-  llvm::offloading::emitOffloadingEntry(M, I.Var, getDeviceSideName(I.D), 
VarSize,
- DeviceVarFlags::OffloadGlobalSurfaceEntry,
- Section);
+  llvm::offloading::emitOffloadingEntry(
+  M, I.Var, getDeviceSideName(I.D), VarSize,
+  DeviceVarFlags::OffloadGlobalSurfaceEntry, Section);
 } else if (I.Flags.getKind() == DeviceVarFlags::Texture) {
-  llvm::offloading::emitOffloadingEntry(M, I.Var, getDeviceSideName(I.D), 
VarSize,
- DeviceVarFlags::OffloadGlobalTextureEntry,
- Section);
+  llvm::offloading::emitOffloadingEntry(
+  M, I.Var, getDeviceSideName(I.D), VarSize,
+  DeviceVarFlags::OffloadGlobalTextureEntry, Section);
 }
   }
 }
diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index d765d2bd7b14..62c97ff7f292 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -13,7 +13,6 @@
 
//===--===//
 
 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
-#include "llvm/Frontend/Offloading/Utility.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
@@ -24,6 +23,7 @@
 #include "llvm/Analysis/ScalarEvolution.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Bitcode/BitcodeReader.h"
+#include "llvm/Frontend/Offloading/Utility.h"
 #include "llvm/Frontend/OpenMP/OMPGridValues.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
@@ -5891,8 +5891,9 @@ void OpenMPIRBuilder::createOffloadEntry(Constant *ID, 
Constant *Addr,
  GlobalValue::LinkageTypes,
  StringRef Name) {
   if (!Config.isGPU()) {
-llvm::offloading::emitOffloadingEntry(M, ID, Name.empty() ? Addr->getName()
-: Name, Size, Flags, "omp_offloading_entries");
+llvm::offloading::emitOffloadingEntry(
+M, ID, Name.empty() ? Addr->getName() : Name, Size, Flags,
+"omp_offloading_entries");
 return;
   }
   // TODO: Add support for global variables on the device after declare target

``




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


[clang-tools-extra] [libc++] Implement ranges::iota (PR #68494)

2023-10-24 Thread James E T Smith via cfe-commits

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


[clang] [InstCombine] Add combines/simplifications for `llvm.ptrmask` (PR #67166)

2023-10-24 Thread via cfe-commits

goldsteinn wrote:

Rebased ontop of nikic's patch

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


[clang] [InstCombine] Add combines/simplifications for `llvm.ptrmask` (PR #67166)

2023-10-24 Thread via cfe-commits


@@ -6411,6 +6411,41 @@ static Value *simplifyBinaryIntrinsic(Function *F, Value 
*Op0, Value *Op1,
   return Constant::getNullValue(ReturnType);
 break;
   }
+  case Intrinsic::ptrmask: {
+if (isa(Op0) || isa(Op1))
+  return PoisonValue::get(Op0->getType());
+
+// NOTE: We can't apply this simplifications based on the value of Op1
+// because we need to preserve provenance.
+if (Q.isUndefValue(Op0) || match(Op0, m_Zero()))
+  return Constant::getNullValue(Op0->getType());
+
+if (Op1->getType()->getScalarSizeInBits() ==
+Q.DL.getPointerTypeSizeInBits(Op0->getType())) {
+  if (match(Op1, m_PtrToInt(m_Specific(Op0
+return Op0;
+
+  // NOTE: We may have attributes associated with the return value of the
+  // llvm.ptrmask intrinsic that will be lost when we just return the
+  // operand. We should try to preserve them.
+  if (match(Op1, m_AllOnes()) || Q.isUndefValue(Op1))
+return Op0;
+
+  Constant *C;
+  if (match(Op1, m_ImmConstant(C))) {
+KnownBits PtrKnown =
+computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);

goldsteinn wrote:

Done

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


[clang] [InstCombine] Add combines/simplifications for `llvm.ptrmask` (PR #67166)

2023-10-24 Thread via cfe-commits

https://github.com/goldsteinn updated 
https://github.com/llvm/llvm-project/pull/67166

>From 9f9f1d20759f6a9d71f9131baa656bfb7d459095 Mon Sep 17 00:00:00 2001
From: Noah Goldstein 
Date: Fri, 22 Sep 2023 08:21:21 -0500
Subject: [PATCH 1/6] [InstSimplify] Add tests for simplify `llvm.ptrmask`; NFC

Differential Revision: https://reviews.llvm.org/D156632
---
 llvm/test/Transforms/InstSimplify/ptrmask.ll | 366 +++
 1 file changed, 366 insertions(+)
 create mode 100644 llvm/test/Transforms/InstSimplify/ptrmask.ll

diff --git a/llvm/test/Transforms/InstSimplify/ptrmask.ll 
b/llvm/test/Transforms/InstSimplify/ptrmask.ll
new file mode 100644
index 000..aeb02cf4718e9c0
--- /dev/null
+++ b/llvm/test/Transforms/InstSimplify/ptrmask.ll
@@ -0,0 +1,366 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --version 2
+; RUN: opt < %s -passes=instsimplify -S | FileCheck %s
+
+target datalayout = "p1:64:64:64:32"
+
+declare ptr addrspace(1) @llvm.ptrmask.p1.i32(ptr addrspace(1) , i32)
+declare ptr @llvm.ptrmask.p0.i64(ptr, i64)
+
+declare <2 x ptr addrspace(1) > @llvm.ptrmask.v2p1.v2i32(<2 x ptr addrspace(1) 
>, <2 x i32>)
+declare <2 x ptr> @llvm.ptrmask.v2p1.v2i64(<2 x ptr>, <2 x i64>)
+
+define ptr @ptrmask_simplify_poison_mask(ptr %p) {
+; CHECK-LABEL: define ptr @ptrmask_simplify_poison_mask
+; CHECK-SAME: (ptr [[P:%.*]]) {
+; CHECK-NEXT:[[R:%.*]] = call ptr @llvm.ptrmask.p0.i64(ptr [[P]], i64 
poison)
+; CHECK-NEXT:ret ptr [[R]]
+;
+  %r = call ptr @llvm.ptrmask.p0.i64(ptr %p, i64 poison)
+  ret ptr %r
+}
+
+define <2 x ptr addrspace(1) > @ptrmask_simplify_poison_mask_vec(<2 x ptr 
addrspace(1) > %p) {
+; CHECK-LABEL: define <2 x ptr addrspace(1)> @ptrmask_simplify_poison_mask_vec
+; CHECK-SAME: (<2 x ptr addrspace(1)> [[P:%.*]]) {
+; CHECK-NEXT:[[R:%.*]] = call <2 x ptr addrspace(1)> 
@llvm.ptrmask.v2p1.v2i32(<2 x ptr addrspace(1)> [[P]], <2 x i32> poison)
+; CHECK-NEXT:ret <2 x ptr addrspace(1)> [[R]]
+;
+  %r = call <2 x ptr addrspace(1) > @llvm.ptrmask.v2p1.v2i32(<2 x ptr 
addrspace(1) > %p, <2 x i32> poison)
+  ret <2 x ptr addrspace(1) > %r
+}
+
+define <2 x ptr addrspace(1) > 
@ptrmask_simplify_poison_and_zero_i32_vec_fail(<2 x ptr addrspace(1) > %p) {
+; CHECK-LABEL: define <2 x ptr addrspace(1)> 
@ptrmask_simplify_poison_and_zero_i32_vec_fail
+; CHECK-SAME: (<2 x ptr addrspace(1)> [[P:%.*]]) {
+; CHECK-NEXT:[[R:%.*]] = call <2 x ptr addrspace(1)> 
@llvm.ptrmask.v2p1.v2i32(<2 x ptr addrspace(1)> [[P]], <2 x i32> )
+; CHECK-NEXT:ret <2 x ptr addrspace(1)> [[R]]
+;
+  %r = call <2 x ptr addrspace(1) > @llvm.ptrmask.v2p1.v2i32(<2 x ptr 
addrspace(1) > %p, <2 x i32> )
+  ret <2 x ptr addrspace(1) > %r
+}
+
+define <2 x ptr> @ptrmask_simplify_undef_and_ones_vec(<2 x ptr> %p) {
+; CHECK-LABEL: define <2 x ptr> @ptrmask_simplify_undef_and_ones_vec
+; CHECK-SAME: (<2 x ptr> [[P:%.*]]) {
+; CHECK-NEXT:[[R:%.*]] = call <2 x ptr> @llvm.ptrmask.v2p0.v2i64(<2 x ptr> 
[[P]], <2 x i64> )
+; CHECK-NEXT:ret <2 x ptr> [[R]]
+;
+  %r = call <2 x ptr> @llvm.ptrmask.v2p1.v2i64(<2 x ptr> %p, <2 x i64> )
+  ret <2 x ptr> %r
+}
+
+define <2 x ptr> @ptrmask_simplify_poison_and_ones_vec(<2 x ptr> %p) {
+; CHECK-LABEL: define <2 x ptr> @ptrmask_simplify_poison_and_ones_vec
+; CHECK-SAME: (<2 x ptr> [[P:%.*]]) {
+; CHECK-NEXT:[[R:%.*]] = call <2 x ptr> @llvm.ptrmask.v2p0.v2i64(<2 x ptr> 
[[P]], <2 x i64> )
+; CHECK-NEXT:ret <2 x ptr> [[R]]
+;
+  %r = call <2 x ptr> @llvm.ptrmask.v2p1.v2i64(<2 x ptr> %p, <2 x i64> )
+  ret <2 x ptr> %r
+}
+
+define <2 x ptr> @ptrmask_simplify_ones_vec(<2 x ptr> %p) {
+; CHECK-LABEL: define <2 x ptr> @ptrmask_simplify_ones_vec
+; CHECK-SAME: (<2 x ptr> [[P:%.*]]) {
+; CHECK-NEXT:[[R:%.*]] = call <2 x ptr> @llvm.ptrmask.v2p0.v2i64(<2 x ptr> 
[[P]], <2 x i64> )
+; CHECK-NEXT:ret <2 x ptr> [[R]]
+;
+  %r = call <2 x ptr> @llvm.ptrmask.v2p1.v2i64(<2 x ptr> %p, <2 x i64> )
+  ret <2 x ptr> %r
+}
+
+define <2 x ptr addrspace(1) > @ptrmask_simplify_ones_fail_vec(<2 x ptr 
addrspace(1) > %p) {
+; CHECK-LABEL: define <2 x ptr addrspace(1)> @ptrmask_simplify_ones_fail_vec
+; CHECK-SAME: (<2 x ptr addrspace(1)> [[P:%.*]]) {
+; CHECK-NEXT:[[R:%.*]] = call <2 x ptr addrspace(1)> 
@llvm.ptrmask.v2p1.v2i32(<2 x ptr addrspace(1)> [[P]], <2 x i32> )
+; CHECK-NEXT:ret <2 x ptr addrspace(1)> [[R]]
+;
+  %r = call <2 x ptr addrspace(1) > @llvm.ptrmask.v2p1.v2i32(<2 x ptr 
addrspace(1) > %p, <2 x i32> )
+  ret <2 x ptr addrspace(1) > %r
+}
+
+define ptr addrspace(1) @ptrmask_simplify_undef_mask(ptr addrspace(1) %p) {
+; CHECK-LABEL: define ptr addrspace(1) @ptrmask_simplify_undef_mask
+; CHECK-SAME: (ptr addrspace(1) [[P:%.*]]) {
+; CHECK-NEXT:[[R:%.*]] = call ptr addrspace(1) @llvm.ptrmask.p1.i32(ptr 
addrspace(1) [[P]], i32 undef)
+; CHECK-NEXT:ret ptr addrspace(1) [[R]]
+;
+  %r = call ptr addrspace(1) @llvm.ptrmask.p1.i32(ptr addrspace(1) %p, i32 
undef)
+  ret ptr addrspace(1) %r
+}
+
+define

[clang] [Offloading][NFC] Move creation of offloading entries from OpenMP (PR #70116)

2023-10-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Joseph Huber (jhuber6)


Changes

Summary:
This patch is a first step to remove dependencies on the OpenMPIRBuilder
for creating generic offloading entires. This patch changes no
functionality and merely moves the code around. In the future the
interface will be changed to allow for more code re-use in the
registeration and creation of offloading entries as well as a more
generic interface for CUDA, HIP, OpenMP, and SYCL(?). Doing this as a
first step to reduce the noise involved in the functional changes.


---
Full diff: https://github.com/llvm/llvm-project/pull/70116.diff


10 Files Affected:

- (modified) clang/lib/CodeGen/CGCUDANV.cpp (+6-7) 
- (modified) clang/lib/CodeGen/CMakeLists.txt (+1) 
- (added) llvm/include/llvm/Frontend/Offloading/Utility.h (+37) 
- (modified) llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h (-21) 
- (modified) llvm/include/llvm/Frontend/OpenMP/OMPKinds.def (-2) 
- (modified) llvm/lib/Frontend/CMakeLists.txt (+1) 
- (added) llvm/lib/Frontend/Offloading/CMakeLists.txt (+14) 
- (added) llvm/lib/Frontend/Offloading/Utility.cpp (+76) 
- (modified) llvm/lib/Frontend/OpenMP/CMakeLists.txt (+1) 
- (modified) llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp (+3-39) 


``diff
diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp
index 8a1212f2272e87a..a8b9c1325731aa6 100644
--- a/clang/lib/CodeGen/CGCUDANV.cpp
+++ b/clang/lib/CodeGen/CGCUDANV.cpp
@@ -19,6 +19,7 @@
 #include "clang/Basic/Cuda.h"
 #include "clang/CodeGen/CodeGenABITypes.h"
 #include "clang/CodeGen/ConstantInitBuilder.h"
+#include "llvm/Frontend/Offloading/Utility.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DerivedTypes.h"
@@ -1129,13 +1130,11 @@ void CGNVCUDARuntime::transformManagedVars() {
 // registered. The linker will provide a pointer to this section so we can
 // register the symbols with the linked device image.
 void CGNVCUDARuntime::createOffloadingEntries() {
-  llvm::OpenMPIRBuilder OMPBuilder(CGM.getModule());
-  OMPBuilder.initialize();
-
   StringRef Section = CGM.getLangOpts().HIP ? "hip_offloading_entries"
 : "cuda_offloading_entries";
+  llvm::Module &M = CGM.getModule();
   for (KernelInfo &I : EmittedKernels)
-OMPBuilder.emitOffloadingEntry(KernelHandles[I.Kernel->getName()],
+llvm::offloading::emitOffloadingEntry(M, 
KernelHandles[I.Kernel->getName()],
getDeviceSideName(cast(I.D)), 0,
DeviceVarFlags::OffloadGlobalEntry, 
Section);
 
@@ -1143,17 +1142,17 @@ void CGNVCUDARuntime::createOffloadingEntries() {
 uint64_t VarSize =
 CGM.getDataLayout().getTypeAllocSize(I.Var->getValueType());
 if (I.Flags.getKind() == DeviceVarFlags::Variable) {
-  OMPBuilder.emitOffloadingEntry(
+  llvm::offloading::emitOffloadingEntry(M, 
   I.Var, getDeviceSideName(I.D), VarSize,
   I.Flags.isManaged() ? DeviceVarFlags::OffloadGlobalManagedEntry
   : DeviceVarFlags::OffloadGlobalEntry,
   Section);
 } else if (I.Flags.getKind() == DeviceVarFlags::Surface) {
-  OMPBuilder.emitOffloadingEntry(I.Var, getDeviceSideName(I.D), VarSize,
+  llvm::offloading::emitOffloadingEntry(M, I.Var, getDeviceSideName(I.D), 
VarSize,
  DeviceVarFlags::OffloadGlobalSurfaceEntry,
  Section);
 } else if (I.Flags.getKind() == DeviceVarFlags::Texture) {
-  OMPBuilder.emitOffloadingEntry(I.Var, getDeviceSideName(I.D), VarSize,
+  llvm::offloading::emitOffloadingEntry(M, I.Var, getDeviceSideName(I.D), 
VarSize,
  DeviceVarFlags::OffloadGlobalTextureEntry,
  Section);
 }
diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt
index d67ce982d78acf3..da98848e3b44387 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -11,6 +11,7 @@ set(LLVM_LINK_COMPONENTS
   Extensions
   FrontendHLSL
   FrontendOpenMP
+  FrontendOffloading
   HIPStdPar
   IPO
   IRPrinter
diff --git a/llvm/include/llvm/Frontend/Offloading/Utility.h 
b/llvm/include/llvm/Frontend/Offloading/Utility.h
new file mode 100644
index 000..f74f9e3ff119fd8
--- /dev/null
+++ b/llvm/include/llvm/Frontend/Offloading/Utility.h
@@ -0,0 +1,37 @@
+//===- Utility.h - Collection of geneirc offloading utilities 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "llvm/IR/Module.h"
+#include "llvm/Object/OffloadBinary.h"
+
+namespace llvm {
+namespace offloading {
+
+

[clang] [Offloading][NFC] Move creation of offloading entries from OpenMP (PR #70116)

2023-10-24 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 created 
https://github.com/llvm/llvm-project/pull/70116

Summary:
This patch is a first step to remove dependencies on the OpenMPIRBuilder
for creating generic offloading entires. This patch changes no
functionality and merely moves the code around. In the future the
interface will be changed to allow for more code re-use in the
registeration and creation of offloading entries as well as a more
generic interface for CUDA, HIP, OpenMP, and SYCL(?). Doing this as a
first step to reduce the noise involved in the functional changes.


>From 93d72202bc5776483eddb9285ab384979caa85f4 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Tue, 24 Oct 2023 15:27:21 -0500
Subject: [PATCH] [Offloading][NFC] Move creation of offloading entries from
 OpenMP

Summary:
This patch is a first step to remove dependencies on the OpenMPIRBuilder
for creating generic offloading entires. This patch changes no
functionality and merely moves the code around. In the future the
interface will be changed to allow for more code re-use in the
registeration and creation of offloading entries as well as a more
generic interface for CUDA, HIP, OpenMP, and SYCL(?). Doing this as a
first step to reduce the noise involved in the functional changes.
---
 clang/lib/CodeGen/CGCUDANV.cpp| 13 ++--
 clang/lib/CodeGen/CMakeLists.txt  |  1 +
 .../llvm/Frontend/Offloading/Utility.h| 37 +
 .../llvm/Frontend/OpenMP/OMPIRBuilder.h   | 21 -
 .../include/llvm/Frontend/OpenMP/OMPKinds.def |  2 -
 llvm/lib/Frontend/CMakeLists.txt  |  1 +
 llvm/lib/Frontend/Offloading/CMakeLists.txt   | 14 
 llvm/lib/Frontend/Offloading/Utility.cpp  | 76 +++
 llvm/lib/Frontend/OpenMP/CMakeLists.txt   |  1 +
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp | 42 +-
 10 files changed, 139 insertions(+), 69 deletions(-)
 create mode 100644 llvm/include/llvm/Frontend/Offloading/Utility.h
 create mode 100644 llvm/lib/Frontend/Offloading/CMakeLists.txt
 create mode 100644 llvm/lib/Frontend/Offloading/Utility.cpp

diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp
index 8a1212f2272e87a..a8b9c1325731aa6 100644
--- a/clang/lib/CodeGen/CGCUDANV.cpp
+++ b/clang/lib/CodeGen/CGCUDANV.cpp
@@ -19,6 +19,7 @@
 #include "clang/Basic/Cuda.h"
 #include "clang/CodeGen/CodeGenABITypes.h"
 #include "clang/CodeGen/ConstantInitBuilder.h"
+#include "llvm/Frontend/Offloading/Utility.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DerivedTypes.h"
@@ -1129,13 +1130,11 @@ void CGNVCUDARuntime::transformManagedVars() {
 // registered. The linker will provide a pointer to this section so we can
 // register the symbols with the linked device image.
 void CGNVCUDARuntime::createOffloadingEntries() {
-  llvm::OpenMPIRBuilder OMPBuilder(CGM.getModule());
-  OMPBuilder.initialize();
-
   StringRef Section = CGM.getLangOpts().HIP ? "hip_offloading_entries"
 : "cuda_offloading_entries";
+  llvm::Module &M = CGM.getModule();
   for (KernelInfo &I : EmittedKernels)
-OMPBuilder.emitOffloadingEntry(KernelHandles[I.Kernel->getName()],
+llvm::offloading::emitOffloadingEntry(M, 
KernelHandles[I.Kernel->getName()],
getDeviceSideName(cast(I.D)), 0,
DeviceVarFlags::OffloadGlobalEntry, 
Section);
 
@@ -1143,17 +1142,17 @@ void CGNVCUDARuntime::createOffloadingEntries() {
 uint64_t VarSize =
 CGM.getDataLayout().getTypeAllocSize(I.Var->getValueType());
 if (I.Flags.getKind() == DeviceVarFlags::Variable) {
-  OMPBuilder.emitOffloadingEntry(
+  llvm::offloading::emitOffloadingEntry(M, 
   I.Var, getDeviceSideName(I.D), VarSize,
   I.Flags.isManaged() ? DeviceVarFlags::OffloadGlobalManagedEntry
   : DeviceVarFlags::OffloadGlobalEntry,
   Section);
 } else if (I.Flags.getKind() == DeviceVarFlags::Surface) {
-  OMPBuilder.emitOffloadingEntry(I.Var, getDeviceSideName(I.D), VarSize,
+  llvm::offloading::emitOffloadingEntry(M, I.Var, getDeviceSideName(I.D), 
VarSize,
  DeviceVarFlags::OffloadGlobalSurfaceEntry,
  Section);
 } else if (I.Flags.getKind() == DeviceVarFlags::Texture) {
-  OMPBuilder.emitOffloadingEntry(I.Var, getDeviceSideName(I.D), VarSize,
+  llvm::offloading::emitOffloadingEntry(M, I.Var, getDeviceSideName(I.D), 
VarSize,
  DeviceVarFlags::OffloadGlobalTextureEntry,
  Section);
 }
diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt
index d67ce982d78acf3..da98848e3b44387 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -11,6 +11,7 @@ set(LLVM_LINK_COMPONENTS
   Extensions
   FrontendHLSL
   FrontendOp

[clang] [C23] Use thread_local semantics (PR #70107)

2023-10-24 Thread Erich Keane via cfe-commits

https://github.com/erichkeane approved this pull request.


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


[clang] [C23] Use thread_local semantics (PR #70107)

2023-10-24 Thread Aaron Ballman via cfe-commits


@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple i686-pc-linux-gnu -std=c23 -emit-llvm -o - %s | 
FileCheck %s
+
+// Ensure that thread_local and _Thread_local emit the same codegen. See
+// https://github.com/llvm/llvm-project/issues/70068 for details.
+
+void func(void) {
+  static thread_local int i = 12;
+  static _Thread_local int j = 13;
+
+  extern thread_local int k;
+  extern thread_local int l;
+
+  (void)k;
+  (void)l;
+}
+
+// CHECK:  @func.i = internal thread_local global i32 12, align 4
+// CHECK-NEXT: @func.j = internal thread_local global i32 13, align 4
+// CHECK-NEXT: @k = external thread_local global i32, align 4
+// CHECK-NEXT: @l = external thread_local global i32, align 4
+
+// CHECK:  define dso_local void @func()
+// CHECK-NEXT: entry:
+// CHECK-NEXT: %[[K:.+]] = call align 4 ptr @llvm.threadlocal.address.p0(ptr 
align 4 @k)
+// CHECK-NEXT: %{{.+}} = load i32, ptr %[[K]], align 4

AaronBallman wrote:

Okay, I removed those bits.

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


[clang] [C23] Use thread_local semantics (PR #70107)

2023-10-24 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman updated 
https://github.com/llvm/llvm-project/pull/70107

>From 9db10fc83ec3683b1d5b6f8606fc37a83fe224fa Mon Sep 17 00:00:00 2001
From: Aaron Ballman 
Date: Tue, 24 Oct 2023 15:15:15 -0400
Subject: [PATCH 1/3] [C23] Use thread_local semantics

When implementing thread_local as a keyword in C23, we accidentally
started using C++11 thread_local semantics when using that keyword
instead of using C11 _Thread_local semantics.

This oversight is fixed by pretending the user wrote _Thread_local
instead. This doesn't have the best behavior in terms of diagnostics,
but it does correct the semantic behavior.

Fixes https://github.com/llvm/llvm-project/issues/70068
---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Parse/ParseDecl.cpp | 11 +--
 clang/test/CodeGen/thread_local.c | 27 +++
 clang/test/Sema/thread_local.c| 16 
 4 files changed, 55 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGen/thread_local.c
 create mode 100644 clang/test/Sema/thread_local.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cf3f0c343b4d014..b104c5da97ab124 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -493,6 +493,9 @@ Bug Fixes in This Version
   Fixes (`#65143 `_)
 - Fix crash in formatting the real/imaginary part of a complex lvalue.
   Fixes (`#69218 `_)
+- No longer use C++ ``thread_local`` semantics in C23 when using
+  ``thread_local`` instead of ``_Thread_local``.
+  Fixes (`#70068 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 14a28e5a31c57db..43c18090d6ef79c 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -4076,8 +4076,15 @@ void Parser::ParseDeclarationSpecifiers(
 case tok::kw_thread_local:
   if (getLangOpts().C23)
 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
-  isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, 
Loc,
-   PrevSpec, DiagID);
+  // We map thread_local to _Thread_local in C23 mode so it retains the C
+  // semantics rather than getting the C++ semantics.
+  // FIXME: diagnostics will now show _Thread_local when the user wrote
+  // thread_local in source in C23 mode; we need some general way to
+  // identify which way the user spelled the keyword in source.
+  isInvalid = DS.SetStorageClassSpecThread(
+  getLangOpts().C23 ? DeclSpec::TSCS__Thread_local
+: DeclSpec::TSCS_thread_local,
+  Loc, PrevSpec, DiagID);
   isStorageClass = true;
   break;
 case tok::kw__Thread_local:
diff --git a/clang/test/CodeGen/thread_local.c 
b/clang/test/CodeGen/thread_local.c
new file mode 100644
index 000..2daa43492cbf271
--- /dev/null
+++ b/clang/test/CodeGen/thread_local.c
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple i686-pc-linux-gnu -std=c23 -emit-llvm -o - %s | 
FileCheck %s
+
+// Ensure that thread_local and _Thread_local emit the same codegen. See
+// https://github.com/llvm/llvm-project/issues/70068 for details.
+
+void func(void) {
+  static thread_local int i = 12;
+  static _Thread_local int j = 13;
+
+  extern thread_local int k;
+  extern thread_local int l;
+
+  (void)k;
+  (void)l;
+}
+
+// CHECK:  @func.i = internal thread_local global i32 12, align 4
+// CHECK-NEXT: @func.j = internal thread_local global i32 13, align 4
+// CHECK-NEXT: @k = external thread_local global i32, align 4
+// CHECK-NEXT: @l = external thread_local global i32, align 4
+
+// CHECK:  define dso_local void @func()
+// CHECK-NEXT: entry:
+// CHECK-NEXT: %0 = call align 4 ptr @llvm.threadlocal.address.p0(ptr align 4 
@k)
+// CHECK-NEXT: %1 = load i32, ptr %0, align 4
+// CHECK-NEXT: %2 = call align 4 ptr @llvm.threadlocal.address.p0(ptr align 4 
@l)
+// CHECK-NEXT: %3 = load i32, ptr %2, align 4
diff --git a/clang/test/Sema/thread_local.c b/clang/test/Sema/thread_local.c
new file mode 100644
index 000..c4a4dd4ceb1cd0d
--- /dev/null
+++ b/clang/test/Sema/thread_local.c
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c23 %s -verify
+
+// Ensure that thread_local and _Thread_local are synonyms in C23 and both
+// restrict local variables to be explicitly static or extern.
+void func(void) {
+  // FIXME: it would be nice if the diagnostic said 'thread_local' in this 
case.
+  thread_local int i = 12;  // expected-error {{'_Thread_local' variables must 
have global storage}}
+  _Thread_local int j = 13; // expected-error {{'_Thread_local' variables must 
have global storage}}
+
+  static thread_local int k = 14;
+  static _Thread_local int l = 15;
+
+  extern thread_local 

[clang] [C23] Use thread_local semantics (PR #70107)

2023-10-24 Thread Erich Keane via cfe-commits


@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple i686-pc-linux-gnu -std=c23 -emit-llvm -o - %s | 
FileCheck %s
+
+// Ensure that thread_local and _Thread_local emit the same codegen. See
+// https://github.com/llvm/llvm-project/issues/70068 for details.
+
+void func(void) {
+  static thread_local int i = 12;
+  static _Thread_local int j = 13;
+
+  extern thread_local int k;
+  extern thread_local int l;
+
+  (void)k;
+  (void)l;
+}
+
+// CHECK:  @func.i = internal thread_local global i32 12, align 4
+// CHECK-NEXT: @func.j = internal thread_local global i32 13, align 4
+// CHECK-NEXT: @k = external thread_local global i32, align 4
+// CHECK-NEXT: @l = external thread_local global i32, align 4
+
+// CHECK:  define dso_local void @func()
+// CHECK-NEXT: entry:
+// CHECK-NEXT: %[[K:.+]] = call align 4 ptr @llvm.threadlocal.address.p0(ptr 
align 4 @k)
+// CHECK-NEXT: %{{.+}} = load i32, ptr %[[K]], align 4

erichkeane wrote:

Probably not worth having anything up to or including the equals sign here, it 
doesn't really add anything.  Same on line 27.

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


[clang] [C23] Use thread_local semantics (PR #70107)

2023-10-24 Thread Aaron Ballman via cfe-commits


@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple i686-pc-linux-gnu -std=c23 -emit-llvm -o - %s | 
FileCheck %s
+
+// Ensure that thread_local and _Thread_local emit the same codegen. See
+// https://github.com/llvm/llvm-project/issues/70068 for details.
+
+void func(void) {
+  static thread_local int i = 12;
+  static _Thread_local int j = 13;
+
+  extern thread_local int k;
+  extern thread_local int l;
+
+  (void)k;
+  (void)l;
+}
+
+// CHECK:  @func.i = internal thread_local global i32 12, align 4
+// CHECK-NEXT: @func.j = internal thread_local global i32 13, align 4
+// CHECK-NEXT: @k = external thread_local global i32, align 4
+// CHECK-NEXT: @l = external thread_local global i32, align 4
+
+// CHECK:  define dso_local void @func()
+// CHECK-NEXT: entry:
+// CHECK-NEXT: %0 = call align 4 ptr @llvm.threadlocal.address.p0(ptr align 4 
@k)

AaronBallman wrote:

Thanks! I always forget that rule. This should be fixed now.

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


[clang] [C23] Use thread_local semantics (PR #70107)

2023-10-24 Thread Aaron Ballman via cfe-commits


@@ -4076,8 +4076,15 @@ void Parser::ParseDeclarationSpecifiers(
 case tok::kw_thread_local:
   if (getLangOpts().C23)
 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
-  isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, 
Loc,
-   PrevSpec, DiagID);
+  // We map thread_local to _Thread_local in C23 mode so it retains the C
+  // semantics rather than getting the C++ semantics.
+  // FIXME: diagnostics will now show _Thread_local when the user wrote

AaronBallman wrote:

This should be fixed now.

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


[clang-tools-extra] [OpenMPIRBuilder] Remove wrapper function in `createTask`, `createTeams` (PR #67723)

2023-10-24 Thread Johannes Doerfert via cfe-commits


@@ -1736,26 +1750,20 @@ OpenMPIRBuilder::createTask(const LocationDescription 
&Loc,
 
 StaleCI->eraseFromParent();
 
-// Emit the body for wrapper function
-BasicBlock *WrapperEntryBB =
-BasicBlock::Create(M.getContext(), "", WrapperFunc);
-Builder.SetInsertPoint(WrapperEntryBB);
+Builder.SetInsertPoint(TaskAllocaBB, TaskAllocaBB->begin());
 if (HasShareds) {
-  llvm::Value *Shareds =
-  Builder.CreateLoad(VoidPtr, WrapperFunc->getArg(1));
-  Builder.CreateCall(&OutlinedFn, {Shareds});
-} else {
-  Builder.CreateCall(&OutlinedFn);
+  LoadInst *Shareds = Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
+  OutlinedFn.getArg(1)->replaceUsesWithIf(
+  Shareds, [Shareds](Use &U) { return U.getUser() != Shareds; });
+}
+
+while (!ToBeDeleted.empty()) {
+  ToBeDeleted.top()->eraseFromParent();
+  ToBeDeleted.pop();

jdoerfert wrote:

There is no need to pop anything, we have this code in other places already, 
why do we need to come up with new and exciting ways to do the same thing?

```
for (auto *TBD : ToBeDeleted)
  TBD->eraseFromParent
```

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


[libunwind] [OpenMPIRBuilder] Remove wrapper function in `createTask`, `createTeams` (PR #67723)

2023-10-24 Thread Johannes Doerfert via cfe-commits


@@ -5771,84 +5779,63 @@ OpenMPIRBuilder::createTeams(const LocationDescription 
&Loc,
   BasicBlock *AllocaBB =
   splitBB(Builder, /*CreateBranch=*/true, "teams.alloca");
 
+  // Generate the body of teams.
+  InsertPointTy AllocaIP(AllocaBB, AllocaBB->begin());
+  InsertPointTy CodeGenIP(BodyBB, BodyBB->begin());
+  BodyGenCB(AllocaIP, CodeGenIP);
+
   OutlineInfo OI;
   OI.EntryBB = AllocaBB;
   OI.ExitBB = ExitBB;
   OI.OuterAllocaBB = &OuterAllocaBB;
-  OI.PostOutlineCB = [this, Ident](Function &OutlinedFn) {
-// The input IR here looks like the following-
-// ```
-// func @current_fn() {
-//   outlined_fn(%args)
-// }
-// func @outlined_fn(%args) { ... }
-// ```
-//
-// This is changed to the following-
-//
-// ```
-// func @current_fn() {
-//   runtime_call(..., wrapper_fn, ...)
-// }
-// func @wrapper_fn(..., %args) {
-//   outlined_fn(%args)
-// }
-// func @outlined_fn(%args) { ... }
-// ```
 
+  // Insert fake values for global tid and bound tid.
+  std::stack ToBeDeleted;
+  InsertPointTy OuterAllocaIP(&OuterAllocaBB, OuterAllocaBB.begin());
+  OI.ExcludeArgsFromAggregate.push_back(createFakeIntVal(
+  Builder, OuterAllocaIP, ToBeDeleted, AllocaIP, "gid", true));
+  OI.ExcludeArgsFromAggregate.push_back(createFakeIntVal(
+  Builder, OuterAllocaIP, ToBeDeleted, AllocaIP, "tid", true));
+
+  OI.PostOutlineCB = [this, Ident, ToBeDeleted](Function &OutlinedFn) mutable {
 // The stale call instruction will be replaced with a new call instruction
-// for runtime call with a wrapper function.
+// for runtime call with the outlined function.
 
 assert(OutlinedFn.getNumUses() == 1 &&
"there must be a single user for the outlined function");
 CallInst *StaleCI = cast(OutlinedFn.user_back());
+ToBeDeleted.push(StaleCI);
+
+assert((OutlinedFn.arg_size() == 2 || OutlinedFn.arg_size() == 3) &&
+   "Outlined function must have two or three arguments only");
+
+bool HasShared = OutlinedFn.arg_size() == 3;
 
-// Create the wrapper function.
-SmallVector WrapperArgTys{Builder.getPtrTy(), Builder.getPtrTy()};
-for (auto &Arg : OutlinedFn.args())
-  WrapperArgTys.push_back(Arg.getType());
-FunctionCallee WrapperFuncVal = M.getOrInsertFunction(
-(Twine(OutlinedFn.getName()) + ".teams").str(),
-FunctionType::get(Builder.getVoidTy(), WrapperArgTys, false));
-Function *WrapperFunc = dyn_cast(WrapperFuncVal.getCallee());
-WrapperFunc->getArg(0)->setName("global_tid");
-WrapperFunc->getArg(1)->setName("bound_tid");
-if (WrapperFunc->arg_size() > 2)
-  WrapperFunc->getArg(2)->setName("data");
-
-// Emit the body of the wrapper function - just a call to outlined function
-// and return statement.
-BasicBlock *WrapperEntryBB =
-BasicBlock::Create(M.getContext(), "entrybb", WrapperFunc);
-Builder.SetInsertPoint(WrapperEntryBB);
-SmallVector Args;
-for (size_t ArgIndex = 2; ArgIndex < WrapperFunc->arg_size(); ArgIndex++)
-  Args.push_back(WrapperFunc->getArg(ArgIndex));
-Builder.CreateCall(&OutlinedFn, Args);
-Builder.CreateRetVoid();
-
-OutlinedFn.addFnAttr(Attribute::AttrKind::AlwaysInline);
+OutlinedFn.getArg(0)->setName("global.tid.ptr");
+OutlinedFn.getArg(1)->setName("bound.tid.ptr");
+if (HasShared)
+  OutlinedFn.getArg(2)->setName("data");
 
 // Call to the runtime function for teams in the current function.
 assert(StaleCI && "Error while outlining - no CallInst user found for the "
   "outlined function.");
 Builder.SetInsertPoint(StaleCI);
-Args = {Ident, Builder.getInt32(StaleCI->arg_size()), WrapperFunc};
-for (Use &Arg : StaleCI->args())
-  Args.push_back(Arg);
+SmallVector Args = {
+Ident, Builder.getInt32(StaleCI->arg_size() - 2), &OutlinedFn};
+if (HasShared)
+  Args.push_back(StaleCI->getArgOperand(2));
 Builder.CreateCall(getOrCreateRuntimeFunctionPtr(
omp::RuntimeFunction::OMPRTL___kmpc_fork_teams),
Args);
-StaleCI->eraseFromParent();
+
+while (!ToBeDeleted.empty()) {
+  ToBeDeleted.top()->eraseFromParent();
+  ToBeDeleted.pop();

jdoerfert wrote:

same

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


[clang] [C23] Use thread_local semantics (PR #70107)

2023-10-24 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman updated 
https://github.com/llvm/llvm-project/pull/70107

>From 9db10fc83ec3683b1d5b6f8606fc37a83fe224fa Mon Sep 17 00:00:00 2001
From: Aaron Ballman 
Date: Tue, 24 Oct 2023 15:15:15 -0400
Subject: [PATCH 1/2] [C23] Use thread_local semantics

When implementing thread_local as a keyword in C23, we accidentally
started using C++11 thread_local semantics when using that keyword
instead of using C11 _Thread_local semantics.

This oversight is fixed by pretending the user wrote _Thread_local
instead. This doesn't have the best behavior in terms of diagnostics,
but it does correct the semantic behavior.

Fixes https://github.com/llvm/llvm-project/issues/70068
---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Parse/ParseDecl.cpp | 11 +--
 clang/test/CodeGen/thread_local.c | 27 +++
 clang/test/Sema/thread_local.c| 16 
 4 files changed, 55 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGen/thread_local.c
 create mode 100644 clang/test/Sema/thread_local.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cf3f0c343b4d014..b104c5da97ab124 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -493,6 +493,9 @@ Bug Fixes in This Version
   Fixes (`#65143 `_)
 - Fix crash in formatting the real/imaginary part of a complex lvalue.
   Fixes (`#69218 `_)
+- No longer use C++ ``thread_local`` semantics in C23 when using
+  ``thread_local`` instead of ``_Thread_local``.
+  Fixes (`#70068 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 14a28e5a31c57db..43c18090d6ef79c 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -4076,8 +4076,15 @@ void Parser::ParseDeclarationSpecifiers(
 case tok::kw_thread_local:
   if (getLangOpts().C23)
 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
-  isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, 
Loc,
-   PrevSpec, DiagID);
+  // We map thread_local to _Thread_local in C23 mode so it retains the C
+  // semantics rather than getting the C++ semantics.
+  // FIXME: diagnostics will now show _Thread_local when the user wrote
+  // thread_local in source in C23 mode; we need some general way to
+  // identify which way the user spelled the keyword in source.
+  isInvalid = DS.SetStorageClassSpecThread(
+  getLangOpts().C23 ? DeclSpec::TSCS__Thread_local
+: DeclSpec::TSCS_thread_local,
+  Loc, PrevSpec, DiagID);
   isStorageClass = true;
   break;
 case tok::kw__Thread_local:
diff --git a/clang/test/CodeGen/thread_local.c 
b/clang/test/CodeGen/thread_local.c
new file mode 100644
index 000..2daa43492cbf271
--- /dev/null
+++ b/clang/test/CodeGen/thread_local.c
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple i686-pc-linux-gnu -std=c23 -emit-llvm -o - %s | 
FileCheck %s
+
+// Ensure that thread_local and _Thread_local emit the same codegen. See
+// https://github.com/llvm/llvm-project/issues/70068 for details.
+
+void func(void) {
+  static thread_local int i = 12;
+  static _Thread_local int j = 13;
+
+  extern thread_local int k;
+  extern thread_local int l;
+
+  (void)k;
+  (void)l;
+}
+
+// CHECK:  @func.i = internal thread_local global i32 12, align 4
+// CHECK-NEXT: @func.j = internal thread_local global i32 13, align 4
+// CHECK-NEXT: @k = external thread_local global i32, align 4
+// CHECK-NEXT: @l = external thread_local global i32, align 4
+
+// CHECK:  define dso_local void @func()
+// CHECK-NEXT: entry:
+// CHECK-NEXT: %0 = call align 4 ptr @llvm.threadlocal.address.p0(ptr align 4 
@k)
+// CHECK-NEXT: %1 = load i32, ptr %0, align 4
+// CHECK-NEXT: %2 = call align 4 ptr @llvm.threadlocal.address.p0(ptr align 4 
@l)
+// CHECK-NEXT: %3 = load i32, ptr %2, align 4
diff --git a/clang/test/Sema/thread_local.c b/clang/test/Sema/thread_local.c
new file mode 100644
index 000..c4a4dd4ceb1cd0d
--- /dev/null
+++ b/clang/test/Sema/thread_local.c
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c23 %s -verify
+
+// Ensure that thread_local and _Thread_local are synonyms in C23 and both
+// restrict local variables to be explicitly static or extern.
+void func(void) {
+  // FIXME: it would be nice if the diagnostic said 'thread_local' in this 
case.
+  thread_local int i = 12;  // expected-error {{'_Thread_local' variables must 
have global storage}}
+  _Thread_local int j = 13; // expected-error {{'_Thread_local' variables must 
have global storage}}
+
+  static thread_local int k = 14;
+  static _Thread_local int l = 15;
+
+  extern thread_local 

[clang] [OpenMPIRBuilder] Remove wrapper function in `createTask`, `createTeams` (PR #67723)

2023-10-24 Thread Johannes Doerfert via cfe-commits


@@ -1736,26 +1750,20 @@ OpenMPIRBuilder::createTask(const LocationDescription 
&Loc,
 
 StaleCI->eraseFromParent();
 
-// Emit the body for wrapper function
-BasicBlock *WrapperEntryBB =
-BasicBlock::Create(M.getContext(), "", WrapperFunc);
-Builder.SetInsertPoint(WrapperEntryBB);
+Builder.SetInsertPoint(TaskAllocaBB, TaskAllocaBB->begin());
 if (HasShareds) {
-  llvm::Value *Shareds =
-  Builder.CreateLoad(VoidPtr, WrapperFunc->getArg(1));
-  Builder.CreateCall(&OutlinedFn, {Shareds});
-} else {
-  Builder.CreateCall(&OutlinedFn);
+  LoadInst *Shareds = Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
+  OutlinedFn.getArg(1)->replaceUsesWithIf(
+  Shareds, [Shareds](Use &U) { return U.getUser() != Shareds; });
+}
+
+while (!ToBeDeleted.empty()) {
+  ToBeDeleted.top()->eraseFromParent();
+  ToBeDeleted.pop();

jdoerfert wrote:

There is no need to pop anything, we have this code in other places already, 
why do we need to come up with new and exciting ways to do the same thing?

```
for (auto *TBD : ToBeDeleted)
  TBD->eraseFromParent
```

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


[clang-tools-extra] [OpenMPIRBuilder] Remove wrapper function in `createTask`, `createTeams` (PR #67723)

2023-10-24 Thread Johannes Doerfert via cfe-commits


@@ -1523,41 +1560,31 @@ OpenMPIRBuilder::createTask(const LocationDescription 
&Loc,
   BasicBlock *TaskAllocaBB =
   splitBB(Builder, /*CreateBranch=*/true, "task.alloca");
 
+  InsertPointTy TaskAllocaIP =
+  InsertPointTy(TaskAllocaBB, TaskAllocaBB->begin());
+  InsertPointTy TaskBodyIP = InsertPointTy(TaskBodyBB, TaskBodyBB->begin());
+  BodyGenCB(TaskAllocaIP, TaskBodyIP);
+
   OutlineInfo OI;
   OI.EntryBB = TaskAllocaBB;
   OI.OuterAllocaBB = AllocaIP.getBlock();
   OI.ExitBB = TaskExitBB;
-  OI.PostOutlineCB = [this, Ident, Tied, Final, IfCondition,
-  Dependencies](Function &OutlinedFn) {
-// The input IR here looks like the following-
-// ```
-// func @current_fn() {
-//   outlined_fn(%args)
-// }
-// func @outlined_fn(%args) { ... }
-// ```
-//
-// This is changed to the following-
-//
-// ```
-// func @current_fn() {
-//   runtime_call(..., wrapper_fn, ...)
-// }
-// func @wrapper_fn(..., %args) {
-//   outlined_fn(%args)
-// }
-// func @outlined_fn(%args) { ... }
-// ```
 
-// The stale call instruction will be replaced with a new call instruction
-// for runtime call with a wrapper function.
+  // Add the thread ID argument.
+  std::stack ToBeDeleted;

jdoerfert wrote:

Why not a SmallVector, like we use everywhere else? We can reasonably guess the 
size to avoid dynamic allocations.

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


[clang] [OpenMPIRBuilder] Remove wrapper function in `createTask`, `createTeams` (PR #67723)

2023-10-24 Thread Johannes Doerfert via cfe-commits


@@ -1523,41 +1560,31 @@ OpenMPIRBuilder::createTask(const LocationDescription 
&Loc,
   BasicBlock *TaskAllocaBB =
   splitBB(Builder, /*CreateBranch=*/true, "task.alloca");
 
+  InsertPointTy TaskAllocaIP =
+  InsertPointTy(TaskAllocaBB, TaskAllocaBB->begin());
+  InsertPointTy TaskBodyIP = InsertPointTy(TaskBodyBB, TaskBodyBB->begin());
+  BodyGenCB(TaskAllocaIP, TaskBodyIP);
+
   OutlineInfo OI;
   OI.EntryBB = TaskAllocaBB;
   OI.OuterAllocaBB = AllocaIP.getBlock();
   OI.ExitBB = TaskExitBB;
-  OI.PostOutlineCB = [this, Ident, Tied, Final, IfCondition,
-  Dependencies](Function &OutlinedFn) {
-// The input IR here looks like the following-
-// ```
-// func @current_fn() {
-//   outlined_fn(%args)
-// }
-// func @outlined_fn(%args) { ... }
-// ```
-//
-// This is changed to the following-
-//
-// ```
-// func @current_fn() {
-//   runtime_call(..., wrapper_fn, ...)
-// }
-// func @wrapper_fn(..., %args) {
-//   outlined_fn(%args)
-// }
-// func @outlined_fn(%args) { ... }
-// ```
 
-// The stale call instruction will be replaced with a new call instruction
-// for runtime call with a wrapper function.
+  // Add the thread ID argument.
+  std::stack ToBeDeleted;

jdoerfert wrote:

Why not a SmallVector, like we use everywhere else? We can reasonably guess the 
size to avoid dynamic allocations.

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


[libunwind] [OpenMPIRBuilder] Remove wrapper function in `createTask`, `createTeams` (PR #67723)

2023-10-24 Thread Johannes Doerfert via cfe-commits


@@ -1523,41 +1560,31 @@ OpenMPIRBuilder::createTask(const LocationDescription 
&Loc,
   BasicBlock *TaskAllocaBB =
   splitBB(Builder, /*CreateBranch=*/true, "task.alloca");
 
+  InsertPointTy TaskAllocaIP =
+  InsertPointTy(TaskAllocaBB, TaskAllocaBB->begin());
+  InsertPointTy TaskBodyIP = InsertPointTy(TaskBodyBB, TaskBodyBB->begin());
+  BodyGenCB(TaskAllocaIP, TaskBodyIP);
+
   OutlineInfo OI;
   OI.EntryBB = TaskAllocaBB;
   OI.OuterAllocaBB = AllocaIP.getBlock();
   OI.ExitBB = TaskExitBB;
-  OI.PostOutlineCB = [this, Ident, Tied, Final, IfCondition,
-  Dependencies](Function &OutlinedFn) {
-// The input IR here looks like the following-
-// ```
-// func @current_fn() {
-//   outlined_fn(%args)
-// }
-// func @outlined_fn(%args) { ... }
-// ```
-//
-// This is changed to the following-
-//
-// ```
-// func @current_fn() {
-//   runtime_call(..., wrapper_fn, ...)
-// }
-// func @wrapper_fn(..., %args) {
-//   outlined_fn(%args)
-// }
-// func @outlined_fn(%args) { ... }
-// ```
 
-// The stale call instruction will be replaced with a new call instruction
-// for runtime call with a wrapper function.
+  // Add the thread ID argument.
+  std::stack ToBeDeleted;

jdoerfert wrote:

Why not a SmallVector, like we use everywhere else? We can reasonably guess the 
size to avoid dynamic allocations.

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


[libunwind] [OpenMPIRBuilder] Remove wrapper function in `createTask`, `createTeams` (PR #67723)

2023-10-24 Thread Johannes Doerfert via cfe-commits


@@ -1736,26 +1750,20 @@ OpenMPIRBuilder::createTask(const LocationDescription 
&Loc,
 
 StaleCI->eraseFromParent();
 
-// Emit the body for wrapper function
-BasicBlock *WrapperEntryBB =
-BasicBlock::Create(M.getContext(), "", WrapperFunc);
-Builder.SetInsertPoint(WrapperEntryBB);
+Builder.SetInsertPoint(TaskAllocaBB, TaskAllocaBB->begin());
 if (HasShareds) {
-  llvm::Value *Shareds =
-  Builder.CreateLoad(VoidPtr, WrapperFunc->getArg(1));
-  Builder.CreateCall(&OutlinedFn, {Shareds});
-} else {
-  Builder.CreateCall(&OutlinedFn);
+  LoadInst *Shareds = Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
+  OutlinedFn.getArg(1)->replaceUsesWithIf(
+  Shareds, [Shareds](Use &U) { return U.getUser() != Shareds; });
+}
+
+while (!ToBeDeleted.empty()) {
+  ToBeDeleted.top()->eraseFromParent();
+  ToBeDeleted.pop();

jdoerfert wrote:

There is no need to pop anything, we have this code in other places already, 
why do we need to come up with new and exciting ways to do the same thing?

```
for (auto *TBD : ToBeDeleted)
  TBD->eraseFromParent
```

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


[clang] [clang][Interp] Cleaning up `FIXME`s added during `ArrayInitLoopExpr` implementation. (PR #70053)

2023-10-24 Thread via cfe-commits


@@ -389,10 +391,28 @@ template  class LocalScope : public 
VariableScope {
   if (!Local.Desc->isPrimitive() && !Local.Desc->isPrimitiveArray()) {
 this->Ctx->emitGetPtrLocal(Local.Offset, SourceInfo{});
 this->Ctx->emitRecordDestruction(Local.Desc);
+removeIfStoredOpaqueValue(Local);
   }
 }
   }
 
+  void removeStoredOpaqueValues() {
+if (!Idx)
+  return;
+
+for (Scope::Local &Local : this->Ctx->Descriptors[*Idx]) {
+  removeIfStoredOpaqueValue(Local);
+}
+  }
+
+  void removeIfStoredOpaqueValue(const Scope::Local &Local) {
+if (auto *OVE =
+llvm::dyn_cast_or_null(Local.Desc->asExpr());
+OVE && this->Ctx->OpaqueExprs.contains(OVE)) {
+  this->Ctx->OpaqueExprs.erase(OVE);
+};
+  }
+

isuckatcs wrote:

There might be cases like loops or recursive functions, where we might want to 
evaluate the same `OpaqueValueExpr` multiple times, but we will fail if it is 
left in the map. I'm just trying to be careful here.

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


[clang] [C23] Use thread_local semantics (PR #70107)

2023-10-24 Thread Erich Keane via cfe-commits


@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple i686-pc-linux-gnu -std=c23 -emit-llvm -o - %s | 
FileCheck %s
+
+// Ensure that thread_local and _Thread_local emit the same codegen. See
+// https://github.com/llvm/llvm-project/issues/70068 for details.
+
+void func(void) {
+  static thread_local int i = 12;
+  static _Thread_local int j = 13;
+
+  extern thread_local int k;
+  extern thread_local int l;
+
+  (void)k;
+  (void)l;
+}
+
+// CHECK:  @func.i = internal thread_local global i32 12, align 4
+// CHECK-NEXT: @func.j = internal thread_local global i32 13, align 4
+// CHECK-NEXT: @k = external thread_local global i32, align 4
+// CHECK-NEXT: @l = external thread_local global i32, align 4
+
+// CHECK:  define dso_local void @func()
+// CHECK-NEXT: entry:
+// CHECK-NEXT: %0 = call align 4 ptr @llvm.threadlocal.address.p0(ptr align 4 
@k)

erichkeane wrote:

for the %0-3 you probably want to do wildcards, since these can sometimes end 
up with 'names' depending on your config.  The rest I think are all ok.

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


[clang] [C23] Use thread_local semantics (PR #70107)

2023-10-24 Thread via cfe-commits


@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c23 %s -verify
+
+// Ensure that thread_local and _Thread_local are synonyms in C23 and both
+// restrict local variables to be explicitly static or extern.
+void func(void) {
+  // FIXME: it would be nice if the diagnostic said 'thread_local' in this 
case.
+  thread_local int i = 12;  // expected-error {{'_Thread_local' variables must 
have global storage}}

cor3ntin wrote:

Another solution would be to say 'thread local variables' which is spelling 
agnostic.

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


  1   2   3   4   >