[PATCH] D123952: [FPEnv] Allow CompoundStmt to keep FP options

2022-05-23 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff updated this revision to Diff 431294.
sepavloff added a comment.

Update after D125635  and rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123952

Files:
  clang/include/clang/AST/JSONNodeDumper.h
  clang/include/clang/AST/Stmt.h
  clang/include/clang/AST/TextNodeDumper.h
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Sema/ScopeInfo.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/JSONNodeDumper.cpp
  clang/lib/AST/Stmt.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/Analysis/BodyFarm.cpp
  clang/lib/Basic/LangOptions.cpp
  clang/lib/CodeGen/CGCoroutine.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/test/AST/ast-dump-fpfeatures.cpp
  clang/test/AST/ast-dump-pragma-json.c
  clang/test/AST/ast-print-fp-pragmas.c

Index: clang/test/AST/ast-print-fp-pragmas.c
===
--- /dev/null
+++ clang/test/AST/ast-print-fp-pragmas.c
@@ -0,0 +1,69 @@
+// RUN: %clang_cc1 -ast-print %s -o - | FileCheck %s
+
+float func_1(float x, float y) {
+#pragma STDC FENV_ACCESS ON
+  if (x != 0) {
+return y;
+  }
+  return x + y;
+}
+
+// CHECK-LABEL: float func_1(float x, float y) {
+// CHECK-NEXT:  #pragma STDC FENV_ACCESS ON
+// CHECK-NEXT:  if (x != 0) {
+// CHECK-NEXT:  return y;
+// CHECK-NEXT:  }
+// CHECK-NEXT:  return x + y;
+// CHECK-NEXT:  }
+
+float func_2(float x, float y) {
+#pragma STDC FENV_ACCESS ON
+  if (x != 0) {
+  #pragma STDC FENV_ACCESS OFF
+return y;
+  }
+  return x + y;
+}
+
+// CHECK-LABEL: float func_2(float x, float y) {
+// CHECK-NEXT:  #pragma STDC FENV_ACCESS ON
+// CHECK-NEXT:  if (x != 0) {
+// CHECK-NEXT:  #pragma STDC FENV_ACCESS OFF
+// CHECK-NEXT:  return y;
+// CHECK-NEXT:  }
+// CHECK-NEXT:  return x + y;
+// CHECK-NEXT:  }
+
+float func_3(float x, float y) {
+#pragma STDC FENV_ROUND FE_DOWNWARD
+  return x + y;
+}
+
+// CHECK-LABEL: float func_3(float x, float y) {
+// CHECK-NEXT:  #pragma STDC FENV_ROUND FE_UPWARD
+// CHECK-NEXT:  return x + y;
+// CHECK-NEXT:  }
+
+float func_4(float x, float y, float z) {
+#pragma STDC FENV_ACCESS ON
+#pragma clang fp exceptions(maytrap)
+#pragma STDC FENV_ROUND FE_UPWARD
+  if (z != 0) {
+  #pragma STDC FENV_ACCESS OFF
+  #pragma STDC FENV_ROUND FE_TOWARDZERO
+return z + x;
+  }
+  return x + y;
+}
+
+// CHECK-LABEL: float func_4(float x, float y, float z) {
+// CHECK-NEXT:  #pragma STDC FENV_ACCESS ON
+// CHECK-NEXT:  #pragma clang fp exceptions(maytrap)
+// CHECK-NEXT:  #pragma STDC FENV_ROUND FE_DOWNWARD
+// CHECK-NEXT:  if (z != 0) {
+// CHECK-NEXT:  #pragma STDC FENV_ACCESS OFF
+// CHECK-NEXT:  #pragma STDC FENV_ROUND FE_TOWARDZERO
+// CHECK-NEXT:  return z + x;
+// CHECK-NEXT:  }
+// CHECK-NEXT:  return x + y;
+// CHECK-NEXT:  }
Index: clang/test/AST/ast-dump-pragma-json.c
===
--- /dev/null
+++ clang/test/AST/ast-dump-pragma-json.c
@@ -0,0 +1,485 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ast-dump=json %s | FileCheck %s
+
+float func_16(float x, float y) {
+  #pragma STDC FENV_ROUND FE_TOWARDZERO
+  if (x < 0) {
+#pragma STDC FENV_ROUND FE_UPWARD
+return x - y;
+  }
+  return x + y;
+}
+
+// NOTE: CHECK lines have been autogenerated by gen_ast_dump_json_test.py
+// using --filters=CompoundStmt
+
+
+// CHECK-NOT: {{^}}Dumping
+// CHECK:  "kind": "CompoundStmt",
+// CHECK-NEXT:  "range": {
+// CHECK-NEXT:   "begin": {
+// CHECK-NEXT:"offset": 116,
+// CHECK-NEXT:"col": 33,
+// CHECK-NEXT:"tokLen": 1
+// CHECK-NEXT:   },
+// CHECK-NEXT:   "end": {
+// CHECK-NEXT:"offset": 249,
+// CHECK-NEXT:"line": 10,
+// CHECK-NEXT:"col": 1,
+// CHECK-NEXT:"tokLen": 1
+// CHECK-NEXT:   }
+// CHECK-NEXT:  },
+// CHECK-NEXT:  "fpoptions": {
+// CHECK-NEXT:   "RoundingMode": 0
+// CHECK-NEXT:  },
+// CHECK-NEXT:  "inner": [
+// CHECK-NEXT:   {
+// CHECK-NEXT:"id": "0x{{.*}}",
+// CHECK-NEXT:"kind": "IfStmt",
+// CHECK-NEXT:"range": {
+// CHECK-NEXT: "begin": {
+// CHECK-NEXT:  "offset": 160,
+// CHECK-NEXT:  "line": 5,
+// CHECK-NEXT:  "col": 3,
+// CHECK-NEXT:  "tokLen": 2
+// CHECK-NEXT: },
+// CHECK-NEXT: "end": {
+// CHECK-NEXT:  "offset": 231,
+// CHECK-NEXT:  "line": 8,
+// CHECK-NEXT:  "col": 3,
+// CHECK-NEXT:  "tokLen": 1
+// CHECK-NEXT: }
+// CHECK-NEXT:},
+// CHECK-NEXT:"inner": [
+// CHECK-NEXT: {
+// CHECK-NEXT:  "id": "0x{{.*}}",
+// CHECK-NEXT:  "kind": "BinaryOperator",
+// CHECK-NEXT:  "range": {
+// CHECK-NEXT:   "begin":

[clang] 32f189b - [analyzer] Implement assumeInclusiveRange in terms of assumeInclusiveRangeDual

2022-05-23 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2022-05-23T09:32:44+02:00
New Revision: 32f189b0d9a881341e19e17a459f5b9cac4b0484

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

LOG: [analyzer] Implement assumeInclusiveRange in terms of 
assumeInclusiveRangeDual

Depends on D124758. This is the very same thing we have done for
assumeDual, but this time we do it for assumeInclusiveRange. This patch
is basically a no-brainer copy of that previous patch.

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h

clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
index f0dbcfd7dbff4..bd92e7ff9af93 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
@@ -94,35 +94,18 @@ class ConstraintManager {
   /// not perfectly precise and this may happen very rarely.)
   ProgramStatePair assumeDual(ProgramStateRef State, DefinedSVal Cond);
 
-  virtual ProgramStateRef assumeInclusiveRange(ProgramStateRef State,
-   NonLoc Value,
-   const llvm::APSInt &From,
-   const llvm::APSInt &To,
-   bool InBound) = 0;
-
-  virtual ProgramStatePair assumeInclusiveRangeDual(ProgramStateRef State,
-NonLoc Value,
-const llvm::APSInt &From,
-const llvm::APSInt &To) {
-ProgramStateRef StInRange =
-assumeInclusiveRange(State, Value, From, To, true);
-
-// If StTrue is infeasible, asserting the falseness of Cond is unnecessary
-// because the existing constraints already establish this.
-if (!StInRange)
-  return ProgramStatePair((ProgramStateRef)nullptr, State);
-
-ProgramStateRef StOutOfRange =
-assumeInclusiveRange(State, Value, From, To, false);
-if (!StOutOfRange) {
-  // We are careful to return the original state, /not/ StTrue,
-  // because we want to avoid having callers generate a new node
-  // in the ExplodedGraph.
-  return ProgramStatePair(State, (ProgramStateRef)nullptr);
-}
-
-return ProgramStatePair(StInRange, StOutOfRange);
-  }
+  ProgramStateRef assumeInclusiveRange(ProgramStateRef State, NonLoc Value,
+   const llvm::APSInt &From,
+   const llvm::APSInt &To, bool InBound);
+
+  /// Returns a pair of states (StInRange, StOutOfRange) where the given value
+  /// is assumed to be in the range or out of the range, respectively.
+  /// (Note that these two states might be equal if the parent state turns out
+  /// to be infeasible. This may happen if the underlying constraint solver is
+  /// not perfectly precise and this may happen very rarely.)
+  ProgramStatePair assumeInclusiveRangeDual(ProgramStateRef State, NonLoc 
Value,
+const llvm::APSInt &From,
+const llvm::APSInt &To);
 
   /// If a symbol is perfectly constrained to a constant, attempt
   /// to return the concrete value.
@@ -163,6 +146,12 @@ class ConstraintManager {
   virtual ProgramStateRef assumeInternal(ProgramStateRef state,
  DefinedSVal Cond, bool Assumption) = 
0;
 
+  virtual ProgramStateRef assumeInclusiveRangeInternal(ProgramStateRef State,
+   NonLoc Value,
+   const llvm::APSInt 
&From,
+   const llvm::APSInt &To,
+   bool InBound) = 0;
+
   /// canReasonAbout - Not all ConstraintManagers can accurately reason about
   ///  all SVal values.  This method returns true if the ConstraintManager can
   ///  reasonably handle a given SVal value.  This is typically queried by

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
index 50206f6883adb..725140e073c61 100644
--- 
a/clang/include/clang/S

[clang] 96fba64 - [analyzer][NFC] Factor out the copy-paste code repetition of assumeDual and assumeInclusiveRangeDual

2022-05-23 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2022-05-23T09:32:44+02:00
New Revision: 96fba640cf58402b1015924f6582b14c6ac8cc32

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

LOG: [analyzer][NFC] Factor out the copy-paste code repetition of assumeDual 
and assumeInclusiveRangeDual

Depends on D125892. There might be efficiency and performance
implications by using a lambda. Thus, I am going to conduct measurements
to see if there is any noticeable impact.
I've been thinking about two more alternatives:
1) Make `assumeDualImpl` a variadic template and (perfect) forward the
   arguments for the used `assume` function.
2) Use a macros.
I have concerns though, whether these alternatives would deteriorate the
readability of the code.

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
index bd92e7ff9af9..755371f93b9c 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
@@ -162,6 +162,10 @@ class ConstraintManager {
   /// Returns whether or not a symbol is known to be null ("true"), known to be
   /// non-null ("false"), or may be either ("underconstrained").
   virtual ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym);
+
+  template 
+  ProgramStatePair assumeDualImpl(ProgramStateRef &State,
+  AssumeFunction &Assume);
 };
 
 std::unique_ptr

diff  --git a/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp 
b/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
index 8a3ee5fb6504..096266f75ce6 100644
--- a/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -42,12 +42,14 @@ ConditionTruthVal 
ConstraintManager::checkNull(ProgramStateRef State,
   return {};
 }
 
+template 
 ConstraintManager::ProgramStatePair
-ConstraintManager::assumeDual(ProgramStateRef State, DefinedSVal Cond) {
-  ProgramStateRef StTrue = assumeInternal(State, Cond, true);
+ConstraintManager::assumeDualImpl(ProgramStateRef &State,
+  AssumeFunction &Assume) {
+  ProgramStateRef StTrue = Assume(true);
 
   if (!StTrue) {
-ProgramStateRef StFalse = assumeInternal(State, Cond, false);
+ProgramStateRef StFalse = Assume(false);
 if (LLVM_UNLIKELY(!StFalse)) { // both infeasible
   ProgramStateRef StInfeasible = 
State->cloneAsPosteriorlyOverconstrained();
   assert(StInfeasible->isPosteriorlyOverconstrained());
@@ -63,7 +65,7 @@ ConstraintManager::assumeDual(ProgramStateRef State, 
DefinedSVal Cond) {
 return ProgramStatePair(nullptr, StFalse);
   }
 
-  ProgramStateRef StFalse = assumeInternal(State, Cond, false);
+  ProgramStateRef StFalse = Assume(false);
   if (!StFalse) {
 return ProgramStatePair(StTrue, nullptr);
   }
@@ -71,36 +73,22 @@ ConstraintManager::assumeDual(ProgramStateRef State, 
DefinedSVal Cond) {
   return ProgramStatePair(StTrue, StFalse);
 }
 
+ConstraintManager::ProgramStatePair
+ConstraintManager::assumeDual(ProgramStateRef State, DefinedSVal Cond) {
+  auto AssumeFun = [&](bool Assumption) {
+return assumeInternal(State, Cond, Assumption);
+  };
+  return assumeDualImpl(State, AssumeFun);
+}
+
 ConstraintManager::ProgramStatePair
 ConstraintManager::assumeInclusiveRangeDual(ProgramStateRef State, NonLoc 
Value,
 const llvm::APSInt &From,
 const llvm::APSInt &To) {
-  ProgramStateRef StInRange =
-  assumeInclusiveRangeInternal(State, Value, From, To, true);
-  if (!StInRange) {
-ProgramStateRef StOutOfRange =
-assumeInclusiveRangeInternal(State, Value, From, To, false);
-if (LLVM_UNLIKELY(!StOutOfRange)) { // both infeasible
-  ProgramStateRef StInfeasible = 
State->cloneAsPosteriorlyOverconstrained();
-  assert(StInfeasible->isPosteriorlyOverconstrained());
-  // Checkers might rely on the API contract that both returned states
-  // cannot be null. Thus, we return StInfeasible for both branches because
-  // it might happen that a Checker uncoditionally uses one of them if the
-  // other is a nullptr. This may also happen with the non-dual and
-  // adjacent `assume(true)` and `assume(false)` calls. By implementing
-  // assume in therms of assumeDual, we can keep our API contract there as
-  // well.
-  return ProgramStatePair(StInfeasible, StInfe

[PATCH] D125892: [analyzer] Implement assumeInclusiveRange in terms of assumeInclusiveRangeDual

2022-05-23 Thread Gabor Marton via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG32f189b0d9a8: [analyzer] Implement assumeInclusiveRange in 
terms of assumeInclusiveRangeDual (authored by martong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125892

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
  clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp

Index: clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
@@ -91,7 +91,7 @@
   } // end switch
 }
 
-ProgramStateRef SimpleConstraintManager::assumeInclusiveRange(
+ProgramStateRef SimpleConstraintManager::assumeInclusiveRangeInternal(
 ProgramStateRef State, NonLoc Value, const llvm::APSInt &From,
 const llvm::APSInt &To, bool InRange) {
 
Index: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -71,8 +71,49 @@
   return ProgramStatePair(StTrue, StFalse);
 }
 
+ConstraintManager::ProgramStatePair
+ConstraintManager::assumeInclusiveRangeDual(ProgramStateRef State, NonLoc Value,
+const llvm::APSInt &From,
+const llvm::APSInt &To) {
+  ProgramStateRef StInRange =
+  assumeInclusiveRangeInternal(State, Value, From, To, true);
+  if (!StInRange) {
+ProgramStateRef StOutOfRange =
+assumeInclusiveRangeInternal(State, Value, From, To, false);
+if (LLVM_UNLIKELY(!StOutOfRange)) { // both infeasible
+  ProgramStateRef StInfeasible = State->cloneAsPosteriorlyOverconstrained();
+  assert(StInfeasible->isPosteriorlyOverconstrained());
+  // Checkers might rely on the API contract that both returned states
+  // cannot be null. Thus, we return StInfeasible for both branches because
+  // it might happen that a Checker uncoditionally uses one of them if the
+  // other is a nullptr. This may also happen with the non-dual and
+  // adjacent `assume(true)` and `assume(false)` calls. By implementing
+  // assume in therms of assumeDual, we can keep our API contract there as
+  // well.
+  return ProgramStatePair(StInfeasible, StInfeasible);
+}
+  }
+
+  ProgramStateRef StOutOfRange =
+  assumeInclusiveRangeInternal(State, Value, From, To, false);
+  if (!StOutOfRange) {
+return ProgramStatePair(StInRange, nullptr);
+  }
+
+  return ProgramStatePair(StInRange, StOutOfRange);
+}
+
 ProgramStateRef ConstraintManager::assume(ProgramStateRef State,
   DefinedSVal Cond, bool Assumption) {
   ConstraintManager::ProgramStatePair R = assumeDual(State, Cond);
   return Assumption ? R.first : R.second;
 }
+
+ProgramStateRef
+ConstraintManager::assumeInclusiveRange(ProgramStateRef State, NonLoc Value,
+const llvm::APSInt &From,
+const llvm::APSInt &To, bool InBound) {
+  ConstraintManager::ProgramStatePair R =
+  assumeInclusiveRangeDual(State, Value, From, To);
+  return InBound ? R.first : R.second;
+}
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
@@ -34,16 +34,6 @@
   // Implementation for interface from ConstraintManager.
   //===--===//
 
-  /// Ensures that the DefinedSVal conditional is expressed as a NonLoc by
-  /// creating boolean casts to handle Loc's.
-  ProgramStateRef assumeInternal(ProgramStateRef State, DefinedSVal Cond,
- bool Assumption) override;
-
-  ProgramStateRef assumeInclusiveRange(ProgramStateRef State, NonLoc Value,
-   const llvm::APSInt &From,
-   const llvm::APSInt &To,
-   bool InRange) override;
-
 protected:
   //===--===//
   // Interface that subclasses must implement.
@@ -74,6 +64,17 @@
   // Internal implementation.
   //===--===//
 
+  /// Ensures that the Defin

[PATCH] D125954: [analyzer][NFC] Factor out the copy-paste code repetition of assumeDual and assumeInclusiveRangeDual

2022-05-23 Thread Gabor Marton via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG96fba640cf58: [analyzer][NFC] Factor out the copy-paste code 
repetition of assumeDual and… (authored by martong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125954

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp


Index: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -42,12 +42,14 @@
   return {};
 }
 
+template 
 ConstraintManager::ProgramStatePair
-ConstraintManager::assumeDual(ProgramStateRef State, DefinedSVal Cond) {
-  ProgramStateRef StTrue = assumeInternal(State, Cond, true);
+ConstraintManager::assumeDualImpl(ProgramStateRef &State,
+  AssumeFunction &Assume) {
+  ProgramStateRef StTrue = Assume(true);
 
   if (!StTrue) {
-ProgramStateRef StFalse = assumeInternal(State, Cond, false);
+ProgramStateRef StFalse = Assume(false);
 if (LLVM_UNLIKELY(!StFalse)) { // both infeasible
   ProgramStateRef StInfeasible = 
State->cloneAsPosteriorlyOverconstrained();
   assert(StInfeasible->isPosteriorlyOverconstrained());
@@ -63,7 +65,7 @@
 return ProgramStatePair(nullptr, StFalse);
   }
 
-  ProgramStateRef StFalse = assumeInternal(State, Cond, false);
+  ProgramStateRef StFalse = Assume(false);
   if (!StFalse) {
 return ProgramStatePair(StTrue, nullptr);
   }
@@ -71,36 +73,22 @@
   return ProgramStatePair(StTrue, StFalse);
 }
 
+ConstraintManager::ProgramStatePair
+ConstraintManager::assumeDual(ProgramStateRef State, DefinedSVal Cond) {
+  auto AssumeFun = [&](bool Assumption) {
+return assumeInternal(State, Cond, Assumption);
+  };
+  return assumeDualImpl(State, AssumeFun);
+}
+
 ConstraintManager::ProgramStatePair
 ConstraintManager::assumeInclusiveRangeDual(ProgramStateRef State, NonLoc 
Value,
 const llvm::APSInt &From,
 const llvm::APSInt &To) {
-  ProgramStateRef StInRange =
-  assumeInclusiveRangeInternal(State, Value, From, To, true);
-  if (!StInRange) {
-ProgramStateRef StOutOfRange =
-assumeInclusiveRangeInternal(State, Value, From, To, false);
-if (LLVM_UNLIKELY(!StOutOfRange)) { // both infeasible
-  ProgramStateRef StInfeasible = 
State->cloneAsPosteriorlyOverconstrained();
-  assert(StInfeasible->isPosteriorlyOverconstrained());
-  // Checkers might rely on the API contract that both returned states
-  // cannot be null. Thus, we return StInfeasible for both branches because
-  // it might happen that a Checker uncoditionally uses one of them if the
-  // other is a nullptr. This may also happen with the non-dual and
-  // adjacent `assume(true)` and `assume(false)` calls. By implementing
-  // assume in therms of assumeDual, we can keep our API contract there as
-  // well.
-  return ProgramStatePair(StInfeasible, StInfeasible);
-}
-  }
-
-  ProgramStateRef StOutOfRange =
-  assumeInclusiveRangeInternal(State, Value, From, To, false);
-  if (!StOutOfRange) {
-return ProgramStatePair(StInRange, nullptr);
-  }
-
-  return ProgramStatePair(StInRange, StOutOfRange);
+  auto AssumeFun = [&](bool Assumption) {
+return assumeInclusiveRangeInternal(State, Value, From, To, Assumption);
+  };
+  return assumeDualImpl(State, AssumeFun);
 }
 
 ProgramStateRef ConstraintManager::assume(ProgramStateRef State,
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
@@ -162,6 +162,10 @@
   /// Returns whether or not a symbol is known to be null ("true"), known to be
   /// non-null ("false"), or may be either ("underconstrained").
   virtual ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym);
+
+  template 
+  ProgramStatePair assumeDualImpl(ProgramStateRef &State,
+  AssumeFunction &Assume);
 };
 
 std::unique_ptr


Index: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -42,12 +42,14 @@
   return {};
 }
 
+template 
 ConstraintManager::ProgramStatePair
-ConstraintManager::assumeDual(ProgramStateRef State, DefinedSVal Cond) {
-  ProgramStateRef StTrue = assumeInternal(State, Cond, true);
+ConstraintMan

[clang] 1b89a25 - [C++20] [Coroutines] Conform the updates for CWG issue 2585

2022-05-23 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-05-23T15:49:17+08:00
New Revision: 1b89a25a9b960886e486eb20b755634613c088f8

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

LOG: [C++20] [Coroutines] Conform the updates for CWG issue 2585

According to the updates in CWG issue 2585
https://cplusplus.github.io/CWG/issues/2585.html, we shouldn't find an
allocation function with (size, p0, …, pn) in global scope.

Added: 
clang/test/SemaCXX/coroutine-allocs2.cpp

Modified: 
clang/lib/Sema/SemaCoroutine.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaCoroutine.cpp 
b/clang/lib/Sema/SemaCoroutine.cpp
index b43b0b3eb957c..4281bb690ebff 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -1239,6 +1239,41 @@ bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
   return true;
 }
 
+// Collect placement arguments for allocation function of coroutine FD.
+// Return true if we collect placement arguments succesfully. Return false,
+// otherwise.
+static bool collectPlacementArgs(Sema &S, FunctionDecl &FD, SourceLocation Loc,
+ SmallVectorImpl &PlacementArgs) {
+  if (auto *MD = dyn_cast(&FD)) {
+if (MD->isInstance() && !isLambdaCallOperator(MD)) {
+  ExprResult ThisExpr = S.ActOnCXXThis(Loc);
+  if (ThisExpr.isInvalid())
+return false;
+  ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
+  if (ThisExpr.isInvalid())
+return false;
+  PlacementArgs.push_back(ThisExpr.get());
+}
+  }
+
+  for (auto *PD : FD.parameters()) {
+if (PD->getType()->isDependentType())
+  continue;
+
+// Build a reference to the parameter.
+auto PDLoc = PD->getLocation();
+ExprResult PDRefExpr =
+S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
+   ExprValueKind::VK_LValue, PDLoc);
+if (PDRefExpr.isInvalid())
+  return false;
+
+PlacementArgs.push_back(PDRefExpr.get());
+  }
+
+  return true;
+}
+
 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
   // Form and check allocation and deallocation calls.
   assert(!IsPromiseDependentType &&
@@ -1255,13 +1290,7 @@ bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
   // allocated, followed by the coroutine function's arguments. If a matching
   // allocation function exists, use it. Otherwise, use an allocation function
   // that just takes the requested size.
-
-  FunctionDecl *OperatorNew = nullptr;
-  FunctionDecl *OperatorDelete = nullptr;
-  FunctionDecl *UnusedResult = nullptr;
-  bool PassAlignment = false;
-  SmallVector PlacementArgs;
-
+  //
   // [dcl.fct.def.coroutine]p9
   //   An implementation may need to allocate additional storage for a
   //   coroutine.
@@ -1288,31 +1317,12 @@ bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
   // and p_i denotes the i-th function parameter otherwise. For a non-static
   // member function, q_1 is an lvalue that denotes *this; any other q_i is an
   // lvalue that denotes the parameter copy corresponding to p_i.
-  if (auto *MD = dyn_cast(&FD)) {
-if (MD->isInstance() && !isLambdaCallOperator(MD)) {
-  ExprResult ThisExpr = S.ActOnCXXThis(Loc);
-  if (ThisExpr.isInvalid())
-return false;
-  ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
-  if (ThisExpr.isInvalid())
-return false;
-  PlacementArgs.push_back(ThisExpr.get());
-}
-  }
-  for (auto *PD : FD.parameters()) {
-if (PD->getType()->isDependentType())
-  continue;
 
-// Build a reference to the parameter.
-auto PDLoc = PD->getLocation();
-ExprResult PDRefExpr =
-S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
-   ExprValueKind::VK_LValue, PDLoc);
-if (PDRefExpr.isInvalid())
-  return false;
-
-PlacementArgs.push_back(PDRefExpr.get());
-  }
+  FunctionDecl *OperatorNew = nullptr;
+  FunctionDecl *OperatorDelete = nullptr;
+  FunctionDecl *UnusedResult = nullptr;
+  bool PassAlignment = false;
+  SmallVector PlacementArgs;
 
   bool PromiseContainNew = [this, &PromiseType]() -> bool {
 DeclarationName NewName =
@@ -1330,8 +1340,10 @@ bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
 //   The allocation function's name is looked up by searching for it in the
 // scope of the promise type.
 // - If any declarations are found, ...
-// - Otherwise, a search is performed in the global scope.
-Sema::AllocationFunctionScope NewScope = PromiseContainNew ? 
Sema::AFS_Class : Sema::AFS_Global;
+// - If no declarations are found in the scope of the promise type, a 
search
+// is performed in the global scope.
+Sema::AllocationFunctionScope NewScope =
+PromiseContainNew ? Sema::AFS

[PATCH] D119544: Deferred Concept Instantiation Implementation

2022-05-23 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

In D119544#3527556 , @erichkeane 
wrote:

> In D119544#3526810 , @ChuanqiXu 
> wrote:
>
>> In D119544#3494281 , @erichkeane 
>> wrote:
>>
>>> Updated to include the fix for the libcxx issue, which was that we weren't 
>>> properly differentiating between 'friend' functions based on concepts.  
>>> I'll likely be submitting this early monday or so, but would like to give 
>>> @ChuanqiXu  a chance to check out the changes.
>>>
>>> This is the same as my 'last' committed version of this patch, plus the 
>>> changes I split out into here for easier review: 
>>> https://reviews.llvm.org/D125020
>>
>> Sorry that I missed the ping. The change in that revision looks good to me.
>>
>>> I THINK what we want to do instead of trying to 're setup' the template 
>>> arguments (and instead of just 'keeping' the uninstantiated expression) is 
>>> to run some level of 'tree-transform' that updates the names of the 
>>> template parameters (including depths/etc), but without doing lookup. This 
>>> I think would fix our 'friend function' issue, and our 'comparing 
>>> constraints' stuff work correctly as well (rather than storing an 
>>> instantiated version, but not reusing it except for comparing them).
>>
>> I agree this should be a better direction.
>
> I actually got a response from Richard who seems to be more in favor of the 
> solution I tried initially (the one in this patch!).  The problems I have 
> with it I think get solved by the 'friend function' rules that I pasted 
> above, so I THINK I can fix those and be ok.  I'll still need SOME level of 
> tree-transform, but only to see if it depends on the enclosing template.

Great!

>> I agree this one should be fine. I think we could fix the problem by making 
>> non-template function inside a template class to be a dependent type. Like 
>> this one is accepted: >https://godbolt.org/z/MorzcqE1a
>> This bug might not be horrible since few developer would write friend 
>> function definition which doesn't touch the enclosing class.
>
> Yeah, that is a really strange one.  I don't think we can make it dependent 
> as then it wouldn't be callable when fully instantiate-able.  I don't have a 
> good idea how to make this work in the AST though, and might end up leaving 
> it as a 'fixme'.  As you said, I think you're right that this is a very small 
> bug-vector.

Yeah, my point is that this is not your fault. And we could fix the problem 
later when we have time since it is not hurry.


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

https://reviews.llvm.org/D119544

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


[PATCH] D124750: [MLIR] Add a utility to sort the operands of commutative ops

2022-05-23 Thread Srishti Srivastava via Phabricator via cfe-commits
srishti-pm added a comment.
Herald added a subscriber: bzcheeseman.

@Mogball @mehdi_amini @jpienaar, sorry there haven't been any updates from my 
side here for the past 10 or so days. I had been busy in some other tasks. I 
have started working on this again.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124750

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


[PATCH] D126186: [clang-tidy] Extend cert-oop57-cpp to check non-zero memset values

2022-05-23 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 created this revision.
gamesh411 added reviewers: steakhal, martong, whisperity.
gamesh411 added a project: clang-tools-extra.
Herald added subscribers: carlosgalvezp, Szelethus, dkrupp, rnkovacs, xazax.hun.
Herald added a project: All.
gamesh411 requested review of this revision.
Herald added a subscriber: cfe-commits.

Clang Tidy check cert-oop57-cpp now checks for arbitrary-valued integer
literals in memset expressions containing non-trivially
default-constructible instances. Previously it only checked 0 values.

Note that the first non-compliant example of
https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP57-CPP.+Prefer+special+member+functions+and+overloaded+operators+to+C+Standard+Library+functions
 requires this.

A comparative analysis of OS projects is currently running to see the impact of 
this change.


https://reviews.llvm.org/D126186

Files:
  clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp
@@ -88,3 +88,10 @@
   mymemcmp(&Data, &Other, sizeof(Data));
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: consider using comparison 
operators instead of calling 'mymemcmp'
 }
+
+void nonNullSetValue() {
+  NonTrivial Data;
+  // Check non-null-valued second argument.
+  std::memset(&Data, 1, sizeof(Data));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: calling 'memset' on a 
non-trivially default constructible class is undefined
+}
Index: clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
===
--- clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
+++ clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
@@ -90,7 +90,7 @@
   callExpr(callee(namedDecl(hasAnyName(
utils::options::parseListPair(BuiltinMemSet, 
MemSetNames,
ArgChecker(unless(isTriviallyDefaultConstructible()),
-  expr(integerLiteral(equals(0)
+  expr(integerLiteral(
   .bind("lazyConstruct"),
   this);
   Finder->addMatcher(


Index: clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp
@@ -88,3 +88,10 @@
   mymemcmp(&Data, &Other, sizeof(Data));
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: consider using comparison operators instead of calling 'mymemcmp'
 }
+
+void nonNullSetValue() {
+  NonTrivial Data;
+  // Check non-null-valued second argument.
+  std::memset(&Data, 1, sizeof(Data));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: calling 'memset' on a non-trivially default constructible class is undefined
+}
Index: clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
===
--- clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
+++ clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
@@ -90,7 +90,7 @@
   callExpr(callee(namedDecl(hasAnyName(
utils::options::parseListPair(BuiltinMemSet, MemSetNames,
ArgChecker(unless(isTriviallyDefaultConstructible()),
-  expr(integerLiteral(equals(0)
+  expr(integerLiteral(
   .bind("lazyConstruct"),
   this);
   Finder->addMatcher(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 9e9cf3f - Revert "[C++20] [Coroutines] Conform the updates for CWG issue 2585"

2022-05-23 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-05-23T16:21:42+08:00
New Revision: 9e9cf3fa3d282644dd6802cbdf84f4ca6f932fa0

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

LOG: Revert "[C++20] [Coroutines] Conform the updates for CWG issue 2585"

This reverts commit 1b89a25a9b960886e486eb20b755634613c088f8.

The test would fail in windows versions.

Added: 


Modified: 
clang/lib/Sema/SemaCoroutine.cpp

Removed: 
clang/test/SemaCXX/coroutine-allocs2.cpp



diff  --git a/clang/lib/Sema/SemaCoroutine.cpp 
b/clang/lib/Sema/SemaCoroutine.cpp
index 4281bb690ebff..b43b0b3eb957c 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -1239,41 +1239,6 @@ bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
   return true;
 }
 
-// Collect placement arguments for allocation function of coroutine FD.
-// Return true if we collect placement arguments succesfully. Return false,
-// otherwise.
-static bool collectPlacementArgs(Sema &S, FunctionDecl &FD, SourceLocation Loc,
- SmallVectorImpl &PlacementArgs) {
-  if (auto *MD = dyn_cast(&FD)) {
-if (MD->isInstance() && !isLambdaCallOperator(MD)) {
-  ExprResult ThisExpr = S.ActOnCXXThis(Loc);
-  if (ThisExpr.isInvalid())
-return false;
-  ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
-  if (ThisExpr.isInvalid())
-return false;
-  PlacementArgs.push_back(ThisExpr.get());
-}
-  }
-
-  for (auto *PD : FD.parameters()) {
-if (PD->getType()->isDependentType())
-  continue;
-
-// Build a reference to the parameter.
-auto PDLoc = PD->getLocation();
-ExprResult PDRefExpr =
-S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
-   ExprValueKind::VK_LValue, PDLoc);
-if (PDRefExpr.isInvalid())
-  return false;
-
-PlacementArgs.push_back(PDRefExpr.get());
-  }
-
-  return true;
-}
-
 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
   // Form and check allocation and deallocation calls.
   assert(!IsPromiseDependentType &&
@@ -1290,7 +1255,13 @@ bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
   // allocated, followed by the coroutine function's arguments. If a matching
   // allocation function exists, use it. Otherwise, use an allocation function
   // that just takes the requested size.
-  //
+
+  FunctionDecl *OperatorNew = nullptr;
+  FunctionDecl *OperatorDelete = nullptr;
+  FunctionDecl *UnusedResult = nullptr;
+  bool PassAlignment = false;
+  SmallVector PlacementArgs;
+
   // [dcl.fct.def.coroutine]p9
   //   An implementation may need to allocate additional storage for a
   //   coroutine.
@@ -1317,12 +1288,31 @@ bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
   // and p_i denotes the i-th function parameter otherwise. For a non-static
   // member function, q_1 is an lvalue that denotes *this; any other q_i is an
   // lvalue that denotes the parameter copy corresponding to p_i.
+  if (auto *MD = dyn_cast(&FD)) {
+if (MD->isInstance() && !isLambdaCallOperator(MD)) {
+  ExprResult ThisExpr = S.ActOnCXXThis(Loc);
+  if (ThisExpr.isInvalid())
+return false;
+  ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
+  if (ThisExpr.isInvalid())
+return false;
+  PlacementArgs.push_back(ThisExpr.get());
+}
+  }
+  for (auto *PD : FD.parameters()) {
+if (PD->getType()->isDependentType())
+  continue;
 
-  FunctionDecl *OperatorNew = nullptr;
-  FunctionDecl *OperatorDelete = nullptr;
-  FunctionDecl *UnusedResult = nullptr;
-  bool PassAlignment = false;
-  SmallVector PlacementArgs;
+// Build a reference to the parameter.
+auto PDLoc = PD->getLocation();
+ExprResult PDRefExpr =
+S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
+   ExprValueKind::VK_LValue, PDLoc);
+if (PDRefExpr.isInvalid())
+  return false;
+
+PlacementArgs.push_back(PDRefExpr.get());
+  }
 
   bool PromiseContainNew = [this, &PromiseType]() -> bool {
 DeclarationName NewName =
@@ -1340,10 +1330,8 @@ bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
 //   The allocation function's name is looked up by searching for it in the
 // scope of the promise type.
 // - If any declarations are found, ...
-// - If no declarations are found in the scope of the promise type, a 
search
-// is performed in the global scope.
-Sema::AllocationFunctionScope NewScope =
-PromiseContainNew ? Sema::AFS_Class : Sema::AFS_Global;
+// - Otherwise, a search is performed in the global scope.
+Sema::AllocationFunctionScope NewScope = PromiseContainNew ? 
Sema::AFS_Class : Sema::AFS_Global;
 S.FindAllocationFunctions(Loc

[PATCH] D126137: [X86] Add support for `-mharden-sls=all`

2022-05-23 Thread Kristof Beyls via Phabricator via cfe-commits
kristof.beyls added a comment.

See https://gcc.gnu.org/onlinedocs/gcc/AArch64-Options.html, documentation for 
"mharden-sls": For AArch64, the options available on the command line are 
"retbr", "blr", "none" and "all".
I don't think the options necessarily have to be the same for x86.
But assuming I understand this patch correctly, it seems to me that with this 
patch -mharden-sls=all would mean fundamentally slightly different things for 
x86 vs arm and aarch64, which could be confusing to users.
IIUC this patch correctly, this patch implements the equivalent of 
aarch64/arm's -mharden-sls=retbr (i.e. add a straight-line-speculation 
mitigation for returns and indirect jumps, but not for indirect function calls).
Therefore, I wonder if it wouldn't be better to name this -mharden-sls=retbr 
for more consistency across architectures?
Or is the indirect function call case not relevant for x86 (sorry - I'm not up 
to speed on the details on the x86 side)?

Or does `MBB.back().getDesc().isIndirectBranch()` also return True for indirect 
calls, in which case my whole remark here can probably be ignored?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126137

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


[PATCH] D126187: [C++20] [Coroutines] Conform the updates for CWG issue 2585

2022-05-23 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu created this revision.
ChuanqiXu added a reviewer: erichkeane.
ChuanqiXu added a project: clang.
Herald added a project: All.
ChuanqiXu requested review of this revision.
Herald added a subscriber: cfe-commits.

This is the  following update for the update in CWG issue 2585: 
https://cplusplus.github.io/CWG/issues/2585.html

The new updates in CWG issue 2585 say that we shouldn't lookup ::operator 
new(std::size_t, p0, ..., p1) in global scope.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126187

Files:
  clang/lib/Sema/SemaCoroutine.cpp
  clang/test/SemaCXX/coroutine-allocs2.cpp

Index: clang/test/SemaCXX/coroutine-allocs2.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/coroutine-allocs2.cpp
@@ -0,0 +1,31 @@
+// Tests that we wouldn't generate an allocation call in global scope with (std::size_t, p0, ..., pn)
+// Although this test generates codes, it aims to test the semantics. So it is put here.
+// RUN: %clang_cc1 %s -std=c++20 -S -triple x86_64-unknown-linux-gnu -emit-llvm -disable-llvm-passes %s -o - | FileCheck %s
+#include "Inputs/std-coroutine.h"
+
+namespace std {
+typedef decltype(sizeof(int)) size_t;
+}
+
+struct Allocator {};
+
+struct resumable {
+  struct promise_type {
+
+resumable get_return_object() { return {}; }
+auto initial_suspend() { return std::suspend_always(); }
+auto final_suspend() noexcept { return std::suspend_always(); }
+void unhandled_exception() {}
+void return_void(){};
+  };
+};
+
+void *operator new(std::size_t, void*);
+
+resumable f1(void *) {
+  co_return;
+}
+
+// CHECK: coro.alloc:
+// CHECK-NEXT: [[SIZE:%.+]] = call [[BITWIDTH:.+]] @llvm.coro.size.[[BITWIDTH]]()
+// CHECK-NEXT: call {{.*}} ptr @_Znwm([[BITWIDTH]] noundef [[SIZE]])
Index: clang/lib/Sema/SemaCoroutine.cpp
===
--- clang/lib/Sema/SemaCoroutine.cpp
+++ clang/lib/Sema/SemaCoroutine.cpp
@@ -1239,6 +1239,41 @@
   return true;
 }
 
+// Collect placement arguments for allocation function of coroutine FD.
+// Return true if we collect placement arguments succesfully. Return false,
+// otherwise.
+static bool collectPlacementArgs(Sema &S, FunctionDecl &FD, SourceLocation Loc,
+ SmallVectorImpl &PlacementArgs) {
+  if (auto *MD = dyn_cast(&FD)) {
+if (MD->isInstance() && !isLambdaCallOperator(MD)) {
+  ExprResult ThisExpr = S.ActOnCXXThis(Loc);
+  if (ThisExpr.isInvalid())
+return false;
+  ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
+  if (ThisExpr.isInvalid())
+return false;
+  PlacementArgs.push_back(ThisExpr.get());
+}
+  }
+
+  for (auto *PD : FD.parameters()) {
+if (PD->getType()->isDependentType())
+  continue;
+
+// Build a reference to the parameter.
+auto PDLoc = PD->getLocation();
+ExprResult PDRefExpr =
+S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
+   ExprValueKind::VK_LValue, PDLoc);
+if (PDRefExpr.isInvalid())
+  return false;
+
+PlacementArgs.push_back(PDRefExpr.get());
+  }
+
+  return true;
+}
+
 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
   // Form and check allocation and deallocation calls.
   assert(!IsPromiseDependentType &&
@@ -1255,13 +1290,7 @@
   // allocated, followed by the coroutine function's arguments. If a matching
   // allocation function exists, use it. Otherwise, use an allocation function
   // that just takes the requested size.
-
-  FunctionDecl *OperatorNew = nullptr;
-  FunctionDecl *OperatorDelete = nullptr;
-  FunctionDecl *UnusedResult = nullptr;
-  bool PassAlignment = false;
-  SmallVector PlacementArgs;
-
+  //
   // [dcl.fct.def.coroutine]p9
   //   An implementation may need to allocate additional storage for a
   //   coroutine.
@@ -1288,31 +1317,12 @@
   // and p_i denotes the i-th function parameter otherwise. For a non-static
   // member function, q_1 is an lvalue that denotes *this; any other q_i is an
   // lvalue that denotes the parameter copy corresponding to p_i.
-  if (auto *MD = dyn_cast(&FD)) {
-if (MD->isInstance() && !isLambdaCallOperator(MD)) {
-  ExprResult ThisExpr = S.ActOnCXXThis(Loc);
-  if (ThisExpr.isInvalid())
-return false;
-  ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
-  if (ThisExpr.isInvalid())
-return false;
-  PlacementArgs.push_back(ThisExpr.get());
-}
-  }
-  for (auto *PD : FD.parameters()) {
-if (PD->getType()->isDependentType())
-  continue;
 
-// Build a reference to the parameter.
-auto PDLoc = PD->getLocation();
-ExprResult PDRefExpr =
-S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
-   ExprValueKind::VK_LValue, PDLoc);
-if (PDRefExpr.isInvalid())
-  return false;
-
-PlacementArgs.push_back(PDRefExpr.get());

[PATCH] D126186: [clang-tidy] Extend cert-oop57-cpp to check non-zero memset values

2022-05-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added reviewers: njames93, aaron.ballman, alexfh.
steakhal added a comment.

Looks reasonable to me.


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

https://reviews.llvm.org/D126186

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


[PATCH] D125911: [pseudo] (trivial) bracket-matching

2022-05-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/pseudo/unittests/BracketTest.cpp:103
+TEST(Bracket, SimplePair) {
+  verifyBrackets("^{ ^[ ^( ^)  ^( ^) ^] ^}");
+  verifyBrackets(") ^{ ^[ ^] ^} (");

sammccall wrote:
> hokein wrote:
> > For this simple case, just using `^` is fine.
> > 
> > I think in the near future, we would need more to verify that e.g. which 
> > two brackets are paired. And since we're defining some  some common 
> > functions used by the tests, I wonder what's the plan here (using something 
> > like `{ $1^( $1^)`?)
> > I think in the near future, we would need more to verify that e.g. which 
> > two brackets are paired.
> 
> I thought about the simplest way to specify these tests, and I think the `^` 
> is sufficient.
> 
> The combination of:
> a) the set of brackets that are paired
> b) for each bracket, knowing whether it is paired forwards or backwards
> c) certainty that brackets are well-nested
> fully determines the bracket pairing.
> 
> The test specifies a) and we check it, and b) and c) can be verified with no 
> extra information.
> 
> Does this make sense? It's a little implicit, but makes the testcases much 
> more readable than having to specifiy `$1^` etc.
> If so, I'll explain this in a comment.
Sure, using `^` is sufficient, and agree that make test cases more readable.

I was a bit worried about the error-repair cases. For these cases, I thought b) 
(e.g. we know this `{` should be paired with the last `}`, not the next one) is 
more important, it is probably better explicitly specify in the test, rather 
than doing it silently. I think we can use trailing comments to explain that 
while keeping `^`.

```
class A ^{ // A
  void foo() {
^} // A
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125911

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


[PATCH] D125862: [clang][driver] Add gcc-toolset/devtoolset 12 to prefixes

2022-05-23 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8717b492dfcd: [clang][driver] Dynamically select 
gcc-toolset/devtoolset version (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D125862?vs=430597&id=431314#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125862

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/unittests/Driver/ToolChainTest.cpp

Index: clang/unittests/Driver/ToolChainTest.cpp
===
--- clang/unittests/Driver/ToolChainTest.cpp
+++ clang/unittests/Driver/ToolChainTest.cpp
@@ -610,4 +610,92 @@
   DiagConsumer->clear();
 }
 
+TEST(ToolChainTest, Toolsets) {
+  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
+  IntrusiveRefCntPtr DiagID(new DiagnosticIDs());
+  struct TestDiagnosticConsumer : public DiagnosticConsumer {};
+
+  // Check (newer) GCC toolset installation.
+  {
+IntrusiveRefCntPtr InMemoryFileSystem(
+new llvm::vfs::InMemoryFileSystem);
+
+// These should be ignored
+InMemoryFileSystem->addFile("/opt/rh/gcc-toolset-2", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+InMemoryFileSystem->addFile("/opt/rh/gcc-toolset-", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+InMemoryFileSystem->addFile("/opt/rh/gcc-toolset--", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+InMemoryFileSystem->addFile("/opt/rh/gcc-toolset--1", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+
+// File needed for GCC installation detection.
+InMemoryFileSystem->addFile(
+"/opt/rh/gcc-toolset-12/lib/gcc/x86_64-redhat-linux/11/crtbegin.o", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+
+DiagnosticsEngine Diags(DiagID, &*DiagOpts, new TestDiagnosticConsumer);
+Driver TheDriver("/bin/clang", "x86_64-redhat-linux", Diags,
+ "clang LLVM compiler", InMemoryFileSystem);
+std::unique_ptr C(TheDriver.BuildCompilation({"-v"}));
+ASSERT_TRUE(C);
+std::string S;
+{
+  llvm::raw_string_ostream OS(S);
+  C->getDefaultToolChain().printVerboseInfo(OS);
+}
+if (is_style_windows(llvm::sys::path::Style::native))
+  std::replace(S.begin(), S.end(), '\\', '/');
+EXPECT_EQ("Found candidate GCC installation: "
+  "/opt/rh/gcc-toolset-12/lib/gcc/x86_64-redhat-linux/11\n"
+  "Selected GCC installation: "
+  "/opt/rh/gcc-toolset-12/lib/gcc/x86_64-redhat-linux/11\n"
+  "Candidate multilib: .;@m64\n"
+  "Selected multilib: .;@m64\n",
+  S);
+  }
+
+  // And older devtoolset.
+  {
+IntrusiveRefCntPtr InMemoryFileSystem(
+new llvm::vfs::InMemoryFileSystem);
+
+// These should be ignored
+InMemoryFileSystem->addFile("/opt/rh/devtoolset-2", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+InMemoryFileSystem->addFile("/opt/rh/devtoolset-", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+InMemoryFileSystem->addFile("/opt/rh/devtoolset--", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+InMemoryFileSystem->addFile("/opt/rh/devtoolset--1", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+
+// File needed for GCC installation detection.
+InMemoryFileSystem->addFile(
+"/opt/rh/devtoolset-12/lib/gcc/x86_64-redhat-linux/11/crtbegin.o", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+
+DiagnosticsEngine Diags(DiagID, &*DiagOpts, new TestDiagnosticConsumer);
+Driver TheDriver("/bin/clang", "x86_64-redhat-linux", Diags,
+ "clang LLVM compiler", InMemoryFileSystem);
+std::unique_ptr C(TheDriver.BuildCompilation({"-v"}));
+ASSERT_TRUE(C);
+std::string S;
+{
+  llvm::raw_string_ostream OS(S);
+  C->getDefaultToolChain().printVerboseInfo(OS);
+}
+if (is_style_windows(llvm::sys::path::Style::native))
+  std::replace(S.begin(), S.end(), '\\', '/');
+EXPECT_EQ("Found candidate GCC installation: "
+  "/opt/rh/devtoolset-12/lib/gcc/x86_64-redhat-linux/11\n"
+  "Selected GCC installation: "
+  "/opt/rh/devtoolset-12/lib/gcc/x86_64-redhat-linux/11\n"
+  "Candidate multilib: .;@m64\n"
+  "Selected multilib: .;@m64\n",
+  S);
+  }
+}
+
 } // end anonymous namespace.
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2130,17 +2130,31 @@
   // and gcc-toolsets.
   if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linu

[clang] 8717b49 - [clang][driver] Dynamically select gcc-toolset/devtoolset version

2022-05-23 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2022-05-23T11:34:38+02:00
New Revision: 8717b492dfcd12d6387543a2f8322e0cf9059982

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

LOG: [clang][driver] Dynamically select gcc-toolset/devtoolset version

And pick the highest one, instead of adding all possibilities to the
prefixes.

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Gnu.cpp
clang/unittests/Driver/ToolChainTest.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index 38280a2e36526..29e6295103c7a 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2130,17 +2130,31 @@ void 
Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
   // and gcc-toolsets.
   if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux &&
   D.getVFS().exists("/opt/rh")) {
-Prefixes.push_back("/opt/rh/gcc-toolset-11/root/usr");
-Prefixes.push_back("/opt/rh/gcc-toolset-10/root/usr");
-Prefixes.push_back("/opt/rh/devtoolset-11/root/usr");
-Prefixes.push_back("/opt/rh/devtoolset-10/root/usr");
-Prefixes.push_back("/opt/rh/devtoolset-9/root/usr");
-Prefixes.push_back("/opt/rh/devtoolset-8/root/usr");
-Prefixes.push_back("/opt/rh/devtoolset-7/root/usr");
-Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
-Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
-Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
-Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
+// Find the directory in /opt/rh/ starting with gcc-toolset-* or
+// devtoolset-* with the highest version number and add that
+// one to our prefixes.
+std::string ChosenToolsetDir;
+unsigned ChosenToolsetVersion = 0;
+std::error_code EC;
+for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin("/opt/rh", 
EC),
+   LE;
+ !EC && LI != LE; LI = LI.increment(EC)) {
+  StringRef ToolsetDir = llvm::sys::path::filename(LI->path());
+  unsigned ToolsetVersion;
+  if ((!ToolsetDir.startswith("gcc-toolset-") &&
+   !ToolsetDir.startswith("devtoolset-")) ||
+  ToolsetDir.substr(ToolsetDir.rfind('-') + 1)
+  .getAsInteger(10, ToolsetVersion))
+continue;
+
+  if (ToolsetVersion > ChosenToolsetVersion) {
+ChosenToolsetVersion = ToolsetVersion;
+ChosenToolsetDir = "/opt/rh/" + ToolsetDir.str();
+  }
+}
+
+if (ChosenToolsetVersion > 0)
+  Prefixes.push_back(ChosenToolsetDir);
   }
 
   // Fall back to /usr which is used by most non-Solaris systems.

diff  --git a/clang/unittests/Driver/ToolChainTest.cpp 
b/clang/unittests/Driver/ToolChainTest.cpp
index c652b093dc993..4d2d938a50005 100644
--- a/clang/unittests/Driver/ToolChainTest.cpp
+++ b/clang/unittests/Driver/ToolChainTest.cpp
@@ -610,4 +610,92 @@ TEST(DxcModeTest, ValidatorVersionValidation) {
   DiagConsumer->clear();
 }
 
+TEST(ToolChainTest, Toolsets) {
+  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
+  IntrusiveRefCntPtr DiagID(new DiagnosticIDs());
+  struct TestDiagnosticConsumer : public DiagnosticConsumer {};
+
+  // Check (newer) GCC toolset installation.
+  {
+IntrusiveRefCntPtr InMemoryFileSystem(
+new llvm::vfs::InMemoryFileSystem);
+
+// These should be ignored
+InMemoryFileSystem->addFile("/opt/rh/gcc-toolset-2", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+InMemoryFileSystem->addFile("/opt/rh/gcc-toolset-", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+InMemoryFileSystem->addFile("/opt/rh/gcc-toolset--", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+InMemoryFileSystem->addFile("/opt/rh/gcc-toolset--1", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+
+// File needed for GCC installation detection.
+InMemoryFileSystem->addFile(
+"/opt/rh/gcc-toolset-12/lib/gcc/x86_64-redhat-linux/11/crtbegin.o", 0,
+llvm::MemoryBuffer::getMemBuffer("\n"));
+
+DiagnosticsEngine Diags(DiagID, &*DiagOpts, new TestDiagnosticConsumer);
+Driver TheDriver("/bin/clang", "x86_64-redhat-linux", Diags,
+ "clang LLVM compiler", InMemoryFileSystem);
+std::unique_ptr C(TheDriver.BuildCompilation({"-v"}));
+ASSERT_TRUE(C);
+std::string S;
+{
+  llvm::raw_string_ostream OS(S);
+  C->getDefaultToolChain().printVerboseInfo(OS);
+}
+if (is_style_windows(llvm::sys::path::Style::native))
+  std::replace(S.begin(), S.end(), '\\', '/');
+EXPECT_EQ("Found candidate GCC installation: "
+  "/opt/rh/gcc

[PATCH] D123235: [OpenMP] atomic compare fail : Parser & AST support

2022-05-23 Thread Sunil K via Phabricator via cfe-commits
koops updated this revision to Diff 431315.
koops added a comment.

Fixing a minor error : clang formatting of variable names to avoid build errors.


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

https://reviews.llvm.org/D123235

Files:
  clang/include/clang/AST/ASTNodeTraverser.h
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/atomic_ast_print.cpp
  clang/test/OpenMP/atomic_messages.cpp
  clang/tools/libclang/CIndex.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -199,6 +199,7 @@
 def OMPC_Update : Clause<"update"> { let clangClass = "OMPUpdateClause"; }
 def OMPC_Capture : Clause<"capture"> { let clangClass = "OMPCaptureClause"; }
 def OMPC_Compare : Clause<"compare"> { let clangClass = "OMPCompareClause"; }
+def OMPC_Fail : Clause<"fail"> { let clangClass = "OMPFailClause"; }
 def OMPC_SeqCst : Clause<"seq_cst"> { let clangClass = "OMPSeqCstClause"; }
 def OMPC_AcqRel : Clause<"acq_rel"> { let clangClass = "OMPAcqRelClause"; }
 def OMPC_Acquire : Clause<"acquire"> { let clangClass = "OMPAcquireClause"; }
@@ -569,7 +570,8 @@
 VersionedClause,
 VersionedClause,
 VersionedClause,
-VersionedClause
+VersionedClause,
+VersionedClause
   ];
 }
 def OMP_Target : Directive<"target"> {
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -1807,6 +1807,7 @@
 CHECK_SIMPLE_CLAUSE(Align, OMPC_align)
 CHECK_SIMPLE_CLAUSE(Compare, OMPC_compare)
 CHECK_SIMPLE_CLAUSE(CancellationConstructType, OMPC_cancellation_construct_type)
+CHECK_SIMPLE_CLAUSE(Fail, OMPC_fail)
 
 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2278,6 +2278,8 @@
 
 void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
 
+void OMPClauseEnqueue::VisitOMPFailClause(const OMPFailClause *) {}
+
 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
 
 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
Index: clang/test/OpenMP/atomic_messages.cpp
===
--- clang/test/OpenMP/atomic_messages.cpp
+++ clang/test/OpenMP/atomic_messages.cpp
@@ -958,6 +958,24 @@
 // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'capture' clause}}
 #pragma omp atomic compare compare capture capture
   { v = a; if (a > b) a = b; }
+// expected-error@+1 {{expected 'compare' clause with the 'fail' modifier}}
+#pragma omp atomic fail(seq_cst)
+  if(v == a) { v = a; }
+// expected-error@+1 {{expected '(' after 'fail'}}
+#pragma omp atomic compare fail
+  if(v < a) { v = a; }
+// expected-error@+1 {{expected a memory order clause}}
+#pragma omp atomic compare fail(capture)
+  if(v < a) { v = a; }
+ // expected-error@+2 {{expected ')' after 'atomic compare fail'}}
+ // expected-warning@+1 {{extra tokens at the end of '#pragma omp atomic' are ignored}}
+#pragma omp atomic compare fail(seq_cst | acquire)
+  if(v < a) { v = a; }
+// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'fail' clause}}
+#pragma omp atomic compare fail(relaxed) fail(seq_cst)
+  if(v < a) { v = a; }
+
+
 #endif
   // expected-note@+1 {{in instantiation of function template specialization 'mixed' requested here}}
   return mixed();
Index: clang/test/OpenMP/atomic_ast_print.cpp
===
--- clang/test/OpenMP/atomic_ast_print.cpp
+++ clang/test/OpenMP/atomic_ast_print.cpp
@@ -226,6 +226,16 @@
   { v = a; if (a < b) { a = b; } }
 #pragma omp atomic compare capture hint(6)
   { v = a == b; if (v) a = c; }
+#pragma omp atomic compare fail(acq_rel)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(acquire)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(release)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(relaxed)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(seq_cst)
+  { i

[PATCH] D124690: [clangd] add inlay hints for std::forward-ed parameter packs

2022-05-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D124690#3530272 , @upsj wrote:

> I will update this to split up the control flow into a visitor just 
> collecting a single recursion level and the high-level mapping. A general 
> question here would be whether we should do the resolution by parameter or by 
> parameter pack. Doing it by parameter (like I did it right now) is much 
> easier for inlay hints, especially if the pack gets split up into different 
> parts, but that may not necessarily be the case for template functions and 
> more fuzzy cases like signature help/autocomplete.

I'm not sure I have perfectly grasped the distinction you're drawing, but IIUC 
the dilemma:

- we could query separately where each arg is forwarded to. For multiple 
forwards, the recursive step is "what param is arg N of this callee ultimately 
bound to"
- we could query where a range of args is forwarded to. The recursive step is 
"what params are args [N-M] of this callee ultimately bound to"

Seems like the first is simpler but the second is more efficient. The second 
also more clearly ensures we don't give inconsistent results for adjacent 
parameters.
The approach you take now where you walk->cache->query does manage to combine 
the best of both (though I find it complex in other ways).
This is a tricky tradeoff. My guess is that it's fine to start with the simple 
param-by-param query, and leave a FIXME on the recursive function that querying 
a range at a time would be more efficient for large packs.




Comment at: clang-tools-extra/clangd/InlayHints.cpp:261
+private:
+  void handleParmVarDeclName(const FunctionDecl *Callee, size_t I) {
+const auto *Param = Callee->getParamDecl(I);

upsj wrote:
> sammccall wrote:
> > Unless I'm missing something, going looking in the redecls of the function 
> > for a parameter name doesn't seem in scope for this patch.
> > 
> > We don't support it in inlay hints elsewhere, and it's not clear it has 
> > anything to do with forwarding functions.
> > Maybe the added complexity is justifiable if this logic can be shared with 
> > different functions (hover, signature help) but I don't think it belongs in 
> > this patch.
> This was already functionality previously available in 
> `chooseParameterNames`, I thought I would need to do the same thing here, but 
> turns out that I can get the `FunctionDecl` from a `ParmVarDecl`, so this can 
> stay in its previous place.
You're right, sorry!
I think the the version we have is pretty opportunistic: this is a couple of 
lines of code, so why not?
I don't think we should aim for parity with it, but rather just handle whatever 
cases are both useful & trivial to implement (in this patch)

> I can get the FunctionDecl from a ParmVarDecl, so this can stay in its 
> previous place.
This sounds good to me - means we can drop this map right? That was the main 
piece I was concerned with.



Comment at: clang-tools-extra/clangd/InlayHints.cpp:314
+if (auto *FuncCandidate = dyn_cast_or_null(Candidate)) {
+  if (FuncCandidate->getNumParams() == D->getNumArgs()) {
+if (MatchingDecl) {

upsj wrote:
> There is probably more generic functionality available for this?
Not AFAIK. There's a bunch of rich info about overload sets and their quality, 
but it's discarded after Sema and not preserved in the AST I think.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

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


[PATCH] D126186: [clang-tidy] Extend cert-oop57-cpp to check non-zero memset values

2022-05-23 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 added a comment.

F23163926: CSA_20testbench_20report.zip 
There is no change in the results as far as these OS are concerned.


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

https://reviews.llvm.org/D126186

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


[PATCH] D124690: [clangd] add inlay hints for std::forward-ed parameter packs

2022-05-23 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj added a comment.

Yes, I think that's a good summary. Only a small clarification:

> we could query separately where each arg is forwarded to. For multiple 
> forwards, the recursive step is "what param is arg N of this callee 
> ultimately bound to"

I was thinking of implementing this as "what parameters are the following 
arguments bound to in a direct call", which doesn't have the aforementioned 
efficiency issues, and is basically a single recursion level of what I had 
previously implemented. Since (at least afaik) there is no way to have a 
parameter pack split up between different function calls (at least from the AST 
standpoint where we here only allow std::forward or plain parameters), the 
input would be a FunctionDecl and vector/set of ParmVarDecl and the output 
would be a map ParmVarDecl -> ParmVarDecl plus an Optional 
telling us whether we need to recurse further. Unrolling the recursion would 
also make it easier to limit the depth to which we unpack forwarded parameters.




Comment at: clang-tools-extra/clangd/InlayHints.cpp:261
+private:
+  void handleParmVarDeclName(const FunctionDecl *Callee, size_t I) {
+const auto *Param = Callee->getParamDecl(I);

sammccall wrote:
> upsj wrote:
> > sammccall wrote:
> > > Unless I'm missing something, going looking in the redecls of the 
> > > function for a parameter name doesn't seem in scope for this patch.
> > > 
> > > We don't support it in inlay hints elsewhere, and it's not clear it has 
> > > anything to do with forwarding functions.
> > > Maybe the added complexity is justifiable if this logic can be shared 
> > > with different functions (hover, signature help) but I don't think it 
> > > belongs in this patch.
> > This was already functionality previously available in 
> > `chooseParameterNames`, I thought I would need to do the same thing here, 
> > but turns out that I can get the `FunctionDecl` from a `ParmVarDecl`, so 
> > this can stay in its previous place.
> You're right, sorry!
> I think the the version we have is pretty opportunistic: this is a couple of 
> lines of code, so why not?
> I don't think we should aim for parity with it, but rather just handle 
> whatever cases are both useful & trivial to implement (in this patch)
> 
> > I can get the FunctionDecl from a ParmVarDecl, so this can stay in its 
> > previous place.
> This sounds good to me - means we can drop this map right? That was the main 
> piece I was concerned with.
Yes, we can do the same in the InlayHintVisitor, though it becomes a bit more 
complex there, since we don't have the index of the argument, which might 
require a linear search, as different forwarded ParmVarDecls can come from 
different FunctionDecls


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

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


[PATCH] D126186: [clang-tidy] Extend cert-oop57-cpp to check non-zero memset values

2022-05-23 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

Please upload diff with full context.
Can you add a note about this in the release notes.

As a side point I'm not sure this change really follows what the rule is trying 
to before. The rule is about not using std::memset to reinitialise objects that 
aren't trivial. Having said that limiting it to only 0 does seem a little 
restrictive,


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

https://reviews.llvm.org/D126186

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


[PATCH] D126186: [clang-tidy] Extend cert-oop57-cpp to check non-zero memset values

2022-05-23 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 431319.
gamesh411 added a comment.

Added a release note
Also generated the full context (arcanist could validate the site certificate, 
that's why I had to resort to manual diff creation. Was there a certificate 
change on the reviews.llmv.org site maybe?)


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

https://reviews.llvm.org/D126186

Files:
  clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
  docs/ReleaseNotes.rst
  test/clang-tidy/checkers/cert-oop57-cpp.cpp


Index: test/clang-tidy/checkers/cert-oop57-cpp.cpp
===
--- test/clang-tidy/checkers/cert-oop57-cpp.cpp
+++ test/clang-tidy/checkers/cert-oop57-cpp.cpp
@@ -88,3 +88,10 @@
   mymemcmp(&Data, &Other, sizeof(Data));
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: consider using comparison 
operators instead of calling 'mymemcmp'
 }
+
+void nonNullSetValue() {
+  NonTrivial Data;
+  // Check non-null-valued second argument.
+  std::memset(&Data, 1, sizeof(Data));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: calling 'memset' on a 
non-trivially default constructible class is undefined
+}
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -198,6 +198,9 @@
   ` to simplify 
expressions
   using DeMorgan's Theorem.
 
+- Made :doc:`cert-oop57-cpp ` more sensitive
+  by checking for non-zero integer literal  memset arguments as well.
+
 Removed checks
 ^^
 
Index: clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
===
--- clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
+++ clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
@@ -90,7 +90,7 @@
   callExpr(callee(namedDecl(hasAnyName(
utils::options::parseListPair(BuiltinMemSet, 
MemSetNames,
ArgChecker(unless(isTriviallyDefaultConstructible()),
-  expr(integerLiteral(equals(0)
+  expr(integerLiteral(
   .bind("lazyConstruct"),
   this);
   Finder->addMatcher(


Index: test/clang-tidy/checkers/cert-oop57-cpp.cpp
===
--- test/clang-tidy/checkers/cert-oop57-cpp.cpp
+++ test/clang-tidy/checkers/cert-oop57-cpp.cpp
@@ -88,3 +88,10 @@
   mymemcmp(&Data, &Other, sizeof(Data));
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: consider using comparison operators instead of calling 'mymemcmp'
 }
+
+void nonNullSetValue() {
+  NonTrivial Data;
+  // Check non-null-valued second argument.
+  std::memset(&Data, 1, sizeof(Data));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: calling 'memset' on a non-trivially default constructible class is undefined
+}
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -198,6 +198,9 @@
   ` to simplify expressions
   using DeMorgan's Theorem.
 
+- Made :doc:`cert-oop57-cpp ` more sensitive
+  by checking for non-zero integer literal  memset arguments as well.
+
 Removed checks
 ^^
 
Index: clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
===
--- clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
+++ clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
@@ -90,7 +90,7 @@
   callExpr(callee(namedDecl(hasAnyName(
utils::options::parseListPair(BuiltinMemSet, MemSetNames,
ArgChecker(unless(isTriviallyDefaultConstructible()),
-  expr(integerLiteral(equals(0)
+  expr(integerLiteral(
   .bind("lazyConstruct"),
   this);
   Finder->addMatcher(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126137: [X86] Add support for `-mharden-sls=all`

2022-05-23 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei updated this revision to Diff 431322.
pengfei added a comment.

Replaced `isIndirectBranch` with `isUnconditionalBranch` + `isReturn`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126137

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Driver/ToolChains/Arch/X86.cpp
  clang/test/Driver/x86-target-features.c
  llvm/lib/Target/X86/X86.td
  llvm/lib/Target/X86/X86AsmPrinter.cpp
  llvm/lib/Target/X86/X86AsmPrinter.h
  llvm/test/CodeGen/X86/speculation-hardening-sls.ll

Index: llvm/test/CodeGen/X86/speculation-hardening-sls.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/speculation-hardening-sls.ll
@@ -0,0 +1,91 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -mattr=harden-sls-all -verify-machineinstrs -mtriple=x86_64-unknown-unknown < %s | FileCheck %s
+
+define dso_local i32 @double_return(i32 %a, i32 %b) local_unnamed_addr {
+; CHECK-LABEL: double_return:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:testl %edi, %edi
+; CHECK-NEXT:jle .LBB0_2
+; CHECK-NEXT:  # %bb.1: # %if.then
+; CHECK-NEXT:movl %edi, %eax
+; CHECK-NEXT:cltd
+; CHECK-NEXT:idivl %esi
+; CHECK-NEXT:retq
+; CHECK-NEXT:int3
+; CHECK-NEXT:  .LBB0_2: # %if.else
+; CHECK-NEXT:movl %esi, %eax
+; CHECK-NEXT:cltd
+; CHECK-NEXT:idivl %edi
+; CHECK-NEXT:retq
+; CHECK-NEXT:int3
+entry:
+  %cmp = icmp sgt i32 %a, 0
+  br i1 %cmp, label %if.then, label %if.else
+
+if.then:  ; preds = %entry
+  %div = sdiv i32 %a, %b
+  ret i32 %div
+
+if.else:  ; preds = %entry
+  %div1 = sdiv i32 %b, %a
+  ret i32 %div1
+}
+
+@__const.indirect_branch.ptr = private unnamed_addr constant [2 x i8*] [i8* blockaddress(@indirect_branch, %return), i8* blockaddress(@indirect_branch, %l2)], align 8
+
+; Function Attrs: norecurse nounwind readnone
+define dso_local i32 @indirect_branch(i32 %a, i32 %b, i32 %i) {
+; CHECK-LABEL: indirect_branch:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:movslq %edx, %rax
+; CHECK-NEXT:jmpq *.L__const.indirect_branch.ptr(,%rax,8)
+; CHECK-NEXT:  .Ltmp0: # Block address taken
+; CHECK-NEXT:  .LBB1_2: # %return
+; CHECK-NEXT:xorl %eax, %eax
+; CHECK-NEXT:retq
+; CHECK-NEXT:int3
+; CHECK-NEXT:  .Ltmp1: # Block address taken
+; CHECK-NEXT:  .LBB1_1: # %l2
+; CHECK-NEXT:movl $1, %eax
+; CHECK-NEXT:retq
+; CHECK-NEXT:int3
+entry:
+  %idxprom = sext i32 %i to i64
+  %arrayidx = getelementptr inbounds [2 x i8*], [2 x i8*]* @__const.indirect_branch.ptr, i64 0, i64 %idxprom
+  %0 = load i8*, i8** %arrayidx, align 8
+  indirectbr i8* %0, [label %return, label %l2]
+
+l2:   ; preds = %entry
+  br label %return
+
+return:   ; preds = %entry, %l2
+  %retval.0 = phi i32 [ 1, %l2 ], [ 0, %entry ]
+  ret i32 %retval.0
+}
+
+define i32 @asmgoto() {
+; CHECK-LABEL: asmgoto:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:#APP
+; CHECK-NEXT:jmp .Ltmp2
+; CHECK-NEXT:#NO_APP
+; CHECK-NEXT:  # %bb.1: # %asm.fallthrough
+; CHECK-NEXT:xorl %eax, %eax
+; CHECK-NEXT:retq
+; CHECK-NEXT:int3
+; CHECK-NEXT:  .Ltmp2: # Block address taken
+; CHECK-NEXT:  .LBB2_2: # %d
+; CHECK-NEXT:movl $1, %eax
+; CHECK-NEXT:retq
+; CHECK-NEXT:int3
+entry:
+  callbr void asm sideeffect "jmp $0", "X"(i8* blockaddress(@asmgoto, %d))
+to label %asm.fallthrough [label %d]
+ ; The asm goto above produces a direct branch:
+
+asm.fallthrough:   ; preds = %entry
+  ret i32 0
+
+d: ; preds = %asm.fallthrough, %entry
+  ret i32 1
+}
Index: llvm/lib/Target/X86/X86AsmPrinter.h
===
--- llvm/lib/Target/X86/X86AsmPrinter.h
+++ llvm/lib/Target/X86/X86AsmPrinter.h
@@ -131,10 +131,7 @@
 
   void emitInstruction(const MachineInstr *MI) override;
 
-  void emitBasicBlockEnd(const MachineBasicBlock &MBB) override {
-AsmPrinter::emitBasicBlockEnd(MBB);
-SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
-  }
+  void emitBasicBlockEnd(const MachineBasicBlock &MBB) override;
 
   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
const char *ExtraCode, raw_ostream &O) override;
Index: llvm/lib/Target/X86/X86AsmPrinter.cpp
===
--- llvm/lib/Target/X86/X86AsmPrinter.cpp
+++ llvm/lib/Target/X86/X86AsmPrinter.cpp
@@ -336,6 +336,18 @@
   }
 }
 
+void X86AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {
+  AsmPrinter::emitBasicBlockEnd(MBB);
+  auto I = MBB.getLastNonDebugInstr();
+  if (I != MBB.end() && Subtarget->hardenSlsAll() &&
+  (I->getDesc().isUnconditionalBranch() || I->getDes

[PATCH] D126191: [Clang][CodeGen] Fix the cmse-clear-return.c test.

2022-05-23 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev created this revision.
Herald added a project: All.
kosarev requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Caught with D125604 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126191

Files:
  clang/test/CodeGen/cmse-clear-return.c


Index: clang/test/CodeGen/cmse-clear-return.c
===
--- clang/test/CodeGen/cmse-clear-return.c
+++ clang/test/CodeGen/cmse-clear-return.c
@@ -228,11 +228,12 @@
 
 T14 t14;
 __attribute__((cmse_nonsecure_entry)) T14 f14(void) { return t14; }
-// CHECK: define {{.*}} @f14()
-// CHECK: [[R:%.*]] = load
-// CHECK-LE-NOPT-NEXT: [[AND:%.+]] = and i32 [[R]], -1
-// CHECK-BE-NOPT-NEXT: [[AND:%.+]] = and i32 [[R]], -1
-// CHECK_NEXT: ret i32 [[AND]]
+// CHECK: define {{.*}} @f14()
+// CHECK: [[R:%.*]] = load
+// CHECK-LE-OPT:  ret i32 [[R]]
+// CHECK-LE-NOPT: [[AND:%.+]] = and i32 [[R]], -1
+// CHECK-LE-NOPT: ret i32 [[AND]]
+// CHECK-BE-OPT:  ret i32 [[R]]
 
 // LE: ..11 ..11   0xf3f3/-3085
 // BE: 11.. 11..   0xcfcf/-808452097


Index: clang/test/CodeGen/cmse-clear-return.c
===
--- clang/test/CodeGen/cmse-clear-return.c
+++ clang/test/CodeGen/cmse-clear-return.c
@@ -228,11 +228,12 @@
 
 T14 t14;
 __attribute__((cmse_nonsecure_entry)) T14 f14(void) { return t14; }
-// CHECK: define {{.*}} @f14()
-// CHECK: [[R:%.*]] = load
-// CHECK-LE-NOPT-NEXT: [[AND:%.+]] = and i32 [[R]], -1
-// CHECK-BE-NOPT-NEXT: [[AND:%.+]] = and i32 [[R]], -1
-// CHECK_NEXT: ret i32 [[AND]]
+// CHECK: define {{.*}} @f14()
+// CHECK: [[R:%.*]] = load
+// CHECK-LE-OPT:  ret i32 [[R]]
+// CHECK-LE-NOPT: [[AND:%.+]] = and i32 [[R]], -1
+// CHECK-LE-NOPT: ret i32 [[AND]]
+// CHECK-BE-OPT:  ret i32 [[R]]
 
 // LE: ..11 ..11   0xf3f3/-3085
 // BE: 11.. 11..   0xcfcf/-808452097
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126192: [Driver] Support linking with lld for target AVR

2022-05-23 Thread Ben Shi via Phabricator via cfe-commits
benshi001 created this revision.
benshi001 added reviewers: aykevl, MaskRay.
Herald added subscribers: StephenFan, Jim, dylanmckay.
Herald added a project: All.
benshi001 requested review of this revision.
Herald added subscribers: cfe-commits, jacquesguan.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126192

Files:
  clang/lib/Driver/ToolChains/AVR.cpp
  clang/test/Driver/Inputs/basic_avr_tree/usr/bin/ld.lld
  clang/test/Driver/Inputs/basic_avr_tree/usr/lib/avr/lib/ldscripts/avr5.xn
  clang/test/Driver/avr-toolchain.c

Index: clang/test/Driver/avr-toolchain.c
===
--- clang/test/Driver/avr-toolchain.c
+++ clang/test/Driver/avr-toolchain.c
@@ -53,8 +53,15 @@
 // LINKA-NOT: warning: {{.*}} data section address
 
 // RUN: %clang -### --target=avr --sysroot=%S/Inputs/ -mmcu=atmega328 %s 2>&1 | FileCheck --check-prefixes=NOGCC %s
-// NOGCC: warning: no avr-gcc installation can be found on the system, cannot link standard libraries
+// NOGCC: error: invalid linker
 // NOGCC: warning: standard library not linked and so no interrupt vector table or compiler runtime routines will be linked
 // NOGCC-NOT: warning: {{.*}} microcontroller
 // NOGCC-NOT: warning: {{.*}} avr-libc
 // NOGCC-NOT: warning: {{.*}} data section address
+
+// RUN: %clang -### --target=avr --sysroot=%S/Inputs/basic_avr_tree -mmcu=atmega328 %s -fuse-ld=avrld 2>&1 | FileCheck --check-prefix=NOLD %s
+// NOLD: error: invalid linker
+
+// RUN: %clang -### --target=avr --sysroot=%S/Inputs/basic_avr_tree -mmcu=atmega328 %s -fuse-ld=lld 2>&1 | FileCheck --check-prefix=LLD %s
+// LLD: {{".*lld"}} {{.*}} "-e" "__vectors" "-T" {{".*avr5.xn"}}
+// LLD-NOT: "-mavr5"
Index: clang/lib/Driver/ToolChains/AVR.cpp
===
--- clang/lib/Driver/ToolChains/AVR.cpp
+++ clang/lib/Driver/ToolChains/AVR.cpp
@@ -429,9 +429,24 @@
   // Compute information about the target AVR.
   std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
   llvm::Optional FamilyName = GetMCUFamilyName(CPU);
+  llvm::Optional AVRLibcRoot = TC.findAVRLibcInstallation();
   llvm::Optional SectionAddressData = GetMCUSectionAddressData(CPU);
 
+  // Compute the linker program path, and use GNU "avr-ld" as default.
   std::string Linker = getToolChain().GetProgramPath(getShortName());
+  const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
+  if (A) {
+std::string UseLinker = A->getValue();
+// Compute full path of ld.lld.
+if (UseLinker == "lld")
+  Linker = getToolChain().GetProgramPath("ld.lld");
+else
+  Linker = UseLinker;
+  }
+  // Check if the linker program is valid.
+  if (!llvm::sys::fs::can_execute(Linker))
+D.Diag(diag::err_drv_invalid_linker_name) << Linker;
+
   ArgStringList CmdArgs;
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
 
@@ -450,17 +465,11 @@
   if (!Args.hasArg(options::OPT_nostdlib) &&
   !Args.hasArg(options::OPT_nodefaultlibs)) {
 if (!CPU.empty()) {
-Optional FamilyName = GetMCUFamilyName(CPU);
-Optional AVRLibcRoot = TC.findAVRLibcInstallation();
-
   if (!FamilyName) {
 // We do not have an entry for this CPU in the family
 // mapping table yet.
 D.Diag(diag::warn_drv_avr_family_linking_stdlibs_not_implemented)
 << CPU;
-  } else if (TC.getGCCInstallPath().empty()) {
-// We can not link since there is no avr-ld.
-D.Diag(diag::warn_drv_avr_gcc_not_found);
   } else if (!AVRLibcRoot) {
 // No avr-libc found and so no runtime linked.
 D.Diag(diag::warn_drv_avr_libc_not_found);
@@ -473,7 +482,6 @@
 LinkStdlib = true;
   }
 }
-
 if (!LinkStdlib)
   D.Diag(diag::warn_drv_avr_stdlib_not_linked);
   }
@@ -508,11 +516,28 @@
 
 CmdArgs.push_back("--end-group");
 
-// Specify the family name as the emulation mode to use.
-// This is almost always required because otherwise avr-ld
-// will assume 'avr2' and warn about the program being larger
-// than the bare minimum supports.
-CmdArgs.push_back(Args.MakeArgString(std::string("-m") + *FamilyName));
+// Add specific options for different linkers.
+if (Linker.find("avr-ld") != std::string::npos) {
+  // Specify the family name as the emulation mode to use.
+  // This is almost always required because otherwise avr-ld
+  // will assume 'avr2' and warn about the program being larger
+  // than the bare minimum supports.
+  CmdArgs.push_back(Args.MakeArgString(std::string("-m") + *FamilyName));
+} else if (Linker.find("ld.lld") != std::string::npos) {
+  // We must explicitly specify `__vectors` as the entry for lld.
+  CmdArgs.push_back(Args.MakeArgString("-e"));
+  CmdArgs.push_back(Args.MakeArgString("__vectors"));
+  // We must explicitly spefify the linker script (for lld), which has
+  // alr

[PATCH] D126186: [clang-tidy] Extend cert-oop57-cpp to check non-zero memset values

2022-05-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D126186#3530967 , @gamesh411 wrote:

> Was there a certificate change on the reviews.llmv.org site maybe?)

Yes, AFAIK.

Please redo the measurement, it doesn't look right.
F23164509: image.png 


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

https://reviews.llvm.org/D126186

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


[PATCH] D126137: [X86] Add support for `-mharden-sls=all`

2022-05-23 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added a comment.

In D126137#3530777 , @kristof.beyls 
wrote:

> See https://gcc.gnu.org/onlinedocs/gcc/AArch64-Options.html, documentation 
> for "mharden-sls": For AArch64, the options available on the command line are 
> "retbr", "blr", "none" and "all".
> I don't think the options necessarily have to be the same for x86.
> But assuming I understand this patch correctly, it seems to me that with this 
> patch -mharden-sls=all would mean fundamentally slightly different things for 
> x86 vs arm and aarch64, which could be confusing to users.
> IIUC this patch correctly, this patch implements the equivalent of 
> aarch64/arm's -mharden-sls=retbr (i.e. add a straight-line-speculation 
> mitigation for returns and indirect jumps, but not for indirect function 
> calls).
> Therefore, I wonder if it wouldn't be better to name this -mharden-sls=retbr 
> for more consistency across architectures?
> Or is the indirect function call case not relevant for x86 (sorry - I'm not 
> up to speed on the details on the x86 side)?
>
> Or does `MBB.back().getDesc().isIndirectBranch()` also return True for 
> indirect calls, in which case my whole remark here can probably be ignored?

Thanks for the information! I referred to the AArch64's implementation when I 
wrote the patch. But the ideas came from GCC. You can find the documentation of 
X86 on GCC https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html#x86-Options 
which has already been different from AArch64. The `all` here means 'return' + 
'indirect-jmp'. So, yes, there's no indirect function call here. But it matches 
with GCC X86's options. (A tangential question is do we need these two options 
expect `all`? @nickdesaulniers)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126137

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


[PATCH] D126186: [clang-tidy] Extend cert-oop57-cpp to check non-zero memset values

2022-05-23 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

This diff looks like it's rooted on the clang-tools-extra directory which is 
why the pre-merge bot is failing to build.


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

https://reviews.llvm.org/D126186

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


[PATCH] D126126: [analyzer][NFC] Inline and simplify nonloc::ConcreteInt functions

2022-05-23 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:90
-SVal SimpleSValBuilder::evalMinus(NonLoc val) {
-  switch (val.getSubKind()) {
-  case nonloc::ConcreteIntKind:

I'd rather keep the `switch` because in D125318 we are going to extend with 
`nonloc::SymbolValKind` so, soon it will no longer be  a standalone case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126126

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


[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-05-23 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson created this revision.
Herald added a project: All.
royjacobson requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch implements a necessary part of P0848, the overload resolution for 
destructors.
It is now possible to overload destructors based on constraints, and the 
eligible destructor
will be selected at the end of the class.

The approach this patch takes is to perform the overload resolution after 
instantiating the members
in Sema::InstantiateClass, and to remove from the CXXRecordDecl all 
declarations of non-selected
destructors.

This is the approach that I found that can satisfy the following requirements:

1. The overload resolution and constraint checking is performed after the other 
members are defined but before the type is complete. This is important because 
constraints can check other members of the class, but the result of the 
overload resolution can change the type traits (triviallity etc.) of the class.
2. The order of (visible) functions in the AST is kept. This is important 
because it affects ABI through the order of functions in the vtable.

Note: this is only enabled for CPP20 - I tested it without the CPP20 
restriction and
all the tests passed, so I can remove the restriction. I slightly prefer to 
remove it because
it will be easier to get coverage for this and it seems safer.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126194

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/CXX/class/class.dtor/p4.cpp
  clang/test/CXX/over/over.match/over.match.viable/p3.cpp

Index: clang/test/CXX/over/over.match/over.match.viable/p3.cpp
===
--- clang/test/CXX/over/over.match/over.match.viable/p3.cpp
+++ clang/test/CXX/over/over.match/over.match.viable/p3.cpp
@@ -49,7 +49,6 @@
   S(A) requires false;
   S(double) requires true;
   ~S() requires false;
-  // expected-note@-1 2{{because 'false' evaluated to false}}
   ~S() requires true;
   operator int() requires true;
   operator int() requires false;
@@ -58,11 +57,7 @@
 void bar() {
   WrapsStatics::foo(A{});
   S{1.}.foo(A{});
-  // expected-error@-1{{invalid reference to function '~S': constraints not satisfied}}
-  // Note - this behavior w.r.t. constrained dtors is a consequence of current
-  // wording, which does not invoke overload resolution when a dtor is called.
-  // P0848 is set to address this issue.
+
   S s = 1;
-  // expected-error@-1{{invalid reference to function '~S': constraints not satisfied}}
   int a = s;
 }
Index: clang/test/CXX/class/class.dtor/p4.cpp
===
--- /dev/null
+++ clang/test/CXX/class/class.dtor/p4.cpp
@@ -0,0 +1,74 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+template 
+struct A {
+  ~A() = delete; // expected-note {{explicitly marked deleted}}
+  ~A() requires(N == 1) = delete; // expected-note {{explicitly marked deleted}}
+};
+
+template 
+struct B {
+  ~B() requires(N == 1) = delete; // expected-note {{explicitly marked deleted}}
+  virtual ~B() = delete; // expected-note {{explicitly marked deleted}}
+};
+
+template
+concept CO1 = N == 1;
+
+template
+concept CO2 = N > 0;
+
+template 
+struct C {
+  ~C() = delete; // expected-note {{explicitly marked deleted}}
+  ~C() requires(CO1) = delete;
+  ~C() requires(CO1 && CO2) = delete; // expected-note {{explicitly marked deleted}}
+};
+
+template 
+struct D {
+  ~D() requires(N != 0) = delete; // expected-note {{explicitly marked deleted}}
+  // expected-note@-1 {{candidate function has been explicitly deleted}}
+  // expected-note@-2 {{candidate function not viable: constraints not satisfied}}
+  // expected-note@-3 {{evaluated to false}}
+  ~D() requires(N == 1) = delete;
+  // expected-note@-1 {{candidate function has been explicitly deleted}}
+  // expected-note@-2 {{candidate function not viable: constraints not satisfied}}
+  // expected-note@-3 {{evaluated to false}}
+};
+
+template 
+concept Foo = requires (T t) {
+  { t.foo() };
+};
+
+template
+struct E {
+  void foo();
+  ~E();
+  ~E() requires Foo = delete;  // expected-note {{explicitly marked deleted}}
+};
+
+template struct A<1>;
+template struct A<2>;
+template struct B<1>;
+template struct B<2>;
+template struct C<1>;
+template struct C<2>;
+template struct D<0>;  // expected-error {{no viable destructor found for class 'D<0>'}} expected-note {{in instantiation of template}}
+template struct D<1>;  // expected-error {{destructor of class 'D<1>' is ambiguous}} expected-note {{in instantiation of template}}
+template struct D<2>;
+template struct E<1>;
+
+int main() {
+  A<1> a1; // expected-error {{attempt to use a deleted function}}
+  A<2> a2; // expected-error {{attempt to use a deleted function}}
+  B<1> b1; // expected-error {{attempt to use a deleted function}}

[PATCH] D126192: [Driver] Support linking with lld for target AVR

2022-05-23 Thread Ben Shi via Phabricator via cfe-commits
benshi001 updated this revision to Diff 431332.

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

https://reviews.llvm.org/D126192

Files:
  clang/lib/Driver/ToolChains/AVR.cpp
  clang/test/Driver/Inputs/basic_avr_tree/usr/bin/ld.lld
  clang/test/Driver/Inputs/basic_avr_tree/usr/lib/avr/lib/ldscripts/avr5.xn
  clang/test/Driver/avr-toolchain.c

Index: clang/test/Driver/avr-toolchain.c
===
--- clang/test/Driver/avr-toolchain.c
+++ clang/test/Driver/avr-toolchain.c
@@ -53,8 +53,16 @@
 // LINKA-NOT: warning: {{.*}} data section address
 
 // RUN: %clang -### --target=avr --sysroot=%S/Inputs/ -mmcu=atmega328 %s 2>&1 | FileCheck --check-prefixes=NOGCC %s
-// NOGCC: warning: no avr-gcc installation can be found on the system, cannot link standard libraries
+// NOGCC: error: invalid linker
 // NOGCC: warning: standard library not linked and so no interrupt vector table or compiler runtime routines will be linked
 // NOGCC-NOT: warning: {{.*}} microcontroller
 // NOGCC-NOT: warning: {{.*}} avr-libc
 // NOGCC-NOT: warning: {{.*}} data section address
+
+// RUN: %clang -### --target=avr --sysroot=%S/Inputs/basic_avr_tree -mmcu=atmega328 %s -fuse-ld=avrld 2>&1 | FileCheck --check-prefix=NOLD %s
+// NOLD: error: invalid linker
+
+// RUN: %clang -### --target=avr --sysroot=%S/Inputs/basic_avr_tree -mmcu=atmega328 %s -fuse-ld=ld.lld 2>&1 | FileCheck --check-prefix=LLD %s
+// LLD: {{".*lld"}} {{.*}} "-e" "__vectors" "-T" {{".*avr5.xn"}}
+// LLD-NOT: "avr-ld"
+// LLD-NOT: "-mavr5"
Index: clang/lib/Driver/ToolChains/AVR.cpp
===
--- clang/lib/Driver/ToolChains/AVR.cpp
+++ clang/lib/Driver/ToolChains/AVR.cpp
@@ -429,9 +429,20 @@
   // Compute information about the target AVR.
   std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
   llvm::Optional FamilyName = GetMCUFamilyName(CPU);
+  llvm::Optional AVRLibcRoot = TC.findAVRLibcInstallation();
   llvm::Optional SectionAddressData = GetMCUSectionAddressData(CPU);
 
-  std::string Linker = getToolChain().GetProgramPath(getShortName());
+  // Compute the linker program path, and use GNU "avr-ld" as default.
+  const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
+  std::string Linker(A ? A->getValue() : getShortName());
+  if (!llvm::sys::fs::can_execute(Linker)) {
+std::string FullPath = getToolChain().GetProgramPath(Linker.c_str());
+if (!llvm::sys::fs::can_execute(FullPath))
+  D.Diag(diag::err_drv_invalid_linker_name) << Linker;
+else
+  Linker = FullPath;
+  }
+
   ArgStringList CmdArgs;
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
 
@@ -450,17 +461,11 @@
   if (!Args.hasArg(options::OPT_nostdlib) &&
   !Args.hasArg(options::OPT_nodefaultlibs)) {
 if (!CPU.empty()) {
-Optional FamilyName = GetMCUFamilyName(CPU);
-Optional AVRLibcRoot = TC.findAVRLibcInstallation();
-
   if (!FamilyName) {
 // We do not have an entry for this CPU in the family
 // mapping table yet.
 D.Diag(diag::warn_drv_avr_family_linking_stdlibs_not_implemented)
 << CPU;
-  } else if (TC.getGCCInstallPath().empty()) {
-// We can not link since there is no avr-ld.
-D.Diag(diag::warn_drv_avr_gcc_not_found);
   } else if (!AVRLibcRoot) {
 // No avr-libc found and so no runtime linked.
 D.Diag(diag::warn_drv_avr_libc_not_found);
@@ -473,7 +478,6 @@
 LinkStdlib = true;
   }
 }
-
 if (!LinkStdlib)
   D.Diag(diag::warn_drv_avr_stdlib_not_linked);
   }
@@ -508,11 +512,28 @@
 
 CmdArgs.push_back("--end-group");
 
-// Specify the family name as the emulation mode to use.
-// This is almost always required because otherwise avr-ld
-// will assume 'avr2' and warn about the program being larger
-// than the bare minimum supports.
-CmdArgs.push_back(Args.MakeArgString(std::string("-m") + *FamilyName));
+// Add specific options for different linkers.
+if (Linker.find("avr-ld") != std::string::npos) {
+  // Specify the family name as the emulation mode to use.
+  // This is almost always required because otherwise avr-ld
+  // will assume 'avr2' and warn about the program being larger
+  // than the bare minimum supports.
+  CmdArgs.push_back(Args.MakeArgString(std::string("-m") + *FamilyName));
+} else if (Linker.find("ld.lld") != std::string::npos) {
+  // We must explicitly specify `__vectors` as the entry for lld.
+  CmdArgs.push_back(Args.MakeArgString("-e"));
+  CmdArgs.push_back(Args.MakeArgString("__vectors"));
+  // We must explicitly spefify the linker script (for lld), which has
+  // already been integrated into avr-libc, and whose full path is
+  // expected to be $AVR-LIBC/lib/ldscripts/$FamilyName.xn .
+  if (AVRLibcRoot && FamilyName) {
+std::string Prefix(*AVRLibcRoot + "/lib/ldscripts/")

[PATCH] D126192: [Driver] Support linking with lld for target AVR

2022-05-23 Thread Ben Shi via Phabricator via cfe-commits
benshi001 added inline comments.



Comment at: clang/lib/Driver/ToolChains/AVR.cpp:461
 << CPU;
-  } else if (TC.getGCCInstallPath().empty()) {
-// We can not link since there is no avr-ld.

This check is no longer needed, since we will check `if 
(!llvm::sys::fs::can_execute(FullPath))` at above lines.



Comment at: clang/lib/Driver/ToolChains/AVR.cpp:526
+  CmdArgs.push_back(Args.MakeArgString("__vectors"));
+  // We must explicitly spefify the linker script (for lld), which has
+  // already been integrated into avr-libc, and whose full path is

I am not familiar with avr-ld internal, but it will implicitly:

1. Use `__vectors` as the entry;
2. Use `$AVR-LIBC/lib/ldscripts/$FamilyName.xn` as the linker script;
 


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

https://reviews.llvm.org/D126192

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


[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-05-23 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson updated this revision to Diff 431333.
royjacobson added a comment.

Fix typo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126194

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/CXX/class/class.dtor/p4.cpp
  clang/test/CXX/over/over.match/over.match.viable/p3.cpp

Index: clang/test/CXX/over/over.match/over.match.viable/p3.cpp
===
--- clang/test/CXX/over/over.match/over.match.viable/p3.cpp
+++ clang/test/CXX/over/over.match/over.match.viable/p3.cpp
@@ -49,7 +49,6 @@
   S(A) requires false;
   S(double) requires true;
   ~S() requires false;
-  // expected-note@-1 2{{because 'false' evaluated to false}}
   ~S() requires true;
   operator int() requires true;
   operator int() requires false;
@@ -58,11 +57,7 @@
 void bar() {
   WrapsStatics::foo(A{});
   S{1.}.foo(A{});
-  // expected-error@-1{{invalid reference to function '~S': constraints not satisfied}}
-  // Note - this behavior w.r.t. constrained dtors is a consequence of current
-  // wording, which does not invoke overload resolution when a dtor is called.
-  // P0848 is set to address this issue.
+
   S s = 1;
-  // expected-error@-1{{invalid reference to function '~S': constraints not satisfied}}
   int a = s;
 }
Index: clang/test/CXX/class/class.dtor/p4.cpp
===
--- /dev/null
+++ clang/test/CXX/class/class.dtor/p4.cpp
@@ -0,0 +1,74 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+template 
+struct A {
+  ~A() = delete; // expected-note {{explicitly marked deleted}}
+  ~A() requires(N == 1) = delete; // expected-note {{explicitly marked deleted}}
+};
+
+template 
+struct B {
+  ~B() requires(N == 1) = delete; // expected-note {{explicitly marked deleted}}
+  virtual ~B() = delete; // expected-note {{explicitly marked deleted}}
+};
+
+template
+concept CO1 = N == 1;
+
+template
+concept CO2 = N > 0;
+
+template 
+struct C {
+  ~C() = delete; // expected-note {{explicitly marked deleted}}
+  ~C() requires(CO1) = delete;
+  ~C() requires(CO1 && CO2) = delete; // expected-note {{explicitly marked deleted}}
+};
+
+template 
+struct D {
+  ~D() requires(N != 0) = delete; // expected-note {{explicitly marked deleted}}
+  // expected-note@-1 {{candidate function has been explicitly deleted}}
+  // expected-note@-2 {{candidate function not viable: constraints not satisfied}}
+  // expected-note@-3 {{evaluated to false}}
+  ~D() requires(N == 1) = delete;
+  // expected-note@-1 {{candidate function has been explicitly deleted}}
+  // expected-note@-2 {{candidate function not viable: constraints not satisfied}}
+  // expected-note@-3 {{evaluated to false}}
+};
+
+template 
+concept Foo = requires (T t) {
+  { t.foo() };
+};
+
+template
+struct E {
+  void foo();
+  ~E();
+  ~E() requires Foo = delete;  // expected-note {{explicitly marked deleted}}
+};
+
+template struct A<1>;
+template struct A<2>;
+template struct B<1>;
+template struct B<2>;
+template struct C<1>;
+template struct C<2>;
+template struct D<0>;  // expected-error {{no viable destructor found for class 'D<0>'}} expected-note {{in instantiation of template}}
+template struct D<1>;  // expected-error {{destructor of class 'D<1>' is ambiguous}} expected-note {{in instantiation of template}}
+template struct D<2>;
+template struct E<1>;
+
+int main() {
+  A<1> a1; // expected-error {{attempt to use a deleted function}}
+  A<2> a2; // expected-error {{attempt to use a deleted function}}
+  B<1> b1; // expected-error {{attempt to use a deleted function}}
+  B<2> b2; // expected-error {{attempt to use a deleted function}}
+  C<1> c1; // expected-error {{attempt to use a deleted function}}
+  C<2> c2; // expected-error {{attempt to use a deleted function}}
+  D<0> d0;
+  D<1> d1;
+  D<2> d2; // expected-error {{attempt to use a deleted function}}
+  E<1> e1; // expected-error {{attempt to use a deleted function}}
+}
Index: clang/lib/Sema/SemaTemplateInstantiate.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -2320,6 +2320,81 @@
 }
   };
 
+  /// [class.dtor]p4:
+  ///   At the end of the definition of a class, overload resolution is
+  ///   performed among the prospective destructors declared in that class with
+  ///   an empty argument list to select the destructor for the class, also
+  ///   known as the selected destructor.
+  ///
+  /// To achieve that, we remove all non-selected destructors from the AST,
+  /// which is a bit unusual. We can't let those declarations be in AST and rely
+  /// on LookupSpecialMember to return the correct declaration because a lot of
+  /// code relies on CXXRecordDecl::getDestructor() which assumes there can only
+  /// 

[PATCH] D126127: [analyzer][NFC] Relocate unary transfer functions

2022-05-23 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

> This is an initial step of removing the SimpleSValBuilder abstraction. The 
> SValBuilder alone should be enough.

Perhaps this should be part of another patch stack?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126127

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


[clang] a020006 - Add support of the next Debian (Debian 13 - Trixie)

2022-05-23 Thread Sylvestre Ledru via cfe-commits

Author: Sylvestre Ledru
Date: 2022-05-23T13:47:13+02:00
New Revision: a02000611a8fc4843f7a3077d8bb4840ef08de8b

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

LOG: Add support of the next Debian (Debian 13 - Trixie)

Added: 


Modified: 
clang/include/clang/Driver/Distro.h
clang/lib/Driver/Distro.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Distro.h 
b/clang/include/clang/Driver/Distro.h
index 2723f75e89458..c31fbd4e93f1a 100644
--- a/clang/include/clang/Driver/Distro.h
+++ b/clang/include/clang/Driver/Distro.h
@@ -38,6 +38,7 @@ class Distro {
 DebianBuster,
 DebianBullseye,
 DebianBookworm,
+DebianTrixie,
 Exherbo,
 RHEL5,
 RHEL6,
@@ -121,7 +122,7 @@ class Distro {
   bool IsOpenSUSE() const { return DistroVal == OpenSUSE; }
 
   bool IsDebian() const {
-return DistroVal >= DebianLenny && DistroVal <= DebianBookworm;
+return DistroVal >= DebianLenny && DistroVal <= DebianTrixie;
   }
 
   bool IsUbuntu() const {

diff  --git a/clang/lib/Driver/Distro.cpp b/clang/lib/Driver/Distro.cpp
index 5ac38c34d1128..b0e2f3ac94c75 100644
--- a/clang/lib/Driver/Distro.cpp
+++ b/clang/lib/Driver/Distro.cpp
@@ -153,6 +153,8 @@ static Distro::DistroType 
DetectDistro(llvm::vfs::FileSystem &VFS) {
 return Distro::DebianBullseye;
   case 12:
 return Distro::DebianBookworm;
+  case 13:
+return Distro::DebianTrixie;
   default:
 return Distro::UnknownDistro;
   }



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


[clang] 6f4dc5d - Add support of the next Ubuntu (Ubuntu 22.10 - Kinetic Kudu)

2022-05-23 Thread Sylvestre Ledru via cfe-commits

Author: Sylvestre Ledru
Date: 2022-05-23T13:49:34+02:00
New Revision: 6f4dc5dae60598e71c8211b0c1a705474b0a223f

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

LOG: Add support of the next Ubuntu (Ubuntu 22.10 - Kinetic Kudu)

Added: 


Modified: 
clang/include/clang/Driver/Distro.h
clang/lib/Driver/Distro.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Distro.h 
b/clang/include/clang/Driver/Distro.h
index c31fbd4e93f1..01d66b30b038 100644
--- a/clang/include/clang/Driver/Distro.h
+++ b/clang/include/clang/Driver/Distro.h
@@ -75,6 +75,7 @@ class Distro {
 UbuntuHirsute,
 UbuntuImpish,
 UbuntuJammy,
+UbuntuKinetic,
 UnknownDistro
   };
 
@@ -126,7 +127,7 @@ class Distro {
   }
 
   bool IsUbuntu() const {
-return DistroVal >= UbuntuHardy && DistroVal <= UbuntuJammy;
+return DistroVal >= UbuntuHardy && DistroVal <= UbuntuKinetic;
   }
 
   bool IsAlpineLinux() const { return DistroVal == AlpineLinux; }

diff  --git a/clang/lib/Driver/Distro.cpp b/clang/lib/Driver/Distro.cpp
index b0e2f3ac94c7..1898667279cc 100644
--- a/clang/lib/Driver/Distro.cpp
+++ b/clang/lib/Driver/Distro.cpp
@@ -91,6 +91,7 @@ static Distro::DistroType 
DetectLsbRelease(llvm::vfs::FileSystem &VFS) {
 .Case("hirsute", Distro::UbuntuHirsute)
 .Case("impish", Distro::UbuntuImpish)
 .Case("jammy", Distro::UbuntuJammy)
+.Case("kinetic", Distro::UbuntuKinetic)
 .Default(Distro::UnknownDistro);
   return Version;
 }



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


[PATCH] D126128: [analyzer][NFC] Inline loc::ConcreteInt::evalBinOp

2022-05-23 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

Looks, good, but it was a struggle to follow if you did the inlining right or 
not. TBH, someone else should also check it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126128

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


[PATCH] D126130: [analyzer][NFC] Remove unused SVal::hasConjuredSymbol

2022-05-23 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

> Remove unused SVal::hasConjuredSymbol

The title seems to be off with the changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126130

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


[PATCH] D126189: [C++20][Modules] Build module static initializers per P1874R1.

2022-05-23 Thread Iain Sandoe via Phabricator via cfe-commits
iains created this revision.
Herald added a project: All.
iains added reviewers: urnathan, Bigcheese, ChuanqiXu, jansvoboda11.
iains added a subscriber: clang-modules.
iains edited the summary of this revision.
iains edited the summary of this revision.
iains edited the summary of this revision.
iains edited the summary of this revision.
iains edited the summary of this revision.
iains updated this revision to Diff 431313.
iains added a comment.
iains published this revision for review.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

just updated description


Currently we only implement this for the Itanium ABI since the correct
mangling for the initializers in other ABIs is not yet known.

Intended result:

For a module (instead of the generic CXX initializer) we emit a module init
that:

- wraps the contained initializations in a control variable to ensure that the 
inits only happen once, even if a module is imported many times by imports of 
the main unit.
- calls module initialisers for imported modules first.  Note that the order of 
module import is not significant, and therefore neither is the order of 
imported module initializers.
- We then call initializers for the Global Module Fragment (if present)
- We then call initializers for the current module.
- We then call initializers for the Private Module Fragment (if present)

For a non-module TU that imports at least one module we emit a regular CXX
init that:

- Calls the initializers for any imported modules first.
- Then proceeds as normal with remaining inits.

Implementation:

- We provide the module pointer in the AST Context so that CodeGen can act on 
it and its sub-modules.
- We need to account for module build lines like this: ` clang -cc1 -std=c++20 
Foo.pcm -emit-obj -o Foo.o` or ` clang -cc1 -std=c++20 -xc++-module Foo.cpp 
-emit-obj -o Foo.o`
- in order to do this, we add to ParseAST to set the module pointer in the 
ASTContext, once we establish that this is a module build and we know the 
module pointer. To be able to do this, we make the query for current module 
public in Sema.
- iIn CodeGen, we determine if the current build requires a CXX20-style module 
init and, if so, we defer any module initializers during the "Eagerly Emitted" 
phase.
- We then walk the module initializers at the end of the TU but before emitting 
deferred inits (which adds any hidden and static ones, fixing 
https://github.com/llvm/llvm-project/issues/51873 ).
- We then proceed to emit the deferred inits and continue to emit the CXX init 
function.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126189

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/Parse/ParseAST.cpp
  clang/test/CodeGen/module-intializer.cpp

Index: clang/test/CodeGen/module-intializer.cpp
===
--- /dev/null
+++ clang/test/CodeGen/module-intializer.cpp
@@ -0,0 +1,172 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: cd %t
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 N.cpp \
+// RUN:-emit-module-interface -o N.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 N.pcm -S -emit-llvm \
+// RUN:  -o - | FileCheck %s --check-prefix=CHECK-N
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 O.cpp \
+// RUN:-emit-module-interface -o O.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 O.pcm -S -emit-llvm \
+// RUN:  -o - | FileCheck %s --check-prefix=CHECK-O
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M-part.cpp \
+// RUN:-emit-module-interface -o M-part.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M-part.pcm -S \
+// RUN: -emit-llvm -o - | FileCheck %s --check-prefix=CHECK-P
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M.cpp \
+// RUN: -fmodule-file=N.pcm -fmodule-file=O.pcm -fmodule-file=M-part.pcm \
+// RUN:-emit-module-interface -o M.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M.pcm -S -emit-llvm \
+// RUN:  -o - | FileCheck %s --check-prefix=CHECK-M
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 useM.cpp \
+// RUN: -fmodule-file=M.pcm -S -emit-llvm  -o - \
+// RUN: | FileCheck %s --check-prefix=CHECK-USE
+
+//--- N-h.h
+
+struct Oink {
+  Oink(){};
+};
+
+Oink Hog;
+
+//--- N.cpp
+
+module;
+#include "N-h.h"
+
+export module N;
+
+export struct Quack {
+  Quack(){};
+};
+
+export Quack Duck;
+
+// CHECK-N: define internal void @__cxx_global_var_init
+// CHECK-N: call void @_ZN4OinkC1Ev
+// CHECK-N: define internal void @__cxx_global_var_init
+// CHECK-N: call void @_ZNW1N5QuackC1Ev
+// CHECK-N: define void @_ZGIW1N
+// CHECK-N: store i8 1, ptr @_ZGIW1N__in_chrg
+// CHECK-N: call void @__cxx_global_var_init
+// CHECK-N: call void @__cxx_global_var_init
+
+//--- O-h.h
+
+struct Meow 

[PATCH] D126123: [analyzer][NFC] MemRegion::getRegion() never returns null

2022-05-23 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Is it documented with `getRegion`?  Could we decorate that with 
`returns-nonnull` 
https://clang.llvm.org/docs/AttributeReference.html#returns-nonnull ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126123

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


[PATCH] D126077: Fix stack crash in classIsDerivedFrom triggered by clang-tidy

2022-05-23 Thread Anton Fedorov via Phabricator via cfe-commits
datacompboy updated this revision to Diff 431339.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126077

Files:
  clang/lib/ASTMatchers/ASTMatchFinder.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -168,6 +168,14 @@
varDecl(hasType(namedDecl(hasName("S"));
 }
 
+TEST(TypeMatcherDeathTest, isDerivedRecursion) {
+  EXPECT_TRUE(notMatches(
+  "template struct t1;"
+  "template struct t2: t1< T > {};"
+  "template struct t1: t2< T > {};",
+  cxxRecordDecl(isDerivedFrom("::T";
+}
+
 TEST(TypeMatcher, MatchesDeclTypes) {
   // TypedefType -> TypedefNameDecl
   EXPECT_TRUE(matches("typedef int I; void f(I i);",
Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -44,6 +44,12 @@
 // optimize this on.
 static const unsigned MaxMemoizationEntries = 1;
 
+// The maximum number of steps thru ancestors allowed to run before
+// give up. The limit could only be hit by infinity / too deep
+// recursion or very complicated automatically generated types
+// inheritance.
+static const unsigned MaxDerivationComplexity = 1;
+
 enum class MatchType {
   Ancestors,
 
@@ -1357,35 +1363,47 @@
 // Returns true if the given C++ class is directly or indirectly derived
 // from a base type with the given name.  A class is not considered to be
 // derived from itself.
-bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
+bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *DeclarationIn,
  const Matcher &Base,
  BoundNodesTreeBuilder *Builder,
  bool Directly) {
-  if (!Declaration->hasDefinition())
-return false;
-  for (const auto &It : Declaration->bases()) {
-const Type *TypeNode = It.getType().getTypePtr();
+  SmallVector DeclarationsStack;
+  int iterations = 0;
+  DeclarationsStack.push_back(DeclarationIn);
+  while (!DeclarationsStack.empty()) {
+const CXXRecordDecl *Declaration = DeclarationsStack.pop_back_val();
+if (++iterations > MaxDerivationComplexity ||
+DeclarationsStack.size() > MaxDerivationComplexity) {
+  // This can happen in case of too deep derivation chain or recursion.
+  return false;
+}
+if (!Declaration->hasDefinition())
+  return false;
+for (const auto &It : Declaration->bases()) {
+  const Type *TypeNode = It.getType().getTypePtr();
 
-if (typeHasMatchingAlias(TypeNode, Base, Builder))
-  return true;
+  if (typeHasMatchingAlias(TypeNode, Base, Builder))
+return true;
 
-// FIXME: Going to the primary template here isn't really correct, but
-// unfortunately we accept a Decl matcher for the base class not a Type
-// matcher, so it's the best thing we can do with our current interface.
-CXXRecordDecl *ClassDecl = getAsCXXRecordDeclOrPrimaryTemplate(TypeNode);
-if (!ClassDecl)
-  continue;
-if (ClassDecl == Declaration) {
-  // This can happen for recursive template definitions.
-  continue;
-}
-BoundNodesTreeBuilder Result(*Builder);
-if (Base.matches(*ClassDecl, this, &Result)) {
-  *Builder = std::move(Result);
-  return true;
+  // FIXME: Going to the primary template here isn't really correct, but
+  // unfortunately we accept a Decl matcher for the base class not a Type
+  // matcher, so it's the best thing we can do with our current interface.
+  CXXRecordDecl *ClassDecl = getAsCXXRecordDeclOrPrimaryTemplate(TypeNode);
+  if (!ClassDecl)
+continue;
+  if (ClassDecl == Declaration) {
+// This can happen for recursive template definitions.
+continue;
+  }
+  BoundNodesTreeBuilder Result(*Builder);
+  if (Base.matches(*ClassDecl, this, &Result)) {
+*Builder = std::move(Result);
+return true;
+  }
+  if (!Directly) {
+DeclarationsStack.push_back(ClassDecl);
+  }
 }
-if (!Directly && classIsDerivedFrom(ClassDecl, Base, Builder, Directly))
-  return true;
   }
   return false;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125693: [DebugInfo][WIP] Support types, imports and static locals declared in a lexical block (3/5)

2022-05-23 Thread Kristina Bessonova via Phabricator via cfe-commits
krisb added a comment.

Thank you, @asavonic for your comments!

I've added some more details about the issues this is going to fix, hope it'll 
help to review the patchset.

In D125693#3523278 , @asavonic wrote:

> Thanks a lot for the patch! It would be great to get this issue finally 
> fixed. I assume that this is the main patch, other patches in the stack seem 
> like just preparation/adjustments needed for this one to work.

Correct. The first two patches were extracted to just make this one a bit 
smaller and easier to review.




Comment at: llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp:1382
+  assert((!GV->getScope() || !isa(GV->getScope())) &&
+ "Unexpected function-local declaration!");
   if (Processed.insert(GV).second)

asavonic wrote:
> So here we discard LLVM IR metadata that have local declarations tied to a 
> CU, right? This will break compatibility with old LLVM IR. Can we do some 
> upgrade to convert this "old style" metadata the way we expect it now? Does 
> it make sense to support both variants?
Good question. I haven't thought about backward compatibility, not even sure we 
have some requirements for this. The easiest option seems to increase debug 
metadata version and drop debug info if it isn't compatible with this one as it 
done in AutoUpgrade. This prevents producing incorrect DWARF for ill-formed 
metadata.

Upgrading "old style" metadata would be a bit tricky. Current implementation 
assumes that all the local declarations (excluding regular local vars and 
labels) are referenced by parent's localDecls field, including types. Before 
this patchset there were no ways to find types except by references from their 
uses. So, to find all the function-local types we may need to iterate over all 
instructions and parse all debug metadata, which likely increases compile time. 
Not sure this trade-off is a worth one.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125693

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


[PATCH] D125487: [Tooling/DependencyScanning] Refactor dependency scanning to produce pre-lexed preprocessor directive tokens, instead of minimized sources

2022-05-23 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 accepted this revision.
jansvoboda11 added a comment.
This revision is now accepted and ready to land.

LGTM, nice cleanup! Left a couple of nits.




Comment at: clang/lib/Lex/DependencyDirectivesScanner.cpp:153
+
+  SmallVector CurDirToks;
+  SmallVector DirsWithToks;

Can you add a comment explaining the relationship between the members?



Comment at: clang/unittests/Lex/DependencyDirectivesScannerTest.cpp:114
+  EXPECT_EQ(cxx_export_module_decl, Directives[19].Kind);
+  EXPECT_EQ(cxx_import_decl, Directives[20].Kind);
+  EXPECT_EQ(pp_eof, Directives[21].Kind);

What's the reason being these changes?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125487

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


[PATCH] D126198: [analyzer][NFCi] Annotate major nonnull returning functions

2022-05-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: NoQ, martong, Szelethus.
Herald added subscribers: manas, ASDenysPetrov, dkrupp, donat.nagy, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun.
Herald added a project: All.
steakhal requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch annotates the most important analyzer function APIs.
Also adds a couple of assertions for uncovering any potential issues earlier in 
the constructor; in those cases, the member functions were already 
dereferencing the members unconditionally anyway.

Measurements showed no performance impact, nor crashes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126198

Files:
  clang/include/clang/Analysis/AnalysisDeclContext.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp

Index: clang/lib/StaticAnalyzer/Core/MemRegion.cpp
===
--- clang/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ clang/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -162,7 +162,9 @@
 }
 
 ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const SubRegion *sReg)
-: DeclRegion(sReg, ObjCIvarRegionKind), IVD(ivd) {}
+: DeclRegion(sReg, ObjCIvarRegionKind), IVD(ivd) {
+  assert(IVD);
+}
 
 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
 
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
@@ -48,6 +48,7 @@
 assert(isValidTypeForSymbol(r->getValueType()));
   }
 
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
   const TypedValueRegion* getRegion() const { return R; }
 
   static void Profile(llvm::FoldingSetNodeID& profile, const TypedValueRegion* R) {
@@ -95,8 +96,10 @@
 assert(isValidTypeForSymbol(t));
   }
 
+  /// It might return null.
   const Stmt *getStmt() const { return S; }
   unsigned getCount() const { return Count; }
+  /// It might return null.
   const void *getTag() const { return SymbolTag; }
 
   QualType getType() const override;
@@ -140,7 +143,9 @@
 assert(isValidTypeForSymbol(r->getValueType()));
   }
 
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
   SymbolRef getParentSymbol() const { return parentSymbol; }
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
   const TypedValueRegion *getRegion() const { return R; }
 
   QualType getType() const override;
@@ -179,6 +184,7 @@
 assert(r);
   }
 
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
   const SubRegion *getRegion() const { return R; }
 
   QualType getType() const override;
@@ -226,29 +232,37 @@
   assert(tag);
 }
 
-  const MemRegion *getRegion() const { return R; }
-  const Stmt *getStmt() const { return S; }
-  const LocationContext *getLocationContext() const { return LCtx; }
-  unsigned getCount() const { return Count; }
-  const void *getTag() const { return Tag; }
+LLVM_ATTRIBUTE_RETURNS_NONNULL
+const MemRegion *getRegion() const { return R; }
 
-  QualType getType() const override;
+LLVM_ATTRIBUTE_RETURNS_NONNULL
+const Stmt *getStmt() const { return S; }
 
-  StringRef getKindStr() const override;
+LLVM_ATTRIBUTE_RETURNS_NONNULL
+const LocationContext *getLocationContext() const { return LCtx; }
 
-  void dumpToStream(raw_ostream &os) const override;
+unsigned getCount() const { return Count; }
 
-  static void Profile(llvm::FoldingSetNodeID& profile, const MemRegion *R,
-  const Stmt *S, QualType T, const LocationContext *LCtx,
-  unsigned Count, const void *Tag) {
-profile.AddInteger((unsigned) SymbolMetadataKind);
-profile.AddPointer(R);
-profile.AddPointer(S);
-profile.Add(T);
-profile.AddPointer(LCtx);
-profile.AddInteger(Count);
-profile.AddPointer(Tag);
-  }
+LLVM_ATTRIBUTE_RETURNS_NONNULL
+const void *getTag() const { return Tag; }
+
+QualType getType() const override;
+
+StringRef getKindStr() const override;
+
+void dumpToStream(raw_ostream &os) const override;
+
+static void Profile(llvm::FoldingSetNodeID &profile, const MemRegion *R,
+const Stmt *S, QualType T, const LocationContext *LCtx,
+  

[PATCH] D126198: [analyzer][NFCi] Annotate major nonnull returning functions

2022-05-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 431343.
steakhal added a comment.

fix typo `migth` -> `might`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126198

Files:
  clang/include/clang/Analysis/AnalysisDeclContext.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp

Index: clang/lib/StaticAnalyzer/Core/MemRegion.cpp
===
--- clang/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ clang/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -162,7 +162,9 @@
 }
 
 ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const SubRegion *sReg)
-: DeclRegion(sReg, ObjCIvarRegionKind), IVD(ivd) {}
+: DeclRegion(sReg, ObjCIvarRegionKind), IVD(ivd) {
+  assert(IVD);
+}
 
 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
 
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
@@ -48,6 +48,7 @@
 assert(isValidTypeForSymbol(r->getValueType()));
   }
 
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
   const TypedValueRegion* getRegion() const { return R; }
 
   static void Profile(llvm::FoldingSetNodeID& profile, const TypedValueRegion* R) {
@@ -95,8 +96,10 @@
 assert(isValidTypeForSymbol(t));
   }
 
+  /// It might return null.
   const Stmt *getStmt() const { return S; }
   unsigned getCount() const { return Count; }
+  /// It might return null.
   const void *getTag() const { return SymbolTag; }
 
   QualType getType() const override;
@@ -140,7 +143,9 @@
 assert(isValidTypeForSymbol(r->getValueType()));
   }
 
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
   SymbolRef getParentSymbol() const { return parentSymbol; }
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
   const TypedValueRegion *getRegion() const { return R; }
 
   QualType getType() const override;
@@ -179,6 +184,7 @@
 assert(r);
   }
 
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
   const SubRegion *getRegion() const { return R; }
 
   QualType getType() const override;
@@ -226,29 +232,37 @@
   assert(tag);
 }
 
-  const MemRegion *getRegion() const { return R; }
-  const Stmt *getStmt() const { return S; }
-  const LocationContext *getLocationContext() const { return LCtx; }
-  unsigned getCount() const { return Count; }
-  const void *getTag() const { return Tag; }
+LLVM_ATTRIBUTE_RETURNS_NONNULL
+const MemRegion *getRegion() const { return R; }
 
-  QualType getType() const override;
+LLVM_ATTRIBUTE_RETURNS_NONNULL
+const Stmt *getStmt() const { return S; }
 
-  StringRef getKindStr() const override;
+LLVM_ATTRIBUTE_RETURNS_NONNULL
+const LocationContext *getLocationContext() const { return LCtx; }
 
-  void dumpToStream(raw_ostream &os) const override;
+unsigned getCount() const { return Count; }
 
-  static void Profile(llvm::FoldingSetNodeID& profile, const MemRegion *R,
-  const Stmt *S, QualType T, const LocationContext *LCtx,
-  unsigned Count, const void *Tag) {
-profile.AddInteger((unsigned) SymbolMetadataKind);
-profile.AddPointer(R);
-profile.AddPointer(S);
-profile.Add(T);
-profile.AddPointer(LCtx);
-profile.AddInteger(Count);
-profile.AddPointer(Tag);
-  }
+LLVM_ATTRIBUTE_RETURNS_NONNULL
+const void *getTag() const { return Tag; }
+
+QualType getType() const override;
+
+StringRef getKindStr() const override;
+
+void dumpToStream(raw_ostream &os) const override;
+
+static void Profile(llvm::FoldingSetNodeID &profile, const MemRegion *R,
+const Stmt *S, QualType T, const LocationContext *LCtx,
+unsigned Count, const void *Tag) {
+  profile.AddInteger((unsigned)SymbolMetadataKind);
+  profile.AddPointer(R);
+  profile.AddPointer(S);
+  profile.Add(T);
+  profile.AddPointer(LCtx);
+  profile.AddInteger(Count);
+  profile.AddPointer(Tag);
+}
 
   void Profile(llvm::FoldingSetNodeID& profile) override {
 Profile(profile, R, S, T, LCtx, Count, Tag);
@@ -287,6 +301,7 @@
 
   QualType getType() const override { return ToTy; }
 
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
  

[PATCH] D126123: [analyzer][NFC] MemRegion::getRegion() never returns null

2022-05-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D126123#3531112 , @martong wrote:

> Is it documented with `getRegion`?  Could we decorate that with 
> `returns-nonnull` 
> https://clang.llvm.org/docs/AttributeReference.html#returns-nonnull ?

Ah, I thought one of my changes addressing this was already on review.
It turns out it was not the case. Now I uploaded it for review: D126198 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126123

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


[PATCH] D126130: [analyzer][NFC] Remove unused SVal::hasConjuredSymbol

2022-05-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 431344.
steakhal added a comment.

upload the right diff


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126130

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
  clang/lib/StaticAnalyzer/Core/SVals.cpp


Index: clang/lib/StaticAnalyzer/Core/SVals.cpp
===
--- clang/lib/StaticAnalyzer/Core/SVals.cpp
+++ clang/lib/StaticAnalyzer/Core/SVals.cpp
@@ -43,25 +43,6 @@
 // Utility methods.
 
//===--===//
 
-bool SVal::hasConjuredSymbol() const {
-  if (Optional SV = getAs()) {
-SymbolRef sym = SV->getSymbol();
-if (isa(sym))
-  return true;
-  }
-
-  if (Optional RV = getAs()) {
-const MemRegion *R = RV->getRegion();
-if (const auto *SR = dyn_cast(R)) {
-  SymbolRef sym = SR->getSymbol();
-  if (isa(sym))
-return true;
-}
-  }
-
-  return false;
-}
-
 const FunctionDecl *SVal::getAsFunctionDecl() const {
   if (Optional X = getAs()) {
 const MemRegion* R = X->getRegion();
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
@@ -154,9 +154,6 @@
 
   bool isZeroConstant() const;
 
-  /// hasConjuredSymbol - If this SVal wraps a conjured symbol, return true;
-  bool hasConjuredSymbol() const;
-
   /// getAsFunctionDecl - If this SVal is a MemRegionVal and wraps a
   /// CodeTextRegion wrapping a FunctionDecl, return that FunctionDecl.
   /// Otherwise return 0.


Index: clang/lib/StaticAnalyzer/Core/SVals.cpp
===
--- clang/lib/StaticAnalyzer/Core/SVals.cpp
+++ clang/lib/StaticAnalyzer/Core/SVals.cpp
@@ -43,25 +43,6 @@
 // Utility methods.
 //===--===//
 
-bool SVal::hasConjuredSymbol() const {
-  if (Optional SV = getAs()) {
-SymbolRef sym = SV->getSymbol();
-if (isa(sym))
-  return true;
-  }
-
-  if (Optional RV = getAs()) {
-const MemRegion *R = RV->getRegion();
-if (const auto *SR = dyn_cast(R)) {
-  SymbolRef sym = SR->getSymbol();
-  if (isa(sym))
-return true;
-}
-  }
-
-  return false;
-}
-
 const FunctionDecl *SVal::getAsFunctionDecl() const {
   if (Optional X = getAs()) {
 const MemRegion* R = X->getRegion();
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
@@ -154,9 +154,6 @@
 
   bool isZeroConstant() const;
 
-  /// hasConjuredSymbol - If this SVal wraps a conjured symbol, return true;
-  bool hasConjuredSymbol() const;
-
   /// getAsFunctionDecl - If this SVal is a MemRegionVal and wraps a
   /// CodeTextRegion wrapping a FunctionDecl, return that FunctionDecl.
   /// Otherwise return 0.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126130: [analyzer][NFC] Remove unused SVal::hasConjuredSymbol

2022-05-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D126130#3531108 , @martong wrote:

>> Remove unused SVal::hasConjuredSymbol
>
> The title seems to be off with the changes.

Ah, right. Once I tried using `arc`, and I get everything messed up. Never 
again!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126130

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


[PATCH] D125488: [Preprocessor] Make the special lexing for dependency scanning a first-class feature of the `Preprocessor` and `Lexer`

2022-05-23 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 accepted this revision.
jansvoboda11 added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125488

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


[PATCH] D126126: [analyzer][NFC] Inline and simplify nonloc::ConcreteInt functions

2022-05-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal abandoned this revision.
steakhal added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:90
-SVal SimpleSValBuilder::evalMinus(NonLoc val) {
-  switch (val.getSubKind()) {
-  case nonloc::ConcreteIntKind:

martong wrote:
> I'd rather keep the `switch` because in D125318 we are going to extend with 
> `nonloc::SymbolValKind` so, soon it will no longer be  a standalone case.
Okay, let's postpone this until things get settled with the unary ops stuff.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126126

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


[PATCH] D126191: [Clang][CodeGen] Fix the cmse-clear-return.c test.

2022-05-23 Thread Nikita Popov via Phabricator via cfe-commits
nikic accepted this revision.
nikic added a comment.
This revision is now accepted and ready to land.

Not familiar with this test, but the change looks reasonable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126191

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


[PATCH] D126198: [analyzer][NFCi] Annotate major nonnull returning functions

2022-05-23 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

Looks good, with minor revisions.




Comment at: clang/include/clang/Analysis/AnalysisDeclContext.h:233
+  : Kind(k), Ctx(ctx), Parent(parent), ID(ID) {
+assert(Ctx);
+  }

To be consistent with the other hunks, where you assert on the parameter, not 
on the member.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h:919
 public:
+  // TODO what does this return?
   virtual const ValueDecl *getDecl() const = 0;





Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h:1021
 assert(!cast(SReg)->getStackFrame()->inTopFrame());
+assert(OriginExpr);
   }





Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h:1091
+  : DeclRegion(sReg, FieldRegionKind), FD(fd) {
+assert(FD);
+  }




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126198

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


[PATCH] D126186: [clang-tidy] Extend cert-oop57-cpp to check non-zero memset values

2022-05-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D126186#3530938 , @njames93 wrote:

> As a side point I'm not sure this change really follows what the rule is 
> trying to enforce. The rule is about not using std::memset to reinitialise 
> objects that aren't trivial. Having said that limiting it to only 0 does seem 
> a little restrictive,

I think this change makes sense for the rule as it's written, per "Do not use 
std::memset() to initialize an object of nontrivial class type as it may not 
properly initialize the value representation of the object." The noncompliant 
example was using zero initialization, but there's nothing inherently special 
about `0` except for how commonly used it is as a default value.


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

https://reviews.llvm.org/D126186

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


[PATCH] D126186: [clang-tidy] Extend cert-oop57-cpp to check non-zero memset values

2022-05-23 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 431348.
gamesh411 added a comment.

Add full diff with arcanist


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126186

Files:
  clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp
@@ -88,3 +88,10 @@
   mymemcmp(&Data, &Other, sizeof(Data));
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: consider using comparison 
operators instead of calling 'mymemcmp'
 }
+
+void nonNullSetValue() {
+  NonTrivial Data;
+  // Check non-null-valued second argument.
+  std::memset(&Data, 1, sizeof(Data));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: calling 'memset' on a 
non-trivially default constructible class is undefined
+}
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -198,6 +198,9 @@
   ` to simplify 
expressions
   using DeMorgan's Theorem.
 
+- Made :doc:`cert-oop57-cpp ` more sensitive
+  by checking for non-zero integer literal  memset arguments as well.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
===
--- clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
+++ clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
@@ -90,7 +90,7 @@
   callExpr(callee(namedDecl(hasAnyName(
utils::options::parseListPair(BuiltinMemSet, 
MemSetNames,
ArgChecker(unless(isTriviallyDefaultConstructible()),
-  expr(integerLiteral(equals(0)
+  expr(integerLiteral(
   .bind("lazyConstruct"),
   this);
   Finder->addMatcher(


Index: clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cert-oop57-cpp.cpp
@@ -88,3 +88,10 @@
   mymemcmp(&Data, &Other, sizeof(Data));
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: consider using comparison operators instead of calling 'mymemcmp'
 }
+
+void nonNullSetValue() {
+  NonTrivial Data;
+  // Check non-null-valued second argument.
+  std::memset(&Data, 1, sizeof(Data));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: calling 'memset' on a non-trivially default constructible class is undefined
+}
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -198,6 +198,9 @@
   ` to simplify expressions
   using DeMorgan's Theorem.
 
+- Made :doc:`cert-oop57-cpp ` more sensitive
+  by checking for non-zero integer literal  memset arguments as well.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
===
--- clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
+++ clang-tools-extra/clang-tidy/cert/NonTrivialTypesLibcMemoryCallsCheck.cpp
@@ -90,7 +90,7 @@
   callExpr(callee(namedDecl(hasAnyName(
utils::options::parseListPair(BuiltinMemSet, MemSetNames,
ArgChecker(unless(isTriviallyDefaultConstructible()),
-  expr(integerLiteral(equals(0)
+  expr(integerLiteral(
   .bind("lazyConstruct"),
   this);
   Finder->addMatcher(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126189: [C++20][Modules] Build module static initializers per P1874R1.

2022-05-23 Thread Nathan Sidwell via Phabricator via cfe-commits
urnathan added inline comments.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:626-627
+  // We create the function, even if it is empty, since an importer of this
+  // module will refer to it unconditionally (there is no way for an importer
+  // to know if the function could be omitted at this time).
+

'at this time' is ambiguous.  I think it means 'the current compiler 
implementation state', but it could also mean 'at this point in the 
compilation'.  I don't  think there's a general problem with such an 
optimization -- we could emit a flag into the BMI.  It's just we don't have the 
smarts to do that just yet.  right?



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:629
+
+  // Module initialisers for imported modules are emitted first.
+  // Collect the modules that we import

I'm with Morse about this, even before coming to live where I do.  You've used 
both 'ise' and 'ize'. s/ise/ize/


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126189

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


[PATCH] D126198: [analyzer][NFCi] Annotate major nonnull returning functions

2022-05-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/include/clang/Analysis/AnalysisDeclContext.h:233
+  : Kind(k), Ctx(ctx), Parent(parent), ID(ID) {
+assert(Ctx);
+  }

martong wrote:
> To be consistent with the other hunks, where you assert on the parameter, not 
> on the member.
It's totally messed up, there is absolutely no consistency regarding this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126198

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


[clang] 0eccc92 - Revert "[clang][driver] Dynamically select gcc-toolset/devtoolset version"

2022-05-23 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2022-05-23T15:22:27+02:00
New Revision: 0eccc92fa0fd1794988cd6bfeca2314107567fdb

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

LOG: Revert "[clang][driver] Dynamically select gcc-toolset/devtoolset version"

This reverts commit 8717b492dfcd12d6387543a2f8322e0cf9059982.

The new unittest fails on Windows buildbots, e.g.
https://lab.llvm.org/buildbot/#/builders/119/builds/8647

Added: 


Modified: 
clang/lib/Driver/ToolChains/Gnu.cpp
clang/unittests/Driver/ToolChainTest.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index 29e6295103c7..38280a2e3652 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2130,31 +2130,17 @@ void 
Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
   // and gcc-toolsets.
   if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux &&
   D.getVFS().exists("/opt/rh")) {
-// Find the directory in /opt/rh/ starting with gcc-toolset-* or
-// devtoolset-* with the highest version number and add that
-// one to our prefixes.
-std::string ChosenToolsetDir;
-unsigned ChosenToolsetVersion = 0;
-std::error_code EC;
-for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin("/opt/rh", 
EC),
-   LE;
- !EC && LI != LE; LI = LI.increment(EC)) {
-  StringRef ToolsetDir = llvm::sys::path::filename(LI->path());
-  unsigned ToolsetVersion;
-  if ((!ToolsetDir.startswith("gcc-toolset-") &&
-   !ToolsetDir.startswith("devtoolset-")) ||
-  ToolsetDir.substr(ToolsetDir.rfind('-') + 1)
-  .getAsInteger(10, ToolsetVersion))
-continue;
-
-  if (ToolsetVersion > ChosenToolsetVersion) {
-ChosenToolsetVersion = ToolsetVersion;
-ChosenToolsetDir = "/opt/rh/" + ToolsetDir.str();
-  }
-}
-
-if (ChosenToolsetVersion > 0)
-  Prefixes.push_back(ChosenToolsetDir);
+Prefixes.push_back("/opt/rh/gcc-toolset-11/root/usr");
+Prefixes.push_back("/opt/rh/gcc-toolset-10/root/usr");
+Prefixes.push_back("/opt/rh/devtoolset-11/root/usr");
+Prefixes.push_back("/opt/rh/devtoolset-10/root/usr");
+Prefixes.push_back("/opt/rh/devtoolset-9/root/usr");
+Prefixes.push_back("/opt/rh/devtoolset-8/root/usr");
+Prefixes.push_back("/opt/rh/devtoolset-7/root/usr");
+Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
+Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
+Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
+Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
   }
 
   // Fall back to /usr which is used by most non-Solaris systems.

diff  --git a/clang/unittests/Driver/ToolChainTest.cpp 
b/clang/unittests/Driver/ToolChainTest.cpp
index 4d2d938a5000..c652b093dc99 100644
--- a/clang/unittests/Driver/ToolChainTest.cpp
+++ b/clang/unittests/Driver/ToolChainTest.cpp
@@ -610,92 +610,4 @@ TEST(DxcModeTest, ValidatorVersionValidation) {
   DiagConsumer->clear();
 }
 
-TEST(ToolChainTest, Toolsets) {
-  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
-  IntrusiveRefCntPtr DiagID(new DiagnosticIDs());
-  struct TestDiagnosticConsumer : public DiagnosticConsumer {};
-
-  // Check (newer) GCC toolset installation.
-  {
-IntrusiveRefCntPtr InMemoryFileSystem(
-new llvm::vfs::InMemoryFileSystem);
-
-// These should be ignored
-InMemoryFileSystem->addFile("/opt/rh/gcc-toolset-2", 0,
-llvm::MemoryBuffer::getMemBuffer("\n"));
-InMemoryFileSystem->addFile("/opt/rh/gcc-toolset-", 0,
-llvm::MemoryBuffer::getMemBuffer("\n"));
-InMemoryFileSystem->addFile("/opt/rh/gcc-toolset--", 0,
-llvm::MemoryBuffer::getMemBuffer("\n"));
-InMemoryFileSystem->addFile("/opt/rh/gcc-toolset--1", 0,
-llvm::MemoryBuffer::getMemBuffer("\n"));
-
-// File needed for GCC installation detection.
-InMemoryFileSystem->addFile(
-"/opt/rh/gcc-toolset-12/lib/gcc/x86_64-redhat-linux/11/crtbegin.o", 0,
-llvm::MemoryBuffer::getMemBuffer("\n"));
-
-DiagnosticsEngine Diags(DiagID, &*DiagOpts, new TestDiagnosticConsumer);
-Driver TheDriver("/bin/clang", "x86_64-redhat-linux", Diags,
- "clang LLVM compiler", InMemoryFileSystem);
-std::unique_ptr C(TheDriver.BuildCompilation({"-v"}));
-ASSERT_TRUE(C);
-std::string S;
-{
-  llvm::raw_string_ostream OS(S);
-  C->getDefaultToolChain().printVerboseInfo(OS);
-}
-if (is_style_windows(llvm::sys::path::Style::native))
-  std::replace(S.begin(), S.end(), '\\', '/');
-EXPECT_EQ("Found candidate GCC inst

[PATCH] D124776: [SPIR-V] Allow setting SPIR-V version via target triple

2022-05-23 Thread Anastasia Stulova via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG72832efc941a: [SPIR-V] Allow setting SPIR-V version via 
target triple. (authored by Anastasia).

Changed prior to commit:
  https://reviews.llvm.org/D124776?vs=429678&id=431353#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124776

Files:
  llvm/docs/SPIRVUsage.rst
  llvm/docs/UserGuides.rst
  llvm/include/llvm/ADT/Triple.h
  llvm/lib/Support/Triple.cpp
  llvm/unittests/ADT/TripleTest.cpp

Index: llvm/unittests/ADT/TripleTest.cpp
===
--- llvm/unittests/ADT/TripleTest.cpp
+++ llvm/unittests/ADT/TripleTest.cpp
@@ -243,11 +243,85 @@
 
   T = Triple("spirv32-unknown-unknown");
   EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv32v1.0-unknown-unknown");
+  EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v10, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv32v1.1-unknown-unknown");
+  EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v11, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv32v1.2-unknown-unknown");
+  EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v12, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv32v1.3-unknown-unknown");
+  EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v13, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv32v1.4-unknown-unknown");
+  EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v14, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv32v1.5-unknown-unknown");
+  EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v15, T.getSubArch());
   EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
   EXPECT_EQ(Triple::UnknownOS, T.getOS());
 
   T = Triple("spirv64-unknown-unknown");
   EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv64v1.0-unknown-unknown");
+  EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v10, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv64v1.1-unknown-unknown");
+  EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v11, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv64v1.2-unknown-unknown");
+  EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v12, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv64v1.3-unknown-unknown");
+  EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v13, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv64v1.4-unknown-unknown");
+  EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v14, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv64v1.5-unknown-unknown");
+  EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v15, T.getSubArch());
   EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
   EXPECT_EQ(Triple::UnknownOS, T.getOS());
 
Index: llvm/lib/Support/Triple.cpp
===
--- llvm/lib/Support/Triple.cpp
+++ llvm/lib/Support/Triple.cpp
@@ -495,8 +495,10 @@
 .Case("hsail64", Triple::hsail64)
 .Case("spir", Triple::spir)
 .Case("spir64", Triple::spir64)
-.Case("spirv32", Triple::spirv32)
-.Case("spirv64", Triple::spirv64)
+.Cases("spirv32", "spirv32v1.0", "spirv32v1.1", "spirv32v1.2",
+   "spirv32v1.3", "spirv32v1.4", "spirv32v1.5", Triple::spirv32)
+.Cases("spirv64", "spirv64v1.0", "spirv64v1.1", "spirv64v1.2",
+   "spirv64v1.3", "spirv64v1.4", "spirv64v1.5", Triple::spirv64)
 .StartsWith("kalimba", Triple::kalimba)
 .Case("lanai", Triple::lanai)
 .Case("renderscript

[PATCH] D126127: [analyzer][NFC] Relocate unary transfer functions

2022-05-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 431354.
steakhal added a comment.

Pull out of the original patch stack


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126127

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp


Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -56,8 +56,6 @@
   : SValBuilder(alloc, context, stateMgr) {}
   ~SimpleSValBuilder() override {}
 
-  SVal evalMinus(NonLoc val) override;
-  SVal evalComplement(NonLoc val) override;
   SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
NonLoc lhs, NonLoc rhs, QualType resultTy) override;
   SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
@@ -82,28 +80,6 @@
   return new SimpleSValBuilder(alloc, context, stateMgr);
 }
 
-//===--===//
-// Transfer function for unary operators.
-//===--===//
-
-SVal SimpleSValBuilder::evalMinus(NonLoc val) {
-  switch (val.getSubKind()) {
-  case nonloc::ConcreteIntKind:
-return val.castAs().evalMinus(*this);
-  default:
-return UnknownVal();
-  }
-}
-
-SVal SimpleSValBuilder::evalComplement(NonLoc X) {
-  switch (X.getSubKind()) {
-  case nonloc::ConcreteIntKind:
-return X.castAs().evalComplement(*this);
-  default:
-return UnknownVal();
-  }
-}
-
 // Checks if the negation the value and flipping sign preserve
 // the semantics on the operation in the resultType
 static bool isNegationValuePreserving(const llvm::APSInt &Value,
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -434,6 +434,28 @@
   return UnknownVal();
 }
 
+//===--===//
+// Transfer function for unary operators.
+//===--===//
+
+SVal SValBuilder::evalMinus(NonLoc val) {
+  switch (val.getSubKind()) {
+  case nonloc::ConcreteIntKind:
+return val.castAs().evalMinus(*this);
+  default:
+return UnknownVal();
+  }
+}
+
+SVal SValBuilder::evalComplement(NonLoc X) {
+  switch (X.getSubKind()) {
+  case nonloc::ConcreteIntKind:
+return X.castAs().evalComplement(*this);
+  default:
+return UnknownVal();
+  }
+}
+
 SVal SValBuilder::evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
 SVal lhs, SVal rhs, QualType type) {
   if (lhs.isUndef() || rhs.isUndef())
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
@@ -120,9 +120,8 @@
   SVal evalIntegralCast(ProgramStateRef state, SVal val, QualType castTy,
 QualType originalType);
 
-  virtual SVal evalMinus(NonLoc val) = 0;
-
-  virtual SVal evalComplement(NonLoc val) = 0;
+  SVal evalMinus(NonLoc val);
+  SVal evalComplement(NonLoc val);
 
   /// Create a new value which represents a binary expression with two non-
   /// location operands.


Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -56,8 +56,6 @@
   : SValBuilder(alloc, context, stateMgr) {}
   ~SimpleSValBuilder() override {}
 
-  SVal evalMinus(NonLoc val) override;
-  SVal evalComplement(NonLoc val) override;
   SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
NonLoc lhs, NonLoc rhs, QualType resultTy) override;
   SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
@@ -82,28 +80,6 @@
   return new SimpleSValBuilder(alloc, context, stateMgr);
 }
 
-//===--===//
-// Transfer function for unary operators.
-//===--===//
-
-SVal SimpleSValBuilder::evalMinus(NonLoc val) {
-  switch (val.getSubKind()) {
-  case nonloc::ConcreteIntKind:
-return val.castAs().evalMinus(*this);
-  default:
-return UnknownVal();
-  }
-}
-
-SVal SimpleSValBuilder::evalComplement(NonLoc X) {
-  switch (X.getSubKind()) {
-  case nonloc::ConcreteIntKind:
-return X.cast

[PATCH] D126187: [C++20] [Coroutines] Conform the updates for CWG issue 2585

2022-05-23 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Also needs some release notes.




Comment at: clang/lib/Sema/SemaCoroutine.cpp:1293
   // that just takes the requested size.
-
-  FunctionDecl *OperatorNew = nullptr;
-  FunctionDecl *OperatorDelete = nullptr;
-  FunctionDecl *UnusedResult = nullptr;
-  bool PassAlignment = false;
-  SmallVector PlacementArgs;
-
+  //
   // [dcl.fct.def.coroutine]p9

Extra comment line.



Comment at: clang/lib/Sema/SemaCoroutine.cpp:1355
+  // We don't expect to call to global operator new with (size, p0, …, pn).
+  if (PromiseContainNew && !collectPlacementArgs(S, FD, Loc, PlacementArgs))
+return false;

Can you explain how this works?  I'm not seeing what part of the collection of 
placement args would prohibit the call you're talking about.



Comment at: clang/test/SemaCXX/coroutine-allocs2.cpp:2
+// Tests that we wouldn't generate an allocation call in global scope with 
(std::size_t, p0, ..., pn)
+// Although this test generates codes, it aims to test the semantics. So it is 
put here.
+// RUN: %clang_cc1 %s -std=c++20 -S -triple x86_64-unknown-linux-gnu 
-emit-llvm -disable-llvm-passes %s -o - | FileCheck %s

I'm not a fan at all of having a FIleCheck-type-test in Sema, and this DOES 
validate semantics.  Is there any way to get this to emit an error instead?  
Perhaps declare the generated operator-new as 'deleted' and show that it 
chooses THAT one instead by an error?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126187

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


[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-05-23 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

How much of P0848 is missing after this?  If nothing/not much, should we update 
cxx_status.html as well?




Comment at: clang/lib/Sema/SemaTemplateInstantiate.cpp:2330
+  /// To achieve that, we remove all non-selected destructors from the AST,
+  /// which is a bit unusual. We can't let those declarations be in AST and 
rely
+  /// on LookupSpecialMember to return the correct declaration because a lot of

I don't think this ends up being acceptable (removing them from the AST).  
Instead, we should probably mark them as "invalid" and update getDestructor to 
only return the 'only' destructor, or the first not-invalid one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126194

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


[PATCH] D126134: [clang-tidy] Improve add_new_check.py to recognize more checks

2022-05-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thanks for this! It generally LGTM (though my Python skills are not 
particularly awesome, so take it with a grain of salt). Just a few questions at 
this point.




Comment at: clang-tools-extra/clang-tidy/add_new_check.py:335-336
+module_file = get_module_filename(module_path, module_name)
+if not os.path.isfile(module_file):
+  return ''
+with io.open(module_file, 'r') as f:

Do we have to check this or can we rely on open failing because it's not a 
file? (It tripped my psychic TOCTOU sensor.)



Comment at: clang-tools-extra/clang-tidy/add_new_check.py:352
+  stmt = code[stmt_start_pos+1:stmt_end_pos]
+  matches = re.search('registerCheck<([^>:]*)>\(\s*"([^"]*)"\s*\)', stmt)
+  if matches and matches[2] == full_check_name:

It's a bit early for me to fully grok regex, but: is this going to handle line 
continuations/newlines okay? I don't know if those show up in cases that matter 
right now, but I wanted to make sure it was being thought about.



Comment at: clang-tools-extra/clang-tidy/add_new_check.py:371
+
+# The constructor might be inline in the header
+if not matches:




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126134

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


[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-05-23 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

In D126194#3531267 , @erichkeane 
wrote:

> How much of P0848 is missing after this?  If nothing/not much, should we 
> update cxx_status.html as well?

P0848 applies to all special member function. At best we could mark it partial 
but most of the work still need to be done.
I gave a shot to P0848 a few months ago, but my assesment is that clang might 
have to significantly refactor of special member functions to do that cleanly




Comment at: clang/lib/Sema/SemaTemplateInstantiate.cpp:2330
+  /// To achieve that, we remove all non-selected destructors from the AST,
+  /// which is a bit unusual. We can't let those declarations be in AST and 
rely
+  /// on LookupSpecialMember to return the correct declaration because a lot of

erichkeane wrote:
> I don't think this ends up being acceptable (removing them from the AST).  
> Instead, we should probably mark them as "invalid" and update getDestructor 
> to only return the 'only' destructor, or the first not-invalid one.
I'd rather we stay consistent with the wording, keep track of a selected 
destructor which would be returned by `getDestructor`. it's more surgery but 
it's a lot cleaner imo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126194

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


[PATCH] D126172: [clang] Fix comparison of TemplateArgument when they are of template kind

2022-05-23 Thread Robert Esclapez via Phabricator via cfe-commits
roberteg16 updated this revision to Diff 431356.
roberteg16 added a comment.

Stricten comparison


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126172

Files:
  clang/lib/AST/TemplateBase.cpp
  clang/test/CXX/dcl/dcl.fct/p17.cpp


Index: clang/test/CXX/dcl/dcl.fct/p17.cpp
===
--- clang/test/CXX/dcl/dcl.fct/p17.cpp
+++ clang/test/CXX/dcl/dcl.fct/p17.cpp
@@ -257,4 +257,23 @@
   static_assert(is_same_v);
   // expected-error@-1{{no matching}}
   static_assert(is_same_v);
-}
+
+  // clang-format off
+  template  struct S3 {};
+  // expected-note@-1 {{'S3' declared here}}
+  // expected-note@-2 {{template is declared here}}
+  void f23(C2<::S3> auto);
+  // expected-error@-1 {{no template named 'S3' in the global namespace; did 
you mean simply 'S3'?}}
+  // expected-error@-2 {{use of class template '::S3' requires template 
arguments}}
+  // clang-format on
+} // namespace constrained
+
+template  struct S4 {};
+// expected-note@-1 {{template is declared here}}
+
+namespace constrained {
+// clang-format off
+void f24(C2<::S4> auto);
+// expected-error@-1 {{use of class template '::S4' requires template 
arguments}}
+// clang-format on
+} // namespace constrained
Index: clang/lib/AST/TemplateBase.cpp
===
--- clang/lib/AST/TemplateBase.cpp
+++ clang/lib/AST/TemplateBase.cpp
@@ -370,7 +370,8 @@
 
   case Template:
   case TemplateExpansion:
-return TemplateArg.Name == Other.TemplateArg.Name &&
+return getAsTemplateOrTemplatePattern().getAsTemplateDecl() ==
+   Other.getAsTemplateOrTemplatePattern().getAsTemplateDecl() &&
TemplateArg.NumExpansions == Other.TemplateArg.NumExpansions;
 
   case Declaration:


Index: clang/test/CXX/dcl/dcl.fct/p17.cpp
===
--- clang/test/CXX/dcl/dcl.fct/p17.cpp
+++ clang/test/CXX/dcl/dcl.fct/p17.cpp
@@ -257,4 +257,23 @@
   static_assert(is_same_v);
   // expected-error@-1{{no matching}}
   static_assert(is_same_v);
-}
+
+  // clang-format off
+  template  struct S3 {};
+  // expected-note@-1 {{'S3' declared here}}
+  // expected-note@-2 {{template is declared here}}
+  void f23(C2<::S3> auto);
+  // expected-error@-1 {{no template named 'S3' in the global namespace; did you mean simply 'S3'?}}
+  // expected-error@-2 {{use of class template '::S3' requires template arguments}}
+  // clang-format on
+} // namespace constrained
+
+template  struct S4 {};
+// expected-note@-1 {{template is declared here}}
+
+namespace constrained {
+// clang-format off
+void f24(C2<::S4> auto);
+// expected-error@-1 {{use of class template '::S4' requires template arguments}}
+// clang-format on
+} // namespace constrained
Index: clang/lib/AST/TemplateBase.cpp
===
--- clang/lib/AST/TemplateBase.cpp
+++ clang/lib/AST/TemplateBase.cpp
@@ -370,7 +370,8 @@
 
   case Template:
   case TemplateExpansion:
-return TemplateArg.Name == Other.TemplateArg.Name &&
+return getAsTemplateOrTemplatePattern().getAsTemplateDecl() ==
+   Other.getAsTemplateOrTemplatePattern().getAsTemplateDecl() &&
TemplateArg.NumExpansions == Other.TemplateArg.NumExpansions;
 
   case Declaration:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 3e0be56 - [MSVC, ARM64] Add __writex18 intrinsics

2022-05-23 Thread Stephen Long via cfe-commits

Author: Stephen Long
Date: 2022-05-23T07:01:11-07:00
New Revision: 3e0be5610ff0e9d5bb15f2872bac8cd17bfcc34a

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

LOG: [MSVC, ARM64] Add __writex18 intrinsics

https://docs.microsoft.com/en-us/cpp/intrinsics/arm64-intrinsics?view=msvc-170

  void __writex18byte(unsigned long, unsigned char)
  void __writex18word(unsigned long, unsigned short)
  void __writex18dword(unsigned long, unsigned long)
  void __writex18qword(unsigned long, unsigned __int64)

Given the lack of documentation of the intrinsics, we chose to align the offset 
with just
`CharUnits::One()` when calling `IRBuilderBase::CreateAlignedStore()`.

Reviewed By: efriedma

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

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsAArch64.def
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Headers/intrin.h
clang/test/CodeGen/arm64-microsoft-intrinsics.c

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsAArch64.def 
b/clang/include/clang/Basic/BuiltinsAArch64.def
index cebd1c07fbcc..a04b48dd128e 100644
--- a/clang/include/clang/Basic/BuiltinsAArch64.def
+++ b/clang/include/clang/Basic/BuiltinsAArch64.def
@@ -251,6 +251,11 @@ TARGET_HEADER_BUILTIN(__umulh, "ULLiULLiULLi", "nh", 
"intrin.h", ALL_MS_LANGUAGE
 
 TARGET_HEADER_BUILTIN(__break, "vi", "nh", "intrin.h", ALL_MS_LANGUAGES, "")
 
+TARGET_HEADER_BUILTIN(__writex18byte,  "vULiUc", "nh", "intrin.h", 
ALL_MS_LANGUAGES, "")
+TARGET_HEADER_BUILTIN(__writex18word,  "vULiUs", "nh", "intrin.h", 
ALL_MS_LANGUAGES, "")
+TARGET_HEADER_BUILTIN(__writex18dword, "vULiULi", "nh", "intrin.h", 
ALL_MS_LANGUAGES, "")
+TARGET_HEADER_BUILTIN(__writex18qword, "vULiULLi", "nh", "intrin.h", 
ALL_MS_LANGUAGES, "")
+
 #undef BUILTIN
 #undef LANGBUILTIN
 #undef TARGET_HEADER_BUILTIN

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 2ee734550dc1..6168ba938db4 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -9952,6 +9952,31 @@ Value *CodeGenFunction::EmitAArch64BuiltinExpr(unsigned 
BuiltinID,
 return HigherBits;
   }
 
+  if (BuiltinID == AArch64::BI__writex18byte ||
+  BuiltinID == AArch64::BI__writex18word ||
+  BuiltinID == AArch64::BI__writex18dword ||
+  BuiltinID == AArch64::BI__writex18qword) {
+llvm::Type *IntTy = ConvertType(E->getArg(1)->getType());
+
+// Read x18 as i8*
+LLVMContext &Context = CGM.getLLVMContext();
+llvm::Metadata *Ops[] = {llvm::MDString::get(Context, "x18")};
+llvm::MDNode *RegName = llvm::MDNode::get(Context, Ops);
+llvm::Value *Metadata = llvm::MetadataAsValue::get(Context, RegName);
+llvm::Function *F =
+CGM.getIntrinsic(llvm::Intrinsic::read_register, {Int64Ty});
+llvm::Value *X18 = Builder.CreateCall(F, Metadata);
+X18 = Builder.CreateIntToPtr(X18, llvm::PointerType::get(Int8Ty, 0));
+
+// Store val at x18 + offset
+Value *Offset = Builder.CreateZExt(EmitScalarExpr(E->getArg(0)), Int64Ty);
+Value *Ptr = Builder.CreateGEP(Int8Ty, X18, Offset);
+Ptr = Builder.CreatePointerCast(Ptr, llvm::PointerType::get(IntTy, 0));
+Value *Val = EmitScalarExpr(E->getArg(1));
+StoreInst *Store = Builder.CreateAlignedStore(Val, Ptr, CharUnits::One());
+return Store;
+  }
+
   // Handle MSVC intrinsics before argument evaluation to prevent double
   // evaluation.
   if (Optional MsvcIntId = translateAarch64ToMsvcIntrin(BuiltinID))

diff  --git a/clang/lib/Headers/intrin.h b/clang/lib/Headers/intrin.h
index 07fcae36020d..dbc5159853dd 100644
--- a/clang/lib/Headers/intrin.h
+++ b/clang/lib/Headers/intrin.h
@@ -562,6 +562,11 @@ __int64 __mulh(__int64 __a, __int64 __b);
 unsigned __int64 __umulh(unsigned __int64 __a, unsigned __int64 __b);
 
 void __break(int);
+
+void __writex18byte(unsigned long offset, unsigned char data);
+void __writex18word(unsigned long offset, unsigned short data);
+void __writex18dword(unsigned long offset, unsigned long data);
+void __writex18qword(unsigned long offset, unsigned __int64 data);
 #endif
 
 
/**\

diff  --git a/clang/test/CodeGen/arm64-microsoft-intrinsics.c 
b/clang/test/CodeGen/arm64-microsoft-intrinsics.c
index ecf271bae580..a9b1d444553f 100644
--- a/clang/test/CodeGen/arm64-microsoft-intrinsics.c
+++ b/clang/test/CodeGen/arm64-microsoft-intrinsics.c
@@ -119,5 +119,73 @@ unsigned __int64 check__getReg(void) {
 
 // CHECK-MSVC: call i64 @llvm.read_register.i64(metadata ![[MD2:.*]])
 // CHECK-MSVC: call i64 @llvm.read_register.i64(metadata ![[MD3:.*]])
+
+void check__writex18byte(unsigned long offset, unsigned char data) {
+  __writex18byte(offset, data);
+}
+
+// CHECK-MSVC: %[[DATA_ADDR:.

[PATCH] D126023: [MSVC, ARM64] Add __writex18 intrinsics

2022-05-23 Thread Stephen Long via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3e0be5610ff0: [MSVC, ARM64] Add __writex18 intrinsics 
(authored by steplong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126023

Files:
  clang/include/clang/Basic/BuiltinsAArch64.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/intrin.h
  clang/test/CodeGen/arm64-microsoft-intrinsics.c

Index: clang/test/CodeGen/arm64-microsoft-intrinsics.c
===
--- clang/test/CodeGen/arm64-microsoft-intrinsics.c
+++ clang/test/CodeGen/arm64-microsoft-intrinsics.c
@@ -119,5 +119,73 @@
 
 // CHECK-MSVC: call i64 @llvm.read_register.i64(metadata ![[MD2:.*]])
 // CHECK-MSVC: call i64 @llvm.read_register.i64(metadata ![[MD3:.*]])
+
+void check__writex18byte(unsigned long offset, unsigned char data) {
+  __writex18byte(offset, data);
+}
+
+// CHECK-MSVC: %[[DATA_ADDR:.*]] = alloca i8, align 1
+// CHECK-MSVC: %[[OFFSET_ADDR:.*]] = alloca i32, align 4
+// CHECK-MSVC: store i8 %data, i8* %[[DATA_ADDR]], align 1
+// CHECK-MSVC: store i32 %offset, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[X18:.*]] = call i64 @llvm.read_register.i64(metadata ![[MD2]])
+// CHECK-MSVC: %[[X18_AS_PTR:.*]] = inttoptr i64 %[[X18]] to i8*
+// CHECK-MSVC: %[[OFFSET:.*]] = load i32, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[ZEXT_OFFSET:.*]] = zext i32 %[[OFFSET]] to i64
+// CHECK-MSVC: %[[PTR:.*]] = getelementptr i8, i8* %[[X18_AS_PTR]], i64 %[[ZEXT_OFFSET]]
+// CHECK-MSVC: %[[DATA:.*]] = load i8, i8* %[[DATA_ADDR]], align 1
+// CHECK-MSVC: store i8 %[[DATA]], i8* %[[PTR]], align 1
+
+void check__writex18word(unsigned long offset, unsigned short data) {
+  __writex18word(offset, data);
+}
+
+// CHECK-MSVC: %[[DATA_ADDR:.*]] = alloca i16, align 2
+// CHECK-MSVC: %[[OFFSET_ADDR:.*]] = alloca i32, align 4
+// CHECK-MSVC: store i16 %data, i16* %[[DATA_ADDR]], align 2
+// CHECK-MSVC: store i32 %offset, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[X18:.*]] = call i64 @llvm.read_register.i64(metadata ![[MD2]])
+// CHECK-MSVC: %[[X18_AS_PTR:.*]] = inttoptr i64 %[[X18]] to i8*
+// CHECK-MSVC: %[[OFFSET:.*]] = load i32, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[ZEXT_OFFSET:.*]] = zext i32 %[[OFFSET]] to i64
+// CHECK-MSVC: %[[PTR:.*]] = getelementptr i8, i8* %[[X18_AS_PTR]], i64 %[[ZEXT_OFFSET]]
+// CHECK-MSVC: %[[BITCAST_PTR:.*]] = bitcast i8* %[[PTR]] to i16*
+// CHECK-MSVC: %[[DATA:.*]] = load i16, i16* %[[DATA_ADDR]], align 2
+// CHECK-MSVC: store i16 %[[DATA]], i16* %[[BITCAST_PTR]], align 1
+
+void check__writex18dword(unsigned long offset, unsigned long data) {
+  __writex18dword(offset, data);
+}
+
+// CHECK-MSVC: %[[DATA_ADDR:.*]] = alloca i32, align 4
+// CHECK-MSVC: %[[OFFSET_ADDR:.*]] = alloca i32, align 4
+// CHECK-MSVC: store i32 %data, i32* %[[DATA_ADDR]], align 4
+// CHECK-MSVC: store i32 %offset, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[X18:.*]] = call i64 @llvm.read_register.i64(metadata ![[MD2]])
+// CHECK-MSVC: %[[X18_AS_PTR:.*]] = inttoptr i64 %[[X18]] to i8*
+// CHECK-MSVC: %[[OFFSET:.*]] = load i32, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[ZEXT_OFFSET:.*]] = zext i32 %[[OFFSET]] to i64
+// CHECK-MSVC: %[[PTR:.*]] = getelementptr i8, i8* %[[X18_AS_PTR]], i64 %[[ZEXT_OFFSET]]
+// CHECK-MSVC: %[[BITCAST_PTR:.*]] = bitcast i8* %[[PTR]] to i32*
+// CHECK-MSVC: %[[DATA:.*]] = load i32, i32* %[[DATA_ADDR]], align 4
+// CHECK-MSVC: store i32 %[[DATA]], i32* %[[BITCAST_PTR]], align 1
+
+void check__writex18qword(unsigned long offset, unsigned __int64 data) {
+  __writex18qword(offset, data);
+}
+
+// CHECK-MSVC: %[[DATA_ADDR:.*]] = alloca i64, align 8
+// CHECK-MSVC: %[[OFFSET_ADDR:.*]] = alloca i32, align 4
+// CHECK-MSVC: store i64 %data, i64* %[[DATA_ADDR]], align 8
+// CHECK-MSVC: store i32 %offset, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[X18:.*]] = call i64 @llvm.read_register.i64(metadata ![[MD2]])
+// CHECK-MSVC: %[[X18_AS_PTR:.*]] = inttoptr i64 %[[X18]] to i8*
+// CHECK-MSVC: %[[OFFSET:.*]] = load i32, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[ZEXT_OFFSET:.*]] = zext i32 %[[OFFSET]] to i64
+// CHECK-MSVC: %[[PTR:.*]] = getelementptr i8, i8* %[[X18_AS_PTR]], i64 %[[ZEXT_OFFSET]]
+// CHECK-MSVC: %[[BITCAST_PTR:.*]] = bitcast i8* %[[PTR]] to i64*
+// CHECK-MSVC: %[[DATA:.*]] = load i64, i64* %[[DATA_ADDR]], align 8
+// CHECK-MSVC: store i64 %[[DATA]], i64* %[[BITCAST_PTR]], align 1
+
 // CHECK-MSVC: ![[MD2]] = !{!"x18"}
 // CHECK-MSVC: ![[MD3]] = !{!"sp"}
Index: clang/lib/Headers/intrin.h
===
--- clang/lib/Headers/intrin.h
+++ clang/lib/Headers/intrin.h
@@ -562,6 +562,11 @@
 unsigned __int64 __umulh(unsigned __int64 __a, unsigned __int64 __b);
 
 void __break(int);
+
+void __writex18byte(unsigned long offset, unsigned char data);
+void __writex18word(unsigned long offse

[PATCH] D126186: [clang-tidy] Extend cert-oop57-cpp to check non-zero memset values

2022-05-23 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:201
 
+- Made :doc:`cert-oop57-cpp ` more sensitive
+  by checking for non-zero integer literal  memset arguments as well.

Please sort entries in section alphabetically.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:202
+- Made :doc:`cert-oop57-cpp ` more sensitive
+  by checking for non-zero integer literal  memset arguments as well.
+

Please fix double space and enclose `memset` into double back-ticks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126186

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


[PATCH] D125904: [Cuda] Use fallback method to mangle externalized decls if no CUID given

2022-05-23 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125904

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


[PATCH] D126198: [analyzer][NFCi] Annotate major nonnull returning functions

2022-05-23 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

I prefer references to annotations, but this is also a step in the right 
direction :l


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126198

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


[PATCH] D126134: [clang-tidy] Improve add_new_check.py to recognize more checks

2022-05-23 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood marked 2 inline comments as done.
LegalizeAdulthood added inline comments.



Comment at: clang-tools-extra/clang-tidy/add_new_check.py:335-336
+module_file = get_module_filename(module_path, module_name)
+if not os.path.isfile(module_file):
+  return ''
+with io.open(module_file, 'r') as f:

aaron.ballman wrote:
> Do we have to check this or can we rely on open failing because it's not a 
> file? (It tripped my psychic TOCTOU sensor.)
If we don't check here, then it throws an exception when attempting to open the 
file.



Comment at: clang-tools-extra/clang-tidy/add_new_check.py:352
+  stmt = code[stmt_start_pos+1:stmt_end_pos]
+  matches = re.search('registerCheck<([^>:]*)>\(\s*"([^"]*)"\s*\)', stmt)
+  if matches and matches[2] == full_check_name:

aaron.ballman wrote:
> It's a bit early for me to fully grok regex, but: is this going to handle 
> line continuations/newlines okay? I don't know if those show up in cases that 
> matter right now, but I wanted to make sure it was being thought about.
`\s` matches any single whitespace character and `\s*` matches zero or more 
whitespace characters.  I could sprinkle some more in between tokens, but this 
catches the existing code correctly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126134

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


[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-05-23 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson added a comment.

In D126194#3531280 , @cor3ntin wrote:

> In D126194#3531267 , @erichkeane 
> wrote:
>
>> How much of P0848 is missing after this?  If nothing/not much, should we 
>> update cxx_status.html as well?
>
> P0848 applies to all special member function. At best we could mark it 
> partial but most of the work still need to be done.
> I gave a shot to P0848 a few months ago, but my assesment is that clang might 
> have to significantly refactor of special member functions to do that cleanly

Corentin, are there other places like getDestructor where we need the 
constraints Sema information in the AST? I hoped the other special member 
functions go through LookupSpecialMember which does the needed overload 
resolution.

So as far as I understand the code base, the P0848 part that remains is 
computing the SMFs that are 'eligible' and update the type traits 
(trivial/trivially copyable) accordingly. Currently we mark those inside 
CXXRecordDecl::addedMember, so we'll probably have to override them. I also 
don't understand how exactly the eligibility checks interact with the deferred 
concept checking.

BTW, this also interacts funnily with other type traits. For example, this is 
apparently legal

  #include 
  template
  struct A {
A& operator=(A&&) requires true;
virtual A& operator=(A&&);
  };
  static_assert(!std::is_aggregate_v>);

So ineligible SMFs are ineligible only for the purpose of [copy]triviality, and 
can still have other visible effects!

About the status page - we're going to break ABI when we implement the type 
traits change so I don't think we should update it yet.




Comment at: clang/lib/Sema/SemaTemplateInstantiate.cpp:2330
+  /// To achieve that, we remove all non-selected destructors from the AST,
+  /// which is a bit unusual. We can't let those declarations be in AST and 
rely
+  /// on LookupSpecialMember to return the correct declaration because a lot of

cor3ntin wrote:
> erichkeane wrote:
> > I don't think this ends up being acceptable (removing them from the AST).  
> > Instead, we should probably mark them as "invalid" and update getDestructor 
> > to only return the 'only' destructor, or the first not-invalid one.
> I'd rather we stay consistent with the wording, keep track of a selected 
> destructor which would be returned by `getDestructor`. it's more surgery but 
> it's a lot cleaner imo
Corentin, do you suggest doing this in CXXRecordDecl explicitly?

Erich - I agree, this seems like a better solution, although this is a bit of 
abuse to 'invalid' in the case of less-constrained candidates. Ideally we might 
want another AST property of 'eligible' and keep track of things there, but I 
don't really know the AST code well enough to do it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126194

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


[PATCH] D126162: [clang-tidy] Extend SimplifyBooleanExpr demorgan support.

2022-05-23 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood accepted this revision.
LegalizeAdulthood added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126162

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


[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-05-23 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/Sema/SemaTemplateInstantiate.cpp:2330
+  /// To achieve that, we remove all non-selected destructors from the AST,
+  /// which is a bit unusual. We can't let those declarations be in AST and 
rely
+  /// on LookupSpecialMember to return the correct declaration because a lot of

royjacobson wrote:
> cor3ntin wrote:
> > erichkeane wrote:
> > > I don't think this ends up being acceptable (removing them from the AST). 
> > >  Instead, we should probably mark them as "invalid" and update 
> > > getDestructor to only return the 'only' destructor, or the first 
> > > not-invalid one.
> > I'd rather we stay consistent with the wording, keep track of a selected 
> > destructor which would be returned by `getDestructor`. it's more surgery 
> > but it's a lot cleaner imo
> Corentin, do you suggest doing this in CXXRecordDecl explicitly?
> 
> Erich - I agree, this seems like a better solution, although this is a bit of 
> abuse to 'invalid' in the case of less-constrained candidates. Ideally we 
> might want another AST property of 'eligible' and keep track of things there, 
> but I don't really know the AST code well enough to do it.
I like the idea of marking them eligible that way.  If this JUST has to do with 
Destructors for now, adding a bit to `CXXDestructorDecl` is a pretty trivial 
thing to do.  I'm pretty sure it is defined in `DeclCXX.h`. At that point, we 
just need to make sure it is checked during 'getDestructor' (or at least, 
around any calls to that).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126194

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


[PATCH] D126134: [clang-tidy] Improve add_new_check.py to recognize more checks

2022-05-23 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood marked 2 inline comments as done.
LegalizeAdulthood added a comment.

Another observation:
If some new pattern comes up and fixits aren't recognized for a check, it might 
be better
to switch to a whitelist for checks with fixits rather than going crazier on 
the file scraping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126134

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


[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-05-23 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson added inline comments.



Comment at: clang/lib/Sema/SemaTemplateInstantiate.cpp:2330
+  /// To achieve that, we remove all non-selected destructors from the AST,
+  /// which is a bit unusual. We can't let those declarations be in AST and 
rely
+  /// on LookupSpecialMember to return the correct declaration because a lot of

erichkeane wrote:
> royjacobson wrote:
> > cor3ntin wrote:
> > > erichkeane wrote:
> > > > I don't think this ends up being acceptable (removing them from the 
> > > > AST).  Instead, we should probably mark them as "invalid" and update 
> > > > getDestructor to only return the 'only' destructor, or the first 
> > > > not-invalid one.
> > > I'd rather we stay consistent with the wording, keep track of a selected 
> > > destructor which would be returned by `getDestructor`. it's more surgery 
> > > but it's a lot cleaner imo
> > Corentin, do you suggest doing this in CXXRecordDecl explicitly?
> > 
> > Erich - I agree, this seems like a better solution, although this is a bit 
> > of abuse to 'invalid' in the case of less-constrained candidates. Ideally 
> > we might want another AST property of 'eligible' and keep track of things 
> > there, but I don't really know the AST code well enough to do it.
> I like the idea of marking them eligible that way.  If this JUST has to do 
> with Destructors for now, adding a bit to `CXXDestructorDecl` is a pretty 
> trivial thing to do.  I'm pretty sure it is defined in `DeclCXX.h`. At that 
> point, we just need to make sure it is checked during 'getDestructor' (or at 
> least, around any calls to that).
I think we'll need it soon for the other SMF as well. (Or maybe even for all 
member functions if CWG2421 is ever resolved). 

So maybe I should just take some time to look at `FunctionDeclBitfields` and 
see if I can update it. (I hope updating the ast printers isn't too hard)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126194

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


[PATCH] D126198: [analyzer][NFCi] Annotate major nonnull returning functions

2022-05-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 431379.
steakhal marked an inline comment as done.
steakhal added a comment.

`assert(ctx)`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126198

Files:
  clang/include/clang/Analysis/AnalysisDeclContext.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp

Index: clang/lib/StaticAnalyzer/Core/MemRegion.cpp
===
--- clang/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ clang/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -162,7 +162,9 @@
 }
 
 ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const SubRegion *sReg)
-: DeclRegion(sReg, ObjCIvarRegionKind), IVD(ivd) {}
+: DeclRegion(sReg, ObjCIvarRegionKind), IVD(ivd) {
+  assert(IVD);
+}
 
 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
 
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
@@ -48,6 +48,7 @@
 assert(isValidTypeForSymbol(r->getValueType()));
   }
 
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
   const TypedValueRegion* getRegion() const { return R; }
 
   static void Profile(llvm::FoldingSetNodeID& profile, const TypedValueRegion* R) {
@@ -95,8 +96,10 @@
 assert(isValidTypeForSymbol(t));
   }
 
+  /// It might return null.
   const Stmt *getStmt() const { return S; }
   unsigned getCount() const { return Count; }
+  /// It might return null.
   const void *getTag() const { return SymbolTag; }
 
   QualType getType() const override;
@@ -140,7 +143,9 @@
 assert(isValidTypeForSymbol(r->getValueType()));
   }
 
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
   SymbolRef getParentSymbol() const { return parentSymbol; }
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
   const TypedValueRegion *getRegion() const { return R; }
 
   QualType getType() const override;
@@ -179,6 +184,7 @@
 assert(r);
   }
 
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
   const SubRegion *getRegion() const { return R; }
 
   QualType getType() const override;
@@ -226,29 +232,37 @@
   assert(tag);
 }
 
-  const MemRegion *getRegion() const { return R; }
-  const Stmt *getStmt() const { return S; }
-  const LocationContext *getLocationContext() const { return LCtx; }
-  unsigned getCount() const { return Count; }
-  const void *getTag() const { return Tag; }
+LLVM_ATTRIBUTE_RETURNS_NONNULL
+const MemRegion *getRegion() const { return R; }
 
-  QualType getType() const override;
+LLVM_ATTRIBUTE_RETURNS_NONNULL
+const Stmt *getStmt() const { return S; }
 
-  StringRef getKindStr() const override;
+LLVM_ATTRIBUTE_RETURNS_NONNULL
+const LocationContext *getLocationContext() const { return LCtx; }
 
-  void dumpToStream(raw_ostream &os) const override;
+unsigned getCount() const { return Count; }
 
-  static void Profile(llvm::FoldingSetNodeID& profile, const MemRegion *R,
-  const Stmt *S, QualType T, const LocationContext *LCtx,
-  unsigned Count, const void *Tag) {
-profile.AddInteger((unsigned) SymbolMetadataKind);
-profile.AddPointer(R);
-profile.AddPointer(S);
-profile.Add(T);
-profile.AddPointer(LCtx);
-profile.AddInteger(Count);
-profile.AddPointer(Tag);
-  }
+LLVM_ATTRIBUTE_RETURNS_NONNULL
+const void *getTag() const { return Tag; }
+
+QualType getType() const override;
+
+StringRef getKindStr() const override;
+
+void dumpToStream(raw_ostream &os) const override;
+
+static void Profile(llvm::FoldingSetNodeID &profile, const MemRegion *R,
+const Stmt *S, QualType T, const LocationContext *LCtx,
+unsigned Count, const void *Tag) {
+  profile.AddInteger((unsigned)SymbolMetadataKind);
+  profile.AddPointer(R);
+  profile.AddPointer(S);
+  profile.Add(T);
+  profile.AddPointer(LCtx);
+  profile.AddInteger(Count);
+  profile.AddPointer(Tag);
+}
 
   void Profile(llvm::FoldingSetNodeID& profile) override {
 Profile(profile, R, S, T, LCtx, Count, Tag);
@@ -287,6 +301,7 @@
 
   QualType getType() const override { return ToTy; }
 
+  LLVM

[PATCH] D126134: [clang-tidy] Improve add_new_check.py to recognize more checks

2022-05-23 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood added inline comments.



Comment at: clang-tools-extra/clang-tidy/add_new_check.py:352
+  stmt = code[stmt_start_pos+1:stmt_end_pos]
+  matches = re.search('registerCheck<([^>:]*)>\(\s*"([^"]*)"\s*\)', stmt)
+  if matches and matches[2] == full_check_name:

LegalizeAdulthood wrote:
> aaron.ballman wrote:
> > It's a bit early for me to fully grok regex, but: is this going to handle 
> > line continuations/newlines okay? I don't know if those show up in cases 
> > that matter right now, but I wanted to make sure it was being thought about.
> `\s` matches any single whitespace character and `\s*` matches zero or more 
> whitespace characters.  I could sprinkle some more in between tokens, but 
> this catches the existing code correctly.
There is some code like this: 
`CheckFactories.registerCheck("cert-oop54-cpp");`
 and I intentionally omit searching for this (`[^:>]*`) because these are 
aliases for other checks.

Which makes me wonder if we want to explicitly register aliases differently 
from regular checks?  If you want to run a list of checks and exclude aliases 
(so the check doesn't run twice), how do you do that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126134

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


[PATCH] D126194: [Concepts] Implement overload resolution for destructors (P0848)

2022-05-23 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/Sema/SemaTemplateInstantiate.cpp:2330
+  /// To achieve that, we remove all non-selected destructors from the AST,
+  /// which is a bit unusual. We can't let those declarations be in AST and 
rely
+  /// on LookupSpecialMember to return the correct declaration because a lot of

royjacobson wrote:
> erichkeane wrote:
> > royjacobson wrote:
> > > cor3ntin wrote:
> > > > erichkeane wrote:
> > > > > I don't think this ends up being acceptable (removing them from the 
> > > > > AST).  Instead, we should probably mark them as "invalid" and update 
> > > > > getDestructor to only return the 'only' destructor, or the first 
> > > > > not-invalid one.
> > > > I'd rather we stay consistent with the wording, keep track of a 
> > > > selected destructor which would be returned by `getDestructor`. it's 
> > > > more surgery but it's a lot cleaner imo
> > > Corentin, do you suggest doing this in CXXRecordDecl explicitly?
> > > 
> > > Erich - I agree, this seems like a better solution, although this is a 
> > > bit of abuse to 'invalid' in the case of less-constrained candidates. 
> > > Ideally we might want another AST property of 'eligible' and keep track 
> > > of things there, but I don't really know the AST code well enough to do 
> > > it.
> > I like the idea of marking them eligible that way.  If this JUST has to do 
> > with Destructors for now, adding a bit to `CXXDestructorDecl` is a pretty 
> > trivial thing to do.  I'm pretty sure it is defined in `DeclCXX.h`. At that 
> > point, we just need to make sure it is checked during 'getDestructor' (or 
> > at least, around any calls to that).
> I think we'll need it soon for the other SMF as well. (Or maybe even for all 
> member functions if CWG2421 is ever resolved). 
> 
> So maybe I should just take some time to look at `FunctionDeclBitfields` and 
> see if I can update it. (I hope updating the ast printers isn't too hard)
I'm pretty sure there is room in there.  Updating the printers should be pretty 
easy as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126194

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


[PATCH] D126134: [clang-tidy] Improve add_new_check.py to recognize more checks

2022-05-23 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood updated this revision to Diff 431383.
LegalizeAdulthood added a comment.

Update from review comments


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

https://reviews.llvm.org/D126134

Files:
  clang-tools-extra/clang-tidy/add_new_check.py
  clang-tools-extra/docs/clang-tidy/checks/list.rst

Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -37,19 +37,19 @@
`altera-struct-pack-align `_, "Yes"
`altera-unroll-loops `_,
`android-cloexec-accept `_, "Yes"
-   `android-cloexec-accept4 `_,
+   `android-cloexec-accept4 `_, "Yes"
`android-cloexec-creat `_, "Yes"
`android-cloexec-dup `_, "Yes"
-   `android-cloexec-epoll-create `_,
-   `android-cloexec-epoll-create1 `_,
-   `android-cloexec-fopen `_,
-   `android-cloexec-inotify-init `_,
-   `android-cloexec-inotify-init1 `_,
-   `android-cloexec-memfd-create `_,
-   `android-cloexec-open `_,
+   `android-cloexec-epoll-create `_, "Yes"
+   `android-cloexec-epoll-create1 `_, "Yes"
+   `android-cloexec-fopen `_, "Yes"
+   `android-cloexec-inotify-init `_, "Yes"
+   `android-cloexec-inotify-init1 `_, "Yes"
+   `android-cloexec-memfd-create `_, "Yes"
+   `android-cloexec-open `_, "Yes"
`android-cloexec-pipe `_, "Yes"
-   `android-cloexec-pipe2 `_,
-   `android-cloexec-socket `_,
+   `android-cloexec-pipe2 `_, "Yes"
+   `android-cloexec-socket `_, "Yes"
`android-comparison-in-temp-failure-retry `_,
`boost-use-to-string `_, "Yes"
`bugprone-argument-comment `_, "Yes"
@@ -105,7 +105,7 @@
`bugprone-terminating-continue `_, "Yes"
`bugprone-throw-keyword-missing `_,
`bugprone-too-small-loop-variable `_,
-   `bugprone-unchecked-optional-access `_, "Yes"
+   `bugprone-unchecked-optional-access `_,
`bugprone-undefined-memory-manipulation `_,
`bugprone-undelegated-constructor `_,
`bugprone-unhandled-exception-at-new `_,
Index: clang-tools-extra/clang-tidy/add_new_check.py
===
--- clang-tools-extra/clang-tidy/add_new_check.py
+++ clang-tools-extra/clang-tidy/add_new_check.py
@@ -158,12 +158,17 @@
'namespace': namespace})
 
 
-# Modifies the module to include the new check.
-def adapt_module(module_path, module, check_name, check_name_camel):
+# Returns the source filename that implements the module.
+def get_module_filename(module_path, module):
   modulecpp = list(filter(
   lambda p: p.lower() == module.lower() + 'tidymodule.cpp',
   os.listdir(module_path)))[0]
-  filename = os.path.join(module_path, modulecpp)
+  return os.path.join(module_path, modulecpp)
+
+
+# Modifies the module to include the new check.
+def adapt_module(module_path, module, check_name, check_name_camel):
+  filename = get_module_filename(module_path, module)
   with io.open(filename, 'r', encoding='utf8') as f:
 lines = f.readlines()
 
@@ -320,24 +325,100 @@
  os.listdir(docs_dir)))
   doc_files.sort()
 
+  # We couldn't find the source file from the check name, so try to find the
+  # class name that corresponds to the check in the module file.
+  def filename_from_module(module_name, check_name):
+module_path = os.path.join(clang_tidy_path, module_name)
+if not os.path.isdir(module_path):
+  return ''
+module_file = get_module_filename(module_path, module_name)
+if not os.path.isfile(module_file):
+  return ''
+with io.open(module_file, 'r') as f:
+  code = f.read()
+  full_check_name = module_name + '-' + check_name
+  name_pos = code.find('"' + full_check_name + '"')
+  if name_pos == -1:
+return ''
+  stmt_end_pos = code.find(';', name_pos)
+  if stmt_end_pos == -1:
+return ''
+  stmt_start_pos = code.rfind(';', 0, name_pos)
+  if stmt_start_pos == -1:
+stmt_start_pos = code.rfind('{', 0, name_pos)
+  if stmt_start_pos == -1:
+return ''
+  stmt = code[stmt_start_pos+1:stmt_end_pos]
+  matches = re.search('registerCheck<([^>:]*)>\(\s*"([^"]*)"\s*\)', stmt)
+  if matches and matches[2] == full_check_name:
+class_name = matches[1]
+if '::' in class_name:
+  parts = class_name.split('::')
+  class_name = parts[-1]
+  class_path = os.path.join(clang_tidy_path, module_name, '..', *parts[0:-1])
+else:
+  class_path = os.path.join(clang_tidy_path, module_name)
+return get_actual_filename(class_path, class_name + '.cpp')
+
+return ''
+
+  # Examine code looking for a c'tor definition to get the base class name.
+  def get_base_class(code, check_file):
+check_class_name = os.path.splitext(os.path.basename(check_file))[0]
+ctor_pattern = check_class_name + '\([^:]*\)\s*:\s*([A-Z][A-Za-z0-9]*Check)\('
+matches = re.search('\s+' + check_class_name +

[PATCH] D126134: [clang-tidy] Improve add_new_check.py to recognize more checks

2022-05-23 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood added inline comments.



Comment at: clang-tools-extra/clang-tidy/add_new_check.py:335-336
+module_file = get_module_filename(module_path, module_name)
+if not os.path.isfile(module_file):
+  return ''
+with io.open(module_file, 'r') as f:

LegalizeAdulthood wrote:
> aaron.ballman wrote:
> > Do we have to check this or can we rely on open failing because it's not a 
> > file? (It tripped my psychic TOCTOU sensor.)
> If we don't check here, then it throws an exception when attempting to open 
> the file.
Also, I was following the existing pattern in this file `:)`


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

https://reviews.llvm.org/D126134

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


[PATCH] D126134: [clang-tidy] Improve add_new_check.py to recognize more checks

2022-05-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM, thank you!




Comment at: clang-tools-extra/clang-tidy/add_new_check.py:335-336
+module_file = get_module_filename(module_path, module_name)
+if not os.path.isfile(module_file):
+  return ''
+with io.open(module_file, 'r') as f:

LegalizeAdulthood wrote:
> LegalizeAdulthood wrote:
> > aaron.ballman wrote:
> > > Do we have to check this or can we rely on open failing because it's not 
> > > a file? (It tripped my psychic TOCTOU sensor.)
> > If we don't check here, then it throws an exception when attempting to open 
> > the file.
> Also, I was following the existing pattern in this file `:)`
Sounds like a good reason to leave it in then, thanks!



Comment at: clang-tools-extra/clang-tidy/add_new_check.py:352
+  stmt = code[stmt_start_pos+1:stmt_end_pos]
+  matches = re.search('registerCheck<([^>:]*)>\(\s*"([^"]*)"\s*\)', stmt)
+  if matches and matches[2] == full_check_name:

LegalizeAdulthood wrote:
> LegalizeAdulthood wrote:
> > aaron.ballman wrote:
> > > It's a bit early for me to fully grok regex, but: is this going to handle 
> > > line continuations/newlines okay? I don't know if those show up in cases 
> > > that matter right now, but I wanted to make sure it was being thought 
> > > about.
> > `\s` matches any single whitespace character and `\s*` matches zero or more 
> > whitespace characters.  I could sprinkle some more in between tokens, but 
> > this catches the existing code correctly.
> There is some code like this: 
> `CheckFactories.registerCheck("cert-oop54-cpp");`
>  and I intentionally omit searching for this (`[^:>]*`) because these are 
> aliases for other checks.
> 
> Which makes me wonder if we want to explicitly register aliases differently 
> from regular checks?  If you want to run a list of checks and exclude aliases 
> (so the check doesn't run twice), how do you do that?
> Which makes me wonder if we want to explicitly register aliases differently 
> from regular checks? If you want to run a list of checks and exclude aliases 
> (so the check doesn't run twice), how do you do that?

You can't, which was the subject of https://reviews.llvm.org/D114317 but it's 
complicated in practice.


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

https://reviews.llvm.org/D126134

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


[PATCH] D123235: [OpenMP] atomic compare fail : Parser & AST support

2022-05-23 Thread Sunil K via Phabricator via cfe-commits
koops updated this revision to Diff 431385.
koops added a comment.

Clang formatting for variables in ParseOpenMP.cpp


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

https://reviews.llvm.org/D123235

Files:
  clang/include/clang/AST/ASTNodeTraverser.h
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/atomic_ast_print.cpp
  clang/test/OpenMP/atomic_messages.cpp
  clang/tools/libclang/CIndex.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -199,6 +199,7 @@
 def OMPC_Update : Clause<"update"> { let clangClass = "OMPUpdateClause"; }
 def OMPC_Capture : Clause<"capture"> { let clangClass = "OMPCaptureClause"; }
 def OMPC_Compare : Clause<"compare"> { let clangClass = "OMPCompareClause"; }
+def OMPC_Fail : Clause<"fail"> { let clangClass = "OMPFailClause"; }
 def OMPC_SeqCst : Clause<"seq_cst"> { let clangClass = "OMPSeqCstClause"; }
 def OMPC_AcqRel : Clause<"acq_rel"> { let clangClass = "OMPAcqRelClause"; }
 def OMPC_Acquire : Clause<"acquire"> { let clangClass = "OMPAcquireClause"; }
@@ -569,7 +570,8 @@
 VersionedClause,
 VersionedClause,
 VersionedClause,
-VersionedClause
+VersionedClause,
+VersionedClause
   ];
 }
 def OMP_Target : Directive<"target"> {
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -1807,6 +1807,7 @@
 CHECK_SIMPLE_CLAUSE(Align, OMPC_align)
 CHECK_SIMPLE_CLAUSE(Compare, OMPC_compare)
 CHECK_SIMPLE_CLAUSE(CancellationConstructType, OMPC_cancellation_construct_type)
+CHECK_SIMPLE_CLAUSE(Fail, OMPC_fail)
 
 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2278,6 +2278,8 @@
 
 void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
 
+void OMPClauseEnqueue::VisitOMPFailClause(const OMPFailClause *) {}
+
 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
 
 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
Index: clang/test/OpenMP/atomic_messages.cpp
===
--- clang/test/OpenMP/atomic_messages.cpp
+++ clang/test/OpenMP/atomic_messages.cpp
@@ -958,6 +958,24 @@
 // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'capture' clause}}
 #pragma omp atomic compare compare capture capture
   { v = a; if (a > b) a = b; }
+// expected-error@+1 {{expected 'compare' clause with the 'fail' modifier}}
+#pragma omp atomic fail(seq_cst)
+  if(v == a) { v = a; }
+// expected-error@+1 {{expected '(' after 'fail'}}
+#pragma omp atomic compare fail
+  if(v < a) { v = a; }
+// expected-error@+1 {{expected a memory order clause}}
+#pragma omp atomic compare fail(capture)
+  if(v < a) { v = a; }
+ // expected-error@+2 {{expected ')' after 'atomic compare fail'}}
+ // expected-warning@+1 {{extra tokens at the end of '#pragma omp atomic' are ignored}}
+#pragma omp atomic compare fail(seq_cst | acquire)
+  if(v < a) { v = a; }
+// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'fail' clause}}
+#pragma omp atomic compare fail(relaxed) fail(seq_cst)
+  if(v < a) { v = a; }
+
+
 #endif
   // expected-note@+1 {{in instantiation of function template specialization 'mixed' requested here}}
   return mixed();
Index: clang/test/OpenMP/atomic_ast_print.cpp
===
--- clang/test/OpenMP/atomic_ast_print.cpp
+++ clang/test/OpenMP/atomic_ast_print.cpp
@@ -226,6 +226,16 @@
   { v = a; if (a < b) { a = b; } }
 #pragma omp atomic compare capture hint(6)
   { v = a == b; if (v) a = c; }
+#pragma omp atomic compare fail(acq_rel)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(acquire)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(release)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(relaxed)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(seq_cst)
+  { if (a < c) { a = c; } }
 #endif

[PATCH] D101471: [clang-tidy] Add proper emplace checks to modernize-use-emplace

2022-05-23 Thread Nicolas van Kempen via Phabricator via cfe-commits
nicovank updated this revision to Diff 431387.
nicovank added a comment.

Update!

1. Rebased.
2. Fixed a minor bug which occasionaly caused false negatives.
3. Cleared up fix/hint generation and another nit following comments.
4. Re-organized and added a couple tests.
5. Made a note of this extension in documentation.

This check has been enabled internally as Facebook (pre-changes discussed 
above) for a bit over a year, with no reported issues.
It should be safe and ready to be upstreamed at this point.
Please let me know of any issues, let's get this landed!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D101471

Files:
  clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.h
  clang-tools-extra/docs/clang-tidy/checks/modernize-use-emplace.rst
  clang-tools-extra/test/clang-tidy/checkers/modernize-use-emplace.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-emplace.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-use-emplace.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-emplace.cpp
@@ -10,15 +10,36 @@
 
 namespace std {
 template 
-class initializer_list
-{
+class initializer_list {
 public:
   initializer_list() noexcept {}
 };
 
+template 
+class pair {
+public:
+  pair() = default;
+  pair(const pair &) = default;
+  pair(pair &&) = default;
+
+  pair(const T1 &, const T2 &) {}
+  pair(T1 &&, T2 &&) {}
+
+  template 
+  pair(const pair &){};
+  template 
+  pair(pair &&){};
+};
+
 template 
 class vector {
 public:
+  using value_type = T;
+
+  class iterator {};
+  class const_iterator {};
+  const_iterator begin() { return const_iterator{}; }
+
   vector() = default;
   vector(initializer_list) {}
 
@@ -27,54 +48,230 @@
 
   template 
   void emplace_back(Args &&... args){};
+  template 
+  iterator emplace(const_iterator pos, Args &&... args){};
   ~vector();
 };
+
 template 
 class list {
 public:
+  using value_type = T;
+
+  class iterator {};
+  class const_iterator {};
+  const_iterator begin() { return const_iterator{}; }
+
   void push_back(const T &) {}
   void push_back(T &&) {}
 
+  template 
+  iterator emplace(const_iterator pos, Args &&... args){};
   template 
   void emplace_back(Args &&... args){};
+  template 
+  void emplace_front(Args &&... args){};
   ~list();
 };
 
 template 
 class deque {
 public:
+  using value_type = T;
+
+  class iterator {};
+  class const_iterator {};
+  const_iterator begin() { return const_iterator{}; }
+
   void push_back(const T &) {}
   void push_back(T &&) {}
 
+  template 
+  iterator emplace(const_iterator pos, Args &&... args){};
   template 
   void emplace_back(Args &&... args){};
+  template 
+  void emplace_front(Args &&... args){};
   ~deque();
 };
 
-template  struct remove_reference { using type = T; };
-template  struct remove_reference { using type = T; };
-template  struct remove_reference { using type = T; };
+template 
+class forward_list {
+public:
+  using value_type = T;
+
+  class iterator {};
+  class const_iterator {};
+  const_iterator begin() { return const_iterator{}; }
+
+  template 
+  void emplace_front(Args &&... args){};
+  template 
+  iterator emplace_after(const_iterator pos, Args &&... args){};
+};
 
-template  class pair {
+template 
+class set {
 public:
-  pair() = default;
-  pair(const pair &) = default;
-  pair(pair &&) = default;
+  using value_type = T;
 
-  pair(const T1 &, const T2 &) {}
-  pair(T1 &&, T2 &&) {}
+  class iterator {};
+  class const_iterator {};
+  const_iterator begin() { return const_iterator{}; }
 
-  template  pair(const pair &){};
-  template  pair(pair &&){};
+  template 
+  void emplace(Args &&... args){};
+  template 
+  iterator emplace_hint(const_iterator pos, Args &&... args){};
 };
 
+template 
+class map {
+public:
+  using value_type = std::pair;
+
+  class iterator {};
+  class const_iterator {};
+  const_iterator begin() { return const_iterator{}; }
+
+  template 
+  void emplace(Args &&... args){};
+  template 
+  iterator emplace_hint(const_iterator pos, Args &&... args){};
+};
+
+template 
+class multiset {
+public:
+  using value_type = T;
+
+  class iterator {};
+  class const_iterator {};
+  const_iterator begin() { return const_iterator{}; }
+
+  template 
+  void emplace(Args &&... args){};
+  template 
+  iterator emplace_hint(const_iterator pos, Args &&... args){};
+};
+
+template 
+class multimap {
+public:
+  using value_type = std::pair;
+
+  class iterator {};
+  class const_iterator {};
+  const_iterator begin() { return const_iterator{}; }
+
+  template 
+  void emplace(Args &&... args){};
+  template 
+  iterator emplace_hint(const_iterator pos, Args &&... args){};
+};
+
+template 
+class unordered_set {
+public:
+  using value_type = T;
+
+  class iterator {};
+  class const_iterator {};
+  c

[PATCH] D126172: [clang] Fix comparison of TemplateArgument when they are of template kind

2022-05-23 Thread Robert Esclapez via Phabricator via cfe-commits
roberteg16 updated this revision to Diff 431389.
roberteg16 added a comment.

Try fix clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126172

Files:
  clang/lib/AST/TemplateBase.cpp
  clang/test/CXX/dcl/dcl.fct/p17.cpp


Index: clang/test/CXX/dcl/dcl.fct/p17.cpp
===
--- clang/test/CXX/dcl/dcl.fct/p17.cpp
+++ clang/test/CXX/dcl/dcl.fct/p17.cpp
@@ -257,4 +257,23 @@
   static_assert(is_same_v);
   // expected-error@-1{{no matching}}
   static_assert(is_same_v);
-}
+
+// clang-format off
+  template  struct S3 {};
+  // expected-note@-1 {{'S3' declared here}}
+  // expected-note@-2 {{template is declared here}}
+  void f23(C2<::S3> auto);
+  // expected-error@-1 {{no template named 'S3' in the global namespace; did 
you mean simply 'S3'?}}
+  // expected-error@-2 {{use of class template '::S3' requires template 
arguments}}
+// clang-format on
+} // namespace constrained
+
+template  struct S4 {};
+// expected-note@-1 {{template is declared here}}
+
+namespace constrained {
+// clang-format off
+void f24(C2<::S4> auto);
+// expected-error@-1 {{use of class template '::S4' requires template 
arguments}}
+// clang-format on
+} // namespace constrained
Index: clang/lib/AST/TemplateBase.cpp
===
--- clang/lib/AST/TemplateBase.cpp
+++ clang/lib/AST/TemplateBase.cpp
@@ -370,7 +370,8 @@
 
   case Template:
   case TemplateExpansion:
-return TemplateArg.Name == Other.TemplateArg.Name &&
+return getAsTemplateOrTemplatePattern().getAsTemplateDecl() ==
+   Other.getAsTemplateOrTemplatePattern().getAsTemplateDecl() &&
TemplateArg.NumExpansions == Other.TemplateArg.NumExpansions;
 
   case Declaration:


Index: clang/test/CXX/dcl/dcl.fct/p17.cpp
===
--- clang/test/CXX/dcl/dcl.fct/p17.cpp
+++ clang/test/CXX/dcl/dcl.fct/p17.cpp
@@ -257,4 +257,23 @@
   static_assert(is_same_v);
   // expected-error@-1{{no matching}}
   static_assert(is_same_v);
-}
+
+// clang-format off
+  template  struct S3 {};
+  // expected-note@-1 {{'S3' declared here}}
+  // expected-note@-2 {{template is declared here}}
+  void f23(C2<::S3> auto);
+  // expected-error@-1 {{no template named 'S3' in the global namespace; did you mean simply 'S3'?}}
+  // expected-error@-2 {{use of class template '::S3' requires template arguments}}
+// clang-format on
+} // namespace constrained
+
+template  struct S4 {};
+// expected-note@-1 {{template is declared here}}
+
+namespace constrained {
+// clang-format off
+void f24(C2<::S4> auto);
+// expected-error@-1 {{use of class template '::S4' requires template arguments}}
+// clang-format on
+} // namespace constrained
Index: clang/lib/AST/TemplateBase.cpp
===
--- clang/lib/AST/TemplateBase.cpp
+++ clang/lib/AST/TemplateBase.cpp
@@ -370,7 +370,8 @@
 
   case Template:
   case TemplateExpansion:
-return TemplateArg.Name == Other.TemplateArg.Name &&
+return getAsTemplateOrTemplatePattern().getAsTemplateDecl() ==
+   Other.getAsTemplateOrTemplatePattern().getAsTemplateDecl() &&
TemplateArg.NumExpansions == Other.TemplateArg.NumExpansions;
 
   case Declaration:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125848: [clang-format] Handle attributes in enum declaration.

2022-05-23 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

This looks good to me, but let the others chime in..


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125848

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


[clang-tools-extra] 89e663c - [clang-tidy] Improve add_new_check.py to recognize more checks

2022-05-23 Thread via cfe-commits

Author: Richard
Date: 2022-05-23T09:47:54-06:00
New Revision: 89e663c4f83a6736fc74a01ec48cb4f01210f86f

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

LOG: [clang-tidy] Improve add_new_check.py to recognize more checks

When looking for whether or not a check provides fixits, the script
examines the implementation of the check.  Some checks are not
implemented in source files that correspond one-to-one with the check
name, e.g. cert-dcl21-cpp.  So if we can't find the check implementation
directly from the check name, open up the corresponding module file and
look for the class name that is registered with the check.  Then consult
the file corresponding to the class name.

Some checks are derived from a base class that implements fixits.  So if
we can't find fixits in the implementation file for a check, scrape out
the name of it's base class.  If it's not ClangTidyCheck, then consult
the base class implementation to look for fixit support.

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

Fixes #55630

Added: 


Modified: 
clang-tools-extra/clang-tidy/add_new_check.py
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/add_new_check.py 
b/clang-tools-extra/clang-tidy/add_new_check.py
index fc83974486314..2e8684ca756dc 100644
--- a/clang-tools-extra/clang-tidy/add_new_check.py
+++ b/clang-tools-extra/clang-tidy/add_new_check.py
@@ -158,12 +158,17 @@ def write_implementation(module_path, module, namespace, 
check_name_camel):
'namespace': namespace})
 
 
-# Modifies the module to include the new check.
-def adapt_module(module_path, module, check_name, check_name_camel):
+# Returns the source filename that implements the module.
+def get_module_filename(module_path, module):
   modulecpp = list(filter(
   lambda p: p.lower() == module.lower() + 'tidymodule.cpp',
   os.listdir(module_path)))[0]
-  filename = os.path.join(module_path, modulecpp)
+  return os.path.join(module_path, modulecpp)
+
+
+# Modifies the module to include the new check.
+def adapt_module(module_path, module, check_name, check_name_camel):
+  filename = get_module_filename(module_path, module)
   with io.open(filename, 'r', encoding='utf8') as f:
 lines = f.readlines()
 
@@ -320,24 +325,100 @@ def update_checks_list(clang_tidy_path):
  os.listdir(docs_dir)))
   doc_files.sort()
 
+  # We couldn't find the source file from the check name, so try to find the
+  # class name that corresponds to the check in the module file.
+  def filename_from_module(module_name, check_name):
+module_path = os.path.join(clang_tidy_path, module_name)
+if not os.path.isdir(module_path):
+  return ''
+module_file = get_module_filename(module_path, module_name)
+if not os.path.isfile(module_file):
+  return ''
+with io.open(module_file, 'r') as f:
+  code = f.read()
+  full_check_name = module_name + '-' + check_name
+  name_pos = code.find('"' + full_check_name + '"')
+  if name_pos == -1:
+return ''
+  stmt_end_pos = code.find(';', name_pos)
+  if stmt_end_pos == -1:
+return ''
+  stmt_start_pos = code.rfind(';', 0, name_pos)
+  if stmt_start_pos == -1:
+stmt_start_pos = code.rfind('{', 0, name_pos)
+  if stmt_start_pos == -1:
+return ''
+  stmt = code[stmt_start_pos+1:stmt_end_pos]
+  matches = re.search('registerCheck<([^>:]*)>\(\s*"([^"]*)"\s*\)', stmt)
+  if matches and matches[2] == full_check_name:
+class_name = matches[1]
+if '::' in class_name:
+  parts = class_name.split('::')
+  class_name = parts[-1]
+  class_path = os.path.join(clang_tidy_path, module_name, '..', 
*parts[0:-1])
+else:
+  class_path = os.path.join(clang_tidy_path, module_name)
+return get_actual_filename(class_path, class_name + '.cpp')
+
+return ''
+
+  # Examine code looking for a c'tor definition to get the base class name.
+  def get_base_class(code, check_file):
+check_class_name = os.path.splitext(os.path.basename(check_file))[0]
+ctor_pattern = check_class_name + 
'\([^:]*\)\s*:\s*([A-Z][A-Za-z0-9]*Check)\('
+matches = re.search('\s+' + check_class_name + '::' + ctor_pattern, code)
+
+# The constructor might be inline in the header.
+if not matches:
+  header_file = os.path.splitext(check_file)[0] + '.h'
+  if not os.path.isfile(header_file):
+return ''
+  with io.open(header_file, encoding='utf8') as f:
+code = f.read()
+  matches = re.search(' ' + ctor_pattern, code)
+
+if matches and matches[1] != 'ClangTidyCheck':
+  return matches[1]
+return ''
+
+  # Some simple heuristics to figure out if a che

[PATCH] D126134: [clang-tidy] Improve add_new_check.py to recognize more checks

2022-05-23 Thread Richard via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG89e663c4f83a: [clang-tidy] Improve add_new_check.py to 
recognize more checks (authored by LegalizeAdulthood).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126134

Files:
  clang-tools-extra/clang-tidy/add_new_check.py
  clang-tools-extra/docs/clang-tidy/checks/list.rst

Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -37,19 +37,19 @@
`altera-struct-pack-align `_, "Yes"
`altera-unroll-loops `_,
`android-cloexec-accept `_, "Yes"
-   `android-cloexec-accept4 `_,
+   `android-cloexec-accept4 `_, "Yes"
`android-cloexec-creat `_, "Yes"
`android-cloexec-dup `_, "Yes"
-   `android-cloexec-epoll-create `_,
-   `android-cloexec-epoll-create1 `_,
-   `android-cloexec-fopen `_,
-   `android-cloexec-inotify-init `_,
-   `android-cloexec-inotify-init1 `_,
-   `android-cloexec-memfd-create `_,
-   `android-cloexec-open `_,
+   `android-cloexec-epoll-create `_, "Yes"
+   `android-cloexec-epoll-create1 `_, "Yes"
+   `android-cloexec-fopen `_, "Yes"
+   `android-cloexec-inotify-init `_, "Yes"
+   `android-cloexec-inotify-init1 `_, "Yes"
+   `android-cloexec-memfd-create `_, "Yes"
+   `android-cloexec-open `_, "Yes"
`android-cloexec-pipe `_, "Yes"
-   `android-cloexec-pipe2 `_,
-   `android-cloexec-socket `_,
+   `android-cloexec-pipe2 `_, "Yes"
+   `android-cloexec-socket `_, "Yes"
`android-comparison-in-temp-failure-retry `_,
`boost-use-to-string `_, "Yes"
`bugprone-argument-comment `_, "Yes"
@@ -105,7 +105,7 @@
`bugprone-terminating-continue `_, "Yes"
`bugprone-throw-keyword-missing `_,
`bugprone-too-small-loop-variable `_,
-   `bugprone-unchecked-optional-access `_, "Yes"
+   `bugprone-unchecked-optional-access `_,
`bugprone-undefined-memory-manipulation `_,
`bugprone-undelegated-constructor `_,
`bugprone-unhandled-exception-at-new `_,
Index: clang-tools-extra/clang-tidy/add_new_check.py
===
--- clang-tools-extra/clang-tidy/add_new_check.py
+++ clang-tools-extra/clang-tidy/add_new_check.py
@@ -158,12 +158,17 @@
'namespace': namespace})
 
 
-# Modifies the module to include the new check.
-def adapt_module(module_path, module, check_name, check_name_camel):
+# Returns the source filename that implements the module.
+def get_module_filename(module_path, module):
   modulecpp = list(filter(
   lambda p: p.lower() == module.lower() + 'tidymodule.cpp',
   os.listdir(module_path)))[0]
-  filename = os.path.join(module_path, modulecpp)
+  return os.path.join(module_path, modulecpp)
+
+
+# Modifies the module to include the new check.
+def adapt_module(module_path, module, check_name, check_name_camel):
+  filename = get_module_filename(module_path, module)
   with io.open(filename, 'r', encoding='utf8') as f:
 lines = f.readlines()
 
@@ -320,24 +325,100 @@
  os.listdir(docs_dir)))
   doc_files.sort()
 
+  # We couldn't find the source file from the check name, so try to find the
+  # class name that corresponds to the check in the module file.
+  def filename_from_module(module_name, check_name):
+module_path = os.path.join(clang_tidy_path, module_name)
+if not os.path.isdir(module_path):
+  return ''
+module_file = get_module_filename(module_path, module_name)
+if not os.path.isfile(module_file):
+  return ''
+with io.open(module_file, 'r') as f:
+  code = f.read()
+  full_check_name = module_name + '-' + check_name
+  name_pos = code.find('"' + full_check_name + '"')
+  if name_pos == -1:
+return ''
+  stmt_end_pos = code.find(';', name_pos)
+  if stmt_end_pos == -1:
+return ''
+  stmt_start_pos = code.rfind(';', 0, name_pos)
+  if stmt_start_pos == -1:
+stmt_start_pos = code.rfind('{', 0, name_pos)
+  if stmt_start_pos == -1:
+return ''
+  stmt = code[stmt_start_pos+1:stmt_end_pos]
+  matches = re.search('registerCheck<([^>:]*)>\(\s*"([^"]*)"\s*\)', stmt)
+  if matches and matches[2] == full_check_name:
+class_name = matches[1]
+if '::' in class_name:
+  parts = class_name.split('::')
+  class_name = parts[-1]
+  class_path = os.path.join(clang_tidy_path, module_name, '..', *parts[0:-1])
+else:
+  class_path = os.path.join(clang_tidy_path, module_name)
+return get_actual_filename(class_path, class_name + '.cpp')
+
+return ''
+
+  # Examine code looking for a c'tor definition to get the base class name.
+  def get_base_class(code, check_file):
+check_class_name = os.path

[PATCH] D126157: [clang-format][NFC] Insert/remove braces in clang/lib/Format/

2022-05-23 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.

LGTM too.. @owenpan this is one of my favourite features!!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126157

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


[PATCH] D125667: [pseudo] A basic implementation of compiling cxx grammar at build time.

2022-05-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/pseudo/lib/cxx/CXX.cpp:17
+static const char *CxxBNF =
+#include "CXXBNF.inc"
+;

this is worth a try, but I think (some versions of?) MSVC don't like long 
string literals.

Stackoverflow says 2k per "chunk" ("one" "two" "three") and 64k total.
Integer arrays can be larger...

So let's start with simple readable options, and make them progressively uglier 
if we hit limits.



Comment at: clang-tools-extra/pseudo/lib/cxx/CXX.cpp:22
+  static std::vector Diags;
+  static std::unique_ptr G = Grammar::parseBNF(CxxBNF, Diags);
+  assert(Diags.empty());

static Grammar &G = *Grammar::parseBNF(...).release();
to avoid destruction



Comment at: clang-tools-extra/pseudo/lib/cxx/CXX.cpp:28
+const LRTable &getLRTable() {
+  static LRTable Table = LRTable::buildSLR(getGrammar());
+  return Table;

similarly &Table = *new LRTable(buildSLR(...));



Comment at: clang-tools-extra/pseudo/lib/grammar/CMakeLists.txt:3
+
+add_clang_library(clangPseudoGrammar
+  Grammar.cpp

a comment why we want minimal deps here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125667

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


[PATCH] D126132: [clang-format] Fix a crash on lambda trailing return type

2022-05-23 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.

LGTM  (sorry I've been slow on the reviews, my day job keeps getting in the way 
;-))


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126132

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


[PATCH] D125970: [amdgpu] Add amdgpu_kernel calling conv attribute to clang

2022-05-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D125970#3527685 , @JonChesterfield 
wrote:

> If it was adding a calling convention, sure - caution warranted. There's no 
> llvm change here though, an existing CC is exposed to C++. No change to the 
> type system either.

This is adding a user-facing calling convention to Clang and it changes the 
type system as a result. For example, lambda function pointer conversion 
operators sometimes are generated for each calling convention so that you can 
form a function pointer of the correct type (this might not be impacted by your 
change here); there's a specific number of bits for representing the 
enumeration of calling conventions and this uses one of those bits, etc.

> I'll propose a patch with some documentation for it if you wish, but it'll 
> just say "For ad hoc debugging of the amdgpu backend". Undocumented seems to 
> state that more clearly.

I continue to question whether we want to support such a calling convention. 
This does not seem to be generally useful enough to warrant inclusion in Clang. 
The fact that you'd like to leave it undocumented as that's more clear for 
users is a pretty good indication that this calling convention doesn't meet the 
bar for an extension.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125970

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


[PATCH] D125961: [clang-format] Don't break lines after pragma region

2022-05-23 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:19604
+
+  EXPECT_EQ("#pragma region TEST(FOO : BAR)", format("#pragma region TEST(FOO 
: BAR)", Style));
+}

do we need to consider endregion at all? it would be nice to have some tests 
that included both.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125961

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


[PATCH] D123235: [OpenMP] atomic compare fail : Parser & AST support

2022-05-23 Thread Sunil K via Phabricator via cfe-commits
koops updated this revision to Diff 431391.

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

https://reviews.llvm.org/D123235

Files:
  clang/include/clang/AST/ASTNodeTraverser.h
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/atomic_ast_print.cpp
  clang/test/OpenMP/atomic_messages.cpp
  clang/tools/libclang/CIndex.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -199,6 +199,7 @@
 def OMPC_Update : Clause<"update"> { let clangClass = "OMPUpdateClause"; }
 def OMPC_Capture : Clause<"capture"> { let clangClass = "OMPCaptureClause"; }
 def OMPC_Compare : Clause<"compare"> { let clangClass = "OMPCompareClause"; }
+def OMPC_Fail : Clause<"fail"> { let clangClass = "OMPFailClause"; }
 def OMPC_SeqCst : Clause<"seq_cst"> { let clangClass = "OMPSeqCstClause"; }
 def OMPC_AcqRel : Clause<"acq_rel"> { let clangClass = "OMPAcqRelClause"; }
 def OMPC_Acquire : Clause<"acquire"> { let clangClass = "OMPAcquireClause"; }
@@ -569,7 +570,8 @@
 VersionedClause,
 VersionedClause,
 VersionedClause,
-VersionedClause
+VersionedClause,
+VersionedClause
   ];
 }
 def OMP_Target : Directive<"target"> {
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -1807,6 +1807,7 @@
 CHECK_SIMPLE_CLAUSE(Align, OMPC_align)
 CHECK_SIMPLE_CLAUSE(Compare, OMPC_compare)
 CHECK_SIMPLE_CLAUSE(CancellationConstructType, OMPC_cancellation_construct_type)
+CHECK_SIMPLE_CLAUSE(Fail, OMPC_fail)
 
 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2278,6 +2278,8 @@
 
 void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
 
+void OMPClauseEnqueue::VisitOMPFailClause(const OMPFailClause *) {}
+
 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
 
 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
Index: clang/test/OpenMP/atomic_messages.cpp
===
--- clang/test/OpenMP/atomic_messages.cpp
+++ clang/test/OpenMP/atomic_messages.cpp
@@ -958,6 +958,24 @@
 // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'capture' clause}}
 #pragma omp atomic compare compare capture capture
   { v = a; if (a > b) a = b; }
+// expected-error@+1 {{expected 'compare' clause with the 'fail' modifier}}
+#pragma omp atomic fail(seq_cst)
+  if(v == a) { v = a; }
+// expected-error@+1 {{expected '(' after 'fail'}}
+#pragma omp atomic compare fail
+  if(v < a) { v = a; }
+// expected-error@+1 {{expected a memory order clause}}
+#pragma omp atomic compare fail(capture)
+  if(v < a) { v = a; }
+ // expected-error@+2 {{expected ')' after 'atomic compare fail'}}
+ // expected-warning@+1 {{extra tokens at the end of '#pragma omp atomic' are ignored}}
+#pragma omp atomic compare fail(seq_cst | acquire)
+  if(v < a) { v = a; }
+// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'fail' clause}}
+#pragma omp atomic compare fail(relaxed) fail(seq_cst)
+  if(v < a) { v = a; }
+
+
 #endif
   // expected-note@+1 {{in instantiation of function template specialization 'mixed' requested here}}
   return mixed();
Index: clang/test/OpenMP/atomic_ast_print.cpp
===
--- clang/test/OpenMP/atomic_ast_print.cpp
+++ clang/test/OpenMP/atomic_ast_print.cpp
@@ -226,6 +226,16 @@
   { v = a; if (a < b) { a = b; } }
 #pragma omp atomic compare capture hint(6)
   { v = a == b; if (v) a = c; }
+#pragma omp atomic compare fail(acq_rel)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(acquire)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(release)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(relaxed)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(seq_cst)
+  { if (a < c) { a = c; } }
 #endif
   return T();
 }
@@ -1099,6 +1109,16 @@
   { v = a; if (a < b) { a = b; } 

[PATCH] D126024: [MSVC, ARM64] Add __readx18 intrinsics

2022-05-23 Thread Stephen Long via Phabricator via cfe-commits
steplong updated this revision to Diff 431392.
steplong added a comment.

- Rebased patch on top of main


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126024

Files:
  clang/include/clang/Basic/BuiltinsAArch64.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/intrin.h
  clang/test/CodeGen/arm64-microsoft-intrinsics.c

Index: clang/test/CodeGen/arm64-microsoft-intrinsics.c
===
--- clang/test/CodeGen/arm64-microsoft-intrinsics.c
+++ clang/test/CodeGen/arm64-microsoft-intrinsics.c
@@ -187,5 +187,64 @@
 // CHECK-MSVC: %[[DATA:.*]] = load i64, i64* %[[DATA_ADDR]], align 8
 // CHECK-MSVC: store i64 %[[DATA]], i64* %[[BITCAST_PTR]], align 1
 
+unsigned char check__readx18byte(unsigned long offset) {
+  return __readx18byte(offset);
+}
+
+// CHECK-MSVC: %[[OFFSET_ADDR:.*]] = alloca i32, align 4
+// CHECK-MSVC: store i32 %offset, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[X18:.*]] = call i64 @llvm.read_register.i64(metadata ![[MD2]])
+// CHECK-MSVC: %[[X18_AS_PTR:.*]] = inttoptr i64 %[[X18]] to i8*
+// CHECK-MSVC: %[[OFFSET:.*]] = load i32, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[ZEXT_OFFSET:.*]] = zext i32 %[[OFFSET]] to i64
+// CHECK-MSVC: %[[PTR:.*]] = getelementptr i8, i8* %[[X18_AS_PTR]], i64 %[[ZEXT_OFFSET]]
+// CHECK-MSVC: %[[RETVAL:.*]] = load i8, i8* %[[PTR]], align 1
+// CHECK-MSVC: ret i8 %[[RETVAL]]
+
+unsigned short check__readx18word(unsigned long offset) {
+  return __readx18word(offset);
+}
+
+// CHECK-MSVC: %[[OFFSET_ADDR:.*]] = alloca i32, align 4
+// CHECK-MSVC: store i32 %offset, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[X18:.*]] = call i64 @llvm.read_register.i64(metadata ![[MD2]])
+// CHECK-MSVC: %[[X18_AS_PTR:.*]] = inttoptr i64 %[[X18]] to i8*
+// CHECK-MSVC: %[[OFFSET:.*]] = load i32, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[ZEXT_OFFSET:.*]] = zext i32 %[[OFFSET]] to i64
+// CHECK-MSVC: %[[PTR:.*]] = getelementptr i8, i8* %[[X18_AS_PTR]], i64 %[[ZEXT_OFFSET]]
+// CHECK-MSVC: %[[BITCAST_PTR:.*]] = bitcast i8* %[[PTR]] to i16*
+// CHECK-MSVC: %[[RETVAL:.*]] = load i16, i16* %[[BITCAST_PTR]], align 1
+// CHECK-MSVC: ret i16 %[[RETVAL]]
+
+unsigned long check__readx18dword(unsigned long offset) {
+  return __readx18dword(offset);
+}
+
+// CHECK-MSVC: %[[OFFSET_ADDR:.*]] = alloca i32, align 4
+// CHECK-MSVC: store i32 %offset, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[X18:.*]] = call i64 @llvm.read_register.i64(metadata ![[MD2]])
+// CHECK-MSVC: %[[X18_AS_PTR:.*]] = inttoptr i64 %[[X18]] to i8*
+// CHECK-MSVC: %[[OFFSET:.*]] = load i32, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[ZEXT_OFFSET:.*]] = zext i32 %[[OFFSET]] to i64
+// CHECK-MSVC: %[[PTR:.*]] = getelementptr i8, i8* %[[X18_AS_PTR]], i64 %[[ZEXT_OFFSET]]
+// CHECK-MSVC: %[[BITCAST_PTR:.*]] = bitcast i8* %[[PTR]] to i32*
+// CHECK-MSVC: %[[RETVAL:.*]] = load i32, i32* %[[BITCAST_PTR]], align 1
+// CHECK-MSVC: ret i32 %[[RETVAL]]
+
+unsigned __int64 check__readx18qword(unsigned long offset) {
+  return __readx18qword(offset);
+}
+
+// CHECK-MSVC: %[[OFFSET_ADDR:.*]] = alloca i32, align 4
+// CHECK-MSVC: store i32 %offset, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[X18:.*]] = call i64 @llvm.read_register.i64(metadata ![[MD2]])
+// CHECK-MSVC: %[[X18_AS_PTR:.*]] = inttoptr i64 %[[X18]] to i8*
+// CHECK-MSVC: %[[OFFSET:.*]] = load i32, i32* %[[OFFSET_ADDR]], align 4
+// CHECK-MSVC: %[[ZEXT_OFFSET:.*]] = zext i32 %[[OFFSET]] to i64
+// CHECK-MSVC: %[[PTR:.*]] = getelementptr i8, i8* %[[X18_AS_PTR]], i64 %[[ZEXT_OFFSET]]
+// CHECK-MSVC: %[[BITCAST_PTR:.*]] = bitcast i8* %[[PTR]] to i64*
+// CHECK-MSVC: %[[RETVAL:.*]] = load i64, i64* %[[BITCAST_PTR]], align 1
+// CHECK-MSVC: ret i64 %[[RETVAL]]
+
 // CHECK-MSVC: ![[MD2]] = !{!"x18"}
 // CHECK-MSVC: ![[MD3]] = !{!"sp"}
Index: clang/lib/Headers/intrin.h
===
--- clang/lib/Headers/intrin.h
+++ clang/lib/Headers/intrin.h
@@ -567,6 +567,11 @@
 void __writex18word(unsigned long offset, unsigned short data);
 void __writex18dword(unsigned long offset, unsigned long data);
 void __writex18qword(unsigned long offset, unsigned __int64 data);
+
+unsigned char __readx18byte(unsigned long offset);
+unsigned short __readx18word(unsigned long offset);
+unsigned long __readx18dword(unsigned long offset);
+unsigned __int64 __readx18qword(unsigned long offset);
 #endif
 
 /**\
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -9977,6 +9977,30 @@
 return Store;
   }
 
+  if (BuiltinID == AArch64::BI__readx18byte ||
+  BuiltinID == AArch64::BI__readx18word ||
+  BuiltinID == AArch64::BI__readx18dword ||
+  BuiltinID == 

[PATCH] D126132: [clang-format] Fix a crash on lambda trailing return type

2022-05-23 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius closed this revision.
curdeius added a comment.

Closing as it landed in 
https://github.com/llvm/llvm-project/commit/130a9cc0a5e25e3be8ff3738518e86ae3ae0b5ba.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126132

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


[clang] a1dcfb7 - [clang] Module global init mangling

2022-05-23 Thread Nathan Sidwell via cfe-commits

Author: Nathan Sidwell
Date: 2022-05-23T09:03:10-07:00
New Revision: a1dcfb75ea8c31dd39edb6bdab6f54cde81cad85

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

LOG: [clang] Module global init mangling

C++20 modules require emission of an initializer function, which is
called by importers of the module.  This implements the mangling for
that function.  It is the one place the ABI exposes partition names in
symbols -- but fortunately only needed by other TUs of that same module.

Reviewed By: bruno

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

Added: 


Modified: 
clang/include/clang/AST/Mangle.h
clang/lib/AST/ItaniumMangle.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Mangle.h 
b/clang/include/clang/AST/Mangle.h
index 9bca97a611d08..96cc8c90a8e83 100644
--- a/clang/include/clang/AST/Mangle.h
+++ b/clang/include/clang/AST/Mangle.h
@@ -199,6 +199,8 @@ class ItaniumMangleContext : public MangleContext {
 
   virtual void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &) = 
0;
 
+  virtual void mangleModuleInitializer(const Module *Module, raw_ostream &) = 
0;
+
   // This has to live here, otherwise the CXXNameMangler won't have access to
   // it.
   virtual DiscriminatorOverrideTy getDiscriminatorOverride() const = 0;

diff  --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp
index b380e02fc8f7d..a9416397c90d6 100644
--- a/clang/lib/AST/ItaniumMangle.cpp
+++ b/clang/lib/AST/ItaniumMangle.cpp
@@ -130,6 +130,8 @@ class ItaniumMangleContextImpl : public 
ItaniumMangleContext {
 
   void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
 
+  void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
+
   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
 // Lambda closure types are already numbered.
 if (isLambda(ND))
@@ -438,7 +440,7 @@ class CXXNameMangler {
   void mangleType(QualType T);
   void mangleNameOrStandardSubstitution(const NamedDecl *ND);
   void mangleLambdaSig(const CXXRecordDecl *Lambda);
-  void mangleModuleNamePrefix(StringRef Name);
+  void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
 
 private:
 
@@ -1057,8 +1059,8 @@ void CXXNameMangler::mangleModuleName(const NamedDecl 
*ND) {
 //  ::=  
 //  ::= 
 //  ::= W 
-// ::= W P  # not (yet) needed
-void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
+// ::= W P 
+void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
   //   ::= S  _
   auto It = ModuleSubstitutions.find(Name);
   if (It != ModuleSubstitutions.end()) {
@@ -1072,10 +1074,14 @@ void CXXNameMangler::mangleModuleNamePrefix(StringRef 
Name) {
   auto Parts = Name.rsplit('.');
   if (Parts.second.empty())
 Parts.second = Parts.first;
-  else
-mangleModuleNamePrefix(Parts.first);
+  else {
+mangleModuleNamePrefix(Parts.first, IsPartition);
+IsPartition = false;
+  }
 
   Out << 'W';
+  if (IsPartition)
+Out << 'P';
   Out << Parts.second.size() << Parts.second;
   ModuleSubstitutions.insert({Name, SeqID++});
 }
@@ -6533,6 +6539,21 @@ void ItaniumMangleContextImpl::mangleLambdaSig(const 
CXXRecordDecl *Lambda,
   Mangler.mangleLambdaSig(Lambda);
 }
 
+void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,
+   raw_ostream &Out) {
+  //  ::= GI   # module initializer function
+  CXXNameMangler Mangler(*this, Out);
+  Mangler.getStream() << "_ZGI";
+  Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
+  if (M->isModulePartition()) {
+// The partition needs including, as partitions can have them too.
+auto Partition = M->Name.find(':');
+Mangler.mangleModuleNamePrefix(
+StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1),
+/*IsPartition*/ true);
+  }
+}
+
 ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context,
DiagnosticsEngine &Diags,
bool IsAux) {



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


[PATCH] D122741: [clang] Module global init mangling

2022-05-23 Thread Nathan Sidwell via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa1dcfb75ea8c: [clang] Module global init mangling (authored 
by urnathan).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D122741?vs=419171&id=431394#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122741

Files:
  clang/include/clang/AST/Mangle.h
  clang/lib/AST/ItaniumMangle.cpp


Index: clang/lib/AST/ItaniumMangle.cpp
===
--- clang/lib/AST/ItaniumMangle.cpp
+++ clang/lib/AST/ItaniumMangle.cpp
@@ -130,6 +130,8 @@
 
   void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
 
+  void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
+
   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
 // Lambda closure types are already numbered.
 if (isLambda(ND))
@@ -438,7 +440,7 @@
   void mangleType(QualType T);
   void mangleNameOrStandardSubstitution(const NamedDecl *ND);
   void mangleLambdaSig(const CXXRecordDecl *Lambda);
-  void mangleModuleNamePrefix(StringRef Name);
+  void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
 
 private:
 
@@ -1057,8 +1059,8 @@
 //  ::=  
 //  ::= 
 //  ::= W 
-// ::= W P  # not (yet) needed
-void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
+// ::= W P 
+void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
   //   ::= S  _
   auto It = ModuleSubstitutions.find(Name);
   if (It != ModuleSubstitutions.end()) {
@@ -1072,10 +1074,14 @@
   auto Parts = Name.rsplit('.');
   if (Parts.second.empty())
 Parts.second = Parts.first;
-  else
-mangleModuleNamePrefix(Parts.first);
+  else {
+mangleModuleNamePrefix(Parts.first, IsPartition);
+IsPartition = false;
+  }
 
   Out << 'W';
+  if (IsPartition)
+Out << 'P';
   Out << Parts.second.size() << Parts.second;
   ModuleSubstitutions.insert({Name, SeqID++});
 }
@@ -6533,6 +6539,21 @@
   Mangler.mangleLambdaSig(Lambda);
 }
 
+void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,
+   raw_ostream &Out) {
+  //  ::= GI   # module initializer function
+  CXXNameMangler Mangler(*this, Out);
+  Mangler.getStream() << "_ZGI";
+  Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
+  if (M->isModulePartition()) {
+// The partition needs including, as partitions can have them too.
+auto Partition = M->Name.find(':');
+Mangler.mangleModuleNamePrefix(
+StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1),
+/*IsPartition*/ true);
+  }
+}
+
 ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context,
DiagnosticsEngine &Diags,
bool IsAux) {
Index: clang/include/clang/AST/Mangle.h
===
--- clang/include/clang/AST/Mangle.h
+++ clang/include/clang/AST/Mangle.h
@@ -199,6 +199,8 @@
 
   virtual void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &) = 
0;
 
+  virtual void mangleModuleInitializer(const Module *Module, raw_ostream &) = 
0;
+
   // This has to live here, otherwise the CXXNameMangler won't have access to
   // it.
   virtual DiscriminatorOverrideTy getDiscriminatorOverride() const = 0;


Index: clang/lib/AST/ItaniumMangle.cpp
===
--- clang/lib/AST/ItaniumMangle.cpp
+++ clang/lib/AST/ItaniumMangle.cpp
@@ -130,6 +130,8 @@
 
   void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
 
+  void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
+
   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
 // Lambda closure types are already numbered.
 if (isLambda(ND))
@@ -438,7 +440,7 @@
   void mangleType(QualType T);
   void mangleNameOrStandardSubstitution(const NamedDecl *ND);
   void mangleLambdaSig(const CXXRecordDecl *Lambda);
-  void mangleModuleNamePrefix(StringRef Name);
+  void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
 
 private:
 
@@ -1057,8 +1059,8 @@
 //		 ::=  
 //	 	 ::= 
 //  ::= W 
-//		::= W P  # not (yet) needed
-void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
+//		::= W P 
+void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
   //   ::= S  _
   auto It = ModuleSubstitutions.find(Name);
   if (It != ModuleSubstitutions.end()) {
@@ -1072,10 +1074,14 @@
   auto Parts = Name.rsplit('.');
   if (Parts.second.empty())
 Parts.second = Parts.first;
-  else
-mangleModuleNamePrefix(Parts.first);
+  else {
+mangleModu

[PATCH] D125848: [clang-format] Handle attributes in enum declaration.

2022-05-23 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

Could you please add test cases with non-empty enums both with and without 
comments please like in the bug report?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125848

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


[PATCH] D125970: [amdgpu] Add amdgpu_kernel calling conv attribute to clang

2022-05-23 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

In D125970#3531645 , @aaron.ballman 
wrote:

> In D125970#3527685 , 
> @JonChesterfield wrote:
>
>> If it was adding a calling convention, sure - caution warranted. There's no 
>> llvm change here though, an existing CC is exposed to C++. No change to the 
>> type system either.
>
> This is adding a user-facing calling convention to Clang and it changes the 
> type system as a result. For example, lambda function pointer conversion 
> operators sometimes are generated for each calling convention so that you can 
> form a function pointer of the correct type (this might not be impacted by 
> your change here); there's a specific number of bits for representing the 
> enumeration of calling conventions and this uses one of those bits, etc.

It slightly changes the type system of C++ code in that the calling convention 
was previously only available in opencl / openmp etc. I was under the 
impression that the compiler data representation cost of calling conventions 
was in LLVM and thus pre-paid for the calling convention this gives access to. 
There's the `enum CallingConv ` which has gained a field, I didn't realise that 
was input into something of limited bitwidth.

>> I'll propose a patch with some documentation for it if you wish, but it'll 
>> just say "For ad hoc debugging of the amdgpu backend". Undocumented seems to 
>> state that more clearly.
>
> I continue to question whether we want to support such a calling convention. 
> This does not seem to be generally useful enough to warrant inclusion in 
> Clang. The fact that you'd like to leave it undocumented as that's more clear 
> for users is a pretty good indication that this calling convention doesn't 
> meet the bar for an extension.

Strictly speaking this lets people write a GPU kernel that can execute on 
AMDGPU in freestanding C++. I happen to want to do that for testing LLVM in the 
immediate instance but there's arguably wider applicability. However, it looks 
like how arguments are represented in this calling convention has some 
strangeness (see discussion with Sam above), particularly with regard to 
address spaces.

I can revert this patch if necessary, but it'll force me to continue trying to 
test our compiler through the lens of opencl, and rules out programming the 
hardware without the various specific language front ends. I think that would 
be a sad loss.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125970

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


[PATCH] D117616: GCC ABI Compatibility: Preserve alignment of non-pod members in packed structs

2022-05-23 Thread Tom Stellard via Phabricator via cfe-commits
tstellar added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:239-243
+- GCC doesn't pack non-POD members in packed structs unless the packed
+  attribute is also specified on the member. Clang historically did perform
+  such packing. Clang now matches the gcc behavior (except on Darwin and PS4).
+  You can switch back to the old ABI behavior with the flag:
+  ``-fclang-abi-compat=13.0``.

dblaikie wrote:
> MatzeB wrote:
> > Ugh... The release notes went missing in `main` now:
> > 
> > * We had them in clang-14, but then reverted in the release process of 
> > clang-14 so they never showed for clang-14.
> > * In `main` we removed all release nodes when going from 14->15.
> > 
> > So this notice is effectively lost now...
> Ah, thanks - readded it in 0b903ef6aa0976a60d3f448837f3c43adaf09cc1
> 
> Anyone have feelings about whether we should move the old ABI under Ver14, 
> instead of Ver13, since the break was never released in Ver14?
That seems fine to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117616

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


  1   2   3   >