[PATCH] D142085: [Clang][RISCV] Add `__riscv_` prefix for all RVV intrinsics

2023-01-19 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD created this revision.
Herald added subscribers: luke, VincentWu, vkmr, frasercrmck, evandro, 
luismarques, apazos, sameer.abuasal, s.egerton, Jim, benna, psnobl, jocewei, 
PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, edward-jones, zzheng, jrtc27, 
shiva0217, kito-cheng, niosHD, sabuasal, simoncook, johnrusso, rbar, asb, 
arichardson.
Herald added a project: All.
eopXD requested review of this revision.
Herald added subscribers: cfe-commits, pcwang-thead, MaskRay.
Herald added a project: clang.

This follows the naming guideline under riscv-c-api-doc to add the
`__riscv_` suffix for all RVV intrinsics.

Pull Request: riscv-non-isa/riscv-c-api-doc#31

Depends on D142016 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D142085

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vaadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vaaddu.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vadc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vand.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vasub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vasubu.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vcompress.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vcpop.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vdiv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vdivu.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfabs.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfclass.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfdiv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfirst.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmacc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmax.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmerge.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmin.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmsac.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmul.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfneg.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmacc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmsac.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrdiv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrec7.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredmax.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredmin.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredosum.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredusum.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrsqrt7.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsgnj.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsgnjn.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsgnjx.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfslide1down.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autog

[PATCH] D141789: [12/15][Clang][RISCV][NFC] Refine the way to check for Policy in riscv_vector_builtin_cg.inc

2023-01-19 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 490386.
eopXD edited the summary of this revision.
eopXD added a comment.

Update code: Address review comment from Craig.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141789

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/CodeGen/CGBuiltin.cpp

Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -19468,10 +19468,11 @@
 
   Intrinsic::ID ID = Intrinsic::not_intrinsic;
   unsigned NF = 1;
-  constexpr unsigned TAIL_UNDISTURBED = 0;
-  constexpr unsigned TAIL_AGNOSTIC = 1;
-  constexpr unsigned TAIL_AGNOSTIC_MASK_AGNOSTIC = 3;
-  int PolicyAttrs = TAIL_UNDISTURBED;
+  // The 0th bit simulates the `vta` of RVV
+  // The 1st bit simulates the `vma` of RVV
+  constexpr unsigned RVV_VTA = 0x1;
+  constexpr unsigned RVV_VMA = 0x2;
+  int PolicyAttrs = 0;
   bool IsMasked = false;
 
   // Required for overloaded intrinsics.
Index: clang/include/clang/Support/RISCVVIntrinsicUtils.h
===
--- clang/include/clang/Support/RISCVVIntrinsicUtils.h
+++ clang/include/clang/Support/RISCVVIntrinsicUtils.h
@@ -423,12 +423,11 @@
 return PolicyAttrs;
   }
   unsigned getPolicyAttrsBits() const {
-// Return following value.
-// constexpr unsigned TAIL_UNDISTURBED = 0;
-// constexpr unsigned TAIL_AGNOSTIC = 1;
-// constexpr unsigned TAIL_AGNOSTIC_MASK_AGNOSTIC = 3;
-// FIXME: how about value 2
-// int PolicyAttrs = TAIL_UNDISTURBED;
+// CGBuiltin.cpp
+// The 0th bit simulates the `vta` of RVV
+// The 1st bit simulates the `vma` of RVV
+// int PolicyAttrs = 0;
+
 assert(PolicyAttrs.IsUnspecified == false);
 
 if (PolicyAttrs.isTUMAPolicy())
@@ -439,10 +438,6 @@
   return 0;
 if (PolicyAttrs.isTAMUPolicy())
   return 1;
-if (PolicyAttrs.isTUPolicy())
-  return 0;
-if (PolicyAttrs.isTAPolicy())
-  return 1;
 
 llvm_unreachable("unsupport policy");
 return 0;
Index: clang/include/clang/Basic/riscv_vector.td
===
--- clang/include/clang/Basic/riscv_vector.td
+++ clang/include/clang/Basic/riscv_vector.td
@@ -467,10 +467,10 @@
 ManualCodegen = [{
   if (IsMasked) {
 std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end() - 1);
-if (PolicyAttrs == TAIL_AGNOSTIC_MASK_AGNOSTIC)
+if ((PolicyAttrs & RVV_VTA) && (PolicyAttrs & RVV_VMA))
   Ops.insert(Ops.begin(), llvm::PoisonValue::get(ResultType));
   } else {
-if (PolicyAttrs == TAIL_AGNOSTIC)
+if (PolicyAttrs & RVV_VTA)
   Ops.insert(Ops.begin(), llvm::PoisonValue::get(ResultType));
   }
 
@@ -649,12 +649,12 @@
 if (IsMasked) {
   // Move mask to right before vl.
   std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end() - 1);
-  if (PolicyAttrs == TAIL_AGNOSTIC_MASK_AGNOSTIC)
+  if ((PolicyAttrs & RVV_VTA) && (PolicyAttrs & RVV_VMA))
 Ops.insert(Ops.begin(), llvm::PoisonValue::get(ResultType));
   Ops.push_back(ConstantInt::get(Ops.back()->getType(), PolicyAttrs));
   IntrinsicTypes = {ResultType, Ops[4]->getType()};
 } else {
-  if (PolicyAttrs == TAIL_AGNOSTIC)
+  if (PolicyAttrs & RVV_VTA)
 Ops.insert(Ops.begin(), llvm::PoisonValue::get(ResultType));
   IntrinsicTypes = {ResultType, Ops[3]->getType()};
 }
@@ -939,8 +939,8 @@
   SmallVector Operands;
 
   // Please refer to comment under 'defvar NFList' in this file
-  if ((IsMasked && PolicyAttrs == TAIL_AGNOSTIC_MASK_AGNOSTIC) ||
-  (!IsMasked && PolicyAttrs == TAIL_AGNOSTIC))
+  if ((IsMasked && (PolicyAttrs & RVV_VTA) && (PolicyAttrs & RVV_VMA)) ||
+  (!IsMasked && PolicyAttrs & RVV_VTA))
 Operands.append(NF, llvm::PoisonValue::get(ResultType));
   else {
 if (IsMasked)
@@ -949,8 +949,8 @@
   Operands.append(Ops.begin() + NF, Ops.begin() + 2 * NF);
   }
   unsigned PtrOperandIdx = IsMasked ?
-(PolicyAttrs == TAIL_AGNOSTIC_MASK_AGNOSTIC) ? NF + 1 : 2 * NF + 1 :
-(PolicyAttrs == TAIL_AGNOSTIC) ? NF : 2 * NF;
+((PolicyAttrs & RVV_VTA) && (PolicyAttrs & RVV_VMA)) ? NF + 1 : 2 * NF + 1 :
+(PolicyAttrs & RVV_VTA) ? NF : 2 * NF;
   Value *PtrOperand = Ops[PtrOperandIdx];
   Value *VLOperand = Ops[PtrOperandIdx + 1];
   Operands.push_back(PtrOperand);
@@ -1004,8 +1004,8 @@
   SmallVector Operands;
 
   // Please refer to comment under 'defvar NFList' in this file
-  if ((IsMasked && PolicyAttrs == TAIL_AGNOSTIC_MASK_AGNOSTIC) ||
-  (!IsMasked && PolicyAttrs == TAIL_AGNOSTIC))
+  if ((IsMasked && (Pol

[PATCH] D142001: [clang] Use FP options from AST for emitting code for casts

2023-01-19 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

Overall looks reasonable.  One question about testing.




Comment at: clang/test/CodeGen/X86/avx512dq-builtins-constrained.c:7
 
-// FIXME: Every instance of "fpexcept.maytrap" is wrong.
+// Any cases of "fpexcept.maytrap" in this test are clang bugs.
+

Can you use `FileCheck --implicit-check-not` to verify this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142001

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


[PATCH] D141789: [12/15][Clang][RISCV][NFC] Refine the way to check for Policy in riscv_vector_builtin_cg.inc

2023-01-19 Thread Craig Topper via Phabricator via cfe-commits
craig.topper accepted this revision.
craig.topper 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/D141789/new/

https://reviews.llvm.org/D141789

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


[clang] 741cb06 - [clang][Interp][NFC] Remove unused functions

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T09:22:57+01:00
New Revision: 741cb06cab5f3943c8037cfec89fc8663d6e4ae6

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

LOG: [clang][Interp][NFC] Remove unused functions

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.h

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 4e4f2eecd172e..a8736314c01d0 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -106,18 +106,6 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   // If the function does not exist yet, it is compiled.
   const Function *getFunction(const FunctionDecl *FD);
 
-  /// Returns the size int bits of an integer.
-  unsigned getIntWidth(QualType Ty) {
-auto &ASTContext = Ctx.getASTContext();
-return ASTContext.getIntWidth(Ty);
-  }
-
-  /// Returns the value of CHAR_BIT.
-  unsigned getCharBit() const {
-auto &ASTContext = Ctx.getASTContext();
-return ASTContext.getTargetInfo().getCharWidth();
-  }
-
   /// Classifies a type.
   std::optional classify(const Expr *E) const {
 return E->isGLValue() ? PT_Ptr : classify(E->getType());
@@ -126,11 +114,6 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
 return Ctx.classify(Ty);
   }
 
-  /// Checks if a pointer needs adjustment.
-  bool needsAdjust(QualType Ty) const {
-return true;
-  }
-
   /// Classifies a known primitive type
   PrimType classifyPrim(QualType Ty) const {
 if (auto T = classify(Ty)) {



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


[clang] 1221af9 - [clang][Interp] Use placement new to construct opcode args into vector

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T09:22:57+01:00
New Revision: 1221af99281c87d35c65110a75f87893ff0fc947

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

LOG: [clang][Interp] Use placement new to construct opcode args into vector

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeEmitter.cpp
clang/lib/AST/Interp/PrimType.h
clang/lib/AST/Interp/Source.h

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeEmitter.cpp 
b/clang/lib/AST/Interp/ByteCodeEmitter.cpp
index ff2136d34872..4633d1e0823b 100644
--- a/clang/lib/AST/Interp/ByteCodeEmitter.cpp
+++ b/clang/lib/AST/Interp/ByteCodeEmitter.cpp
@@ -116,7 +116,8 @@ void ByteCodeEmitter::emitLabel(LabelTy Label) {
   using namespace llvm::support;
 
   /// Rewrite the operand of all jumps to this label.
-  void *Location = Code.data() + Reloc - sizeof(int32_t);
+  void *Location = Code.data() + Reloc - align(sizeof(int32_t));
+  assert(aligned(Location));
   const int32_t Offset = Target - static_cast(Reloc);
   endian::write(Location, Offset);
 }
@@ -126,7 +127,9 @@ void ByteCodeEmitter::emitLabel(LabelTy Label) {
 
 int32_t ByteCodeEmitter::getOffset(LabelTy Label) {
   // Compute the PC offset which the jump is relative to.
-  const int64_t Position = Code.size() + sizeof(Opcode) + sizeof(int32_t);
+  const int64_t Position =
+  Code.size() + align(sizeof(Opcode)) + align(sizeof(int32_t));
+  assert(aligned(Position));
 
   // If target is known, compute jump offset.
   auto It = LabelOffsets.find(Label);
@@ -162,13 +165,17 @@ static void emit(Program &P, std::vector &Code, 
const T &Val,
 return;
   }
 
+  // Access must be aligned!
+  size_t ValPos = align(Code.size());
+  Size = align(Size);
+  assert(aligned(ValPos + Size));
+  Code.resize(ValPos + Size);
+
   if constexpr (!std::is_pointer_v) {
-const char *Data = reinterpret_cast(&Val);
-Code.insert(Code.end(), Data, Data + Size);
+new (Code.data() + ValPos) T(Val);
   } else {
 uint32_t ID = P.getOrCreateNativePointer(Val);
-const char *Data = reinterpret_cast(&ID);
-Code.insert(Code.end(), Data, Data + Size);
+new (Code.data() + ValPos) uint32_t(ID);
   }
 }
 

diff  --git a/clang/lib/AST/Interp/PrimType.h b/clang/lib/AST/Interp/PrimType.h
index 8490c1f6548a..3a77c66c7437 100644
--- a/clang/lib/AST/Interp/PrimType.h
+++ b/clang/lib/AST/Interp/PrimType.h
@@ -59,6 +59,13 @@ constexpr size_t align(size_t Size) {
   return ((Size + alignof(void *) - 1) / alignof(void *)) * alignof(void *);
 }
 
+constexpr bool aligned(uintptr_t Value) { return Value == align(Value); }
+static_assert(aligned(sizeof(void *)));
+
+static inline bool aligned(const void *P) {
+  return aligned(reinterpret_cast(P));
+}
+
 inline bool isPrimitiveIntegral(PrimType Type) {
   switch (Type) {
   case PT_Bool:

diff  --git a/clang/lib/AST/Interp/Source.h b/clang/lib/AST/Interp/Source.h
index de4ae559e4bb..99ffce34c12f 100644
--- a/clang/lib/AST/Interp/Source.h
+++ b/clang/lib/AST/Interp/Source.h
@@ -13,6 +13,7 @@
 #ifndef LLVM_CLANG_AST_INTERP_SOURCE_H
 #define LLVM_CLANG_AST_INTERP_SOURCE_H
 
+#include "PrimType.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/Stmt.h"
 #include "llvm/Support/Endian.h"
@@ -47,9 +48,10 @@ class CodePtr final {
 
   /// Reads data and advances the pointer.
   template  std::enable_if_t::value, T> read() 
{
+assert(aligned(Ptr));
 using namespace llvm::support;
 T Value = endian::read(Ptr);
-Ptr += sizeof(T);
+Ptr += align(sizeof(T));
 return Value;
   }
 



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


[clang] d44f4fa - [clang][Interp][NFC] Initialize constants as ~0u

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T09:22:57+01:00
New Revision: d44f4fac424d70e7c8c463ad9f44a228fc61e9e5

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

LOG: [clang][Interp][NFC] Initialize constants as ~0u

Added: 


Modified: 
clang/lib/AST/Interp/Pointer.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Pointer.h b/clang/lib/AST/Interp/Pointer.h
index 44c485681af5..c0628314e869 100644
--- a/clang/lib/AST/Interp/Pointer.h
+++ b/clang/lib/AST/Interp/Pointer.h
@@ -60,8 +60,8 @@ enum PrimType : unsigned;
 /// Base
 class Pointer {
 private:
-  static constexpr unsigned PastEndMark = (unsigned)-1;
-  static constexpr unsigned RootPtrMark = (unsigned)-1;
+  static constexpr unsigned PastEndMark = ~0u;
+  static constexpr unsigned RootPtrMark = ~0u;
 
 public:
   Pointer() {}



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


[PATCH] D139185: [clang][Interp] Use placement new to construct opcode args into vector

2023-01-19 Thread Timm Bäder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1221af99281c: [clang][Interp] Use placement new to construct 
opcode args into vector (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139185

Files:
  clang/lib/AST/Interp/ByteCodeEmitter.cpp
  clang/lib/AST/Interp/PrimType.h
  clang/lib/AST/Interp/Source.h


Index: clang/lib/AST/Interp/Source.h
===
--- clang/lib/AST/Interp/Source.h
+++ clang/lib/AST/Interp/Source.h
@@ -13,6 +13,7 @@
 #ifndef LLVM_CLANG_AST_INTERP_SOURCE_H
 #define LLVM_CLANG_AST_INTERP_SOURCE_H
 
+#include "PrimType.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/Stmt.h"
 #include "llvm/Support/Endian.h"
@@ -47,9 +48,10 @@
 
   /// Reads data and advances the pointer.
   template  std::enable_if_t::value, T> read() 
{
+assert(aligned(Ptr));
 using namespace llvm::support;
 T Value = endian::read(Ptr);
-Ptr += sizeof(T);
+Ptr += align(sizeof(T));
 return Value;
   }
 
Index: clang/lib/AST/Interp/PrimType.h
===
--- clang/lib/AST/Interp/PrimType.h
+++ clang/lib/AST/Interp/PrimType.h
@@ -59,6 +59,13 @@
   return ((Size + alignof(void *) - 1) / alignof(void *)) * alignof(void *);
 }
 
+constexpr bool aligned(uintptr_t Value) { return Value == align(Value); }
+static_assert(aligned(sizeof(void *)));
+
+static inline bool aligned(const void *P) {
+  return aligned(reinterpret_cast(P));
+}
+
 inline bool isPrimitiveIntegral(PrimType Type) {
   switch (Type) {
   case PT_Bool:
Index: clang/lib/AST/Interp/ByteCodeEmitter.cpp
===
--- clang/lib/AST/Interp/ByteCodeEmitter.cpp
+++ clang/lib/AST/Interp/ByteCodeEmitter.cpp
@@ -116,7 +116,8 @@
   using namespace llvm::support;
 
   /// Rewrite the operand of all jumps to this label.
-  void *Location = Code.data() + Reloc - sizeof(int32_t);
+  void *Location = Code.data() + Reloc - align(sizeof(int32_t));
+  assert(aligned(Location));
   const int32_t Offset = Target - static_cast(Reloc);
   endian::write(Location, Offset);
 }
@@ -126,7 +127,9 @@
 
 int32_t ByteCodeEmitter::getOffset(LabelTy Label) {
   // Compute the PC offset which the jump is relative to.
-  const int64_t Position = Code.size() + sizeof(Opcode) + sizeof(int32_t);
+  const int64_t Position =
+  Code.size() + align(sizeof(Opcode)) + align(sizeof(int32_t));
+  assert(aligned(Position));
 
   // If target is known, compute jump offset.
   auto It = LabelOffsets.find(Label);
@@ -162,13 +165,17 @@
 return;
   }
 
+  // Access must be aligned!
+  size_t ValPos = align(Code.size());
+  Size = align(Size);
+  assert(aligned(ValPos + Size));
+  Code.resize(ValPos + Size);
+
   if constexpr (!std::is_pointer_v) {
-const char *Data = reinterpret_cast(&Val);
-Code.insert(Code.end(), Data, Data + Size);
+new (Code.data() + ValPos) T(Val);
   } else {
 uint32_t ID = P.getOrCreateNativePointer(Val);
-const char *Data = reinterpret_cast(&ID);
-Code.insert(Code.end(), Data, Data + Size);
+new (Code.data() + ValPos) uint32_t(ID);
   }
 }
 


Index: clang/lib/AST/Interp/Source.h
===
--- clang/lib/AST/Interp/Source.h
+++ clang/lib/AST/Interp/Source.h
@@ -13,6 +13,7 @@
 #ifndef LLVM_CLANG_AST_INTERP_SOURCE_H
 #define LLVM_CLANG_AST_INTERP_SOURCE_H
 
+#include "PrimType.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/Stmt.h"
 #include "llvm/Support/Endian.h"
@@ -47,9 +48,10 @@
 
   /// Reads data and advances the pointer.
   template  std::enable_if_t::value, T> read() {
+assert(aligned(Ptr));
 using namespace llvm::support;
 T Value = endian::read(Ptr);
-Ptr += sizeof(T);
+Ptr += align(sizeof(T));
 return Value;
   }
 
Index: clang/lib/AST/Interp/PrimType.h
===
--- clang/lib/AST/Interp/PrimType.h
+++ clang/lib/AST/Interp/PrimType.h
@@ -59,6 +59,13 @@
   return ((Size + alignof(void *) - 1) / alignof(void *)) * alignof(void *);
 }
 
+constexpr bool aligned(uintptr_t Value) { return Value == align(Value); }
+static_assert(aligned(sizeof(void *)));
+
+static inline bool aligned(const void *P) {
+  return aligned(reinterpret_cast(P));
+}
+
 inline bool isPrimitiveIntegral(PrimType Type) {
   switch (Type) {
   case PT_Bool:
Index: clang/lib/AST/Interp/ByteCodeEmitter.cpp
===
--- clang/lib/AST/Interp/ByteCodeEmitter.cpp
+++ clang/lib/AST/Interp/ByteCodeEmitter.cpp
@@ -116,7 +116,8 @@
   using namespace llvm::support;
 
   /// Rewrite the operand of all jumps to this label.
-  void *Location = Code.data() + Reloc - sizeof(int32_t);
+  void *Location 

[PATCH] D136651: [Clang] Give Clang the ability to use a shared stat cache

2023-01-19 Thread Mike Hommey via Phabricator via cfe-commits
glandium added a comment.

In D136651#4064260 , @glandium wrote:

> This broke our mac builds with errors like:
>
>   ld64.lld: error: undefined symbol: CFRunLoopRun
>   >>> referenced by 
> tools/clang/tools/clang-stat-cache/CMakeFiles/clang-stat-cache.dir/clang-stat-cache.cpp.o:(symbol
>  main+0x11be)
>
> (and many more symbols)

Additional information: those are cross-compiled, and for some reason the 
`-framework CoreServices` in the CMakeLists.txt doesn't seem to make it to the 
command line, which is surprising because something similar works fine for e.g. 
dsymutil.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136651

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


[PATCH] D141793: [14/15][Clang][RISCV] Change default policy from TAMU to TAMA

2023-01-19 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.
Herald added a subscriber: luke.



Comment at: 
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vmsgt.c:10
 
-// CHECK-RV64-LABEL: @test_vmsgt_vv_i8mf8_b64(
-// CHECK-RV64-NEXT:  entry:

Why does this test go away?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141793

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


[PATCH] D141796: [15/15][Clang][RISCV][NFC] Set data member under Policy as constants

2023-01-19 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.
Herald added a subscriber: luke.



Comment at: clang/include/clang/Support/RISCVVIntrinsicUtils.h:96
 struct Policy {
-  bool IsUnspecified = false;
+  const bool IsUnspecified = false;
   enum PolicyType {

Should this be a class instead of struct so the members are private?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141796

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


[clang] 6b0cd49 - [clang][Interp] Check Field initialization after constructor call

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T09:42:22+01:00
New Revision: 6b0cd497b0fb584bdc0650b585c5bd1ed9edfc99

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

LOG: [clang][Interp] Check Field initialization after constructor call

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

Added: 


Modified: 
clang/lib/AST/Interp/Descriptor.cpp
clang/lib/AST/Interp/Interp.cpp
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/InterpFrame.cpp
clang/test/AST/Interp/cxx20.cpp
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Descriptor.cpp 
b/clang/lib/AST/Interp/Descriptor.cpp
index 5575fc1e2a6e7..58158cd49cebc 100644
--- a/clang/lib/AST/Interp/Descriptor.cpp
+++ b/clang/lib/AST/Interp/Descriptor.cpp
@@ -126,7 +126,7 @@ static void ctorRecord(Block *B, char *Ptr, bool IsConst, 
bool IsMutable,
 auto *Desc = reinterpret_cast(Ptr + SubOff) - 1;
 Desc->Offset = SubOff;
 Desc->Desc = F;
-Desc->IsInitialized = (B->isStatic() || F->IsArray) && !IsBase;
+Desc->IsInitialized = F->IsArray && !IsBase;
 Desc->IsBase = IsBase;
 Desc->IsActive = IsActive && !IsUnion;
 Desc->IsConst = IsConst || F->IsConst;

diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 940e71df138d3..d493a50486b7a 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -401,6 +401,38 @@ bool CheckPure(InterpState &S, CodePtr OpPC, const 
CXXMethodDecl *MD) {
   return false;
 }
 
+static bool CheckFieldsInitialized(InterpState &S, CodePtr OpPC,
+   const Pointer &BasePtr, const Record *R) {
+  assert(R);
+  bool Result = true;
+  // Check all fields of this record are initialized.
+  for (const Record::Field &F : R->fields()) {
+Pointer FieldPtr = BasePtr.atField(F.Offset);
+QualType FieldType = FieldPtr.getType();
+
+if (FieldType->isRecordType()) {
+  Result &= CheckFieldsInitialized(S, OpPC, FieldPtr, 
FieldPtr.getRecord());
+} else if (FieldType->isArrayType()) {
+  // FIXME: Arrays need to be handled here as well I think.
+} else if (!FieldPtr.isInitialized()) {
+  const SourceInfo &SI = S.Current->getSource(OpPC);
+  S.FFDiag(SI, diag::note_constexpr_uninitialized)
+  << true << F.Decl->getType();
+  SourceLocation SubobjectLoc = F.Decl->getLocation();
+  if (SubobjectLoc.isValid())
+S.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
+  Result = false;
+}
+  }
+  return Result;
+}
+
+bool CheckCtorCall(InterpState &S, CodePtr OpPC, const Pointer &This) {
+  assert(!This.isZero());
+  const Record *R = This.getRecord();
+  return CheckFieldsInitialized(S, OpPC, This, R);
+}
+
 bool Interpret(InterpState &S, APValue &Result) {
   // The current stack frame when we started Interpret().
   // This is being used by the ops to determine wheter

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 07515548a06ba..65a49f21c5dc2 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -91,6 +91,9 @@ bool CheckThis(InterpState &S, CodePtr OpPC, const Pointer 
&This);
 /// Checks if a method is pure virtual.
 bool CheckPure(InterpState &S, CodePtr OpPC, const CXXMethodDecl *MD);
 
+/// Checks that all fields are initialized after a constructor call.
+bool CheckCtorCall(InterpState &S, CodePtr OpPC, const Pointer &This);
+
 /// Checks if Div/Rem operation on LHS and RHS is valid.
 template 
 bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS) {
@@ -1256,8 +1259,10 @@ inline bool ExpandPtr(InterpState &S, CodePtr OpPC) {
 
 inline bool Call(InterpState &S, CodePtr &PC, const Function *Func) {
   auto NewFrame = std::make_unique(S, Func, PC);
+  Pointer ThisPtr;
   if (Func->hasThisPointer()) {
-if (!CheckInvoke(S, PC, NewFrame->getThis())) {
+ThisPtr = NewFrame->getThis();
+if (!CheckInvoke(S, PC, ThisPtr)) {
   return false;
 }
   }
@@ -1275,6 +1280,11 @@ inline bool Call(InterpState &S, CodePtr &PC, const 
Function *Func) {
   if (Interpret(S, CallResult)) {
 NewFrame.release(); // Frame was delete'd already.
 assert(S.Current == FrameBefore);
+
+// For constructors, check that all fields have been initialized.
+if (Func->isConstructor() && !CheckCtorCall(S, PC, ThisPtr))
+  return false;
+
 return true;
   }
 

diff  --git a/clang/lib/AST/Interp/InterpFrame.cpp 
b/clang/lib/AST/Interp/InterpFrame.cpp
index da228d011f874..19ac0bd5433a5 100644
--- a/clang/lib/AST/Interp/InterpFrame.cpp
+++ b/clang/lib/AST/Interp/InterpFrame.cpp
@@ -64,8 +64,6 @@ InterpFrame::InterpFrame(InterpState &S, const Function 
*Func, CodePtr RetPC)
 }
 
 InterpFrame::~InterpFr

[PATCH] D136694: [clang][Interp] Check that constructor calls initialize all record fields

2023-01-19 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 rG6b0cd497b0fb: [clang][Interp] Check Field initialization 
after constructor call (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D136694?vs=479209&id=490394#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136694

Files:
  clang/lib/AST/Interp/Descriptor.cpp
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/InterpFrame.cpp
  clang/test/AST/Interp/cxx20.cpp
  clang/test/AST/Interp/records.cpp

Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -295,13 +295,14 @@
   // ref-note 2{{non-constexpr constructor 'Base' cannot be used in a constant expression}}
   };
 
-  // FIXME: This is currently not being diagnosed with the new constant interpreter.
   constexpr Derived D(12); // ref-error {{must be initialized by a constant expression}} \
// ref-note {{in call to 'Derived(12)'}} \
// ref-note {{declared here}} \
// expected-error {{must be initialized by a constant expression}}
   static_assert(D.Val == 0, ""); // ref-error {{not an integral constant expression}} \
- // ref-note {{initializer of 'D' is not a constant expression}}
+ // ref-note {{initializer of 'D' is not a constant expression}} \
+ // expected-error {{not an integral constant expression}} \
+ // expected-note {{read of object outside its lifetime}}
 
   struct AnotherBase {
 int Val;
Index: clang/test/AST/Interp/cxx20.cpp
===
--- clang/test/AST/Interp/cxx20.cpp
+++ clang/test/AST/Interp/cxx20.cpp
@@ -85,11 +85,10 @@
   // ref-note {{in call to}}
 
 
-struct Int { int a; };
+struct Int { int a; }; // expected-note {{subobject declared here}}
 constexpr int initializedLocal3() {
-  Int i;
-  return i.a; // expected-note {{read of object outside its lifetime}} \
-  // ref-note {{read of uninitialized object is not allowed in a constant expression}}
+  Int i; // expected-note {{subobject of type 'int' is not initialized}}
+  return i.a; // ref-note {{read of uninitialized object is not allowed in a constant expression}}
 }
 static_assert(initializedLocal3() == 20); // expected-error {{not an integral constant expression}} \
   // expected-note {{in call to}} \
@@ -134,3 +133,35 @@
 // ref-note {{declared here}}
 static_assert(!b4); // ref-error {{not an integral constant expression}} \
 // ref-note {{not a constant expression}}
+
+namespace UninitializedFields {
+  class A {
+  public:
+int a; // expected-note {{subobject declared here}} \
+   // ref-note {{subobject declared here}}
+constexpr A() {}
+  };
+  constexpr A a; // expected-error {{must be initialized by a constant expression}} \
+ // expected-note {{subobject of type 'int' is not initialized}} \
+ // ref-error {{must be initialized by a constant expression}} \
+ // ref-note {{subobject of type 'int' is not initialized}}
+
+
+  class Base {
+  public:
+bool b;
+int a; // expected-note {{subobject declared here}} \
+   // ref-note {{subobject declared here}}
+constexpr Base() : b(true) {}
+  };
+
+  class Derived : public Base {
+  public:
+constexpr Derived() : Base() {} // expected-note {{subobject of type 'int' is not initialized}}
+  };
+
+constexpr Derived D; // expected-error {{must be initialized by a constant expression}} \\
+ // expected-note {{in call to 'Derived()'}} \
+ // ref-error {{must be initialized by a constant expression}} \
+ // ref-note {{subobject of type 'int' is not initialized}}
+};
Index: clang/lib/AST/Interp/InterpFrame.cpp
===
--- clang/lib/AST/Interp/InterpFrame.cpp
+++ clang/lib/AST/Interp/InterpFrame.cpp
@@ -64,8 +64,6 @@
 }
 
 InterpFrame::~InterpFrame() {
-  if (Func && Func->isConstructor() && This.isBaseClass())
-This.initialize();
   for (auto &Param : Params)
 S.deallocate(reinterpret_cast(Param.second.get()));
 }
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -91,6 +91,9 @@
 /// Checks if a method is pure v

[PATCH] D140875: [clangd] prototype: Implement unused include warnings with include-cleaner library.

2023-01-19 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:479
+}
+// FIXME: !!this is a hacky way to collect macro references.
+std::vector Macros;

hokein wrote:
> kadircet wrote:
> > this might behave slightly different than what we have in `RecordedPP`, and 
> > rest of the applications of include-cleaner will be using that. can we 
> > expose the pieces in RecordedPP that collects MacroRefs as a separate 
> > handler and attach that collector (combined with the skipped range 
> > collection inside `CollectMainFileMacros` and also still converting to 
> > `MainFileMacros` in the end (as we can't store 
> > sourcelocations/identifierinfos from preamble)?
> > 
> > afterwards we can use the names stored in there to get back to 
> > `IdentifierInfo`s and Ranges stored to get back to `SourceLocation`s. WDYT?
> Yeah, this is a better solution, but I'm not sure whether we should do this 
> before the release cut, it has a side effect of changing the 
> find-macro-reference behavior in clangd. It requires some design/implement 
> work.
> 
> I agree that the current solution is hacky, and eventually will be replaced, 
> but it follows the existing `findReferencedMacros`, so it is not that bad. I 
> tend to land this version before the release cut. What do you think?
> Yeah, this is a better solution, but I'm not sure whether we should do this 
> before the release cut, it has a side effect of changing the 
> find-macro-reference behavior in clangd.

OK, i think you're right about possibly changing semantic highlighting&refs for 
clangd. Let's push this as a follow-up after the branch cut then.

> It requires some design/implement work.

No action needed here just wanted to layout some ideas;
We just need to change the implementation details of CollectMainFileMacros to 
wrap the RecordedPP and add skipped ranges support to it. We might need to do a 
little plumbing to convert between types (as RecordedPP stores 
SourceLocations/MacroInfos that can't be used across preamble and AST) but that 
should be trivial to marshal (we can do the conversion inside EndOfMainFile). I 
haven't fully tried this though, so if you tried and faced certain 
incompatibilities PLMK.

> I agree that the current solution is hacky, and eventually will be replaced, 
> but it follows the existing findReferencedMacros, so it is not that bad. I 
> tend to land this version before the release cut. What do you think?

I am worried that landing this version and letting people use it for 6 months 
might result in us getting bug reports that we can't address until we converge 
(or even worse get bug reports due to behavior change after we converge). But 
changes here are somewhat more justified as we put this as an experimental 
feature, compared to regressions in existing clangd behavior as you pointed out.



Comment at: clang-tools-extra/clangd/IncludeCleaner.h:100
 std::vector computeUnusedIncludes(ParsedAST &AST);
+std::vector computeUnusedIncludesNew(ParsedAST &AST);
 

s/computeUnusedIncludesNew/computeUnusedIncludesExperimental/

can you also add a comment saying that this uses include-cleaner library to 
perform usage analysis?



Comment at: clang-tools-extra/clangd/ParsedAST.cpp:609
+  Config::UnusedIncludesPolicy::Experiment)
+Pragmas.record(*Clang);
   // Copy over the macros in the preamble region of the main file, and combine

hokein wrote:
> kadircet wrote:
> > why do we need to collect pragmas in main file? i think we already have 
> > necessary information available via `IncludeStructure` (it stores keeps and 
> > exports, and we don't care about anything else in the main file AFAICT). so 
> > let's just use the PragmaIncludes we're getting from the Preamble directly? 
> > without even making a copy and returning a reference from the `Preamble` 
> > instead in `ParsedAST::getPragmaIncludes`
> > i think we already have necessary information available via 
> > IncludeStructure (it stores keeps and exports, and we don't care about 
> > anything else in the main file AFAICT)
> 
> The IncludeStructure doesn't have a full support for IWYU export pragma, it 
> only tracks the headers that have the export pragma.
> 
> My understand of the end goal is to use the `PragmaInclude` to handle every 
> IWYU-related things, and we can remove all these IWYU bits in the 
> `IncludeStructure`,  clangd IWYU pragma handling 
> [code](https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/clangd/Headers.cpp#L127-L166).
> The IncludeStructure doesn't have a full support for IWYU export pragma, it 
> only tracks the headers that have the export pragma.

And I think that's all we need for IWYU pragmas inside the main file (as main 
file is a leaf and exporting headers from it doesn't change anything apart from 
making sure we keep them around)

> My understand of the end goal is to use the PragmaI

[PATCH] D142016: [Clang][RISCV] Simplify RVV intrinsic policy suffix

2023-01-19 Thread Craig Topper via Phabricator via cfe-commits
craig.topper accepted this revision.
craig.topper 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/D142016/new/

https://reviews.llvm.org/D142016

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


[PATCH] D141793: [14/15][Clang][RISCV] Change default policy from TAMU to TAMA

2023-01-19 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 490396.
eopXD added a comment.

Recover mis-deleted test cases, which are the instructions with a mask 
destination register.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141793

Files:
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vaadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vaaddu.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vand.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vasub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vasubu.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vdiv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vdivu.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfabs.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfclass.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfdiv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmacc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmax.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmin.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmsac.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmul.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfneg.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmacc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmsac.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrdiv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrec7.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredmax.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredmin.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredosum.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredusum.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrsqrt7.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsgnj.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsgnjn.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsgnjx.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfslide1down.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfslide1up.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsqrt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwmacc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwmsac.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwmul.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwnmacc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwnmsac.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwredosum.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-

[PATCH] D142006: [mlir][bufferization] Fix getAliasingOpOperand/OpResult for non-bufferizable ops

2023-01-19 Thread Matthias Springer via Phabricator via cfe-commits
springerm updated this revision to Diff 490397.
springerm added a comment.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142006

Files:
  clang/lib/AST/Interp/Descriptor.cpp
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/InterpFrame.cpp
  clang/test/AST/Interp/cxx20.cpp
  clang/test/AST/Interp/records.cpp

Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -295,13 +295,14 @@
   // ref-note 2{{non-constexpr constructor 'Base' cannot be used in a constant expression}}
   };
 
-  // FIXME: This is currently not being diagnosed with the new constant interpreter.
   constexpr Derived D(12); // ref-error {{must be initialized by a constant expression}} \
// ref-note {{in call to 'Derived(12)'}} \
// ref-note {{declared here}} \
// expected-error {{must be initialized by a constant expression}}
   static_assert(D.Val == 0, ""); // ref-error {{not an integral constant expression}} \
- // ref-note {{initializer of 'D' is not a constant expression}}
+ // ref-note {{initializer of 'D' is not a constant expression}} \
+ // expected-error {{not an integral constant expression}} \
+ // expected-note {{read of object outside its lifetime}}
 
   struct AnotherBase {
 int Val;
Index: clang/test/AST/Interp/cxx20.cpp
===
--- clang/test/AST/Interp/cxx20.cpp
+++ clang/test/AST/Interp/cxx20.cpp
@@ -85,11 +85,10 @@
   // ref-note {{in call to}}
 
 
-struct Int { int a; };
+struct Int { int a; }; // expected-note {{subobject declared here}}
 constexpr int initializedLocal3() {
-  Int i;
-  return i.a; // expected-note {{read of object outside its lifetime}} \
-  // ref-note {{read of uninitialized object is not allowed in a constant expression}}
+  Int i; // expected-note {{subobject of type 'int' is not initialized}}
+  return i.a; // ref-note {{read of uninitialized object is not allowed in a constant expression}}
 }
 static_assert(initializedLocal3() == 20); // expected-error {{not an integral constant expression}} \
   // expected-note {{in call to}} \
@@ -134,3 +133,35 @@
 // ref-note {{declared here}}
 static_assert(!b4); // ref-error {{not an integral constant expression}} \
 // ref-note {{not a constant expression}}
+
+namespace UninitializedFields {
+  class A {
+  public:
+int a; // expected-note {{subobject declared here}} \
+   // ref-note {{subobject declared here}}
+constexpr A() {}
+  };
+  constexpr A a; // expected-error {{must be initialized by a constant expression}} \
+ // expected-note {{subobject of type 'int' is not initialized}} \
+ // ref-error {{must be initialized by a constant expression}} \
+ // ref-note {{subobject of type 'int' is not initialized}}
+
+
+  class Base {
+  public:
+bool b;
+int a; // expected-note {{subobject declared here}} \
+   // ref-note {{subobject declared here}}
+constexpr Base() : b(true) {}
+  };
+
+  class Derived : public Base {
+  public:
+constexpr Derived() : Base() {} // expected-note {{subobject of type 'int' is not initialized}}
+  };
+
+constexpr Derived D; // expected-error {{must be initialized by a constant expression}} \\
+ // expected-note {{in call to 'Derived()'}} \
+ // ref-error {{must be initialized by a constant expression}} \
+ // ref-note {{subobject of type 'int' is not initialized}}
+};
Index: clang/lib/AST/Interp/InterpFrame.cpp
===
--- clang/lib/AST/Interp/InterpFrame.cpp
+++ clang/lib/AST/Interp/InterpFrame.cpp
@@ -64,8 +64,6 @@
 }
 
 InterpFrame::~InterpFrame() {
-  if (Func && Func->isConstructor() && This.isBaseClass())
-This.initialize();
   for (auto &Param : Params)
 S.deallocate(reinterpret_cast(Param.second.get()));
 }
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -91,6 +91,9 @@
 /// Checks if a method is pure virtual.
 bool CheckPure(InterpState &S, CodePtr OpPC, const CXXMethodDecl *MD);
 
+/// Checks that all fields are initialized after a constructor call.
+bool CheckCtorCall(InterpState

[PATCH] D142006: [mlir][bufferization] Fix getAliasingOpOperand/OpResult for non-bufferizable ops

2023-01-19 Thread Matthias Springer via Phabricator via cfe-commits
springerm updated this revision to Diff 490398.
springerm added a comment.

update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142006

Files:
  mlir/include/mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h
  mlir/lib/Dialect/Bufferization/IR/BufferizableOpInterface.cpp
  mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp
  mlir/lib/Dialect/Bufferization/Transforms/OneShotAnalysis.cpp
  mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize-analysis.mlir
  mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize-partial.mlir
  
mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize-pass-statistics.mlir
  mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize.mlir

Index: mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize.mlir
===
--- mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize.mlir
+++ mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize.mlir
@@ -136,7 +136,7 @@
 
 // CHECK-LABEL: func @select_different_tensors(
 //  CHECK-SAME: %[[t:.*]]: tensor
-func.func @select_different_tensors(%t: tensor, %sz: index, %c: i1) -> tensor {
+func.func @select_different_tensors(%t: tensor, %sz: index, %pos: index, %c: i1) -> f32 {
   // CHECK-DAG: %[[m:.*]] = bufferization.to_memref %[[t]] : memref
   // CHECK-DAG: %[[alloc:.*]] = memref.alloc(%{{.*}}) {{.*}} : memref
   %0 = bufferization.alloc_tensor(%sz) : tensor
@@ -145,7 +145,8 @@
   // CHECK: %[[casted:.*]] = memref.cast %[[alloc]] : memref to memref
   // CHECK: arith.select %{{.*}}, %[[casted]], %[[m]]
   %1 = arith.select %c, %0, %t : tensor
-  return %1 : tensor
+  %2 = tensor.extract %1[%pos] : tensor
+  return %2 : f32
 }
 
 // -
Index: mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize-pass-statistics.mlir
===
--- mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize-pass-statistics.mlir
+++ mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize-pass-statistics.mlir
@@ -5,7 +5,7 @@
 // CHECK:  (S) 1 num-buffer-alloc
 // CHECK:  (S) 1 num-buffer-dealloc
 // CHECK:  (S) 1 num-tensor-in-place
-// CHECK:  (S) 1 num-tensor-out-of-place
+// CHECK:  (S) 2 num-tensor-out-of-place
 func.func @read_after_write_conflict(%cst : f32, %idx : index, %idx2 : index)
 -> (f32, f32) {
   %t = "test.dummy_op"() : () -> (tensor<10xf32>)
Index: mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize-partial.mlir
===
--- mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize-partial.mlir
+++ mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize-partial.mlir
@@ -100,11 +100,14 @@
 %t1: tensor, %o: index, %s: index) -> (tensor, tensor) {
   // CHECK: %[[m1:.*]] = bufferization.to_memref %[[t1]]
   // CHECK: %[[subview:.*]] = memref.subview %[[m1]]
+  // The op must alloc because "test.dummy" may bufferize to a memory write.
+  // CHECK: %[[alloc:.*]] = memref.alloc
+  // CHECK: memref.copy %[[subview]], %[[alloc]]
   %0 = tensor.extract_slice %t1[%o][%s][1] : tensor to tensor
-  // CHECK: %[[subview_tensor:.*]] = bufferization.to_tensor %[[subview]]
-  // CHECK: %[[dummy:.*]] = "test.dummy_op"(%[[subview_tensor]])
+  // CHECK: %[[alloc_tensor:.*]] = bufferization.to_tensor %[[alloc]]
+  // CHECK: %[[dummy:.*]] = "test.dummy_op"(%[[alloc_tensor]])
   %1 = "test.dummy_op"(%0) : (tensor) -> tensor
-  // CHECK: return %[[subview_tensor]], %[[dummy]]
+  // CHECK: return %[[alloc_tensor]], %[[dummy]]
   return %0, %1 : tensor, tensor
 }
 
Index: mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize-analysis.mlir
===
--- /dev/null
+++ mlir/test/Dialect/Bufferization/Transforms/one-shot-bufferize-analysis.mlir
@@ -0,0 +1,34 @@
+// RUN: mlir-opt %s -one-shot-bufferize="test-analysis-only" -allow-unregistered-dialect -split-input-file | FileCheck %s
+
+// CHECK-LABEL: func @unknown_op_aliasing(
+func.func @unknown_op_aliasing(%f: f32, %f2: f32, %pos: index) -> f32 {
+  %0 = tensor.empty() : tensor<10xf32>
+  // CHECK: linalg.fill {__inplace_operands_attr__ = ["none", "true"]}
+  %1 = linalg.fill ins(%f : f32) outs(%0 : tensor<10xf32>) -> tensor<10xf32>
+
+  // Something must bufferize out-of-place because the op may return an alias
+  // of %1.
+  // CHECK: "dummy.dummy_op"(%{{.*}}) {__inplace_operands_attr__ = ["false"]}
+  %alias = "dummy.dummy_op"(%1) : (tensor<10xf32>) -> (tensor<10xf32>)
+
+  // CHECK: linalg.fill {__inplace_operands_attr__ = ["none", "true"]}
+  %2 = linalg.fill ins(%f2 : f32) outs(%1 : tensor<10xf32>) -> tensor<10xf32>
+  %3 = tensor.extract %alias[%pos] : tensor<10xf32>
+  return %3 : f32
+}
+
+// -
+
+// CHECK-LABEL: func @unknown_op_writing(
+func.func @unkno

[PATCH] D138546: Clangd: Preserve target flags in system includes extractor

2023-01-19 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

In D138546#4053538 , @cpsauer wrote:

> @nridge, I took a shot at the change you suggested. Confirming that this what 
> you were thinking of, removing `inferTargetAndDriverMode` from database load 
> and replacing it with a call to the underlying 
> `addTargetAndModeForProgramName` in the `CommandMangler` after the 
> `SystemIncludeExtractor` is invoked?

Yup, that's what I had in mind. Thanks for writing that up!

> Note that I also saw a parallel call to `inferTargetAndDriverMode` in 
> `JSONCompilationDatabasePlugin`, which seemed like it might cause the same 
> problem, so I eliminated the call in there, too.

Oh, huh, I didn't realize that `JSONCompilationDatabasePlugin` has this 
behaviour baked in.

I would err on the side of leaving that call site as is.

My thinking is as follows:

- The general purpose of the compilation database utilities in libTooling is to 
produce command lines that will be fed to the clang driver library.
- The clang driver does support `--target`, and in some cases having that flag 
present is important.
- For clangd's call site, we're not //removing// the logic to add the 
`--target` flag, we're just moving it from an ealier stage of the pipeline to a 
later stage of the pipeline, because our pipeline contains a specialized step 
(SystemIncludeExtractor) that may involve executing a gcc driver with (parts of 
the) the command.
- But for other tools built on libTooling that use 
`JSONCompilationDatabasePlugin`, this change would be removing the `--target` 
logic altogether, which could regress behaviour.

> I then culled the dead code, since there weren't other call sites for the 
> `addTargetAndModeForProgramName` wrappings.

Reagrdless of what we decide about `JSONCompilationDatabasePlugin`, we probably 
shouldn't remove `clang::tooling::inferTargetAndDriverMode()`, as that's a 
public libTooling API that may be used by external projects that use libTooling 
as a library.


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

https://reviews.llvm.org/D138546

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


[PATCH] D141793: [14/15][Clang][RISCV] Change default policy from TAMU to TAMA

2023-01-19 Thread Craig Topper via Phabricator via cfe-commits
craig.topper accepted this revision.
craig.topper 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/D141793/new/

https://reviews.llvm.org/D141793

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


[PATCH] D141796: [15/15][Clang][RISCV][NFC] Set data member under Policy as constants

2023-01-19 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 490400.
eopXD added a comment.

Update code: Address comment from Craig.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141796

Files:
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Support/RISCVVIntrinsicUtils.cpp


Index: clang/lib/Support/RISCVVIntrinsicUtils.cpp
===
--- clang/lib/Support/RISCVVIntrinsicUtils.cpp
+++ clang/lib/Support/RISCVVIntrinsicUtils.cpp
@@ -1011,7 +1011,6 @@
   };
 
   if (PolicyAttrs.isUnspecified()) {
-PolicyAttrs.IsUnspecified = false;
 if (IsMasked) {
   Name += "_m";
   if (HasPolicy)
Index: clang/include/clang/Support/RISCVVIntrinsicUtils.h
===
--- clang/include/clang/Support/RISCVVIntrinsicUtils.h
+++ clang/include/clang/Support/RISCVVIntrinsicUtils.h
@@ -92,14 +92,21 @@
   LLVM_MARK_AS_BITMASK_ENUM(LMUL1),
 };
 
-struct Policy {
-  bool IsUnspecified = false;
+class Policy {
+public:
   enum PolicyType {
 Undisturbed,
 Agnostic,
   };
-  PolicyType TailPolicy = Agnostic;
-  PolicyType MaskPolicy = Agnostic;
+
+private:
+  const bool IsUnspecified = false;
+  // The default assumption for an RVV instruction is TAMA, as an undisturbed
+  // policy generally will affect the performance of an out-of-order core.
+  const PolicyType TailPolicy = Agnostic;
+  const PolicyType MaskPolicy = Agnostic;
+
+public:
   Policy() : IsUnspecified(true) {}
   Policy(PolicyType TailPolicy) : TailPolicy(TailPolicy) {}
   Policy(PolicyType TailPolicy, PolicyType MaskPolicy)
@@ -419,7 +426,6 @@
 return IntrinsicTypes;
   }
   Policy getPolicyAttrs() const {
-assert(PolicyAttrs.IsUnspecified == false);
 return PolicyAttrs;
   }
   unsigned getPolicyAttrsBits() const {
@@ -430,8 +436,6 @@
 // constexpr unsigned RVV_VMA = 0x2;
 // int PolicyAttrs = 0;
 
-assert(PolicyAttrs.IsUnspecified == false);
-
 if (PolicyAttrs.isTUMAPolicy())
   return 2;
 if (PolicyAttrs.isTAMAPolicy())


Index: clang/lib/Support/RISCVVIntrinsicUtils.cpp
===
--- clang/lib/Support/RISCVVIntrinsicUtils.cpp
+++ clang/lib/Support/RISCVVIntrinsicUtils.cpp
@@ -1011,7 +1011,6 @@
   };
 
   if (PolicyAttrs.isUnspecified()) {
-PolicyAttrs.IsUnspecified = false;
 if (IsMasked) {
   Name += "_m";
   if (HasPolicy)
Index: clang/include/clang/Support/RISCVVIntrinsicUtils.h
===
--- clang/include/clang/Support/RISCVVIntrinsicUtils.h
+++ clang/include/clang/Support/RISCVVIntrinsicUtils.h
@@ -92,14 +92,21 @@
   LLVM_MARK_AS_BITMASK_ENUM(LMUL1),
 };
 
-struct Policy {
-  bool IsUnspecified = false;
+class Policy {
+public:
   enum PolicyType {
 Undisturbed,
 Agnostic,
   };
-  PolicyType TailPolicy = Agnostic;
-  PolicyType MaskPolicy = Agnostic;
+
+private:
+  const bool IsUnspecified = false;
+  // The default assumption for an RVV instruction is TAMA, as an undisturbed
+  // policy generally will affect the performance of an out-of-order core.
+  const PolicyType TailPolicy = Agnostic;
+  const PolicyType MaskPolicy = Agnostic;
+
+public:
   Policy() : IsUnspecified(true) {}
   Policy(PolicyType TailPolicy) : TailPolicy(TailPolicy) {}
   Policy(PolicyType TailPolicy, PolicyType MaskPolicy)
@@ -419,7 +426,6 @@
 return IntrinsicTypes;
   }
   Policy getPolicyAttrs() const {
-assert(PolicyAttrs.IsUnspecified == false);
 return PolicyAttrs;
   }
   unsigned getPolicyAttrsBits() const {
@@ -430,8 +436,6 @@
 // constexpr unsigned RVV_VMA = 0x2;
 // int PolicyAttrs = 0;
 
-assert(PolicyAttrs.IsUnspecified == false);
-
 if (PolicyAttrs.isTUMAPolicy())
   return 2;
 if (PolicyAttrs.isTAMAPolicy())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D78028: move shebangs from python2 to python3

2023-01-19 Thread Gianfranco Costamagna via Phabricator via cfe-commits
LocutusOfBorg added a comment.
Herald added a subscriber: jsetoain.

This is still relevant, python2 is dead.


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

https://reviews.llvm.org/D78028

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


[PATCH] D141796: [15/15][Clang][RISCV][NFC] Set data member under Policy as constants

2023-01-19 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 490407.
eopXD marked an inline comment as done.
eopXD added a comment.

Bump CI.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141796

Files:
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Support/RISCVVIntrinsicUtils.cpp


Index: clang/lib/Support/RISCVVIntrinsicUtils.cpp
===
--- clang/lib/Support/RISCVVIntrinsicUtils.cpp
+++ clang/lib/Support/RISCVVIntrinsicUtils.cpp
@@ -1011,7 +1011,6 @@
   };
 
   if (PolicyAttrs.isUnspecified()) {
-PolicyAttrs.IsUnspecified = false;
 if (IsMasked) {
   Name += "_m";
   if (HasPolicy)
Index: clang/include/clang/Support/RISCVVIntrinsicUtils.h
===
--- clang/include/clang/Support/RISCVVIntrinsicUtils.h
+++ clang/include/clang/Support/RISCVVIntrinsicUtils.h
@@ -92,14 +92,21 @@
   LLVM_MARK_AS_BITMASK_ENUM(LMUL1),
 };
 
-struct Policy {
-  bool IsUnspecified = false;
+class Policy {
+public:
   enum PolicyType {
 Undisturbed,
 Agnostic,
   };
-  PolicyType TailPolicy = Agnostic;
-  PolicyType MaskPolicy = Agnostic;
+
+private:
+  const bool IsUnspecified = false;
+  // The default assumption for an RVV instruction is TAMA, as an undisturbed
+  // policy generally will affect the performance of an out-of-order core.
+  const PolicyType TailPolicy = Agnostic;
+  const PolicyType MaskPolicy = Agnostic;
+
+public:
   Policy() : IsUnspecified(true) {}
   Policy(PolicyType TailPolicy) : TailPolicy(TailPolicy) {}
   Policy(PolicyType TailPolicy, PolicyType MaskPolicy)
@@ -419,7 +426,6 @@
 return IntrinsicTypes;
   }
   Policy getPolicyAttrs() const {
-assert(PolicyAttrs.IsUnspecified == false);
 return PolicyAttrs;
   }
   unsigned getPolicyAttrsBits() const {
@@ -430,8 +436,6 @@
 // constexpr unsigned RVV_VMA = 0x2;
 // int PolicyAttrs = 0;
 
-assert(PolicyAttrs.IsUnspecified == false);
-
 if (PolicyAttrs.isTUMAPolicy())
   return 2;
 if (PolicyAttrs.isTAMAPolicy())


Index: clang/lib/Support/RISCVVIntrinsicUtils.cpp
===
--- clang/lib/Support/RISCVVIntrinsicUtils.cpp
+++ clang/lib/Support/RISCVVIntrinsicUtils.cpp
@@ -1011,7 +1011,6 @@
   };
 
   if (PolicyAttrs.isUnspecified()) {
-PolicyAttrs.IsUnspecified = false;
 if (IsMasked) {
   Name += "_m";
   if (HasPolicy)
Index: clang/include/clang/Support/RISCVVIntrinsicUtils.h
===
--- clang/include/clang/Support/RISCVVIntrinsicUtils.h
+++ clang/include/clang/Support/RISCVVIntrinsicUtils.h
@@ -92,14 +92,21 @@
   LLVM_MARK_AS_BITMASK_ENUM(LMUL1),
 };
 
-struct Policy {
-  bool IsUnspecified = false;
+class Policy {
+public:
   enum PolicyType {
 Undisturbed,
 Agnostic,
   };
-  PolicyType TailPolicy = Agnostic;
-  PolicyType MaskPolicy = Agnostic;
+
+private:
+  const bool IsUnspecified = false;
+  // The default assumption for an RVV instruction is TAMA, as an undisturbed
+  // policy generally will affect the performance of an out-of-order core.
+  const PolicyType TailPolicy = Agnostic;
+  const PolicyType MaskPolicy = Agnostic;
+
+public:
   Policy() : IsUnspecified(true) {}
   Policy(PolicyType TailPolicy) : TailPolicy(TailPolicy) {}
   Policy(PolicyType TailPolicy, PolicyType MaskPolicy)
@@ -419,7 +426,6 @@
 return IntrinsicTypes;
   }
   Policy getPolicyAttrs() const {
-assert(PolicyAttrs.IsUnspecified == false);
 return PolicyAttrs;
   }
   unsigned getPolicyAttrsBits() const {
@@ -430,8 +436,6 @@
 // constexpr unsigned RVV_VMA = 0x2;
 // int PolicyAttrs = 0;
 
-assert(PolicyAttrs.IsUnspecified == false);
-
 if (PolicyAttrs.isTUMAPolicy())
   return 2;
 if (PolicyAttrs.isTAMAPolicy())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D142026: Optimize OptTable::findNearest implementation and usage

2023-01-19 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 490412.
serge-sans-paille added a comment.

Thanks @nikic for the review. Remarks taken into account.


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

https://reviews.llvm.org/D142026

Files:
  clang/lib/Driver/Driver.cpp
  llvm/include/llvm/Option/OptTable.h
  llvm/lib/Option/OptTable.cpp


Index: llvm/lib/Option/OptTable.cpp
===
--- llvm/lib/Option/OptTable.cpp
+++ llvm/lib/Option/OptTable.cpp
@@ -227,12 +227,13 @@
 
 unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
unsigned FlagsToInclude, unsigned 
FlagsToExclude,
-   unsigned MinimumLength) const {
+   unsigned MinimumLength,
+   unsigned MaximumDistance) const {
   assert(!Option.empty());
 
   // Consider each [option prefix + option name] pair as a candidate, finding
   // the closest match.
-  unsigned BestDistance = UINT_MAX;
+  unsigned BestDistance = MaximumDistance + 1;
   SmallString<16> Candidate;
   SmallString<16> NormalizedName;
 
@@ -276,6 +277,14 @@
 // appropriate one. For example, if a user asks for "--helm", suggest
 // "--help" over "-help".
 for (auto CandidatePrefix : CandidateInfo.Prefixes) {
+  // If Candidate and NormalizedName have more than 'BestDistance'
+  // characters of difference, no need to compute the edit distance, it's
+  // going to be greater than BestDistance. Don't bother computing 
Candidate
+  // at all.
+  if (std::abs((ssize_t)(CandidatePrefix.size() + CandidateName.size()) -
+   (ssize_t)NormalizedName.size()) > (ssize_t)BestDistance) {
+continue;
+  }
   Candidate = CandidatePrefix;
   Candidate += CandidateName;
   unsigned Distance = StringRef(Candidate).edit_distance(
Index: llvm/include/llvm/Option/OptTable.h
===
--- llvm/include/llvm/Option/OptTable.h
+++ llvm/include/llvm/Option/OptTable.h
@@ -175,11 +175,21 @@
   /// \param [in] MinimumLength - Don't find options shorter than this length.
   /// For example, a minimum length of 3 prevents "-x" from being considered
   /// near to "-S".
+  /// \param [in] MaximumDistance - Don't find options whose distance is 
greater
+  /// than this value.
   ///
   /// \return The edit distance of the nearest string found.
   unsigned findNearest(StringRef Option, std::string &NearestString,
unsigned FlagsToInclude = 0, unsigned FlagsToExclude = 
0,
-   unsigned MinimumLength = 4) const;
+   unsigned MinimumLength = 4,
+   unsigned MaximumDistance = UINT_MAX - 1) const;
+
+  bool findExact(StringRef Option, std::string &ExactString,
+ unsigned FlagsToInclude = 0,
+ unsigned FlagsToExclude = 0) const {
+return findNearest(Option, ExactString, FlagsToInclude, FlagsToExclude,
+   4, 0) == 0;
+  }
 
   /// Parse a single argument; returning the new argument and
   /// updating Index.
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -313,8 +313,8 @@
 std::string Nearest;
 if (getOpts().findNearest(ArgString, Nearest, IncludedFlagsBitmask,
   ExcludedFlagsBitmask) > 1) {
-  if (getOpts().findNearest(ArgString, Nearest, options::CC1Option) == 0 &&
-  !IsCLMode()) {
+  if (!IsCLMode() &&
+  getOpts().findExact(ArgString, Nearest, options::CC1Option)) {
 DiagID = diag::err_drv_unknown_argument_with_suggestion;
 Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest;
   } else {
@@ -339,8 +339,8 @@
 // Warn on joined arguments that are similar to a long argument.
 std::string ArgString = ArgStrings[A->getIndex()];
 std::string Nearest;
-if (getOpts().findNearest("-" + ArgString, Nearest, IncludedFlagsBitmask,
-  ExcludedFlagsBitmask) == 0)
+if (getOpts().findExact("-" + ArgString, Nearest, IncludedFlagsBitmask,
+ExcludedFlagsBitmask))
   Diags.Report(diag::warn_drv_potentially_misspelled_joined_argument)
   << A->getAsString(Args) << Nearest;
   }


Index: llvm/lib/Option/OptTable.cpp
===
--- llvm/lib/Option/OptTable.cpp
+++ llvm/lib/Option/OptTable.cpp
@@ -227,12 +227,13 @@
 
 unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
unsigned FlagsToInclude, unsigned FlagsToExclude,
-   unsigned MinimumLength) const {
+   unsigned MinimumLength,
+   

[PATCH] D142085: [Clang][RISCV] Add `__riscv_` prefix for all RVV intrinsics

2023-01-19 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 490416.
eopXD added a comment.
Herald added a subscriber: arphaman.

Update test cases under test/CodeGen/RISCV/rvv-intrinsics-handcrafted


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142085

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vaadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vaaddu.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vadc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vand.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vasub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vasubu.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vcompress.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vcpop.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vdiv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vdivu.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfabs.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfclass.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfdiv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfirst.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmacc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmax.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmerge.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmin.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmsac.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmul.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfneg.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmacc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmsac.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrdiv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrec7.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredmax.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredmin.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredosum.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredusum.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrsqrt7.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsgnj.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsgnjn.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsgnjx.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfslide1down.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfslide1up.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsqrt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/

[PATCH] D139926: [clangd] Add semantic token for angle brackets

2023-01-19 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

> We can easily check the actual character at the given position in the client, 
> so I could just merge the two highlighting kinds.

Thanks! Note that it might not be as easy at the face of templates, eg:

  #define LESS <
  template LESS typename T > class A {};



> Note that << and >> are not the only (or even the primary, in my mind) issue: 
> there is an ambiguity between  as template argument list delimiters vs. 
> comparison operators.

Right, I was trying to imply all operator uses (e.g. including comparisons).

---

Currently my only high level comment is renaming the new kind to just bracket, 
apart from that i think the idea LG. LMK if you're going to take a look at the 
implementation @nridge, otherwise I am happy to do that as well.




Comment at: clang-tools-extra/clangd/SemanticHighlighting.h:54
   Operator,
+  AngleBracket,
 

actually let's name these as `Bracket` rather than `AngleBracket`, as we might 
want to increase the coverage further in the future (and a use case such as 
yours can still look at the textual tokens to match relevant brackets).



Comment at: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp:939
+
$Class[[S]]$AngleBracket[[<]]$Class[[S]]$AngleBracket[[<]]int$AngleBracket[[>]]$AngleBracket[[>]]
 $LocalVariable_def[[s1]];
+$Class[[S]]<$Class[[S]]$AngleBracket[[<]]int$AngleBracket[[>]]\
+> $LocalVariable_def[[s2]];

i don't think this is enough of a test case, we probably need a bunch other 
like:
```
foo >\
>>

foo >\
 >>
```

i think the firstone is going to highlight `\` for example.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139926

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


[PATCH] D142085: [Clang][RISCV] Add `__riscv_` prefix for all RVV intrinsics

2023-01-19 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 490417.
eopXD added a comment.

Bump CI.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142085

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vaadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vaaddu.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vadc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vand.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vasub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vasubu.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vcompress.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vcpop.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vdiv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vdivu.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfabs.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfclass.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfdiv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfirst.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmacc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmax.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmerge.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmin.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmsac.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmul.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfmv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfneg.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmacc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmsac.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfnmsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrdiv.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrec7.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredmax.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredmin.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredosum.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfredusum.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrsqrt7.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfrsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsgnj.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsgnjn.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsgnjx.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfslide1down.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfslide1up.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsqrt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfsub.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwmacc.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-o

[clang] 5b54cf1 - [clang][Interp] Unify visiting variable declarations

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T10:46:16+01:00
New Revision: 5b54cf1a2892767fe949826a32d7820732028a38

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

LOG: [clang][Interp] Unify visiting variable declarations

We often visit the same variable multiple times, e.g. once when checking
its initializer and later when compiling the function. Unify both of
those in visitVarDecl() and do the returning of the value in
visitDecl().

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/ByteCodeExprGen.h
clang/lib/AST/Interp/ByteCodeStmtGen.cpp
clang/lib/AST/Interp/ByteCodeStmtGen.h
clang/lib/AST/Interp/Program.cpp
clang/lib/AST/Interp/Program.h

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index f4bf162a1454..d0140863c5d7 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -802,6 +802,13 @@ unsigned 
ByteCodeExprGen::allocateLocalPrimitive(DeclTy &&Src,
   PrimType Ty,
   bool IsConst,
   bool IsExtended) {
+  // Make sure we don't accidentally register the same decl twice.
+  if (const auto *VD =
+  dyn_cast_if_present(Src.dyn_cast())) {
+assert(!P.getGlobal(VD));
+assert(Locals.find(VD) == Locals.end());
+  }
+
   // FIXME: There are cases where Src.is() is wrong, e.g.
   //   (int){12} in C. Consider using Expr::isTemporaryObject() instead
   //   or isa().
@@ -817,8 +824,14 @@ unsigned 
ByteCodeExprGen::allocateLocalPrimitive(DeclTy &&Src,
 template 
 std::optional
 ByteCodeExprGen::allocateLocal(DeclTy &&Src, bool IsExtended) {
-  QualType Ty;
+  // Make sure we don't accidentally register the same decl twice.
+  if (const auto *VD =
+  dyn_cast_if_present(Src.dyn_cast())) {
+assert(!P.getGlobal(VD));
+assert(Locals.find(VD) == Locals.end());
+  }
 
+  QualType Ty;
   const ValueDecl *Key = nullptr;
   const Expr *Init = nullptr;
   bool IsTemporary = false;
@@ -1128,41 +1141,87 @@ bool ByteCodeExprGen::visitExpr(const Expr 
*Exp) {
 return this->emitRetValue(Exp);
 }
 
+/// Toplevel visitDecl().
+/// We get here from evaluateAsInitializer().
+/// We need to evaluate the initializer and return its value.
 template 
 bool ByteCodeExprGen::visitDecl(const VarDecl *VD) {
+  std::optional VarT = classify(VD->getType());
+
+  // Create and initialize the variable.
+  if (!this->visitVarDecl(VD))
+return false;
+
+  // Get a pointer to the variable
+  if (shouldBeGloballyIndexed(VD)) {
+auto GlobalIndex = P.getGlobal(VD);
+assert(GlobalIndex); // visitVarDecl() didn't return false.
+if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
+  return false;
+  } else {
+auto Local = Locals.find(VD);
+assert(Local != Locals.end()); // Same here.
+if (!this->emitGetPtrLocal(Local->second.Offset, VD))
+  return false;
+  }
+
+  // Return the value
+  if (VarT) {
+if (!this->emitLoadPop(*VarT, VD))
+  return false;
+
+return this->emitRet(*VarT, VD);
+  }
+
+  return this->emitRetValue(VD);
+}
+
+template 
+bool ByteCodeExprGen::visitVarDecl(const VarDecl *VD) {
   const Expr *Init = VD->getInit();
+  std::optional VarT = classify(VD->getType());
+
+  if (shouldBeGloballyIndexed(VD)) {
+std::optional GlobalIndex = P.getOrCreateGlobal(VD, Init);
+
+if (!GlobalIndex)
+  return this->bail(VD);
+
+assert(Init);
+{
+  DeclScope LocalScope(this, VD);
 
-  if (std::optional I = P.createGlobal(VD, Init)) {
-if (std::optional T = classify(VD->getType())) {
-  {
-// Primitive declarations - compute the value and set it.
-DeclScope LocalScope(this, VD);
-if (!visit(Init))
+  if (VarT) {
+if (!this->visit(Init))
   return false;
+return this->emitInitGlobal(*VarT, *GlobalIndex, VD);
   }
+  return this->visitGlobalInitializer(Init, *GlobalIndex);
+}
+  } else {
+DeclScope LocalScope(this, VD);
+
+if (VarT) {
+  unsigned Offset = this->allocateLocalPrimitive(
+  VD, *VarT, VD->getType().isConstQualified());
+  // Compile the initializer in its own scope.
+  if (Init) {
+ExprScope Scope(this);
+if (!this->visit(Init))
+  return false;
 
-  // If the declaration is global, save the value for later use.
-  if (!this->emitDup(*T, VD))
-return false;
-  if (!this->emitInitGlobal(*T, *I, VD))
-return false;
-  return this->emitRet(*T, VD);
+return this->emitSetLoca

[PATCH] D136815: [clang][Interp] Unify visiting variable declarations

2023-01-19 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 rG5b54cf1a2892: [clang][Interp] Unify visiting variable 
declarations (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D136815?vs=479526&id=490418#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136815

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/lib/AST/Interp/ByteCodeStmtGen.h
  clang/lib/AST/Interp/Program.cpp
  clang/lib/AST/Interp/Program.h

Index: clang/lib/AST/Interp/Program.h
===
--- clang/lib/AST/Interp/Program.h
+++ clang/lib/AST/Interp/Program.h
@@ -79,7 +79,8 @@
   std::optional getGlobal(const ValueDecl *VD);
 
   /// Returns or creates a global an creates an index to it.
-  std::optional getOrCreateGlobal(const ValueDecl *VD);
+  std::optional getOrCreateGlobal(const ValueDecl *VD,
+const Expr *Init = nullptr);
 
   /// Returns or creates a dummy value for parameters.
   std::optional getOrCreateDummy(const ParmVarDecl *PD);
Index: clang/lib/AST/Interp/Program.cpp
===
--- clang/lib/AST/Interp/Program.cpp
+++ clang/lib/AST/Interp/Program.cpp
@@ -125,11 +125,12 @@
   return Index;
 }
 
-std::optional Program::getOrCreateGlobal(const ValueDecl *VD) {
+std::optional Program::getOrCreateGlobal(const ValueDecl *VD,
+   const Expr *Init) {
   if (auto Idx = getGlobal(VD))
 return Idx;
 
-  if (auto Idx = createGlobal(VD, nullptr)) {
+  if (auto Idx = createGlobal(VD, Init)) {
 GlobalIndices[VD] = *Idx;
 return Idx;
   }
@@ -157,6 +158,7 @@
 
 std::optional Program::createGlobal(const ValueDecl *VD,
   const Expr *Init) {
+  assert(!getGlobal(VD));
   bool IsStatic, IsExtern;
   if (auto *Var = dyn_cast(VD)) {
 IsStatic = !Var->hasLocalStorage();
Index: clang/lib/AST/Interp/ByteCodeStmtGen.h
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.h
+++ clang/lib/AST/Interp/ByteCodeStmtGen.h
@@ -64,7 +64,6 @@
   bool visitContinueStmt(const ContinueStmt *S);
 
   /// Compiles a variable declaration.
-  bool visitVarDecl(const VarDecl *VD);
 
 private:
   /// Type of the expression returned by the function.
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -207,7 +207,7 @@
   for (auto *D : DS->decls()) {
 // Variable declarator.
 if (auto *VD = dyn_cast(D)) {
-  if (!visitVarDecl(VD))
+  if (!this->visitVarDecl(VD))
 return false;
   continue;
 }
@@ -391,41 +391,6 @@
   return this->jump(*ContinueLabel);
 }
 
-template 
-bool ByteCodeStmtGen::visitVarDecl(const VarDecl *VD) {
-  if (!VD->hasLocalStorage()) {
-// No code generation required.
-return true;
-  }
-
-  // Integers, pointers, primitives.
-  if (std::optional T = this->classify(VD->getType())) {
-const Expr *Init = VD->getInit();
-
-unsigned Offset =
-this->allocateLocalPrimitive(VD, *T, VD->getType().isConstQualified());
-// Compile the initializer in its own scope.
-if (Init) {
-  ExprScope Scope(this);
-  if (!this->visit(Init))
-return false;
-
-  return this->emitSetLocal(*T, Offset, VD);
-}
-return true;
-  }
-
-  // Composite types - allocate storage and initialize it.
-  if (std::optional Offset = this->allocateLocal(VD)) {
-if (!VD->getInit())
-  return true;
-
-return this->visitLocalInitializer(VD->getInit(), *Offset);
-  }
-
-  return this->bail(VD);
-}
-
 namespace clang {
 namespace interp {
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -132,6 +132,8 @@
   bool visitArrayInitializer(const Expr *Initializer);
   /// Compiles a record initializer.
   bool visitRecordInitializer(const Expr *Initializer);
+  /// Creates and initializes a variable from the given decl.
+  bool visitVarDecl(const VarDecl *VD);
 
   /// Visits an expression and converts it to a boolean.
   bool visitBool(const Expr *E);
@@ -234,6 +236,12 @@
 return T->getAsCXXRecordDecl();
   }
 
+  /// Returns whether we should create a global variable for the
+  /// given VarDecl.
+  bool shouldBeGloballyIndexed(const VarDecl *VD) const {
+return VD->hasGlobalStorage() || VD->isConstexpr();
+  }
+
 protected:
   /// Variable to storage mapping.
   llvm::DenseMap Lo

[clang-tools-extra] ccb6749 - [clangd] Simplify some tests in IncludeCleanerTests, NFC

2023-01-19 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-01-19T10:48:54+01:00
New Revision: ccb67491f0dd55c5bd8ed5f71cb802422bfaa969

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

LOG: [clangd] Simplify some tests in IncludeCleanerTests, NFC

They were pointed out in the review of https://reviews.llvm.org/D140875

Added: 


Modified: 
clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp 
b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
index 9449952b10e80..0e4163122d255 100644
--- a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -340,9 +340,8 @@ TEST(IncludeCleaner, StdlibUnused) {
   TU.AdditionalFiles["queue"] = "#include ";
   TU.ExtraArgs = {"-isystem", testRoot()};
   auto AST = TU.build();
-
-  auto Unused = computeUnusedIncludes(AST);
-  EXPECT_THAT(Unused, ElementsAre(Pointee(writtenInclusion("";
+  EXPECT_THAT(computeUnusedIncludes(AST),
+  ElementsAre(Pointee(writtenInclusion("";
 }
 
 TEST(IncludeCleaner, GetUnusedHeaders) {
@@ -374,11 +373,10 @@ TEST(IncludeCleaner, GetUnusedHeaders) {
   TU.ExtraArgs.push_back("-isystem" + testPath("system"));
   TU.Code = MainFile.str();
   ParsedAST AST = TU.build();
-  std::vector UnusedIncludes;
-  for (const auto &Include : computeUnusedIncludes(AST))
-UnusedIncludes.push_back(Include->Written);
-  EXPECT_THAT(UnusedIncludes,
-  UnorderedElementsAre("\"unused.h\"", "\"dir/unused.h\""));
+  EXPECT_THAT(
+  computeUnusedIncludes(AST),
+  UnorderedElementsAre(Pointee(writtenInclusion("\"unused.h\"")),
+   Pointee(writtenInclusion("\"dir/unused.h\"";
 }
 
 TEST(IncludeCleaner, VirtualBuffers) {



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


[PATCH] D142026: Optimize OptTable::findNearest implementation and usage

2023-01-19 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.

LGTM


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

https://reviews.llvm.org/D142026

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


[PATCH] D142092: [include-mapping] Allow multiple headers for the same symbol. Choose the first header of available ones.

2023-01-19 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo created this revision.
Herald added a project: All.
VitaNuo requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D142092

Files:
  clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
  clang/tools/include-mapping/gen_std.py

Index: clang/tools/include-mapping/gen_std.py
===
--- clang/tools/include-mapping/gen_std.py
+++ clang/tools/include-mapping/gen_std.py
@@ -104,17 +104,12 @@
 os.stat(index_page_path).st_mtime).strftime('%Y-%m-%d')
   print(CODE_PREFIX % (args.language.upper(), cppreference_modified_date))
   for symbol in symbols:
-if len(symbol.headers) == 1:
-  # SYMBOL(unqualified_name, namespace, header)
-  print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
-symbol.headers[0]))
-elif len(symbol.headers) == 0:
+if len(symbol.headers) == 0:
   sys.stderr.write("No header found for symbol %s\n" % symbol.name)
 else:
-  # FIXME: support symbols with multiple headers (e.g. std::move).
-  sys.stderr.write("Ambiguous header for symbol %s: %s\n" % (
-  symbol.name, ', '.join(symbol.headers)))
-
-
+  for header in symbol.headers:
+# SYMBOL(unqualified_name, namespace, header)
+print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
+  header))
 if __name__ == '__main__':
   main()
Index: clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
===
--- clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -8,6 +8,7 @@
 
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "clang/AST/Decl.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 
@@ -16,8 +17,9 @@
 namespace stdlib {
 
 static llvm::StringRef *HeaderNames;
-static std::pair *SymbolNames;
-static unsigned *SymbolHeaderIDs;
+static llvm::DenseMap>
+*SymbolNames;
+static llvm::SmallVector *SymbolHeaderIDs;
 static llvm::DenseMap *HeaderIDs;
 // Maps symbol name -> Symbol::ID, within a namespace.
 using NSSymbolMap = llvm::DenseMap;
@@ -29,7 +31,7 @@
 #include "clang/Tooling/Inclusions/CSymbolMap.inc"
 #include "clang/Tooling/Inclusions/StdSymbolMap.inc"
 #undef SYMBOL
-  SymbolNames = new std::remove_reference_t[SymCount];
+  SymbolNames = new std::remove_reference_t;
   SymbolHeaderIDs =
   new std::remove_reference_t[SymCount];
   NamespaceSymbols = new std::remove_reference_t;
@@ -46,18 +48,31 @@
 return HeaderIDs->try_emplace(Header, HeaderIDs->size()).first->second;
   };
 
-  auto Add = [&, SymIndex(0)](llvm::StringRef Name, llvm::StringRef NS,
-  llvm::StringRef HeaderName) mutable {
+  auto Add = [&, NextAvailSymIndex(0)](llvm::StringRef Name, llvm::StringRef NS,
+   llvm::StringRef HeaderName) mutable {
 if (NS == "None")
   NS = "";
 
-SymbolNames[SymIndex] = {NS, Name};
-SymbolHeaderIDs[SymIndex] = AddHeader(HeaderName);
+bool IsNewSymbol = true;
+int SymIndex = NextAvailSymIndex;
+if (NSSymbolMap *NSSymbols = NamespaceSymbols->lookup(NS)) {
+  auto It = NSSymbols->find(Name);
+  if (It != NSSymbols->end()) {
+SymIndex = It->getSecond();
+IsNewSymbol = false;
+  }
+}
+
+SymbolNames->try_emplace(SymIndex, std::make_pair(NS, Name));
+
+unsigned HeaderID = AddHeader(HeaderName);
+SymbolHeaderIDs[SymIndex].emplace_back(HeaderID);
 
 NSSymbolMap &NSSymbols = AddNS(NS);
 NSSymbols.try_emplace(Name, SymIndex);
 
-++SymIndex;
+if (IsNewSymbol)
+  ++NextAvailSymIndex;
   };
 #define SYMBOL(Name, NS, Header) Add(#Name, #NS, #Header);
 #include "clang/Tooling/Inclusions/CSymbolMap.inc"
@@ -84,8 +99,20 @@
   return Header(It->second);
 }
 llvm::StringRef Header::name() const { return HeaderNames[ID]; }
-llvm::StringRef Symbol::scope() const { return SymbolNames[ID].first; }
-llvm::StringRef Symbol::name() const { return SymbolNames[ID].second; }
+llvm::StringRef Symbol::scope() const {
+  auto It = SymbolNames->find(ID);
+  if (It != SymbolNames->end()) {
+return It->second.first;
+  }
+  return "";
+}
+llvm::StringRef Symbol::name() const {
+  auto It = SymbolNames->find(ID);
+  if (It != SymbolNames->end()) {
+return It->second.second;
+  }
+  return "";
+}
 std::optional Symbol::named(llvm::StringRef Scope,
  llvm::StringRef Name) {
   ensureInitialized();
@@ -96,9 +123,14 @@
   }
   return std::nullopt;
 }
-Header Symbol::header() const { return Header(SymbolHeaderIDs[ID]); }
+
+Header Symbol::header() const { return Header(SymbolHeaderIDs[ID][0]); }
 llvm::SmallVector Symbol::headers() const {
-  return {hea

[clang] 9308014 - [clang][Interp] Diagnose uninitialized array record fields

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T11:07:51+01:00
New Revision: 9308014195e2f091c0025ef4aa26ece080b7da8d

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

LOG: [clang][Interp] Diagnose uninitialized array record fields

Just like we do for record members, diagnose uninitialized array record
fields.

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

Added: 


Modified: 
clang/lib/AST/Interp/Interp.cpp
clang/lib/AST/Interp/Pointer.h
clang/test/AST/Interp/cxx20.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index d493a50486b7..6a600b306bad 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -401,6 +401,48 @@ bool CheckPure(InterpState &S, CodePtr OpPC, const 
CXXMethodDecl *MD) {
   return false;
 }
 
+static void DiagnoseUninitializedSubobject(InterpState &S, const SourceInfo 
&SI,
+   QualType SubObjType,
+   SourceLocation SubObjLoc) {
+  S.FFDiag(SI, diag::note_constexpr_uninitialized) << true << SubObjType;
+  if (SubObjLoc.isValid())
+S.Note(SubObjLoc, diag::note_constexpr_subobject_declared_here);
+}
+
+static bool CheckFieldsInitialized(InterpState &S, CodePtr OpPC,
+   const Pointer &BasePtr, const Record *R);
+
+static bool CheckArrayInitialized(InterpState &S, CodePtr OpPC,
+  const Pointer &BasePtr,
+  const ConstantArrayType *CAT) {
+  bool Result = true;
+  size_t NumElems = CAT->getSize().getZExtValue();
+  QualType ElemType = CAT->getElementType();
+
+  if (isa(ElemType.getTypePtr())) {
+const Record *R = BasePtr.getElemRecord();
+for (size_t I = 0; I != NumElems; ++I) {
+  Pointer ElemPtr = BasePtr.atIndex(I).narrow();
+  Result &= CheckFieldsInitialized(S, OpPC, ElemPtr, R);
+}
+  } else if (auto *ElemCAT = dyn_cast(ElemType)) {
+for (size_t I = 0; I != NumElems; ++I) {
+  Pointer ElemPtr = BasePtr.atIndex(I).narrow();
+  Result &= CheckArrayInitialized(S, OpPC, ElemPtr, ElemCAT);
+}
+  } else {
+for (size_t I = 0; I != NumElems; ++I) {
+  if (!BasePtr.atIndex(I).isInitialized()) {
+DiagnoseUninitializedSubobject(S, S.Current->getSource(OpPC), ElemType,
+   BasePtr.getFieldDesc()->getLocation());
+Result = false;
+  }
+}
+  }
+
+  return Result;
+}
+
 static bool CheckFieldsInitialized(InterpState &S, CodePtr OpPC,
const Pointer &BasePtr, const Record *R) {
   assert(R);
@@ -408,19 +450,17 @@ static bool CheckFieldsInitialized(InterpState &S, 
CodePtr OpPC,
   // Check all fields of this record are initialized.
   for (const Record::Field &F : R->fields()) {
 Pointer FieldPtr = BasePtr.atField(F.Offset);
-QualType FieldType = FieldPtr.getType();
+QualType FieldType = F.Decl->getType();
 
 if (FieldType->isRecordType()) {
   Result &= CheckFieldsInitialized(S, OpPC, FieldPtr, 
FieldPtr.getRecord());
 } else if (FieldType->isArrayType()) {
-  // FIXME: Arrays need to be handled here as well I think.
+  const auto *CAT =
+  cast(FieldType->getAsArrayTypeUnsafe());
+  Result &= CheckArrayInitialized(S, OpPC, FieldPtr, CAT);
 } else if (!FieldPtr.isInitialized()) {
-  const SourceInfo &SI = S.Current->getSource(OpPC);
-  S.FFDiag(SI, diag::note_constexpr_uninitialized)
-  << true << F.Decl->getType();
-  SourceLocation SubobjectLoc = F.Decl->getLocation();
-  if (SubobjectLoc.isValid())
-S.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
+  DiagnoseUninitializedSubobject(S, S.Current->getSource(OpPC),
+ F.Decl->getType(), F.Decl->getLocation());
   Result = false;
 }
   }

diff  --git a/clang/lib/AST/Interp/Pointer.h b/clang/lib/AST/Interp/Pointer.h
index c0628314e869..ce113a54e122 100644
--- a/clang/lib/AST/Interp/Pointer.h
+++ b/clang/lib/AST/Interp/Pointer.h
@@ -242,6 +242,8 @@ class Pointer {
 
   /// Returns the record descriptor of a class.
   Record *getRecord() const { return getFieldDesc()->ElemRecord; }
+  // Returns the element record type, if this is a non-primive array.
+  Record *getElemRecord() const { return getFieldDesc()->ElemDesc->ElemRecord; 
}
   /// Returns the field information.
   const FieldDecl *getField() const { return getFieldDesc()->asFieldDecl(); }
 

diff  --git a/clang/test/AST/Interp/cxx20.cpp b/clang/test/AST/Interp/cxx20.cpp
index de15cc9c259e..e9505b3cf718 100644
--- a/clang/test/AST/Interp/cxx20.cpp
+++ b/clang/test/AST/Interp/cxx20.cpp
@@ -137,8 +137,8 @@ static_assert(!b4)

[PATCH] D136828: [clang][Interp] Diagnose uninitialized array record fields

2023-01-19 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 rG9308014195e2: [clang][Interp] Diagnose uninitialized array 
record fields (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D136828?vs=473405&id=490424#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136828

Files:
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Pointer.h
  clang/test/AST/Interp/cxx20.cpp

Index: clang/test/AST/Interp/cxx20.cpp
===
--- clang/test/AST/Interp/cxx20.cpp
+++ clang/test/AST/Interp/cxx20.cpp
@@ -137,8 +137,8 @@
 namespace UninitializedFields {
   class A {
   public:
-int a; // expected-note {{subobject declared here}} \
-   // ref-note {{subobject declared here}}
+int a; // expected-note 2{{subobject declared here}} \
+   // ref-note 2{{subobject declared here}}
 constexpr A() {}
   };
   constexpr A a; // expected-error {{must be initialized by a constant expression}} \
@@ -164,4 +164,40 @@
  // expected-note {{in call to 'Derived()'}} \
  // ref-error {{must be initialized by a constant expression}} \
  // ref-note {{subobject of type 'int' is not initialized}}
+
+  class C2 {
+  public:
+A a;
+constexpr C2() {} // expected-note {{subobject of type 'int' is not initialized}}
+  };
+  constexpr C2 c2; // expected-error {{must be initialized by a constant expression}} \
+   // expected-note {{in call to 'C2()'}} \
+   // ref-error {{must be initialized by a constant expression}} \
+   // ref-note {{subobject of type 'int' is not initialized}}
+
+
+  // FIXME: These two are currently disabled because the array fields
+  //   cannot be initialized.
+#if 0
+  class C3 {
+  public:
+A a[2];
+constexpr C3() {}
+  };
+  constexpr C3 c3; // expected-error {{must be initialized by a constant expression}} \
+   // expected-note {{subobject of type 'int' is not initialized}} \
+   // ref-error {{must be initialized by a constant expression}} \
+   // ref-note {{subobject of type 'int' is not initialized}}
+
+  class C4 {
+  public:
+bool B[2][3]; // expected-note {{subobject declared here}} \
+  // ref-note {{subobject declared here}}
+constexpr C4(){}
+  };
+  constexpr C4 c4; // expected-error {{must be initialized by a constant expression}} \
+   // expected-note {{subobject of type 'bool' is not initialized}} \
+   // ref-error {{must be initialized by a constant expression}} \
+   // ref-note {{subobject of type 'bool' is not initialized}}
+#endif
 };
Index: clang/lib/AST/Interp/Pointer.h
===
--- clang/lib/AST/Interp/Pointer.h
+++ clang/lib/AST/Interp/Pointer.h
@@ -242,6 +242,8 @@
 
   /// Returns the record descriptor of a class.
   Record *getRecord() const { return getFieldDesc()->ElemRecord; }
+  // Returns the element record type, if this is a non-primive array.
+  Record *getElemRecord() const { return getFieldDesc()->ElemDesc->ElemRecord; }
   /// Returns the field information.
   const FieldDecl *getField() const { return getFieldDesc()->asFieldDecl(); }
 
Index: clang/lib/AST/Interp/Interp.cpp
===
--- clang/lib/AST/Interp/Interp.cpp
+++ clang/lib/AST/Interp/Interp.cpp
@@ -401,6 +401,48 @@
   return false;
 }
 
+static void DiagnoseUninitializedSubobject(InterpState &S, const SourceInfo &SI,
+   QualType SubObjType,
+   SourceLocation SubObjLoc) {
+  S.FFDiag(SI, diag::note_constexpr_uninitialized) << true << SubObjType;
+  if (SubObjLoc.isValid())
+S.Note(SubObjLoc, diag::note_constexpr_subobject_declared_here);
+}
+
+static bool CheckFieldsInitialized(InterpState &S, CodePtr OpPC,
+   const Pointer &BasePtr, const Record *R);
+
+static bool CheckArrayInitialized(InterpState &S, CodePtr OpPC,
+  const Pointer &BasePtr,
+  const ConstantArrayType *CAT) {
+  bool Result = true;
+  size_t NumElems = CAT->getSize().getZExtValue();
+  QualType ElemType = CAT->getElementType();
+
+  if (isa(ElemType.getTypePtr())) {
+const Record *R = BasePtr.getElemRecord();
+for (size_t I = 0; I != NumElems; ++I) {
+  Pointer ElemPtr = BasePtr.atIndex(I).narrow();
+  Result &= CheckFieldsInitialized(S, OpPC, ElemPtr, R);
+}
+  } else if (auto *ElemCAT = dyn_cast(ElemType)) {
+for (size_t I = 0; I != NumElems; ++I) {
+  Pointer ElemPtr = BasePtr.atIndex(I).narrow();
+ 

[PATCH] D142094: [Clang][Doc] Add release note for changes for the RVV intrinsics

2023-01-19 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD created this revision.
eopXD added reviewers: craig.topper, kito-cheng, rogfer01, frasercrmck.
Herald added subscribers: s.egerton, simoncook.
Herald added a project: All.
eopXD requested review of this revision.
Herald added subscribers: cfe-commits, pcwang-thead.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D142094

Files:
  clang/docs/ReleaseNotes.rst


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -806,6 +806,17 @@
 - Fix interaction of ``-mcpu`` and ``-march``, RISC-V backend will take the
   architecture extension union of ``-mcpu`` and ``-march`` before, and now will
   take architecture extensions from ``-march`` if both are given.
+- An overall simplification of the RISC-V Vector intrinsics are done. The
+  simplification is based on
+  `riscv-non-isa/rvv-intrinsic-doc#186 
`_.
+- Intrinsics of `vcompress` and `vmerge` have been adjusted to have interfaces
+  be aligned among `vvm`, `vxm` intrinsics. The adjustment is base on
+  `riscv-non-isa/rvv-intrinsic-doc#185 
`_.
+- All RISC-V Vector intrinsics now share a `__riscv_` prefix, based on the
+  naming convention defined by
+  `riscv-non-isa/riscv-c-api-doc#31 
`_.
+- Note that the RISC-V Vector C intrinsics are still under experiment. The RVV
+  C Intrinsic Task Group is working towards a ratified v1.0.
 
 X86 Support in Clang
 


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -806,6 +806,17 @@
 - Fix interaction of ``-mcpu`` and ``-march``, RISC-V backend will take the
   architecture extension union of ``-mcpu`` and ``-march`` before, and now will
   take architecture extensions from ``-march`` if both are given.
+- An overall simplification of the RISC-V Vector intrinsics are done. The
+  simplification is based on
+  `riscv-non-isa/rvv-intrinsic-doc#186 `_.
+- Intrinsics of `vcompress` and `vmerge` have been adjusted to have interfaces
+  be aligned among `vvm`, `vxm` intrinsics. The adjustment is base on
+  `riscv-non-isa/rvv-intrinsic-doc#185 `_.
+- All RISC-V Vector intrinsics now share a `__riscv_` prefix, based on the
+  naming convention defined by
+  `riscv-non-isa/riscv-c-api-doc#31 `_.
+- Note that the RISC-V Vector C intrinsics are still under experiment. The RVV
+  C Intrinsic Task Group is working towards a ratified v1.0.
 
 X86 Support in Clang
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D142094: [Clang][Doc] Add release note for changes for the RVV intrinsics

2023-01-19 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD added a comment.

These changes described are based on patch(es) under review. This patch should 
land after D142085 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142094

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


[PATCH] D136315: [clang][Darwin] Try to guess the SDK root with xcrun when unspecified

2023-01-19 Thread J. Ryan Stinnett via Phabricator via cfe-commits
jryans added a comment.

@calebzulawski The toolchain is selected based on the target, see 
Driver::getToolChain 
.

Various groups do target macOS from Linux hosts. I'm not quite sure how the SDK 
is meant to be found in such a case though... @thakis, your log seems like it 
passes `SDKROOT`, so is that meant to be what's used for this host and target 
combo?

Let me know if I can assist by reverting the patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136315

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


[PATCH] D136751: [clang][Interp] This pointers are writable in constructors

2023-01-19 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136751

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


[clang] 2aa23ff - [clang][Interp][NFCI] Pull IsConstantContext into State

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T12:16:03+01:00
New Revision: 2aa23ff263a012afaf0dbb05d96a7301fc6cbb57

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

LOG: [clang][Interp][NFCI] Pull IsConstantContext into State

This way we can check for this flag in the new interpreter as well.

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/lib/AST/Interp/InterpState.h
clang/lib/AST/Interp/State.h

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index e3f34579372a..7105c7dfa753 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -925,10 +925,6 @@ namespace {
 /// fold (not just why it's not strictly a constant expression)?
 bool HasFoldFailureDiagnostic;
 
-/// Whether or not we're in a context where the front end requires a
-/// constant value.
-bool InConstantContext;
-
 /// Whether we're checking that an expression is a potential constant
 /// expression. If so, do not fail on constructs that could become constant
 /// later on (such as a use of an undefined global).
@@ -984,8 +980,7 @@ namespace {
   BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
   EvaluatingDecl((const ValueDecl *)nullptr),
   EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
-  HasFoldFailureDiagnostic(false), InConstantContext(false),
-  EvalMode(Mode) {}
+  HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
 
 ~EvalInfo() {
   discardCleanups();

diff  --git a/clang/lib/AST/Interp/InterpState.h 
b/clang/lib/AST/Interp/InterpState.h
index 72f6dd09dc2e..033080637385 100644
--- a/clang/lib/AST/Interp/InterpState.h
+++ b/clang/lib/AST/Interp/InterpState.h
@@ -65,6 +65,7 @@ class InterpState final : public State, public SourceMapper {
   bool noteUndefinedBehavior() override {
 return Parent.noteUndefinedBehavior();
   }
+  bool inConstantContext() const { return Parent.InConstantContext; }
   bool hasActiveDiagnostic() override { return Parent.hasActiveDiagnostic(); }
   void setActiveDiagnostic(bool Flag) override {
 Parent.setActiveDiagnostic(Flag);

diff  --git a/clang/lib/AST/Interp/State.h b/clang/lib/AST/Interp/State.h
index d9a645a3eb3e..131fbcf3cffc 100644
--- a/clang/lib/AST/Interp/State.h
+++ b/clang/lib/AST/Interp/State.h
@@ -71,6 +71,7 @@ class State {
   virtual unsigned getCallStackDepth() = 0;
 
 public:
+  State() : InConstantContext(false) {}
   // Diagnose that the evaluation could not be folded (FF => FoldFailure)
   OptionalDiagnostic
   FFDiag(SourceLocation Loc,
@@ -118,6 +119,10 @@ class State {
 
   const LangOptions &getLangOpts() const;
 
+  /// Whether or not we're in a context where the front end requires a
+  /// constant value.
+  bool InConstantContext;
+
 private:
   void addCallStack(unsigned Limit);
 



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


[PATCH] D141798: Drop the ZeroBehavior parameter from countLeadingZeros and the like (NFC)

2023-01-19 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

@kazu Thanks for dealing with this!

I'd like to build on this and create llvm variants of the C++20  
countl_zero/countr_zero/countl_one/countr_one template functions similar to 
what I did for popcount in D132407  (and have 
MathExtras.h reuse it) - I just wanted to ensure you hadn't already started 
anything similar?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141798

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


[clang] fddf641 - [clang][Interp][NFC] Remove shift error checking code duplication

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T12:18:26+01:00
New Revision: fddf6418e8492a544c9bfdb42a4dbc949d9dc2ee

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

LOG: [clang][Interp][NFC] Remove shift error checking code duplication

Added: 


Modified: 
clang/lib/AST/Interp/Interp.cpp
clang/lib/AST/Interp/Interp.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 6a600b306bad..76ade4401e08 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -401,6 +401,27 @@ bool CheckPure(InterpState &S, CodePtr OpPC, const 
CXXMethodDecl *MD) {
   return false;
 }
 
+template 
+bool CheckShift(InterpState &S, CodePtr OpPC, const RT &RHS, unsigned Bits) {
+  if (RHS.isNegative()) {
+const SourceInfo &Loc = S.Current->getSource(OpPC);
+S.CCEDiag(Loc, diag::note_constexpr_negative_shift) << RHS.toAPSInt();
+return false;
+  }
+
+  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
+  // the shifted type.
+  if (Bits > 1 && RHS >= RT::from(Bits, RHS.bitWidth())) {
+const Expr *E = S.Current->getExpr(OpPC);
+const APSInt Val = RHS.toAPSInt();
+QualType Ty = E->getType();
+S.CCEDiag(E, diag::note_constexpr_large_shift) << Val << Ty << Bits;
+return false;
+  }
+
+  return true;
+}
+
 static void DiagnoseUninitializedSubobject(InterpState &S, const SourceInfo 
&SI,
QualType SubObjType,
SourceLocation SubObjLoc) {

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 65a49f21c5dc..903c68f4511c 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -94,6 +94,10 @@ bool CheckPure(InterpState &S, CodePtr OpPC, const 
CXXMethodDecl *MD);
 /// Checks that all fields are initialized after a constructor call.
 bool CheckCtorCall(InterpState &S, CodePtr OpPC, const Pointer &This);
 
+/// Checks if the shift operation is legal.
+template 
+bool CheckShift(InterpState &S, CodePtr OpPC, const RT &RHS, unsigned Bits);
+
 /// Checks if Div/Rem operation on LHS and RHS is valid.
 template 
 bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS) {
@@ -1180,21 +1184,8 @@ inline bool Shr(InterpState &S, CodePtr OpPC) {
   const auto &LHS = S.Stk.pop();
   const unsigned Bits = LHS.bitWidth();
 
-  if (RHS.isNegative()) {
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.CCEDiag(Loc, diag::note_constexpr_negative_shift) << RHS.toAPSInt();
+  if (!CheckShift(S, OpPC, RHS, Bits))
 return false;
-  }
-
-  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
-  // the shifted type.
-  if (Bits > 1 && RHS >= RT::from(Bits, RHS.bitWidth())) {
-const Expr *E = S.Current->getExpr(OpPC);
-const APSInt Val = RHS.toAPSInt();
-QualType Ty = E->getType();
-S.CCEDiag(E, diag::note_constexpr_large_shift) << Val << Ty << Bits;
-return false;
-  }
 
   unsigned URHS = static_cast(RHS);
   S.Stk.push(LT::from(static_cast(LHS) >> URHS, LHS.bitWidth()));
@@ -1209,21 +1200,8 @@ inline bool Shl(InterpState &S, CodePtr OpPC) {
   const auto &LHS = S.Stk.pop();
   const unsigned Bits = LHS.bitWidth();
 
-  if (RHS.isNegative()) {
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.CCEDiag(Loc, diag::note_constexpr_negative_shift) << RHS.toAPSInt();
-return false;
-  }
-
-  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
-  // the shifted type.
-  if (Bits > 1 && RHS >= RT::from(Bits, RHS.bitWidth())) {
-const Expr *E = S.Current->getExpr(OpPC);
-const APSInt Val = RHS.toAPSInt();
-QualType Ty = E->getType();
-S.CCEDiag(E, diag::note_constexpr_large_shift) << Val << Ty << Bits;
+  if (!CheckShift(S, OpPC, RHS, Bits))
 return false;
-  }
 
   unsigned URHS = static_cast(RHS);
   S.Stk.push(LT::from(static_cast(LHS) << URHS, LHS.bitWidth()));



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


[clang] 9ee0d74 - [clang][Interp][NFC] Move CheckDivRem() implementation into Interp.cpp

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T12:18:34+01:00
New Revision: 9ee0d7494eb35f5addefcb730cdf5c002ddeacd2

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

LOG: [clang][Interp][NFC] Move CheckDivRem() implementation into Interp.cpp

Just like we do with all the other Check* functions.

Added: 


Modified: 
clang/lib/AST/Interp/Interp.cpp
clang/lib/AST/Interp/Interp.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 76ade4401e08..d7195148d015 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -422,6 +422,26 @@ bool CheckShift(InterpState &S, CodePtr OpPC, const RT 
&RHS, unsigned Bits) {
   return true;
 }
 
+template 
+bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS) {
+  if (RHS.isZero()) {
+const SourceInfo &Loc = S.Current->getSource(OpPC);
+S.FFDiag(Loc, diag::note_expr_divide_by_zero);
+return false;
+  }
+
+  if (LHS.isSigned() && LHS.isMin() && RHS.isNegative() && RHS.isMinusOne()) {
+APSInt LHSInt = LHS.toAPSInt();
+SmallString<32> Trunc;
+(-LHSInt.extend(LHSInt.getBitWidth() + 1)).toString(Trunc, 10);
+const SourceInfo &Loc = S.Current->getSource(OpPC);
+const Expr *E = S.Current->getExpr(OpPC);
+S.CCEDiag(Loc, diag::note_constexpr_overflow) << Trunc << E->getType();
+return false;
+  }
+  return true;
+}
+
 static void DiagnoseUninitializedSubobject(InterpState &S, const SourceInfo 
&SI,
QualType SubObjType,
SourceLocation SubObjLoc) {

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 903c68f4511c..3fa977d4a02e 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -100,24 +100,7 @@ bool CheckShift(InterpState &S, CodePtr OpPC, const RT 
&RHS, unsigned Bits);
 
 /// Checks if Div/Rem operation on LHS and RHS is valid.
 template 
-bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS) {
-  if (RHS.isZero()) {
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.FFDiag(Loc, diag::note_expr_divide_by_zero);
-return false;
-  }
-
-  if (LHS.isSigned() && LHS.isMin() && RHS.isNegative() && RHS.isMinusOne()) {
-APSInt LHSInt = LHS.toAPSInt();
-SmallString<32> Trunc;
-(-LHSInt.extend(LHSInt.getBitWidth() + 1)).toString(Trunc, 10);
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-const Expr *E = S.Current->getExpr(OpPC);
-S.CCEDiag(Loc, diag::note_constexpr_overflow) << Trunc << E->getType();
-return false;
-  }
-  return true;
-}
+bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS);
 
 /// Interpreter entry point.
 bool Interpret(InterpState &S, APValue &Result);



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


[clang] 490e821 - [clang][Interp] Implement missing compound assign operators

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T12:24:56+01:00
New Revision: 490e8214fca48824beda8b508d6d6bbbf3d8d9a7

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

LOG: [clang][Interp] Implement missing compound assign operators

Implement mul, div, rem, etc. compound assign operators.

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/literals.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index d0140863c5d7..8565f635eafc 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -525,8 +525,8 @@ bool ByteCodeExprGen::VisitCompoundAssignOperator(
 const CompoundAssignOperator *E) {
   const Expr *LHS = E->getLHS();
   const Expr *RHS = E->getRHS();
-  std::optional LT = classify(E->getLHS()->getType());
-  std::optional RT = classify(E->getRHS()->getType());
+  std::optional LT = classify(E->getComputationLHSType());
+  std::optional RT = classify(E->getComputationResultType());
 
   if (!LT || !RT)
 return false;
@@ -552,10 +552,18 @@ bool 
ByteCodeExprGen::VisitCompoundAssignOperator(
 if (!this->emitSub(*LT, E))
   return false;
 break;
-
   case BO_MulAssign:
+if (!this->emitMul(*LT, E))
+  return false;
+break;
   case BO_DivAssign:
+if (!this->emitDiv(*LT, E))
+  return false;
+break;
   case BO_RemAssign:
+if (!this->emitRem(*LT, E))
+  return false;
+break;
   case BO_ShlAssign:
 if (!this->emitShl(*LT, *RT, E))
   return false;
@@ -565,8 +573,17 @@ bool ByteCodeExprGen::VisitCompoundAssignOperator(
   return false;
 break;
   case BO_AndAssign:
+if (!this->emitBitAnd(*LT, E))
+  return false;
+break;
   case BO_XorAssign:
+if (!this->emitBitXor(*LT, E))
+  return false;
+break;
   case BO_OrAssign:
+if (!this->emitBitOr(*LT, E))
+  return false;
+break;
   default:
 llvm_unreachable("Unimplemented compound assign operator");
   }

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index cd5c9da9bda5..4fc9489941e5 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -469,5 +469,160 @@ namespace IncDec {
 return (a -= a);
   }
   static_assert(subAll(213) == 0, "");
+
+  constexpr bool BoolOr(bool b1, bool b2) {
+bool a;
+a = b1;
+a |= b2;
+return a;
+  }
+  static_assert(BoolOr(true, true), "");
+  static_assert(BoolOr(true, false), "");
+  static_assert(BoolOr(false, true), "");
+  static_assert(!BoolOr(false, false), "");
+
+  constexpr int IntOr(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r |= b;
+return r;
+  }
+  static_assert(IntOr(10, 1) == 11, "");
+  static_assert(IntOr(1337, -1) == -1, "");
+  static_assert(IntOr(0, 12) == 12, "");
+
+  constexpr bool BoolAnd(bool b1, bool b2) {
+bool a;
+a = b1;
+a &= b2;
+return a;
+  }
+  static_assert(BoolAnd(true, true), "");
+  static_assert(!BoolAnd(true, false), "");
+  static_assert(!BoolAnd(false, true), "");
+  static_assert(!BoolAnd(false, false), "");
+
+  constexpr int IntAnd(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r &= b;
+return r;
+  }
+  static_assert(IntAnd(10, 1) == 0, "");
+  static_assert(IntAnd(1337, -1) == 1337, "");
+  static_assert(IntAnd(0, 12) == 0, "");
+
+  constexpr bool BoolXor(bool b1, bool b2) {
+bool a;
+a = b1;
+a ^= b2;
+return a;
+  }
+  static_assert(!BoolXor(true, true), "");
+  static_assert(BoolXor(true, false), "");
+  static_assert(BoolXor(false, true), "");
+  static_assert(!BoolXor(false, false), "");
+
+  constexpr int IntXor(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r ^= b;
+return r;
+  }
+  static_assert(IntXor(10, 1) == 11, "");
+  static_assert(IntXor(10, 10) == 0, "");
+  static_assert(IntXor(12, true) == 13, "");
+
+  constexpr bool BoolRem(bool b1, bool b2) {
+bool a;
+a = b1;
+a %= b2;
+return a;
+  }
+  static_assert(!BoolRem(true, true), "");
+  static_assert(!BoolRem(false, true), "");
+
+  constexpr int IntRem(int a, int b) {
+int r;
+r = a;
+r %= b; // expected-note {{division by zero}} \
+// ref-note {{division by zero}} \
+// expected-note {{outside the range of representable values}} \
+// ref-note {{outside the range of representable values}}
+return r;
+  }
+  static_assert(IntRem(2, 2) == 0, "");
+  static_assert(IntRem(2, 1) == 0, "");
+  static_assert(IntRem(9, 7) == 2, "");
+  static_assert(IntRem(5, 0) == 0, ""); // expected-error {{not an integral 
constant expression}} \
+ 

[PATCH] D137071: [clang][Interp] Implement missing compound assign operators

2023-01-19 Thread Timm Bäder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG490e8214fca4: [clang][Interp] Implement missing compound 
assign operators (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D137071?vs=474273&id=490444#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137071

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/literals.cpp

Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -469,5 +469,160 @@
 return (a -= a);
   }
   static_assert(subAll(213) == 0, "");
+
+  constexpr bool BoolOr(bool b1, bool b2) {
+bool a;
+a = b1;
+a |= b2;
+return a;
+  }
+  static_assert(BoolOr(true, true), "");
+  static_assert(BoolOr(true, false), "");
+  static_assert(BoolOr(false, true), "");
+  static_assert(!BoolOr(false, false), "");
+
+  constexpr int IntOr(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r |= b;
+return r;
+  }
+  static_assert(IntOr(10, 1) == 11, "");
+  static_assert(IntOr(1337, -1) == -1, "");
+  static_assert(IntOr(0, 12) == 12, "");
+
+  constexpr bool BoolAnd(bool b1, bool b2) {
+bool a;
+a = b1;
+a &= b2;
+return a;
+  }
+  static_assert(BoolAnd(true, true), "");
+  static_assert(!BoolAnd(true, false), "");
+  static_assert(!BoolAnd(false, true), "");
+  static_assert(!BoolAnd(false, false), "");
+
+  constexpr int IntAnd(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r &= b;
+return r;
+  }
+  static_assert(IntAnd(10, 1) == 0, "");
+  static_assert(IntAnd(1337, -1) == 1337, "");
+  static_assert(IntAnd(0, 12) == 0, "");
+
+  constexpr bool BoolXor(bool b1, bool b2) {
+bool a;
+a = b1;
+a ^= b2;
+return a;
+  }
+  static_assert(!BoolXor(true, true), "");
+  static_assert(BoolXor(true, false), "");
+  static_assert(BoolXor(false, true), "");
+  static_assert(!BoolXor(false, false), "");
+
+  constexpr int IntXor(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r ^= b;
+return r;
+  }
+  static_assert(IntXor(10, 1) == 11, "");
+  static_assert(IntXor(10, 10) == 0, "");
+  static_assert(IntXor(12, true) == 13, "");
+
+  constexpr bool BoolRem(bool b1, bool b2) {
+bool a;
+a = b1;
+a %= b2;
+return a;
+  }
+  static_assert(!BoolRem(true, true), "");
+  static_assert(!BoolRem(false, true), "");
+
+  constexpr int IntRem(int a, int b) {
+int r;
+r = a;
+r %= b; // expected-note {{division by zero}} \
+// ref-note {{division by zero}} \
+// expected-note {{outside the range of representable values}} \
+// ref-note {{outside the range of representable values}}
+return r;
+  }
+  static_assert(IntRem(2, 2) == 0, "");
+  static_assert(IntRem(2, 1) == 0, "");
+  static_assert(IntRem(9, 7) == 2, "");
+  static_assert(IntRem(5, 0) == 0, ""); // expected-error {{not an integral constant expression}} \
+// expected-note {{in call to 'IntRem(5, 0)'}} \
+// ref-error {{not an integral constant expression}} \
+// ref-note {{in call to 'IntRem(5, 0)'}}
+
+  static_assert(IntRem(INT_MIN, -1) == 0, ""); // expected-error {{not an integral constant expression}} \
+   // expected-note {{in call to 'IntRem}} \
+   // ref-error {{not an integral constant expression}} \
+   // ref-note {{in call to 'IntRem}}
+
+
+
+  constexpr bool BoolDiv(bool b1, bool b2) {
+bool a;
+a = b1;
+a /= b2;
+return a;
+  }
+  static_assert(BoolDiv(true, true), "");
+  static_assert(!BoolDiv(false, true), "");
+
+  constexpr int IntDiv(int a, int b) {
+int r;
+r = a;
+r /= b; // expected-note {{division by zero}} \
+// ref-note {{division by zero}} \
+// expected-note {{outside the range of representable values}} \
+// ref-note {{outside the range of representable values}}
+return r;
+  }
+  static_assert(IntDiv(2, 2) == 1, "");
+  static_assert(IntDiv(12, 20) == 0, "");
+  static_assert(IntDiv(2, 1) == 2, "");
+  static_assert(IntDiv(9, 7) == 1, "");
+  static_assert(IntDiv(5, 0) == 0, ""); // expected-error {{not an integral constant expression}} \
+// expected-note {{in call to 'IntDiv(5, 0)'}} \
+// ref-error {{not an integral constant expression}} \
+// ref-note {{in call to 'IntDiv(5, 0)'}}
+
+  static_assert(IntDiv(INT_MIN, -1) == 0, ""); // expected-error {{not an integral constant expression}} \
+   

[PATCH] D142101: [clang] [extract-api] Don't crash for category in libclang APIs

2023-01-19 Thread Daniel Grumberg via Phabricator via cfe-commits
dang created this revision.
dang added a reviewer: zixuw.
Herald added a subscriber: arphaman.
Herald added a reviewer: ributzka.
Herald added a project: All.
dang requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Remove failure conditions for categories in libclang and return empty
content instead.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D142101

Files:
  clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
  clang/test/Index/extract-api-cursor.m

Index: clang/test/Index/extract-api-cursor.m
===
--- clang/test/Index/extract-api-cursor.m
+++ clang/test/Index/extract-api-cursor.m
@@ -25,6 +25,12 @@
 - (void)derivedMethodWithValue:(id)value;
 @end
 
+/// This won't show up in docs because we can't serialize it
+@interface Derived ()
+/// Derived method in category docs, won't show up either.
+- (void)derivedMethodInCategory;
+@end
+
 // RUN: c-index-test -single-symbol-sgfs local %s | FileCheck %s
 
 // Checking for Foo
@@ -53,7 +59,7 @@
 
 // Checking for baseProperty
 // CHECK-NEXT: "parentContexts":[{"kind":"objective-c.class","name":"Base","usr":"c:objc(cs)Base"}]
-// CHECK-SAME:"relatedSymbols":[{"accessLevel":"public","declarationLanguage":"objective-c"
+// CHECK-SAME: "relatedSymbols":[{"accessLevel":"public","declarationLanguage":"objective-c"
 // CHECK-SAME: "isSystem":false
 // CHECK-SAME: "usr":"c:@S@Foo"}]
 // CHECK-SAME: "relationships":[{"kind":"memberOf","source":"c:objc(cs)Base(py)baseProperty","target":"c:objc(cs)Base"
@@ -63,7 +69,7 @@
 
 // Checking for baseMethodWithArg
 // CHECK-NEXT: "parentContexts":[{"kind":"objective-c.class","name":"Base","usr":"c:objc(cs)Base"}]
-// CHECK-SAME:"relatedSymbols":[]
+// CHECK-SAME: "relatedSymbols":[]
 // CHECK-SAME: "relationships":[{"kind":"memberOf","source":"c:objc(cs)Base(im)baseMethodWithArg:","target":"c:objc(cs)Base"
 // CHECK-SAME: "text":"Base method docs"
 // CHECK-SAME: "kind":{"displayName":"Instance Method","identifier":"objective-c.method"}
@@ -79,7 +85,7 @@
 
 // Checking for protocolProperty
 // CHECK-NEXT: "parentContexts":[{"kind":"objective-c.protocol","name":"Protocol","usr":"c:objc(pl)Protocol"}]
-// CHECK-SAME:"relatedSymbols":[{"accessLevel":"public","declarationLanguage":"objective-c"
+// CHECK-SAME: "relatedSymbols":[{"accessLevel":"public","declarationLanguage":"objective-c"
 // CHECK-SAME: "isSystem":false
 // CHECK-SAME: "usr":"c:@S@Foo"}]
 // CHECK-SAME: "relationships":[{"kind":"memberOf","source":"c:objc(pl)Protocol(py)protocolProperty","target":"c:objc(pl)Protocol"
@@ -89,7 +95,7 @@
 
 // Checking for Derived
 // CHECK-NEXT: "parentContexts":[]
-// CHECK-SAME:"relatedSymbols":[{"accessLevel":"public","declarationLanguage":"objective-c"
+// CHECK-SAME: "relatedSymbols":[{"accessLevel":"public","declarationLanguage":"objective-c"
 // CHECK-SAME: "isSystem":false
 // CHECK-SAME: "usr":"c:objc(cs)Base"}]
 // CHECK-SAME: "relationships":[{"kind":"inheritsFrom","source":"c:objc(cs)Derived","target":"c:objc(cs)Base"
@@ -99,8 +105,11 @@
 
 // Checking for derivedMethodWithValue
 // CHECK-NEXT: "parentContexts":[{"kind":"objective-c.class","name":"Derived","usr":"c:objc(cs)Derived"}]
-// CHECK-SAME:"relatedSymbols":[]
+// CHECK-SAME: "relatedSymbols":[]
 // CHECK-SAME: "relationships":[{"kind":"memberOf","source":"c:objc(cs)Derived(im)derivedMethodWithValue:","target":"c:objc(cs)Derived"
 // CHECK-SAME: "text":"Derived method docs"
 // CHECK-SAME: "kind":{"displayName":"Instance Method","identifier":"objective-c.method"}
 // CHECK-SAME: "title":"derivedMethodWithValue:"
+//
+// CHECK-NOT: This won't show up in docs because we can't serialize it
+// CHECK-NOT: Derived method in category docs, won't show up either.
Index: clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
===
--- clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
@@ -390,7 +390,7 @@
 break;
   case APIRecord::RK_ObjCCategory:
 // We don't serialize out standalone Objective-C category symbols yet.
-llvm_unreachable("Serializing standalone Objective-C category symbols is "
+llvm_unreachable("Serializing standalone Objective-C category symbols is"
  "not supported.");
 break;
   case APIRecord::RK_ObjCProtocol:
@@ -484,6 +484,7 @@
   SmallVector ReverseComponenents;
   ReverseComponenents.emplace_back(Record.USR, Record.Name, Record.getKind());
   const auto *CurrentParent = &Record.ParentInformation;
+  bool FailedToFindParent = false;
   while (CurrentParent && !CurrentParent->empty()) {
 PathComponent CurrentParentComponent(CurrentParent->ParentUSR,
  CurrentParent->ParentName,
@@ -506,8 +507,10 @@
 
 // The parent record doesn't exist which means the symbol shouldn't be
 //

[clang] 2dbcfd2 - Revert "[clang][Interp][NFC] Move CheckDivRem() implementation into Interp.cpp"

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T12:37:20+01:00
New Revision: 2dbcfd298f7cb1454ca16f544b7df980ec8fc17d

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

LOG: Revert "[clang][Interp][NFC] Move CheckDivRem() implementation into 
Interp.cpp"

This reverts commit 9ee0d7494eb35f5addefcb730cdf5c002ddeacd2.

Added: 


Modified: 
clang/lib/AST/Interp/Interp.cpp
clang/lib/AST/Interp/Interp.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index d7195148d015..76ade4401e08 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -422,26 +422,6 @@ bool CheckShift(InterpState &S, CodePtr OpPC, const RT 
&RHS, unsigned Bits) {
   return true;
 }
 
-template 
-bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS) {
-  if (RHS.isZero()) {
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.FFDiag(Loc, diag::note_expr_divide_by_zero);
-return false;
-  }
-
-  if (LHS.isSigned() && LHS.isMin() && RHS.isNegative() && RHS.isMinusOne()) {
-APSInt LHSInt = LHS.toAPSInt();
-SmallString<32> Trunc;
-(-LHSInt.extend(LHSInt.getBitWidth() + 1)).toString(Trunc, 10);
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-const Expr *E = S.Current->getExpr(OpPC);
-S.CCEDiag(Loc, diag::note_constexpr_overflow) << Trunc << E->getType();
-return false;
-  }
-  return true;
-}
-
 static void DiagnoseUninitializedSubobject(InterpState &S, const SourceInfo 
&SI,
QualType SubObjType,
SourceLocation SubObjLoc) {

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 3fa977d4a02e..903c68f4511c 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -100,7 +100,24 @@ bool CheckShift(InterpState &S, CodePtr OpPC, const RT 
&RHS, unsigned Bits);
 
 /// Checks if Div/Rem operation on LHS and RHS is valid.
 template 
-bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS);
+bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS) {
+  if (RHS.isZero()) {
+const SourceInfo &Loc = S.Current->getSource(OpPC);
+S.FFDiag(Loc, diag::note_expr_divide_by_zero);
+return false;
+  }
+
+  if (LHS.isSigned() && LHS.isMin() && RHS.isNegative() && RHS.isMinusOne()) {
+APSInt LHSInt = LHS.toAPSInt();
+SmallString<32> Trunc;
+(-LHSInt.extend(LHSInt.getBitWidth() + 1)).toString(Trunc, 10);
+const SourceInfo &Loc = S.Current->getSource(OpPC);
+const Expr *E = S.Current->getExpr(OpPC);
+S.CCEDiag(Loc, diag::note_constexpr_overflow) << Trunc << E->getType();
+return false;
+  }
+  return true;
+}
 
 /// Interpreter entry point.
 bool Interpret(InterpState &S, APValue &Result);



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


[PATCH] D142101: [clang] [extract-api] Don't crash for category in libclang APIs

2023-01-19 Thread Daniel Grumberg via Phabricator via cfe-commits
dang updated this revision to Diff 490447.
dang added a comment.

Formatting fixes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142101

Files:
  clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
  clang/test/Index/extract-api-cursor.m

Index: clang/test/Index/extract-api-cursor.m
===
--- clang/test/Index/extract-api-cursor.m
+++ clang/test/Index/extract-api-cursor.m
@@ -25,6 +25,12 @@
 - (void)derivedMethodWithValue:(id)value;
 @end
 
+/// This won't show up in docs because we can't serialize it
+@interface Derived ()
+/// Derived method in category docs, won't show up either.
+- (void)derivedMethodInCategory;
+@end
+
 // RUN: c-index-test -single-symbol-sgfs local %s | FileCheck %s
 
 // Checking for Foo
@@ -53,7 +59,7 @@
 
 // Checking for baseProperty
 // CHECK-NEXT: "parentContexts":[{"kind":"objective-c.class","name":"Base","usr":"c:objc(cs)Base"}]
-// CHECK-SAME:"relatedSymbols":[{"accessLevel":"public","declarationLanguage":"objective-c"
+// CHECK-SAME: "relatedSymbols":[{"accessLevel":"public","declarationLanguage":"objective-c"
 // CHECK-SAME: "isSystem":false
 // CHECK-SAME: "usr":"c:@S@Foo"}]
 // CHECK-SAME: "relationships":[{"kind":"memberOf","source":"c:objc(cs)Base(py)baseProperty","target":"c:objc(cs)Base"
@@ -63,7 +69,7 @@
 
 // Checking for baseMethodWithArg
 // CHECK-NEXT: "parentContexts":[{"kind":"objective-c.class","name":"Base","usr":"c:objc(cs)Base"}]
-// CHECK-SAME:"relatedSymbols":[]
+// CHECK-SAME: "relatedSymbols":[]
 // CHECK-SAME: "relationships":[{"kind":"memberOf","source":"c:objc(cs)Base(im)baseMethodWithArg:","target":"c:objc(cs)Base"
 // CHECK-SAME: "text":"Base method docs"
 // CHECK-SAME: "kind":{"displayName":"Instance Method","identifier":"objective-c.method"}
@@ -79,7 +85,7 @@
 
 // Checking for protocolProperty
 // CHECK-NEXT: "parentContexts":[{"kind":"objective-c.protocol","name":"Protocol","usr":"c:objc(pl)Protocol"}]
-// CHECK-SAME:"relatedSymbols":[{"accessLevel":"public","declarationLanguage":"objective-c"
+// CHECK-SAME: "relatedSymbols":[{"accessLevel":"public","declarationLanguage":"objective-c"
 // CHECK-SAME: "isSystem":false
 // CHECK-SAME: "usr":"c:@S@Foo"}]
 // CHECK-SAME: "relationships":[{"kind":"memberOf","source":"c:objc(pl)Protocol(py)protocolProperty","target":"c:objc(pl)Protocol"
@@ -89,7 +95,7 @@
 
 // Checking for Derived
 // CHECK-NEXT: "parentContexts":[]
-// CHECK-SAME:"relatedSymbols":[{"accessLevel":"public","declarationLanguage":"objective-c"
+// CHECK-SAME: "relatedSymbols":[{"accessLevel":"public","declarationLanguage":"objective-c"
 // CHECK-SAME: "isSystem":false
 // CHECK-SAME: "usr":"c:objc(cs)Base"}]
 // CHECK-SAME: "relationships":[{"kind":"inheritsFrom","source":"c:objc(cs)Derived","target":"c:objc(cs)Base"
@@ -99,8 +105,11 @@
 
 // Checking for derivedMethodWithValue
 // CHECK-NEXT: "parentContexts":[{"kind":"objective-c.class","name":"Derived","usr":"c:objc(cs)Derived"}]
-// CHECK-SAME:"relatedSymbols":[]
+// CHECK-SAME: "relatedSymbols":[]
 // CHECK-SAME: "relationships":[{"kind":"memberOf","source":"c:objc(cs)Derived(im)derivedMethodWithValue:","target":"c:objc(cs)Derived"
 // CHECK-SAME: "text":"Derived method docs"
 // CHECK-SAME: "kind":{"displayName":"Instance Method","identifier":"objective-c.method"}
 // CHECK-SAME: "title":"derivedMethodWithValue:"
+
+// CHECK-NOT: This won't show up in docs because we can't serialize it
+// CHECK-NOT: Derived method in category docs, won't show up either.
Index: clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
===
--- clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
@@ -484,6 +484,7 @@
   SmallVector ReverseComponenents;
   ReverseComponenents.emplace_back(Record.USR, Record.Name, Record.getKind());
   const auto *CurrentParent = &Record.ParentInformation;
+  bool FailedToFindParent = false;
   while (CurrentParent && !CurrentParent->empty()) {
 PathComponent CurrentParentComponent(CurrentParent->ParentUSR,
  CurrentParent->ParentName,
@@ -506,8 +507,10 @@
 
 // The parent record doesn't exist which means the symbol shouldn't be
 // treated as part of the current product.
-if (!ParentRecord)
-  return true;
+if (!ParentRecord) {
+  FailedToFindParent = true;
+  break;
+}
 
 ReverseComponenents.push_back(std::move(CurrentParentComponent));
 CurrentParent = &ParentRecord->ParentInformation;
@@ -516,8 +519,9 @@
   for (const auto &PC : reverse(ReverseComponenents))
 ComponentTransformer(PC);
 
-  return false;
+  return FailedToFindParent;
 }
+
 Object serializeParentContext(const PathComponent &PC, Language Lang) {
   Object ParentContextElem;
   ParentContextElem["usr"] = PC.USR;
@@ -530,

[PATCH] D141283: [clang] Improve diagnostic for "initializer-string for char array is too long"

2023-01-19 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

AFAIK we need a name and an email address so the commit can be attributed 
properly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141283

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


[PATCH] D141283: [clang] Improve diagnostic for "initializer-string for char array is too long"

2023-01-19 Thread Evan Smal via Phabricator via cfe-commits
evansmal added a comment.

In D141283#4065117 , @tbaeder wrote:

> AFAIK we need a name and an email address so the commit can be attributed 
> properly.

The commit can be attributed to Evan Smal 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141283

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


[clang] 85acfc6 - Revert "[clang][Interp][NFC] Remove shift error checking code duplication"

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T13:03:20+01:00
New Revision: 85acfc64257b133dcdc1d39f0ea07a0dc30a3656

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

LOG: Revert "[clang][Interp][NFC] Remove shift error checking code duplication"

This reverts commit fddf6418e8492a544c9bfdb42a4dbc949d9dc2ee.

Apparently this also breaks some builders:

/usr/bin/ld: 
EvalEmitter.cpp:(.text._ZN5clang6interp11EvalEmitter7emitShlENS0_8PrimTypeES2_RKNS0_10SourceInfoE+0x1f54):
 undefined reference to `bool 
clang::interp::CheckShift 
>(clang::interp::InterpState&, clang::interp::CodePtr, 
clang::interp::Integral<16u, true> const&, unsigned int)'
/usr/bin/ld: 
EvalEmitter.cpp:(.text._ZN5clang6interp11EvalEmitter7emitShlENS0_8PrimTypeES2_RKNS0_10SourceInfoE+0x1fd4):
 undefined reference to `bool 
clang::interp::CheckShift 
>(clang::interp::InterpState&, clang::interp::CodePtr, 
clang::interp::Integral<32u, true> const&, unsigned int)'
/usr/bin/ld: 
EvalEmitter.cpp:(.text._ZN5clang6interp11EvalEmitter7emitShlENS0_8PrimTypeES2_RKNS0_10SourceInfoE+0x2058):
 undefined reference to `bool 
clang::interp::CheckShift 
>(clang::interp::InterpState&, clang::interp::CodePtr, 
clang::interp::Integral<32u, true> const&, unsigned int)'

(etc)

Added: 


Modified: 
clang/lib/AST/Interp/Interp.cpp
clang/lib/AST/Interp/Interp.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 76ade4401e08..6a600b306bad 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -401,27 +401,6 @@ bool CheckPure(InterpState &S, CodePtr OpPC, const 
CXXMethodDecl *MD) {
   return false;
 }
 
-template 
-bool CheckShift(InterpState &S, CodePtr OpPC, const RT &RHS, unsigned Bits) {
-  if (RHS.isNegative()) {
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.CCEDiag(Loc, diag::note_constexpr_negative_shift) << RHS.toAPSInt();
-return false;
-  }
-
-  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
-  // the shifted type.
-  if (Bits > 1 && RHS >= RT::from(Bits, RHS.bitWidth())) {
-const Expr *E = S.Current->getExpr(OpPC);
-const APSInt Val = RHS.toAPSInt();
-QualType Ty = E->getType();
-S.CCEDiag(E, diag::note_constexpr_large_shift) << Val << Ty << Bits;
-return false;
-  }
-
-  return true;
-}
-
 static void DiagnoseUninitializedSubobject(InterpState &S, const SourceInfo 
&SI,
QualType SubObjType,
SourceLocation SubObjLoc) {

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 903c68f4511c..65a49f21c5dc 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -94,10 +94,6 @@ bool CheckPure(InterpState &S, CodePtr OpPC, const 
CXXMethodDecl *MD);
 /// Checks that all fields are initialized after a constructor call.
 bool CheckCtorCall(InterpState &S, CodePtr OpPC, const Pointer &This);
 
-/// Checks if the shift operation is legal.
-template 
-bool CheckShift(InterpState &S, CodePtr OpPC, const RT &RHS, unsigned Bits);
-
 /// Checks if Div/Rem operation on LHS and RHS is valid.
 template 
 bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS) {
@@ -1184,8 +1180,21 @@ inline bool Shr(InterpState &S, CodePtr OpPC) {
   const auto &LHS = S.Stk.pop();
   const unsigned Bits = LHS.bitWidth();
 
-  if (!CheckShift(S, OpPC, RHS, Bits))
+  if (RHS.isNegative()) {
+const SourceInfo &Loc = S.Current->getSource(OpPC);
+S.CCEDiag(Loc, diag::note_constexpr_negative_shift) << RHS.toAPSInt();
 return false;
+  }
+
+  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
+  // the shifted type.
+  if (Bits > 1 && RHS >= RT::from(Bits, RHS.bitWidth())) {
+const Expr *E = S.Current->getExpr(OpPC);
+const APSInt Val = RHS.toAPSInt();
+QualType Ty = E->getType();
+S.CCEDiag(E, diag::note_constexpr_large_shift) << Val << Ty << Bits;
+return false;
+  }
 
   unsigned URHS = static_cast(RHS);
   S.Stk.push(LT::from(static_cast(LHS) >> URHS, LHS.bitWidth()));
@@ -1200,8 +1209,21 @@ inline bool Shl(InterpState &S, CodePtr OpPC) {
   const auto &LHS = S.Stk.pop();
   const unsigned Bits = LHS.bitWidth();
 
-  if (!CheckShift(S, OpPC, RHS, Bits))
+  if (RHS.isNegative()) {
+const SourceInfo &Loc = S.Current->getSource(OpPC);
+S.CCEDiag(Loc, diag::note_constexpr_negative_shift) << RHS.toAPSInt();
+return false;
+  }
+
+  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
+  // the shifted type.
+  if (Bits > 1 && RHS >= RT::from(Bits, RHS.bitWidth())) {
+const Expr *E = S.Current->getExpr(OpPC);
+const APSInt Val = RHS.toAPSInt();
+QualType Ty = E->getType();
+S.C

[PATCH] D140875: [clangd] prototype: Implement unused include warnings with include-cleaner library.

2023-01-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 490452.
hokein marked 3 inline comments as done.
hokein added a comment.

address comments:

- rename to computeUnusedIncludesExperimental
- use PragmaInclude from preamble, limit the scope of the patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140875

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/ParsedAST.h
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -342,6 +342,8 @@
   auto AST = TU.build();
   EXPECT_THAT(computeUnusedIncludes(AST),
   ElementsAre(Pointee(writtenInclusion("";
+  EXPECT_THAT(computeUnusedIncludesExperimental(AST),
+  ElementsAre(Pointee(writtenInclusion("";
 }
 
 TEST(IncludeCleaner, GetUnusedHeaders) {
@@ -377,6 +379,10 @@
   computeUnusedIncludes(AST),
   UnorderedElementsAre(Pointee(writtenInclusion("\"unused.h\"")),
Pointee(writtenInclusion("\"dir/unused.h\"";
+  EXPECT_THAT(
+  computeUnusedIncludesExperimental(AST),
+  UnorderedElementsAre(Pointee(writtenInclusion("\"unused.h\"")),
+   Pointee(writtenInclusion("\"dir/unused.h\"";
 }
 
 TEST(IncludeCleaner, VirtualBuffers) {
@@ -531,6 +537,9 @@
 // IWYU pragma: private, include "public.h"
 void foo() {}
   )cpp");
+  Config Cfg;
+  Cfg.Diagnostics.UnusedIncludes = Config::Experiment;
+  WithContextValue Ctx(Config::Key, std::move(Cfg));
   ParsedAST AST = TU.build();
 
   auto ReferencedFiles = findReferencedFiles(
@@ -545,6 +554,7 @@
   ReferencedFiles.User.contains(AST.getSourceManager().getMainFileID()));
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
   EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
+  EXPECT_THAT(computeUnusedIncludesExperimental(AST), IsEmpty());
 }
 
 TEST(IncludeCleaner, RecursiveInclusion) {
@@ -573,6 +583,7 @@
 
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
   EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
+  EXPECT_THAT(computeUnusedIncludesExperimental(AST), IsEmpty());
 }
 
 TEST(IncludeCleaner, IWYUPragmaExport) {
@@ -597,6 +608,7 @@
   // FIXME: This is not correct: foo.h is unused but is not diagnosed as such
   // because we ignore headers with IWYU export pragmas for now.
   EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
+  EXPECT_THAT(computeUnusedIncludesExperimental(AST), IsEmpty());
 }
 
 TEST(IncludeCleaner, NoDiagsForObjC) {
Index: clang-tools-extra/clangd/Preamble.h
===
--- clang-tools-extra/clangd/Preamble.h
+++ clang-tools-extra/clangd/Preamble.h
@@ -27,6 +27,7 @@
 #include "Diagnostics.h"
 #include "FS.h"
 #include "Headers.h"
+#include "clang-include-cleaner/Record.h"
 #include "index/CanonicalIncludes.h"
 #include "support/Path.h"
 #include "clang/Frontend/CompilerInvocation.h"
@@ -57,6 +58,8 @@
   // Processes like code completions and go-to-definitions will need #include
   // information, and their compile action skips preamble range.
   IncludeStructure Includes;
+  // Captures #include-mapping information in #included headers.
+  include_cleaner::PragmaIncludes Pragmas;
   // Macros defined in the preamble section of the main file.
   // Users care about headers vs main-file, not preamble vs non-preamble.
   // These should be treated as main-file entities e.g. for code completion.
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -11,6 +11,7 @@
 #include "Config.h"
 #include "Headers.h"
 #include "SourceCode.h"
+#include "clang-include-cleaner/Record.h"
 #include "support/Logger.h"
 #include "support/ThreadsafeFS.h"
 #include "support/Trace.h"
@@ -77,6 +78,9 @@
 
   std::vector takeMarks() { return std::move(Marks); }
 
+  include_cleaner::PragmaIncludes takePragmaIncludes() {
+return std::move(Pragmas);
+  }
   CanonicalIncludes takeCanonicalIncludes() { return std::move(CanonIncludes); }
 
   bool isMainFileIncludeGuarded() const { return IsMainFileIncludeGuarded; }
@@ -118,6 +122,9 @@
 LangOpts = &CI.getLangOpts();
 SourceMgr = &CI.getSourceManager();
 Includes.collect(CI);
+if (Config::current().Diagnostics.UnusedIncludes ==
+Config::UnusedIncludesPolicy::

[PATCH] D140875: [clangd] prototype: Implement unused include warnings with include-cleaner library.

2023-01-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/ParsedAST.cpp:609
+  Config::UnusedIncludesPolicy::Experiment)
+Pragmas.record(*Clang);
   // Copy over the macros in the preamble region of the main file, and combine

kadircet wrote:
> hokein wrote:
> > kadircet wrote:
> > > why do we need to collect pragmas in main file? i think we already have 
> > > necessary information available via `IncludeStructure` (it stores keeps 
> > > and exports, and we don't care about anything else in the main file 
> > > AFAICT). so let's just use the PragmaIncludes we're getting from the 
> > > Preamble directly? without even making a copy and returning a reference 
> > > from the `Preamble` instead in `ParsedAST::getPragmaIncludes`
> > > i think we already have necessary information available via 
> > > IncludeStructure (it stores keeps and exports, and we don't care about 
> > > anything else in the main file AFAICT)
> > 
> > The IncludeStructure doesn't have a full support for IWYU export pragma, it 
> > only tracks the headers that have the export pragma.
> > 
> > My understand of the end goal is to use the `PragmaInclude` to handle every 
> > IWYU-related things, and we can remove all these IWYU bits in the 
> > `IncludeStructure`,  clangd IWYU pragma handling 
> > [code](https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/clangd/Headers.cpp#L127-L166).
> > The IncludeStructure doesn't have a full support for IWYU export pragma, it 
> > only tracks the headers that have the export pragma.
> 
> And I think that's all we need for IWYU pragmas inside the main file (as main 
> file is a leaf and exporting headers from it doesn't change anything apart 
> from making sure we keep them around)
> 
> > My understand of the end goal is to use the PragmaInclude to handle every 
> > IWYU-related things, and we can remove all these IWYU bits in the 
> > IncludeStructure, clangd IWYU pragma handling code.
> 
> Yes, I agree with some version of that, but until then this is introducing 
> some extra changes (+ copying around more information in every AST build). So 
> can we leave this piece out of the initial patch and just use the 
> PragmaInclude we have from Preamble without copying it around?
> Yes, I agree with some version of that, but until then this is introducing 
> some extra changes (+ copying around more information in every AST build). So 
> can we leave this piece out of the initial patch and just use the 
> PragmaInclude we have from Preamble without copying it around?

Sure, that sounds a good plan, and have a better narrowed scope of the patch. 



Comment at: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp:345
   auto Unused = computeUnusedIncludes(AST);
   EXPECT_THAT(Unused, ElementsAre(Pointee(writtenInclusion("";
+  EXPECT_THAT(computeUnusedIncludesNew(AST),

kadircet wrote:
> can you inline the call to `computeUnusedIncludes` into the EXPECT statement 
> here?
sure, since this is not directly related to this patch, addressed in 
ccb67491f0dd55c5bd8ed5f71cb802422bfaa969.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140875

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


[PATCH] D141280: [clang] Build UsingType for elaborated type specifiers.

2023-01-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 490455.
hokein added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141280

Files:
  clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
  clang/include/clang/Sema/DeclSpec.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CXX/drs/dr2xx.cpp
  clang/test/CXX/drs/dr4xx.cpp

Index: clang/test/CXX/drs/dr4xx.cpp
===
--- clang/test/CXX/drs/dr4xx.cpp
+++ clang/test/CXX/drs/dr4xx.cpp
@@ -301,9 +301,8 @@
 struct F;
 struct H;
   }
-  // FIXME: This is ill-formed.
   using N::D;
-  struct dr417::D {}; // expected-warning {{extra qualification}}
+  struct dr417::D {}; // expected-error {{forward declaration of struct cannot}} expected-warning {{extra qualification}}
   using namespace N;
   struct dr417::E {}; // expected-warning {{extra qualification}} expected-error {{no struct named 'E'}}
   struct N::F {};
Index: clang/test/CXX/drs/dr2xx.cpp
===
--- clang/test/CXX/drs/dr2xx.cpp
+++ clang/test/CXX/drs/dr2xx.cpp
@@ -992,7 +992,7 @@
   }
   struct B::V {}; // expected-error {{no struct named 'V'}}
   struct B::W {};
-  struct B::X {}; // FIXME: ill-formed
+  struct B::X {}; // expected-error {{forward declaration of struct cannot have}}
   enum B::Y e; // ok per dr417
   class B::Z z; // ok per dr417
 
@@ -1009,7 +1009,7 @@
   };
   struct D::V {}; // expected-error {{no struct named 'V'}}
   struct D::W {};
-  struct D::X {}; // FIXME: ill-formed
+  struct D::X {}; // expected-error {{forward declaration of struct cannot have}}
   enum D::Y e2; // ok per dr417
   class D::Z z2; // ok per dr417
 }
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -1588,6 +1588,9 @@
 
 // TypeQuals handled by caller.
 Result = Context.getTypeDeclType(D);
+if (const auto *Using =
+dyn_cast_or_null(DS.getRepAsFoundDecl()))
+  Result = Context.getUsingType(Using, Result);
 
 // In both C and C++, make an ElaboratedType.
 ElaboratedTypeKeyword Keyword
Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -10181,11 +10181,14 @@
 
   bool Owned = false;
   bool IsDependent = false;
-  Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name,
-   NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
+  UsingShadowDecl* FoundUsing = nullptr;
+  Decl *TagD =
+  ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name, NameLoc, Attr,
+   AS_none, /*ModulePrivateLoc=*/SourceLocation(),
MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
false, TypeResult(), /*IsTypeSpecifier*/ false,
-   /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get();
+   /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside, FoundUsing)
+  .get();
   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
 
   if (!TagD)
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -16972,6 +16972,7 @@
 if (SS.isEmpty()) {
   bool Owned = false;
   bool IsDependent = false;
+  UsingShadowDecl* FoundUsing = nullptr;
   return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr,
   AS_public,
   /*ModulePrivateLoc=*/SourceLocation(),
@@ -16980,7 +16981,7 @@
   /*ScopedEnumUsesClassTag=*/false,
   /*UnderlyingType=*/TypeResult(),
   /*IsTypeSpecifier=*/false,
-  /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
+  /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside, FoundUsing);
 }
 
 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -16592,7 +16592,8 @@
bool &IsDependent, SourceLocation ScopedEnumKWLoc,
bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
bool IsTypeSpecifier, bool IsTemplateParamOrArg,
-   OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
+   OffsetOfKind OOK, UsingShadowDecl *&FoundUsingShadow,
+ 

[clang] 1499cce - [clang] Improve diagnostic for "initializer-string for char array is too long"

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Evan Smal
Date: 2023-01-19T13:13:08+01:00
New Revision: 1499cce2646cbf4dd78f8534a4e71bd856b10994

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

LOG: [clang] Improve diagnostic for "initializer-string for char array is too 
long"

This patch improves the diagnostic message "initializer-string for
char array is too long" by specifying an expected array length and by
indicating that the initializer string implicitly includes the
null terminator.

Fixes #58829

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

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaInit.cpp
clang/test/CXX/dcl.decl/dcl.init/dcl.init.string/p2.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 2ba52728e9485..69ec2032dcefd 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5965,7 +5965,7 @@ def ext_excess_initializers_in_char_array_initializer : 
ExtWarn<
   "excess elements in char array initializer">,
   InGroup;
 def err_initializer_string_for_char_array_too_long : Error<
-  "initializer-string for char array is too long">;
+  "initializer-string for char array is too long, array size is %0 but 
initializer has size %1 (including the null terminating character)">;
 def ext_initializer_string_for_char_array_too_long : ExtWarn<
   "initializer-string for char array is too long">,
   InGroup;

diff  --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 3597a3147308a..ddb2b5cf5cd16 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -239,6 +239,7 @@ static void CheckStringInit(Expr *Str, QualType &DeclT, 
const ArrayType *AT,
 if (StrLength > CAT->getSize().getZExtValue())
   S.Diag(Str->getBeginLoc(),
  diag::err_initializer_string_for_char_array_too_long)
+  << CAT->getSize().getZExtValue() << StrLength
   << Str->getSourceRange();
   } else {
 // C99 6.7.8p14.

diff  --git a/clang/test/CXX/dcl.decl/dcl.init/dcl.init.string/p2.cpp 
b/clang/test/CXX/dcl.decl/dcl.init/dcl.init.string/p2.cpp
index 3d67fccb42821..8436361f0eb79 100644
--- a/clang/test/CXX/dcl.decl/dcl.init/dcl.init.string/p2.cpp
+++ b/clang/test/CXX/dcl.decl/dcl.init/dcl.init.string/p2.cpp
@@ -1,2 +1,3 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
-char test1[1]="f"; // expected-error {{initializer-string for char array is 
too long}}
+char test1[1]="f"; // expected-error {{initializer-string for char array is 
too long, array size is 1 but initializer has size 2 (including the null 
terminating character)}}
+char test2[1]="";



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


[PATCH] D141283: [clang] Improve diagnostic for "initializer-string for char array is too long"

2023-01-19 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 rG1499cce2646c: [clang] Improve diagnostic for 
"initializer-string for char array is too long" (authored by 
evansmal, committed by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D141283?vs=488012&id=490456#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141283

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaInit.cpp
  clang/test/CXX/dcl.decl/dcl.init/dcl.init.string/p2.cpp


Index: clang/test/CXX/dcl.decl/dcl.init/dcl.init.string/p2.cpp
===
--- clang/test/CXX/dcl.decl/dcl.init/dcl.init.string/p2.cpp
+++ clang/test/CXX/dcl.decl/dcl.init/dcl.init.string/p2.cpp
@@ -1,2 +1,3 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
-char test1[1]="f"; // expected-error {{initializer-string for char array is 
too long}}
+char test1[1]="f"; // expected-error {{initializer-string for char array is 
too long, array size is 1 but initializer has size 2 (including the null 
terminating character)}}
+char test2[1]="";
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -239,6 +239,7 @@
 if (StrLength > CAT->getSize().getZExtValue())
   S.Diag(Str->getBeginLoc(),
  diag::err_initializer_string_for_char_array_too_long)
+  << CAT->getSize().getZExtValue() << StrLength
   << Str->getSourceRange();
   } else {
 // C99 6.7.8p14.
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5965,7 +5965,7 @@
   "excess elements in char array initializer">,
   InGroup;
 def err_initializer_string_for_char_array_too_long : Error<
-  "initializer-string for char array is too long">;
+  "initializer-string for char array is too long, array size is %0 but 
initializer has size %1 (including the null terminating character)">;
 def ext_initializer_string_for_char_array_too_long : ExtWarn<
   "initializer-string for char array is too long">,
   InGroup;


Index: clang/test/CXX/dcl.decl/dcl.init/dcl.init.string/p2.cpp
===
--- clang/test/CXX/dcl.decl/dcl.init/dcl.init.string/p2.cpp
+++ clang/test/CXX/dcl.decl/dcl.init/dcl.init.string/p2.cpp
@@ -1,2 +1,3 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
-char test1[1]="f"; // expected-error {{initializer-string for char array is too long}}
+char test1[1]="f"; // expected-error {{initializer-string for char array is too long, array size is 1 but initializer has size 2 (including the null terminating character)}}
+char test2[1]="";
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -239,6 +239,7 @@
 if (StrLength > CAT->getSize().getZExtValue())
   S.Diag(Str->getBeginLoc(),
  diag::err_initializer_string_for_char_array_too_long)
+  << CAT->getSize().getZExtValue() << StrLength
   << Str->getSourceRange();
   } else {
 // C99 6.7.8p14.
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5965,7 +5965,7 @@
   "excess elements in char array initializer">,
   InGroup;
 def err_initializer_string_for_char_array_too_long : Error<
-  "initializer-string for char array is too long">;
+  "initializer-string for char array is too long, array size is %0 but initializer has size %1 (including the null terminating character)">;
 def ext_initializer_string_for_char_array_too_long : ExtWarn<
   "initializer-string for char array is too long">,
   InGroup;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D139926: [clangd] Add semantic token for angle brackets

2023-01-19 Thread Christian Kandeler via Phabricator via cfe-commits
ckandeler updated this revision to Diff 490457.
ckandeler marked 2 inline comments as done.
ckandeler added a comment.

Made token name more generic, added test cases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139926

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SemanticHighlighting.h
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -130,17 +130,17 @@
 )cpp",
   R"cpp(
   namespace $Namespace_decl[[abc]] {
-template
+template$Bracket[[<]]typename $TemplateParameter_def[[T]]$Bracket[[>]]
 struct $Class_def[[A]] {
   $TemplateParameter[[T]] $Field_decl[[t]];
 };
   }
-  template
-  struct $Class_def[[C]] : $Namespace[[abc]]::$Class[[A]]<$TemplateParameter[[T]]> {
+  template$Bracket[[<]]typename $TemplateParameter_def[[T]]$Bracket[[>]]
+  struct $Class_def[[C]] : $Namespace[[abc]]::$Class[[A]]$Bracket[[<]]$TemplateParameter[[T]]$Bracket[[>]] {
 typename $TemplateParameter[[T]]::$Type_dependentName[[A]]* $Field_decl[[D]];
   };
-  $Namespace[[abc]]::$Class[[A]] $Variable_def[[AA]];
-  typedef $Namespace[[abc]]::$Class[[A]] $Class_decl[[AAA]];
+  $Namespace[[abc]]::$Class[[A]]$Bracket[[<]]int$Bracket[[>]] $Variable_def[[AA]];
+  typedef $Namespace[[abc]]::$Class[[A]]$Bracket[[<]]int$Bracket[[>]] $Class_decl[[AAA]];
   struct $Class_def[[B]] {
 $Class_decl_constrDestr[[B]]();
 ~$Class_decl_constrDestr[[B]]();
@@ -243,36 +243,36 @@
   typedef float $Primitive_decl[[F]];
 )cpp",
   R"cpp(
-  template
+  template$Bracket[[<]]typename $TemplateParameter_def[[T]], typename = void$Bracket[[>]]
   class $Class_def[[A]] {
 $TemplateParameter[[T]] $Field_decl[[AA]];
 $TemplateParameter[[T]] $Method_decl[[foo]]();
   };
-  template
+  template$Bracket[[<]]class $TemplateParameter_def[[TT]]$Bracket[[>]]
   class $Class_def[[B]] {
-$Class[[A]]<$TemplateParameter[[TT]]> $Field_decl[[AA]];
+$Class[[A]]$Bracket[[<]]$TemplateParameter[[TT]]$Bracket[[>]] $Field_decl[[AA]];
   };
-  template
+  template$Bracket[[<]]class $TemplateParameter_def[[TT]], class $TemplateParameter_def[[GG]]$Bracket[[>]]
   class $Class_def[[BB]] {};
   template
   class $Class_def[[BB]]<$TemplateParameter[[T]], int> {};
   template
   class $Class_def[[BB]]<$TemplateParameter[[T]], $TemplateParameter[[T]]*> {};
 
-  template class $TemplateParameter_def[[T]], class $TemplateParameter_def[[C]]>
-  $TemplateParameter[[T]]<$TemplateParameter[[C]]> $Function_decl[[f]]();
+  template$Bracket[[<]]template$Bracket[[<]]class$Bracket[[>]] class $TemplateParameter_def[[T]], class $TemplateParameter_def[[C]]$Bracket[[>]]
+  $TemplateParameter[[T]]$Bracket[[<]]$TemplateParameter[[C]]$Bracket[[>]] $Function_decl[[f]]();
 
-  template
+  template$Bracket[[<]]typename$Bracket[[>]]
   class $Class_def[[Foo]] {};
 
-  template
+  template$Bracket[[<]]typename $TemplateParameter_def[[T]]$Bracket[[>]]
   void $Function_decl[[foo]]($TemplateParameter[[T]] ...);
 )cpp",
   R"cpp(
-  template 
+  template $Bracket[[<]]class $TemplateParameter_def[[T]]$Bracket[[>]]
   struct $Class_def[[Tmpl]] {$TemplateParameter[[T]] $Field_decl[[x]] = 0;};
-  extern template struct $Class_def[[Tmpl]];
-  template struct $Class_def[[Tmpl]];
+  extern template struct $Class_def[[Tmpl]]$Bracket[[<]]float$Bracket[[>]];
+  template struct $Class_def[[Tmpl]]$Bracket[[<]]double$Bracket[[>]];
 )cpp",
   // This test is to guard against highlightings disappearing when using
   // conversion operators as their behaviour in the clang AST differ from
@@ -335,17 +335,17 @@
 )cpp",
   R"cpp(
   class $Class_def[[G]] {};
-  template<$Class[[G]] *$TemplateParameter_def_readonly[[U]]>
+  template$Bracket[[<]]$Class[[G]] *$TemplateParameter_def_readonly[[U]]$Bracket[[>]]
   class $Class_def[[GP]] {};
-  template<$Class[[G]] &$TemplateParameter_def_readonly[[U]]>
+  template$Bracket[[<]]$Class[[G]] &$TemplateParameter_def_readonly[[U]]$Bracket[[>]]
   class $Class_def[[GR]] {};
-  template
+  template$Bracket[[<]]int *$TemplateParameter_def_readonly[[U]]$Bracket[[>]]
   class $Class_def[[IP]] {
 void $Method_def[[f]]() {
   $Operator[[*]]$TemplateParameter_readonly[[U]] $Operator[[+=]] 5;
 }
   };
-  template
+  template$Bracket[[<]]unsigned $TemplateParameter_def_readonly[[U]] = 2$Bracket[[>]]

[PATCH] D139926: [clangd] Add semantic token for angle brackets

2023-01-19 Thread Christian Kandeler via Phabricator via cfe-commits
ckandeler added a comment.

In D139926#4064769 , @kadircet wrote:

>> We can easily check the actual character at the given position in the 
>> client, so I could just merge the two highlighting kinds.
>
> Thanks! Note that it might not be as easy at the face of templates, eg:
>
>   #define LESS <
>   template LESS typename T > class A {};

At least this one doesn't seem to be an issue; added test case.




Comment at: clang-tools-extra/clangd/SemanticHighlighting.h:54
   Operator,
+  AngleBracket,
 

kadircet wrote:
> actually let's name these as `Bracket` rather than `AngleBracket`, as we 
> might want to increase the coverage further in the future (and a use case 
> such as yours can still look at the textual tokens to match relevant 
> brackets).
Yes, I was going to suggest this myself.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139926

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


[PATCH] D141283: [clang] Improve diagnostic for "initializer-string for char array is too long"

2023-01-19 Thread Evan Smal via Phabricator via cfe-commits
evansmal added a comment.

@tbaeder Thank you! :^)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141283

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


[PATCH] D142094: [Clang][Doc] Add release note for changes for the RVV intrinsics

2023-01-19 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD added a comment.

@asb I just saw the cancellation of the sync-up call today. Regarding the 
branch out on 01/24 I think it would be good to have these incompatible changes 
into LLVM 16.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142094

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


[PATCH] D137071: [clang][Interp] Implement missing compound assign operators

2023-01-19 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

Really didn't expect this: 
https://lab.llvm.org/buildbot/#/builders/214/builds/5415

  Command Output (stderr):
  --
  + : 'RUN: at line 1'
  + /scratch/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/bin/clang 
-cc1 -internal-isystem 
/scratch/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/lib/clang/16/include
 -nostdsysteminc -fexperimental-new-constant-interpreter -std=c++11 -verify 
/scratch/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/test/AST/Interp/literals.cpp
  + : 'RUN: at line 2'
  + /scratch/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/bin/clang 
-cc1 -internal-isystem 
/scratch/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/lib/clang/16/include
 -nostdsysteminc -fexperimental-new-constant-interpreter -std=c++20 -verify 
/scratch/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/test/AST/Interp/literals.cpp
  error: 'error' diagnostics seen but not expected: 
File 
/scratch/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/test/AST/Interp/literals.cpp
 Line 481: static assertion failed due to requirement 'BoolOr(false, true)': 
File 
/scratch/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/test/AST/Interp/literals.cpp
 Line 500: static assertion failed due to requirement 'BoolAnd(true, true)': 
File 
/scratch/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/test/AST/Interp/literals.cpp
 Line 521: static assertion failed due to requirement '!BoolXor(true, true)': 
File 
/scratch/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/test/AST/Interp/literals.cpp
 Line 523: static assertion failed due to requirement 'BoolXor(false, true)': 
  4 errors generated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137071

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


[PATCH] D140875: [clangd] prototype: Implement unused include warnings with include-cleaner library.

2023-01-19 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks!




Comment at: clang-tools-extra/clangd/ParsedAST.h:111
 
+  const include_cleaner::PragmaIncludes *getPragmaIncludes() const;
+

can you add a comment saying `might be null if AST is built without a preamble`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140875

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


[clang] 0f5a81c - [clang][Interp][NFC] Remove shift error checking code duplication

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T13:52:47+01:00
New Revision: 0f5a81cb445bb26769d68d3944b6af79072b0cd0

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

LOG: [clang][Interp][NFC] Remove shift error checking code duplication

Added: 


Modified: 
clang/lib/AST/Interp/Interp.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 65a49f21c5dc..338c35cb1835 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -94,6 +94,27 @@ bool CheckPure(InterpState &S, CodePtr OpPC, const 
CXXMethodDecl *MD);
 /// Checks that all fields are initialized after a constructor call.
 bool CheckCtorCall(InterpState &S, CodePtr OpPC, const Pointer &This);
 
+/// Checks if the shift operation is legal.
+template 
+bool CheckShift(InterpState &S, CodePtr OpPC, const RT &RHS, unsigned Bits) {
+  if (RHS.isNegative()) {
+const SourceInfo &Loc = S.Current->getSource(OpPC);
+S.CCEDiag(Loc, diag::note_constexpr_negative_shift) << RHS.toAPSInt();
+return false;
+  }
+
+  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
+  // the shifted type.
+  if (Bits > 1 && RHS >= RT::from(Bits, RHS.bitWidth())) {
+const Expr *E = S.Current->getExpr(OpPC);
+const APSInt Val = RHS.toAPSInt();
+QualType Ty = E->getType();
+S.CCEDiag(E, diag::note_constexpr_large_shift) << Val << Ty << Bits;
+return false;
+  }
+  return true;
+}
+
 /// Checks if Div/Rem operation on LHS and RHS is valid.
 template 
 bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS) {
@@ -1180,21 +1201,8 @@ inline bool Shr(InterpState &S, CodePtr OpPC) {
   const auto &LHS = S.Stk.pop();
   const unsigned Bits = LHS.bitWidth();
 
-  if (RHS.isNegative()) {
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.CCEDiag(Loc, diag::note_constexpr_negative_shift) << RHS.toAPSInt();
-return false;
-  }
-
-  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
-  // the shifted type.
-  if (Bits > 1 && RHS >= RT::from(Bits, RHS.bitWidth())) {
-const Expr *E = S.Current->getExpr(OpPC);
-const APSInt Val = RHS.toAPSInt();
-QualType Ty = E->getType();
-S.CCEDiag(E, diag::note_constexpr_large_shift) << Val << Ty << Bits;
+  if (!CheckShift(S, OpPC, RHS, Bits))
 return false;
-  }
 
   unsigned URHS = static_cast(RHS);
   S.Stk.push(LT::from(static_cast(LHS) >> URHS, LHS.bitWidth()));
@@ -1209,21 +1217,8 @@ inline bool Shl(InterpState &S, CodePtr OpPC) {
   const auto &LHS = S.Stk.pop();
   const unsigned Bits = LHS.bitWidth();
 
-  if (RHS.isNegative()) {
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.CCEDiag(Loc, diag::note_constexpr_negative_shift) << RHS.toAPSInt();
+  if (!CheckShift(S, OpPC, RHS, Bits))
 return false;
-  }
-
-  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
-  // the shifted type.
-  if (Bits > 1 && RHS >= RT::from(Bits, RHS.bitWidth())) {
-const Expr *E = S.Current->getExpr(OpPC);
-const APSInt Val = RHS.toAPSInt();
-QualType Ty = E->getType();
-S.CCEDiag(E, diag::note_constexpr_large_shift) << Val << Ty << Bits;
-return false;
-  }
 
   unsigned URHS = static_cast(RHS);
   S.Stk.push(LT::from(static_cast(LHS) << URHS, LHS.bitWidth()));



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


[clang] f6ea1af - Revert "[clang][Interp] Implement missing compound assign operators"

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T13:52:47+01:00
New Revision: f6ea1af9a4b71d27de2dde629224af1220c5c85b

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

LOG: Revert "[clang][Interp] Implement missing compound assign operators"

This reverts commit 490e8214fca48824beda8b508d6d6bbbf3d8d9a7.

This breaks a builder: https://lab.llvm.org/buildbot/#/builders/214/builds/5415

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/literals.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 8565f635eafc7..d0140863c5d7d 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -525,8 +525,8 @@ bool ByteCodeExprGen::VisitCompoundAssignOperator(
 const CompoundAssignOperator *E) {
   const Expr *LHS = E->getLHS();
   const Expr *RHS = E->getRHS();
-  std::optional LT = classify(E->getComputationLHSType());
-  std::optional RT = classify(E->getComputationResultType());
+  std::optional LT = classify(E->getLHS()->getType());
+  std::optional RT = classify(E->getRHS()->getType());
 
   if (!LT || !RT)
 return false;
@@ -552,18 +552,10 @@ bool 
ByteCodeExprGen::VisitCompoundAssignOperator(
 if (!this->emitSub(*LT, E))
   return false;
 break;
+
   case BO_MulAssign:
-if (!this->emitMul(*LT, E))
-  return false;
-break;
   case BO_DivAssign:
-if (!this->emitDiv(*LT, E))
-  return false;
-break;
   case BO_RemAssign:
-if (!this->emitRem(*LT, E))
-  return false;
-break;
   case BO_ShlAssign:
 if (!this->emitShl(*LT, *RT, E))
   return false;
@@ -573,17 +565,8 @@ bool ByteCodeExprGen::VisitCompoundAssignOperator(
   return false;
 break;
   case BO_AndAssign:
-if (!this->emitBitAnd(*LT, E))
-  return false;
-break;
   case BO_XorAssign:
-if (!this->emitBitXor(*LT, E))
-  return false;
-break;
   case BO_OrAssign:
-if (!this->emitBitOr(*LT, E))
-  return false;
-break;
   default:
 llvm_unreachable("Unimplemented compound assign operator");
   }

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index 4fc9489941e55..cd5c9da9bda51 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -469,160 +469,5 @@ namespace IncDec {
 return (a -= a);
   }
   static_assert(subAll(213) == 0, "");
-
-  constexpr bool BoolOr(bool b1, bool b2) {
-bool a;
-a = b1;
-a |= b2;
-return a;
-  }
-  static_assert(BoolOr(true, true), "");
-  static_assert(BoolOr(true, false), "");
-  static_assert(BoolOr(false, true), "");
-  static_assert(!BoolOr(false, false), "");
-
-  constexpr int IntOr(unsigned a, unsigned b) {
-unsigned r;
-r = a;
-r |= b;
-return r;
-  }
-  static_assert(IntOr(10, 1) == 11, "");
-  static_assert(IntOr(1337, -1) == -1, "");
-  static_assert(IntOr(0, 12) == 12, "");
-
-  constexpr bool BoolAnd(bool b1, bool b2) {
-bool a;
-a = b1;
-a &= b2;
-return a;
-  }
-  static_assert(BoolAnd(true, true), "");
-  static_assert(!BoolAnd(true, false), "");
-  static_assert(!BoolAnd(false, true), "");
-  static_assert(!BoolAnd(false, false), "");
-
-  constexpr int IntAnd(unsigned a, unsigned b) {
-unsigned r;
-r = a;
-r &= b;
-return r;
-  }
-  static_assert(IntAnd(10, 1) == 0, "");
-  static_assert(IntAnd(1337, -1) == 1337, "");
-  static_assert(IntAnd(0, 12) == 0, "");
-
-  constexpr bool BoolXor(bool b1, bool b2) {
-bool a;
-a = b1;
-a ^= b2;
-return a;
-  }
-  static_assert(!BoolXor(true, true), "");
-  static_assert(BoolXor(true, false), "");
-  static_assert(BoolXor(false, true), "");
-  static_assert(!BoolXor(false, false), "");
-
-  constexpr int IntXor(unsigned a, unsigned b) {
-unsigned r;
-r = a;
-r ^= b;
-return r;
-  }
-  static_assert(IntXor(10, 1) == 11, "");
-  static_assert(IntXor(10, 10) == 0, "");
-  static_assert(IntXor(12, true) == 13, "");
-
-  constexpr bool BoolRem(bool b1, bool b2) {
-bool a;
-a = b1;
-a %= b2;
-return a;
-  }
-  static_assert(!BoolRem(true, true), "");
-  static_assert(!BoolRem(false, true), "");
-
-  constexpr int IntRem(int a, int b) {
-int r;
-r = a;
-r %= b; // expected-note {{division by zero}} \
-// ref-note {{division by zero}} \
-// expected-note {{outside the range of representable values}} \
-// ref-note {{outside the range of representable values}}
-return r;
-  }
-  static_assert(IntRem(2, 2) == 0, "");
-  static_assert(IntRem(2, 1) == 0, "");
-  static_assert(IntRem(9, 7) == 2, "");
-  static_assert(IntRem(5, 0) == 0, ""); // expected-error {{not an integral 

[clang] 8df7e81 - Revert "[clang][Interp] Unify visiting variable declarations"

2023-01-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-01-19T13:52:47+01:00
New Revision: 8df7e818de45c367dc497e28d4d0e5a1fa1e64fe

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

LOG: Revert "[clang][Interp] Unify visiting variable declarations"

This reverts commit 5b54cf1a2892767fe949826a32d7820732028a38.

This breaks a builder: https://lab.llvm.org/buildbot/#/builders/5/builds/30854

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/ByteCodeExprGen.h
clang/lib/AST/Interp/ByteCodeStmtGen.cpp
clang/lib/AST/Interp/ByteCodeStmtGen.h
clang/lib/AST/Interp/Program.cpp
clang/lib/AST/Interp/Program.h

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index d0140863c5d7..f4bf162a1454 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -802,13 +802,6 @@ unsigned 
ByteCodeExprGen::allocateLocalPrimitive(DeclTy &&Src,
   PrimType Ty,
   bool IsConst,
   bool IsExtended) {
-  // Make sure we don't accidentally register the same decl twice.
-  if (const auto *VD =
-  dyn_cast_if_present(Src.dyn_cast())) {
-assert(!P.getGlobal(VD));
-assert(Locals.find(VD) == Locals.end());
-  }
-
   // FIXME: There are cases where Src.is() is wrong, e.g.
   //   (int){12} in C. Consider using Expr::isTemporaryObject() instead
   //   or isa().
@@ -824,14 +817,8 @@ unsigned 
ByteCodeExprGen::allocateLocalPrimitive(DeclTy &&Src,
 template 
 std::optional
 ByteCodeExprGen::allocateLocal(DeclTy &&Src, bool IsExtended) {
-  // Make sure we don't accidentally register the same decl twice.
-  if (const auto *VD =
-  dyn_cast_if_present(Src.dyn_cast())) {
-assert(!P.getGlobal(VD));
-assert(Locals.find(VD) == Locals.end());
-  }
-
   QualType Ty;
+
   const ValueDecl *Key = nullptr;
   const Expr *Init = nullptr;
   bool IsTemporary = false;
@@ -1141,87 +1128,41 @@ bool ByteCodeExprGen::visitExpr(const Expr 
*Exp) {
 return this->emitRetValue(Exp);
 }
 
-/// Toplevel visitDecl().
-/// We get here from evaluateAsInitializer().
-/// We need to evaluate the initializer and return its value.
 template 
 bool ByteCodeExprGen::visitDecl(const VarDecl *VD) {
-  std::optional VarT = classify(VD->getType());
-
-  // Create and initialize the variable.
-  if (!this->visitVarDecl(VD))
-return false;
-
-  // Get a pointer to the variable
-  if (shouldBeGloballyIndexed(VD)) {
-auto GlobalIndex = P.getGlobal(VD);
-assert(GlobalIndex); // visitVarDecl() didn't return false.
-if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
-  return false;
-  } else {
-auto Local = Locals.find(VD);
-assert(Local != Locals.end()); // Same here.
-if (!this->emitGetPtrLocal(Local->second.Offset, VD))
-  return false;
-  }
-
-  // Return the value
-  if (VarT) {
-if (!this->emitLoadPop(*VarT, VD))
-  return false;
-
-return this->emitRet(*VarT, VD);
-  }
-
-  return this->emitRetValue(VD);
-}
-
-template 
-bool ByteCodeExprGen::visitVarDecl(const VarDecl *VD) {
   const Expr *Init = VD->getInit();
-  std::optional VarT = classify(VD->getType());
-
-  if (shouldBeGloballyIndexed(VD)) {
-std::optional GlobalIndex = P.getOrCreateGlobal(VD, Init);
-
-if (!GlobalIndex)
-  return this->bail(VD);
-
-assert(Init);
-{
-  DeclScope LocalScope(this, VD);
 
-  if (VarT) {
-if (!this->visit(Init))
+  if (std::optional I = P.createGlobal(VD, Init)) {
+if (std::optional T = classify(VD->getType())) {
+  {
+// Primitive declarations - compute the value and set it.
+DeclScope LocalScope(this, VD);
+if (!visit(Init))
   return false;
-return this->emitInitGlobal(*VarT, *GlobalIndex, VD);
   }
-  return this->visitGlobalInitializer(Init, *GlobalIndex);
-}
-  } else {
-DeclScope LocalScope(this, VD);
-
-if (VarT) {
-  unsigned Offset = this->allocateLocalPrimitive(
-  VD, *VarT, VD->getType().isConstQualified());
-  // Compile the initializer in its own scope.
-  if (Init) {
-ExprScope Scope(this);
-if (!this->visit(Init))
-  return false;
 
-return this->emitSetLocal(*VarT, Offset, VD);
-  }
+  // If the declaration is global, save the value for later use.
+  if (!this->emitDup(*T, VD))
+return false;
+  if (!this->emitInitGlobal(*T, *I, VD))
+return false;
+  return this->emitRet(*T, VD);
 } else {
-  if (std::optional Offset = this->allocateLocal(VD)) {
-if (Init)
-  

[PATCH] D136315: [clang][Darwin] Try to guess the SDK root with xcrun when unspecified

2023-01-19 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

My bot is a Mac. It doesn't set any env vars (other than the ones that lit 
always sets). In theory it shouldn't matter since tests aren't supposed to 
depend on system headers. (Tangential: maybe there should be a flag to turn 
this off and %clang should expand to `clang` with that flag?)

For cross builds, I mostly build cc files that don't include any headers to 
test compiler behavior. But one could uses -isysroot like elsewhere.

I think it'd be good to revert this until it no longer tries to run `xcrun` on 
non-macs, independent of my test failures.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136315

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


[clang] 6ad1b40 - Optimize OptTable::findNearest implementation and usage

2023-01-19 Thread via cfe-commits

Author: serge-sans-paille
Date: 2023-01-19T14:16:29+01:00
New Revision: 6ad1b4095172373590134afff19a7fbad9d7889d

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

LOG: Optimize OptTable::findNearest implementation and usage

When used to find an exact match, some extra context can be used to
totally cut some computations.

This saves 1% of the instruction count when pre processing sqlite3.c
through

valgrind --tool=callgrind ./bin/clang -E sqlite3.c -o/dev/null

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

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
llvm/include/llvm/Option/OptTable.h
llvm/lib/Option/OptTable.cpp

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 12f8c326a..58e1090673fad 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -313,8 +313,8 @@ InputArgList Driver::ParseArgStrings(ArrayRef 
ArgStrings,
 std::string Nearest;
 if (getOpts().findNearest(ArgString, Nearest, IncludedFlagsBitmask,
   ExcludedFlagsBitmask) > 1) {
-  if (getOpts().findNearest(ArgString, Nearest, options::CC1Option) == 0 &&
-  !IsCLMode()) {
+  if (!IsCLMode() &&
+  getOpts().findExact(ArgString, Nearest, options::CC1Option)) {
 DiagID = diag::err_drv_unknown_argument_with_suggestion;
 Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest;
   } else {
@@ -339,8 +339,8 @@ InputArgList Driver::ParseArgStrings(ArrayRef 
ArgStrings,
 // Warn on joined arguments that are similar to a long argument.
 std::string ArgString = ArgStrings[A->getIndex()];
 std::string Nearest;
-if (getOpts().findNearest("-" + ArgString, Nearest, IncludedFlagsBitmask,
-  ExcludedFlagsBitmask) == 0)
+if (getOpts().findExact("-" + ArgString, Nearest, IncludedFlagsBitmask,
+ExcludedFlagsBitmask))
   Diags.Report(diag::warn_drv_potentially_misspelled_joined_argument)
   << A->getAsString(Args) << Nearest;
   }

diff  --git a/llvm/include/llvm/Option/OptTable.h 
b/llvm/include/llvm/Option/OptTable.h
index 25d86c04a43bd..8f13a31aa4221 100644
--- a/llvm/include/llvm/Option/OptTable.h
+++ b/llvm/include/llvm/Option/OptTable.h
@@ -175,11 +175,21 @@ class OptTable {
   /// \param [in] MinimumLength - Don't find options shorter than this length.
   /// For example, a minimum length of 3 prevents "-x" from being considered
   /// near to "-S".
+  /// \param [in] MaximumDistance - Don't find options whose distance is 
greater
+  /// than this value.
   ///
   /// \return The edit distance of the nearest string found.
   unsigned findNearest(StringRef Option, std::string &NearestString,
unsigned FlagsToInclude = 0, unsigned FlagsToExclude = 
0,
-   unsigned MinimumLength = 4) const;
+   unsigned MinimumLength = 4,
+   unsigned MaximumDistance = UINT_MAX - 1) const;
+
+  bool findExact(StringRef Option, std::string &ExactString,
+ unsigned FlagsToInclude = 0,
+ unsigned FlagsToExclude = 0) const {
+return findNearest(Option, ExactString, FlagsToInclude, FlagsToExclude, 4,
+   0) == 0;
+  }
 
   /// Parse a single argument; returning the new argument and
   /// updating Index.

diff  --git a/llvm/lib/Option/OptTable.cpp b/llvm/lib/Option/OptTable.cpp
index dea9fc0eb7857..10f0658bc965a 100644
--- a/llvm/lib/Option/OptTable.cpp
+++ b/llvm/lib/Option/OptTable.cpp
@@ -227,12 +227,13 @@ OptTable::findByPrefix(StringRef Cur, unsigned int 
DisableFlags) const {
 
 unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
unsigned FlagsToInclude, unsigned 
FlagsToExclude,
-   unsigned MinimumLength) const {
+   unsigned MinimumLength,
+   unsigned MaximumDistance) const {
   assert(!Option.empty());
 
   // Consider each [option prefix + option name] pair as a candidate, finding
   // the closest match.
-  unsigned BestDistance = UINT_MAX;
+  unsigned BestDistance = MaximumDistance + 1;
   SmallString<16> Candidate;
   SmallString<16> NormalizedName;
 
@@ -276,6 +277,14 @@ unsigned OptTable::findNearest(StringRef Option, 
std::string &NearestString,
 // appropriate one. For example, if a user asks for "--helm", suggest
 // "--help" over "-help".
 for (auto CandidatePrefix : CandidateInfo.Prefixes) {
+  // If Candidate and NormalizedName have more than 'BestDistance'
+  // characters of 
diff erence, no need to compute the edit distance, it's
+  // going to be greater than BestDistance. D

[PATCH] D142026: Optimize OptTable::findNearest implementation and usage

2023-01-19 Thread serge 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 rG6ad1b4095172: Optimize OptTable::findNearest implementation 
and usage (authored by serge-sans-paille).

Changed prior to commit:
  https://reviews.llvm.org/D142026?vs=490412&id=490465#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142026

Files:
  clang/lib/Driver/Driver.cpp
  llvm/include/llvm/Option/OptTable.h
  llvm/lib/Option/OptTable.cpp


Index: llvm/lib/Option/OptTable.cpp
===
--- llvm/lib/Option/OptTable.cpp
+++ llvm/lib/Option/OptTable.cpp
@@ -227,12 +227,13 @@
 
 unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
unsigned FlagsToInclude, unsigned 
FlagsToExclude,
-   unsigned MinimumLength) const {
+   unsigned MinimumLength,
+   unsigned MaximumDistance) const {
   assert(!Option.empty());
 
   // Consider each [option prefix + option name] pair as a candidate, finding
   // the closest match.
-  unsigned BestDistance = UINT_MAX;
+  unsigned BestDistance = MaximumDistance + 1;
   SmallString<16> Candidate;
   SmallString<16> NormalizedName;
 
@@ -276,6 +277,14 @@
 // appropriate one. For example, if a user asks for "--helm", suggest
 // "--help" over "-help".
 for (auto CandidatePrefix : CandidateInfo.Prefixes) {
+  // If Candidate and NormalizedName have more than 'BestDistance'
+  // characters of difference, no need to compute the edit distance, it's
+  // going to be greater than BestDistance. Don't bother computing 
Candidate
+  // at all.
+  if (std::abs((ssize_t)(CandidatePrefix.size() + CandidateName.size()) -
+   (ssize_t)NormalizedName.size()) > (ssize_t)BestDistance) {
+continue;
+  }
   Candidate = CandidatePrefix;
   Candidate += CandidateName;
   unsigned Distance = StringRef(Candidate).edit_distance(
Index: llvm/include/llvm/Option/OptTable.h
===
--- llvm/include/llvm/Option/OptTable.h
+++ llvm/include/llvm/Option/OptTable.h
@@ -175,11 +175,21 @@
   /// \param [in] MinimumLength - Don't find options shorter than this length.
   /// For example, a minimum length of 3 prevents "-x" from being considered
   /// near to "-S".
+  /// \param [in] MaximumDistance - Don't find options whose distance is 
greater
+  /// than this value.
   ///
   /// \return The edit distance of the nearest string found.
   unsigned findNearest(StringRef Option, std::string &NearestString,
unsigned FlagsToInclude = 0, unsigned FlagsToExclude = 
0,
-   unsigned MinimumLength = 4) const;
+   unsigned MinimumLength = 4,
+   unsigned MaximumDistance = UINT_MAX - 1) const;
+
+  bool findExact(StringRef Option, std::string &ExactString,
+ unsigned FlagsToInclude = 0,
+ unsigned FlagsToExclude = 0) const {
+return findNearest(Option, ExactString, FlagsToInclude, FlagsToExclude, 4,
+   0) == 0;
+  }
 
   /// Parse a single argument; returning the new argument and
   /// updating Index.
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -313,8 +313,8 @@
 std::string Nearest;
 if (getOpts().findNearest(ArgString, Nearest, IncludedFlagsBitmask,
   ExcludedFlagsBitmask) > 1) {
-  if (getOpts().findNearest(ArgString, Nearest, options::CC1Option) == 0 &&
-  !IsCLMode()) {
+  if (!IsCLMode() &&
+  getOpts().findExact(ArgString, Nearest, options::CC1Option)) {
 DiagID = diag::err_drv_unknown_argument_with_suggestion;
 Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest;
   } else {
@@ -339,8 +339,8 @@
 // Warn on joined arguments that are similar to a long argument.
 std::string ArgString = ArgStrings[A->getIndex()];
 std::string Nearest;
-if (getOpts().findNearest("-" + ArgString, Nearest, IncludedFlagsBitmask,
-  ExcludedFlagsBitmask) == 0)
+if (getOpts().findExact("-" + ArgString, Nearest, IncludedFlagsBitmask,
+ExcludedFlagsBitmask))
   Diags.Report(diag::warn_drv_potentially_misspelled_joined_argument)
   << A->getAsString(Args) << Nearest;
   }


Index: llvm/lib/Option/OptTable.cpp
===
--- llvm/lib/Option/OptTable.cpp
+++ llvm/lib/Option/OptTable.cpp
@@ -227,12 +227,13 @@
 
 unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,

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

2023-01-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D141744#4063661 , 
@alexander-shaposhnikov wrote:

> @aaron.ballman - thanks for the review, I've updated the release notes. 
> Regarding LanguageExtensions.rst - somehow I  don't see any appropriate 
> sections in  LanguageExtensions.rst (either about our builtin std::move and 
> friends or [[clang::lifetimebound]]) - didn't change that.

I was thinking we'd want to update: 
https://github.com/llvm/llvm-project/blob/main/clang/docs/LanguageExtensions.rst#__builtin_addressof
 and friends.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141744

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


Re: [clang] 2dbcfd2 - Revert "[clang][Interp][NFC] Move CheckDivRem() implementation into Interp.cpp"

2023-01-19 Thread Roman Lebedev via cfe-commits
Reminder to please always mention the reason for the revert/recommit
in the commit message.

On Thu, Jan 19, 2023 at 2:37 PM Timm Bäder via cfe-commits
 wrote:
>
>
> Author: Timm Bäder
> Date: 2023-01-19T12:37:20+01:00
> New Revision: 2dbcfd298f7cb1454ca16f544b7df980ec8fc17d
>
> URL: 
> https://github.com/llvm/llvm-project/commit/2dbcfd298f7cb1454ca16f544b7df980ec8fc17d
> DIFF: 
> https://github.com/llvm/llvm-project/commit/2dbcfd298f7cb1454ca16f544b7df980ec8fc17d.diff
>
> LOG: Revert "[clang][Interp][NFC] Move CheckDivRem() implementation into 
> Interp.cpp"
>
> This reverts commit 9ee0d7494eb35f5addefcb730cdf5c002ddeacd2.
>
> Added:
>
>
> Modified:
> clang/lib/AST/Interp/Interp.cpp
> clang/lib/AST/Interp/Interp.h
>
> Removed:
>
>
>
> 
> diff  --git a/clang/lib/AST/Interp/Interp.cpp 
> b/clang/lib/AST/Interp/Interp.cpp
> index d7195148d015..76ade4401e08 100644
> --- a/clang/lib/AST/Interp/Interp.cpp
> +++ b/clang/lib/AST/Interp/Interp.cpp
> @@ -422,26 +422,6 @@ bool CheckShift(InterpState &S, CodePtr OpPC, const RT 
> &RHS, unsigned Bits) {
>return true;
>  }
>
> -template 
> -bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS) {
> -  if (RHS.isZero()) {
> -const SourceInfo &Loc = S.Current->getSource(OpPC);
> -S.FFDiag(Loc, diag::note_expr_divide_by_zero);
> -return false;
> -  }
> -
> -  if (LHS.isSigned() && LHS.isMin() && RHS.isNegative() && RHS.isMinusOne()) 
> {
> -APSInt LHSInt = LHS.toAPSInt();
> -SmallString<32> Trunc;
> -(-LHSInt.extend(LHSInt.getBitWidth() + 1)).toString(Trunc, 10);
> -const SourceInfo &Loc = S.Current->getSource(OpPC);
> -const Expr *E = S.Current->getExpr(OpPC);
> -S.CCEDiag(Loc, diag::note_constexpr_overflow) << Trunc << E->getType();
> -return false;
> -  }
> -  return true;
> -}
> -
>  static void DiagnoseUninitializedSubobject(InterpState &S, const SourceInfo 
> &SI,
> QualType SubObjType,
> SourceLocation SubObjLoc) {
>
> diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
> index 3fa977d4a02e..903c68f4511c 100644
> --- a/clang/lib/AST/Interp/Interp.h
> +++ b/clang/lib/AST/Interp/Interp.h
> @@ -100,7 +100,24 @@ bool CheckShift(InterpState &S, CodePtr OpPC, const RT 
> &RHS, unsigned Bits);
>
>  /// Checks if Div/Rem operation on LHS and RHS is valid.
>  template 
> -bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS);
> +bool CheckDivRem(InterpState &S, CodePtr OpPC, const T &LHS, const T &RHS) {
> +  if (RHS.isZero()) {
> +const SourceInfo &Loc = S.Current->getSource(OpPC);
> +S.FFDiag(Loc, diag::note_expr_divide_by_zero);
> +return false;
> +  }
> +
> +  if (LHS.isSigned() && LHS.isMin() && RHS.isNegative() && RHS.isMinusOne()) 
> {
> +APSInt LHSInt = LHS.toAPSInt();
> +SmallString<32> Trunc;
> +(-LHSInt.extend(LHSInt.getBitWidth() + 1)).toString(Trunc, 10);
> +const SourceInfo &Loc = S.Current->getSource(OpPC);
> +const Expr *E = S.Current->getExpr(OpPC);
> +S.CCEDiag(Loc, diag::note_constexpr_overflow) << Trunc << E->getType();
> +return false;
> +  }
> +  return true;
> +}
>
>  /// Interpreter entry point.
>  bool Interpret(InterpState &S, APValue &Result);
>
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] e70ca7b - [clang] Build UsingType for elaborated type specifiers.

2023-01-19 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-01-19T14:20:38+01:00
New Revision: e70ca7b35319a3621f9d9c6475926428f8c5c000

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

LOG: [clang] Build UsingType for elaborated type specifiers.

Support building UsingType for elaborated type specifiers:

```
namespace ns { class Foo {}; }

using ns::Foo;

// The TypeLoc of `Foo` below should be a ElaboratedTypeLoc with an
// inner UsingTypeLoc rather than the underlying `CXXRecordTypeLoc`
class Foo foo;
```

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

Added: 


Modified: 
clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
clang/include/clang/Sema/DeclSpec.h
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/lib/Sema/SemaType.cpp
clang/test/CXX/drs/dr2xx.cpp
clang/test/CXX/drs/dr4xx.cpp

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp 
b/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
index 3b97cc8cdfd55..e5b99ef9a3a00 100644
--- a/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ b/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -150,6 +150,9 @@ TEST(WalkAST, Using) {
 }
 using ns::$explicit^Y;)cpp",
"^Y x;");
+  testWalk(R"cpp(
+namespace ns { class Foo {}; }
+  )cpp", "using ns::$explicit^Foo; class ^Foo foo;");
 }
 
 TEST(WalkAST, Namespaces) {

diff  --git a/clang/include/clang/Sema/DeclSpec.h 
b/clang/include/clang/Sema/DeclSpec.h
index 69fe2c541607b..a95fe5686009b 100644
--- a/clang/include/clang/Sema/DeclSpec.h
+++ b/clang/include/clang/Sema/DeclSpec.h
@@ -506,8 +506,16 @@ class DeclSpec {
 assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
 return TypeRep;
   }
+  // Returns the underlying decl, if any.
   Decl *getRepAsDecl() const {
-assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
+auto *D = getRepAsFoundDecl();
+if (const auto *Using = dyn_cast_or_null(D))
+  return Using->getTargetDecl();
+return D;
+  }
+  // Returns the originally found decl, if any.
+  Decl *getRepAsFoundDecl() const {
+assert(isDeclRep((TST)TypeSpecType) && "DeclSpec does not store a decl");
 return DeclRep;
   }
   Expr *getRepAsExpr() const {

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 7a95989ee6d44..e504111fce059 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3324,7 +3324,9 @@ class Sema final {
   SourceLocation ScopedEnumKWLoc,
   bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
   bool IsTypeSpecifier, bool IsTemplateParamOrArg,
-  OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
+  OffsetOfKind OOK,
+  UsingShadowDecl*& FoundUsingShadow,
+  SkipBodyInfo *SkipBody = nullptr);
 
   DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
  unsigned TagSpec, SourceLocation TagLoc,

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index e6812ac72c885..c7fd1156928ca 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -4965,6 +4965,7 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, 
DeclSpec &DS,
   bool IsDependent = false;
   const char *PrevSpec = nullptr;
   unsigned DiagID;
+  UsingShadowDecl* FoundUsing = nullptr;
   Decl *TagDecl =
   Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS,
 Name, NameLoc, attrs, AS, DS.getModulePrivateSpecLoc(),
@@ -4973,7 +4974,7 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, 
DeclSpec &DS,
 BaseType, DSC == DeclSpecContext::DSC_type_specifier,
 DSC == DeclSpecContext::DSC_template_param ||
 DSC == DeclSpecContext::DSC_template_type_arg,
-OffsetOfState, &SkipBody).get();
+OffsetOfState, FoundUsing, &SkipBody).get();
 
   if (SkipBody.ShouldSkip) {
 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
@@ -4983,8 +4984,8 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, 
DeclSpec &DS,
 T.skipToEnd();
 
 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
-   NameLoc.isValid() ? NameLoc : StartLoc,
-   PrevSpec, DiagID, TagDecl, Owned,
+   NameLoc.isValid() ? NameLoc : StartLoc, PrevSpec,

[PATCH] D141280: [clang] Build UsingType for elaborated type specifiers.

2023-01-19 Thread Haojian Wu 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 rGe70ca7b35319: [clang] Build UsingType for elaborated type 
specifiers. (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D141280?vs=490455&id=490467#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141280

Files:
  clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
  clang/include/clang/Sema/DeclSpec.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CXX/drs/dr2xx.cpp
  clang/test/CXX/drs/dr4xx.cpp

Index: clang/test/CXX/drs/dr4xx.cpp
===
--- clang/test/CXX/drs/dr4xx.cpp
+++ clang/test/CXX/drs/dr4xx.cpp
@@ -301,9 +301,8 @@
 struct F;
 struct H;
   }
-  // FIXME: This is ill-formed.
   using N::D;
-  struct dr417::D {}; // expected-warning {{extra qualification}}
+  struct dr417::D {}; // expected-error {{forward declaration of struct cannot}} expected-warning {{extra qualification}}
   using namespace N;
   struct dr417::E {}; // expected-warning {{extra qualification}} expected-error {{no struct named 'E'}}
   struct N::F {};
Index: clang/test/CXX/drs/dr2xx.cpp
===
--- clang/test/CXX/drs/dr2xx.cpp
+++ clang/test/CXX/drs/dr2xx.cpp
@@ -992,7 +992,7 @@
   }
   struct B::V {}; // expected-error {{no struct named 'V'}}
   struct B::W {};
-  struct B::X {}; // FIXME: ill-formed
+  struct B::X {}; // expected-error {{forward declaration of struct cannot have}}
   enum B::Y e; // ok per dr417
   class B::Z z; // ok per dr417
 
@@ -1009,7 +1009,7 @@
   };
   struct D::V {}; // expected-error {{no struct named 'V'}}
   struct D::W {};
-  struct D::X {}; // FIXME: ill-formed
+  struct D::X {}; // expected-error {{forward declaration of struct cannot have}}
   enum D::Y e2; // ok per dr417
   class D::Z z2; // ok per dr417
 }
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -1588,6 +1588,9 @@
 
 // TypeQuals handled by caller.
 Result = Context.getTypeDeclType(D);
+if (const auto *Using =
+dyn_cast_or_null(DS.getRepAsFoundDecl()))
+  Result = Context.getUsingType(Using, Result);
 
 // In both C and C++, make an ElaboratedType.
 ElaboratedTypeKeyword Keyword
Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -10181,11 +10181,14 @@
 
   bool Owned = false;
   bool IsDependent = false;
-  Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name,
-   NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
+  UsingShadowDecl* FoundUsing = nullptr;
+  Decl *TagD =
+  ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name, NameLoc, Attr,
+   AS_none, /*ModulePrivateLoc=*/SourceLocation(),
MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
false, TypeResult(), /*IsTypeSpecifier*/ false,
-   /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get();
+   /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside, FoundUsing)
+  .get();
   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
 
   if (!TagD)
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -16972,6 +16972,7 @@
 if (SS.isEmpty()) {
   bool Owned = false;
   bool IsDependent = false;
+  UsingShadowDecl* FoundUsing = nullptr;
   return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr,
   AS_public,
   /*ModulePrivateLoc=*/SourceLocation(),
@@ -16980,7 +16981,7 @@
   /*ScopedEnumUsesClassTag=*/false,
   /*UnderlyingType=*/TypeResult(),
   /*IsTypeSpecifier=*/false,
-  /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
+  /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside, FoundUsing);
 }
 
 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -16592,7 +16592,8 @@
bool &IsDependent, SourceLocation ScopedEnumKWLoc,
bool

[PATCH] D142092: [include-mapping] Allow multiple headers for the same symbol. Choose the first header of available ones.

2023-01-19 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 490468.
VitaNuo added a comment.

Remove variant logic in generator.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142092

Files:
  clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
  clang/tools/include-mapping/cppreference_parser.py
  clang/tools/include-mapping/gen_std.py

Index: clang/tools/include-mapping/gen_std.py
===
--- clang/tools/include-mapping/gen_std.py
+++ clang/tools/include-mapping/gen_std.py
@@ -13,12 +13,6 @@
 
 The generated files are located in clang/include/Tooling/Inclusions.
 
-Caveats and FIXMEs:
-  - only symbols directly in "std" namespace are added, we should also add std's
-subnamespace symbols (e.g. chrono).
-  - symbols with multiple variants or defined in multiple headers aren't added,
-e.g. std::move, std::swap
-
 Usage:
   1. Install BeautifulSoup dependency, see instruction:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-beautiful-soup
@@ -104,17 +98,12 @@
 os.stat(index_page_path).st_mtime).strftime('%Y-%m-%d')
   print(CODE_PREFIX % (args.language.upper(), cppreference_modified_date))
   for symbol in symbols:
-if len(symbol.headers) == 1:
-  # SYMBOL(unqualified_name, namespace, header)
-  print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
-symbol.headers[0]))
-elif len(symbol.headers) == 0:
+if len(symbol.headers) == 0:
   sys.stderr.write("No header found for symbol %s\n" % symbol.name)
 else:
-  # FIXME: support symbols with multiple headers (e.g. std::move).
-  sys.stderr.write("Ambiguous header for symbol %s: %s\n" % (
-  symbol.name, ', '.join(symbol.headers)))
-
-
+  for header in symbol.headers:
+# SYMBOL(unqualified_name, namespace, header)
+print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
+  header))
 if __name__ == '__main__':
   main()
Index: clang/tools/include-mapping/cppreference_parser.py
===
--- clang/tools/include-mapping/cppreference_parser.py
+++ clang/tools/include-mapping/cppreference_parser.py
@@ -93,7 +93,7 @@
   abs() (int) 
   acos() 
 
-  Returns a list of tuple (symbol_name, relative_path_to_symbol_page, variant).
+  Returns a list of tuple (symbol_name, relative_path_to_symbol_page).
   """
   symbols = []
   soup = BeautifulSoup(index_page_html, "html.parser")
@@ -103,13 +103,10 @@
 # This accidentally accepts begin/end despite the (iterator) caption: the
 # (since C++11) note is first. They are good symbols, so the bug is unfixed.
 caption = symbol_href.next_sibling
-variant = None
-if isinstance(caption, NavigableString) and "(" in caption:
-  variant = caption.text.strip(" ()")
 symbol_tt = symbol_href.find("tt")
 if symbol_tt:
   symbols.append((symbol_tt.text.rstrip("<>()"), # strip any trailing <>()
-  symbol_href["href"], variant))
+  symbol_href["href"]))
   return symbols
 
 
@@ -118,7 +115,7 @@
 return _ParseSymbolPage(f.read(), name)
 
 
-def _GetSymbols(pool, root_dir, index_page_name, namespace, variants_to_accept):
+def _GetSymbols(pool, root_dir, index_page_name, namespace):
   """Get all symbols listed in the index page. All symbols should be in the
   given namespace.
 
@@ -134,13 +131,7 @@
   with open(index_page_path, "r") as f:
 # Read each symbol page in parallel.
 results = [] # (symbol_name, promise of [header...])
-for symbol_name, symbol_page_path, variant in _ParseIndexPage(f.read()):
-  # Variant symbols (e.g. the std::locale version of isalpha) add ambiguity.
-  # FIXME: use these as a fallback rather than ignoring entirely.
-  variants_for_symbol = variants_to_accept.get(
-  (namespace or "") + symbol_name, ())
-  if variant and variant not in variants_for_symbol:
-continue
+for symbol_name, symbol_page_path in _ParseIndexPage(f.read()):
   path = os.path.join(root_dir, symbol_page_path)
   if os.path.isfile(path):
 results.append((symbol_name,
@@ -166,13 +157,6 @@
   Args:
 parse_pages: a list of tuples (page_root_dir, index_page_name, namespace)
   """
-  # By default we prefer the non-variant versions, as they're more common. But
-  # there are some symbols, whose variant is more common. This list describes
-  # those symbols.
-  variants_to_accept = {
-  # std::remove<> has variant algorithm.
-  "std::remove": ("algorithm"),
-  }
   symbols = []
   # Run many workers to process individual symbol pages under the symbol index.
   # Don't allow workers to capture Ctrl-C.
@@ -180,8 +164,7 @@
   initializer=lambda: signal.signal(signal.SIGINT, signal.SIG_IGN))
   try:
 for root_dir, page_name, namespace

[PATCH] D137071: [clang][Interp] Implement missing compound assign operators

2023-01-19 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

I've seen s390x and AIX builders break here, probably a problem with big-endian 
machines?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137071

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


[PATCH] D141716: [clang][dataflow] Add (initial) debug printing for `Value` and `Environment`.

2023-01-19 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 490470.
ymandel added a comment.

address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141716

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/Value.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/lib/Analysis/FlowSensitive/Value.cpp

Index: clang/lib/Analysis/FlowSensitive/Value.cpp
===
--- clang/lib/Analysis/FlowSensitive/Value.cpp
+++ clang/lib/Analysis/FlowSensitive/Value.cpp
@@ -11,6 +11,7 @@
 //===--===//
 
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Analysis/FlowSensitive/DebugSupport.h"
 #include "llvm/Support/Casting.h"
 
 namespace clang {
@@ -35,5 +36,21 @@
  areEquivalentIndirectionValues(Val1, Val2)));
 }
 
+raw_ostream &operator<<(raw_ostream &OS, const Value &Val) {
+  switch (Val.getKind()) {
+  case Value::Kind::Reference: {
+const auto *RV = cast(&Val);
+return OS << "Reference(" << &RV->getReferentLoc() << ")";
+  }
+  case Value::Kind::Pointer: {
+const auto *PV = dyn_cast(&Val);
+return OS << "Pointer(" << &PV->getPointeeLoc() << ")";
+  }
+  // FIXME: support remaining cases.
+  default:
+return OS << debugString(Val.getKind());
+  }
+}
+
 } // namespace dataflow
 } // namespace clang
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -32,8 +32,10 @@
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/Debug.h"
 #include "llvm/Support/Error.h"
-#include "llvm/Support/ErrorHandling.h"
+
+#define DEBUG_TYPE "clang-dataflow"
 
 namespace clang {
 namespace dataflow {
@@ -431,6 +433,8 @@
   std::min(RelativeMaxIterations, AbsoluteMaxIterations);
   uint32_t Iterations = 0;
   while (const CFGBlock *Block = Worklist.dequeue()) {
+LLVM_DEBUG(llvm::dbgs()
+   << "Processing Block " << Block->getBlockID() << "\n");
 if (++Iterations > MaxIterations) {
   return llvm::createStringError(std::errc::timed_out,
  "maximum number of iterations reached");
@@ -440,8 +444,16 @@
 BlockStates[Block->getBlockID()];
 TypeErasedDataflowAnalysisState NewBlockState =
 transferCFGBlock(*Block, AC);
+LLVM_DEBUG({
+  llvm::errs() << "New Env:\n";
+  NewBlockState.Env.dump();
+});
 
 if (OldBlockState) {
+  LLVM_DEBUG({
+llvm::errs() << "Old Env:\n";
+OldBlockState->Env.dump();
+  });
   if (isLoopHead(*Block)) {
 LatticeJoinEffect Effect1 = Analysis.widenTypeErased(
 NewBlockState.Lattice, OldBlockState->Lattice);
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -786,9 +786,29 @@
   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
 }
 
-void Environment::dump() const {
+void Environment::dump(raw_ostream &OS) const {
+  // FIXME: add printing for remaining fields and allow caller to decide what
+  // fields are printed.
+  OS << "DeclToLoc:\n";
+  for (auto [D, L] : DeclToLoc)
+OS << "  [" << D->getName() << ", " << L << "]\n";
+
+  OS << "ExprToLoc:\n";
+  for (auto [E, L] : ExprToLoc)
+OS << "  [" << E << ", " << L << "]\n";
+
+  OS << "LocToVal:\n";
+  for (auto [L, V] : LocToVal) {
+OS << "  [" << L << ", " << V << ": " << *V << "]\n";
+  }
+
+  OS << "FlowConditionToken:\n";
   DACtx->dumpFlowCondition(*FlowConditionToken);
 }
 
+void Environment::dump() const {
+  dump(llvm::dbgs());
+}
+
 } // namespace dataflow
 } // namespace clang
Index: clang/include/clang/Analysis/FlowSensitive/Value.h
===
--- clang/include/clang/Analysis/FlowSensitive/Value.h
+++ clang/include/clang/Analysis/FlowSensitive/Value.h
@@ -19,6 +19,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 
@@ -310,6 +311,8 @@
   llvm::DenseMap Children;
 };
 
+raw_ostream &operator<<(raw_ostream &OS, const Value &Val);
+
 } // namespace dataflow
 } // namespace clang
 
Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/

[PATCH] D141716: [clang][dataflow] Add (initial) debug printing for `Value` and `Environment`.

2023-01-19 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked an inline comment as done.
ymandel added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:792
+  // fields are printed.
+  llvm::dbgs() << "DeclToLoc:\n";
+  for (auto [D, L] : DeclToLoc)

sgatev wrote:
> Shouldn't this be `OS`? Same for those below.
Yes, good catch!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141716

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


[PATCH] D136651: [Clang] Give Clang the ability to use a shared stat cache

2023-01-19 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D136651#4064474 , @glandium wrote:

> In D136651#4064260 , @glandium 
> wrote:
>
>> This broke our mac builds with errors like:
>>
>>   ld64.lld: error: undefined symbol: CFRunLoopRun
>>   >>> referenced by 
>> tools/clang/tools/clang-stat-cache/CMakeFiles/clang-stat-cache.dir/clang-stat-cache.cpp.o:(symbol
>>  main+0x11be)
>>
>> (and many more symbols)
>
> Additional information: those are cross-compiled, and for some reason the 
> `-framework CoreServices` in the CMakeLists.txt doesn't seem to make it to 
> the command line, which is surprising because something similar works fine 
> for e.g. dsymutil.

I ran into similar issues, not when cross compiling, but when compiling 
natively. In my case, I'm building with `-DLLVM_LINK_LLVM_DYLIB=ON`. Without 
that, it builds correctly for me.

The new tool needs to be linked with `-framework CoreServices`. This does get 
set in `clang/tools/clang-stat-cache/CMakeLists.txt` like this:

  if(APPLE)
  set(CLANG_STAT_CACHE_LIB_DEPS
"-framework CoreServices"
)
  endif()
  
  clang_target_link_libraries(clang-stat-cache
PRIVATE
${CLANG_STAT_CACHE_LIB_DEPS}
)

However, `clang_target_link_libraries` ignores extra dependencies when linking 
against the dylib: 
https://github.com/llvm/llvm-project/blob/a033dbbe5c43247b60869b008e67ed86ed230eaa/clang/cmake/modules/AddClang.cmake#L209-L213

  if (CLANG_LINK_CLANG_DYLIB)
target_link_libraries(${target} ${type} clang-cpp)
  else()
target_link_libraries(${target} ${type} ${ARGN})
  endif()

I guess `clang_target_link_libraries` needs a mechanism to disambiguate between 
generic clang library dependencies (which need to be dropped when linking 
against `clang-cpp` instead) and other dependencies which always are needed. I 
wonder if there's prior art for such disambiguation in other places - e.g. 
`llvm_add_library` does have similar logic for linking against either other 
llvm libraries or the dylib (and handles lots of other options). (I'm a bit out 
of time for digging further into this right now...)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136651

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


[clang-tools-extra] 939dce1 - [clangd] Implement unused include warnings with include-cleaner library.

2023-01-19 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-01-19T14:31:40+01:00
New Revision: 939dce12f9f35f7e0953a036c16e89d30011d047

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

LOG: [clangd] Implement unused include warnings with include-cleaner library.

A prototype of using include-cleaner library in clangd:

- (re)implement clangd's "unused include" warnings with the library
- the new implementation is hidden under a flag 
`Config::UnusedIncludesPolicy::Experiment`

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

Added: 


Modified: 
clang-tools-extra/clangd/CMakeLists.txt
clang-tools-extra/clangd/Config.h
clang-tools-extra/clangd/ConfigCompile.cpp
clang-tools-extra/clangd/IncludeCleaner.cpp
clang-tools-extra/clangd/IncludeCleaner.h
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/ParsedAST.h
clang-tools-extra/clangd/Preamble.cpp
clang-tools-extra/clangd/Preamble.h
clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CMakeLists.txt 
b/clang-tools-extra/clangd/CMakeLists.txt
index a6b6e30df228b..af8a188056738 100644
--- a/clang-tools-extra/clangd/CMakeLists.txt
+++ b/clang-tools-extra/clangd/CMakeLists.txt
@@ -59,6 +59,7 @@ if(MSVC AND NOT CLANG_CL)
 endif()
 
 include_directories(BEFORE "${CMAKE_CURRENT_BINARY_DIR}/../clang-tidy")
+include_directories(BEFORE 
"${CMAKE_CURRENT_SOURCE_DIR}/../include-cleaner/include")
 
 add_clang_library(clangDaemon
   AST.cpp
@@ -162,6 +163,7 @@ clang_target_link_libraries(clangDaemon
   clangDriver
   clangFormat
   clangFrontend
+  clangIncludeCleaner
   clangIndex
   clangLex
   clangSema

diff  --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index cbc9c79a66249..f41906b2f0faf 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -88,7 +88,13 @@ struct Config {
 bool StandardLibrary = true;
   } Index;
 
-  enum UnusedIncludesPolicy { Strict, None };
+  enum UnusedIncludesPolicy {
+/// Diagnose unused includes.
+Strict,
+None,
+/// The same as Strict, but using the include-cleaner library.
+Experiment,
+  };
   /// Controls warnings and errors when parsing code.
   struct {
 bool SuppressAll = false;

diff  --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index 7dd4e16c8f3cc..b1876e21ee30d 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -431,11 +431,13 @@ struct FragmentCompiler {
   });
 
 if (F.UnusedIncludes)
-  if (auto Val = compileEnum(
- "UnusedIncludes", **F.UnusedIncludes)
- .map("Strict", Config::UnusedIncludesPolicy::Strict)
- .map("None", Config::UnusedIncludesPolicy::None)
- .value())
+  if (auto Val =
+  compileEnum("UnusedIncludes",
+**F.UnusedIncludes)
+  .map("Strict", Config::UnusedIncludesPolicy::Strict)
+  .map("Experiment", Config::UnusedIncludesPolicy::Experiment)
+  .map("None", Config::UnusedIncludesPolicy::None)
+  .value())
 Out.Apply.push_back([Val](const Params &, Config &C) {
   C.Diagnostics.UnusedIncludes = *Val;
 });

diff  --git a/clang-tools-extra/clangd/IncludeCleaner.cpp 
b/clang-tools-extra/clangd/IncludeCleaner.cpp
index dbed805142b71..5a7df2fc33f69 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.cpp
+++ b/clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -12,6 +12,8 @@
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "SourceCode.h"
+#include "clang-include-cleaner/Analysis.h"
+#include "clang-include-cleaner/Types.h"
 #include "index/CanonicalIncludes.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
@@ -458,6 +460,9 @@ translateToHeaderIDs(const ReferencedFiles &Files,
   return TranslatedHeaderIDs;
 }
 
+// This is the original clangd-own implementation for computing unused
+// #includes. Eventually it will be deprecated and replaced by the
+// include-cleaner-lib-based implementation.
 std::vector computeUnusedIncludes(ParsedAST &AST) {
   const auto &SM = AST.getSourceManager();
 
@@ -469,11 +474,62 @@ std::vector 
computeUnusedIncludes(ParsedAST &AST) {
   translateToHeaderIDs(ReferencedFiles, AST.getIncludeStructure(), SM);
   return getUnused(AST, ReferencedHeaders, ReferencedFiles.SpelledUmbrellas);
 }
+std::vector computeUnusedIncludesExperimental(ParsedAST 
&AST) {
+   const auto &SM = AST.getSourceManager();
+   const auto &Includes = AST.getIncludeStructure();
+   // FIXME: this map should probably be 

[PATCH] D140875: [clangd] prototype: Implement unused include warnings with include-cleaner library.

2023-01-19 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
hokein marked an inline comment as done.
Closed by commit rG939dce12f9f3: [clangd] Implement unused include warnings 
with include-cleaner library. (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D140875?vs=490452&id=490472#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140875

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/ParsedAST.h
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -342,6 +342,8 @@
   auto AST = TU.build();
   EXPECT_THAT(computeUnusedIncludes(AST),
   ElementsAre(Pointee(writtenInclusion("";
+  EXPECT_THAT(computeUnusedIncludesExperimental(AST),
+  ElementsAre(Pointee(writtenInclusion("";
 }
 
 TEST(IncludeCleaner, GetUnusedHeaders) {
@@ -377,6 +379,10 @@
   computeUnusedIncludes(AST),
   UnorderedElementsAre(Pointee(writtenInclusion("\"unused.h\"")),
Pointee(writtenInclusion("\"dir/unused.h\"";
+  EXPECT_THAT(
+  computeUnusedIncludesExperimental(AST),
+  UnorderedElementsAre(Pointee(writtenInclusion("\"unused.h\"")),
+   Pointee(writtenInclusion("\"dir/unused.h\"";
 }
 
 TEST(IncludeCleaner, VirtualBuffers) {
@@ -531,6 +537,9 @@
 // IWYU pragma: private, include "public.h"
 void foo() {}
   )cpp");
+  Config Cfg;
+  Cfg.Diagnostics.UnusedIncludes = Config::Experiment;
+  WithContextValue Ctx(Config::Key, std::move(Cfg));
   ParsedAST AST = TU.build();
 
   auto ReferencedFiles = findReferencedFiles(
@@ -545,6 +554,7 @@
   ReferencedFiles.User.contains(AST.getSourceManager().getMainFileID()));
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
   EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
+  EXPECT_THAT(computeUnusedIncludesExperimental(AST), IsEmpty());
 }
 
 TEST(IncludeCleaner, RecursiveInclusion) {
@@ -573,6 +583,7 @@
 
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
   EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
+  EXPECT_THAT(computeUnusedIncludesExperimental(AST), IsEmpty());
 }
 
 TEST(IncludeCleaner, IWYUPragmaExport) {
@@ -597,6 +608,7 @@
   // FIXME: This is not correct: foo.h is unused but is not diagnosed as such
   // because we ignore headers with IWYU export pragmas for now.
   EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
+  EXPECT_THAT(computeUnusedIncludesExperimental(AST), IsEmpty());
 }
 
 TEST(IncludeCleaner, NoDiagsForObjC) {
Index: clang-tools-extra/clangd/Preamble.h
===
--- clang-tools-extra/clangd/Preamble.h
+++ clang-tools-extra/clangd/Preamble.h
@@ -27,6 +27,7 @@
 #include "Diagnostics.h"
 #include "FS.h"
 #include "Headers.h"
+#include "clang-include-cleaner/Record.h"
 #include "index/CanonicalIncludes.h"
 #include "support/Path.h"
 #include "clang/Frontend/CompilerInvocation.h"
@@ -57,6 +58,8 @@
   // Processes like code completions and go-to-definitions will need #include
   // information, and their compile action skips preamble range.
   IncludeStructure Includes;
+  // Captures #include-mapping information in #included headers.
+  include_cleaner::PragmaIncludes Pragmas;
   // Macros defined in the preamble section of the main file.
   // Users care about headers vs main-file, not preamble vs non-preamble.
   // These should be treated as main-file entities e.g. for code completion.
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -11,6 +11,7 @@
 #include "Config.h"
 #include "Headers.h"
 #include "SourceCode.h"
+#include "clang-include-cleaner/Record.h"
 #include "support/Logger.h"
 #include "support/ThreadsafeFS.h"
 #include "support/Trace.h"
@@ -77,6 +78,9 @@
 
   std::vector takeMarks() { return std::move(Marks); }
 
+  include_cleaner::PragmaIncludes takePragmaIncludes() {
+return std::move(Pragmas);
+  }
   CanonicalIncludes takeCanonicalIncludes() { return std::move(CanonIncludes); }
 
   bool isMainFileIncludeGuarded() const { return IsMainFileIncludeGuarded; }
@@ -118,6 +122,9 @@
 LangOpts = &CI.getLangOpts();
 SourceMgr = &CI

[PATCH] D136315: [clang][Darwin] Try to guess the SDK root with xcrun when unspecified

2023-01-19 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

I just verified that that does indeed happen, and it does:

  $ strace out/gn/bin/clang --target=x86_64-apple-macos -x c -c /dev/null 2>&1 
| grep xcrun
  access("/usr/bin/xcrun", F_OK)  = -1 ENOENT (No such file or 
directory)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136315

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


[PATCH] D141868: [Clang] [Sema] Removed a fix-it for system headers

2023-01-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

You should also add a release note for the changes.




Comment at: clang/lib/Sema/SemaOverload.cpp:10920
 
-  // If we can fix the conversion, suggest the FixIts.
-  for (std::vector::iterator HI = Cand->Fix.Hints.begin(),
-   HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
-FDiag << *HI;
+  // Check that location of Fn is not in system header (rdar://100890960).
+  if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {

Let's drop the rdar link as that's not helpful for anyone outside of Apple.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141868

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


[PATCH] D142092: [include-mapping] Allow multiple headers for the same symbol. Choose the first header of available ones.

2023-01-19 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 490476.
VitaNuo added a comment.

Restore variant logic for overloads. Remove broken logic for accepted variants.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142092

Files:
  clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
  clang/tools/include-mapping/cppreference_parser.py
  clang/tools/include-mapping/gen_std.py

Index: clang/tools/include-mapping/gen_std.py
===
--- clang/tools/include-mapping/gen_std.py
+++ clang/tools/include-mapping/gen_std.py
@@ -14,10 +14,7 @@
 The generated files are located in clang/include/Tooling/Inclusions.
 
 Caveats and FIXMEs:
-  - only symbols directly in "std" namespace are added, we should also add std's
-subnamespace symbols (e.g. chrono).
-  - symbols with multiple variants or defined in multiple headers aren't added,
-e.g. std::move, std::swap
+  - symbols with multiple variants aren't added, e.g., std::move, std::swap
 
 Usage:
   1. Install BeautifulSoup dependency, see instruction:
@@ -69,7 +66,7 @@
 
 def main():
   args = ParseArg()
-  if args.language == 'cpp':
+  if args.symbols == 'cpp':
 page_root = os.path.join(args.cppreference, "en", "cpp")
 symbol_index_root = os.path.join(page_root, "symbol_index")
 parse_pages =  [
@@ -104,17 +101,12 @@
 os.stat(index_page_path).st_mtime).strftime('%Y-%m-%d')
   print(CODE_PREFIX % (args.language.upper(), cppreference_modified_date))
   for symbol in symbols:
-if len(symbol.headers) == 1:
-  # SYMBOL(unqualified_name, namespace, header)
-  print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
-symbol.headers[0]))
-elif len(symbol.headers) == 0:
+if len(symbol.headers) == 0:
   sys.stderr.write("No header found for symbol %s\n" % symbol.name)
 else:
-  # FIXME: support symbols with multiple headers (e.g. std::move).
-  sys.stderr.write("Ambiguous header for symbol %s: %s\n" % (
-  symbol.name, ', '.join(symbol.headers)))
-
-
+  for header in symbol.headers:
+# SYMBOL(unqualified_name, namespace, header)
+print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
+  header))
 if __name__ == '__main__':
   main()
Index: clang/tools/include-mapping/cppreference_parser.py
===
--- clang/tools/include-mapping/cppreference_parser.py
+++ clang/tools/include-mapping/cppreference_parser.py
@@ -118,7 +118,7 @@
 return _ParseSymbolPage(f.read(), name)
 
 
-def _GetSymbols(pool, root_dir, index_page_name, namespace, variants_to_accept):
+def _GetSymbols(pool, root_dir, index_page_name, namespace):
   """Get all symbols listed in the index page. All symbols should be in the
   given namespace.
 
@@ -137,9 +137,7 @@
 for symbol_name, symbol_page_path, variant in _ParseIndexPage(f.read()):
   # Variant symbols (e.g. the std::locale version of isalpha) add ambiguity.
   # FIXME: use these as a fallback rather than ignoring entirely.
-  variants_for_symbol = variants_to_accept.get(
-  (namespace or "") + symbol_name, ())
-  if variant and variant not in variants_for_symbol:
+  if variant:
 continue
   path = os.path.join(root_dir, symbol_page_path)
   if os.path.isfile(path):
@@ -166,13 +164,6 @@
   Args:
 parse_pages: a list of tuples (page_root_dir, index_page_name, namespace)
   """
-  # By default we prefer the non-variant versions, as they're more common. But
-  # there are some symbols, whose variant is more common. This list describes
-  # those symbols.
-  variants_to_accept = {
-  # std::remove<> has variant algorithm.
-  "std::remove": ("algorithm"),
-  }
   symbols = []
   # Run many workers to process individual symbol pages under the symbol index.
   # Don't allow workers to capture Ctrl-C.
@@ -180,8 +171,7 @@
   initializer=lambda: signal.signal(signal.SIGINT, signal.SIG_IGN))
   try:
 for root_dir, page_name, namespace in parse_pages:
-  symbols.extend(_GetSymbols(pool, root_dir, page_name, namespace,
- variants_to_accept))
+  symbols.extend(_GetSymbols(pool, root_dir, page_name, namespace))
   finally:
 pool.terminate()
 pool.join()
Index: clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
===
--- clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -8,6 +8,7 @@
 
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "clang/AST/Decl.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 
@@ -16,8 +17,9 @@
 namespace stdlib {
 
 static llvm::StringRef *HeaderNames;
-static std::pair *Symbol

[PATCH] D142092: [include-mapping] Allow multiple headers for the same symbol. Choose the first header of available ones.

2023-01-19 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 490478.
VitaNuo added a comment.

Fix typo.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142092

Files:
  clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
  clang/tools/include-mapping/cppreference_parser.py
  clang/tools/include-mapping/gen_std.py

Index: clang/tools/include-mapping/gen_std.py
===
--- clang/tools/include-mapping/gen_std.py
+++ clang/tools/include-mapping/gen_std.py
@@ -14,10 +14,7 @@
 The generated files are located in clang/include/Tooling/Inclusions.
 
 Caveats and FIXMEs:
-  - only symbols directly in "std" namespace are added, we should also add std's
-subnamespace symbols (e.g. chrono).
-  - symbols with multiple variants or defined in multiple headers aren't added,
-e.g. std::move, std::swap
+  - symbols with multiple variants aren't added, e.g., std::move, std::swap
 
 Usage:
   1. Install BeautifulSoup dependency, see instruction:
@@ -104,17 +101,12 @@
 os.stat(index_page_path).st_mtime).strftime('%Y-%m-%d')
   print(CODE_PREFIX % (args.language.upper(), cppreference_modified_date))
   for symbol in symbols:
-if len(symbol.headers) == 1:
-  # SYMBOL(unqualified_name, namespace, header)
-  print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
-symbol.headers[0]))
-elif len(symbol.headers) == 0:
+if len(symbol.headers) == 0:
   sys.stderr.write("No header found for symbol %s\n" % symbol.name)
 else:
-  # FIXME: support symbols with multiple headers (e.g. std::move).
-  sys.stderr.write("Ambiguous header for symbol %s: %s\n" % (
-  symbol.name, ', '.join(symbol.headers)))
-
-
+  for header in symbol.headers:
+# SYMBOL(unqualified_name, namespace, header)
+print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
+  header))
 if __name__ == '__main__':
   main()
Index: clang/tools/include-mapping/cppreference_parser.py
===
--- clang/tools/include-mapping/cppreference_parser.py
+++ clang/tools/include-mapping/cppreference_parser.py
@@ -118,7 +118,7 @@
 return _ParseSymbolPage(f.read(), name)
 
 
-def _GetSymbols(pool, root_dir, index_page_name, namespace, variants_to_accept):
+def _GetSymbols(pool, root_dir, index_page_name, namespace):
   """Get all symbols listed in the index page. All symbols should be in the
   given namespace.
 
@@ -137,9 +137,7 @@
 for symbol_name, symbol_page_path, variant in _ParseIndexPage(f.read()):
   # Variant symbols (e.g. the std::locale version of isalpha) add ambiguity.
   # FIXME: use these as a fallback rather than ignoring entirely.
-  variants_for_symbol = variants_to_accept.get(
-  (namespace or "") + symbol_name, ())
-  if variant and variant not in variants_for_symbol:
+  if variant:
 continue
   path = os.path.join(root_dir, symbol_page_path)
   if os.path.isfile(path):
@@ -166,13 +164,6 @@
   Args:
 parse_pages: a list of tuples (page_root_dir, index_page_name, namespace)
   """
-  # By default we prefer the non-variant versions, as they're more common. But
-  # there are some symbols, whose variant is more common. This list describes
-  # those symbols.
-  variants_to_accept = {
-  # std::remove<> has variant algorithm.
-  "std::remove": ("algorithm"),
-  }
   symbols = []
   # Run many workers to process individual symbol pages under the symbol index.
   # Don't allow workers to capture Ctrl-C.
@@ -180,8 +171,7 @@
   initializer=lambda: signal.signal(signal.SIGINT, signal.SIG_IGN))
   try:
 for root_dir, page_name, namespace in parse_pages:
-  symbols.extend(_GetSymbols(pool, root_dir, page_name, namespace,
- variants_to_accept))
+  symbols.extend(_GetSymbols(pool, root_dir, page_name, namespace))
   finally:
 pool.terminate()
 pool.join()
Index: clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
===
--- clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -8,6 +8,7 @@
 
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "clang/AST/Decl.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 
@@ -16,8 +17,9 @@
 namespace stdlib {
 
 static llvm::StringRef *HeaderNames;
-static std::pair *SymbolNames;
-static unsigned *SymbolHeaderIDs;
+static llvm::DenseMap>
+*SymbolNames;
+static llvm::SmallVector *SymbolHeaderIDs;
 static llvm::DenseMap *HeaderIDs;
 // Maps symbol name -> Symbol::ID, within a namespace.
 using NSSymbolMap = llvm::DenseMap;
@@ -29,7 +31,7 @@
 #include "clang/Tooling/Inclusions/CSymbolMap.inc"
 #inc

[PATCH] D141899: [IR][X86] Remove X86AMX type in LLVM IR instead of target extension

2023-01-19 Thread Nikita Popov via Phabricator via cfe-commits
nikic added a comment.

In D141899#4061237 , @zixuan-wu wrote:

> With considering 
> https://llvm.org/docs/DeveloperPolicy.html#ir-backwards-compatibility I think 
> we need make consensus to choose one option from following 2 options.
>
> 1. Remove X86amx type in IR totally. (what I am doing now)
> 2. Without removing X86amx type in IR, just upgrade the x86amx type to target 
> extension and also upgrade bitcast llvm instruction to intrinsic(required). 
> It also includes changing the testcase to target extension type.

I believe the right option is:

3. Remove x86_amx type from the (in-memory) IR representation, but support an 
auto-upgrade for bitcode only.

We do need bitcode auto-upgrade support as a matter of policy, and we shouldn't 
support both type representation at the same time, that would defeat the point 
of the change.

In D141899#4061174 , @LuoYuanke wrote:

> I think target extension type is nice, if it is introduced 2 years ago I 
> would vote for it. However my concern is the compatibility issue as I 
> explained. We need to be compatible to the IR that built by previous 
> compiler, and be compatible to the 3rd party software that based on the 
> x86_amx type. I can't predict more risks for now if we replace an LLVM IR 
> type, but I believe there is big risk hidden.

Due to bitcode auto-upgrade, compatibility with old IR is retained. As long as 
we avoid some of the API changes here, the impact on downstream code should be 
fairly minimal. (Though as already pointed out, downstream impact generally 
doesn't figure into LLVM design decisions anyway.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141899

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


[PATCH] D141992: [NFC] [Serialization] Add static assert for the size of the decls to mention developers to remember to touch the serializer after them modified the field of decls

2023-01-19 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D141992#4063978 , @ChuanqiXu wrote:

>> Ah, Windows build failures are obviously relevant :) One gotcha here is 
>> going to be to chase down all the sizes of the records on different 
>> platforms.
>
> The failure shouldn't be related the patch since the patch itself should only 
> cause static assert failures. I saw you guys have already found the solutions 
> in D141954 . So I am going to land this.

No, that patch was talking about the libcxx issue.  The windows issues I saw in 
pre-commit CI on this patch were it hitting your assert all over the place.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141992

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


[PATCH] D136315: [clang][Darwin] Try to guess the SDK root with xcrun when unspecified

2023-01-19 Thread Caleb Zulawski via Phabricator via cfe-commits
calebzulawski added a comment.

I don't think we necessarily need to revert due to the xcrun quirk since I 
think it's harmless, though I can provide a follow up change if necessary.  I 
just checked Rust's source as a comparison and it appears that for macOS 
targets it will always attempt to invoke xcrun regardless of host as well.  I 
could see a macOS cross-compiler environment providing an xcrun replacement, 
for example.  The test failures are another issue but I still don't quite 
understand the cause.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136315

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


[PATCH] D141954: Forbid implicit conversion of constraint expression to bool

2023-01-19 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 490490.
erichkeane added a comment.

Fix clang-format, hopefully this saves me from the bots ;)


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

https://reviews.llvm.org/D141954

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaConcept.cpp
  
clang/test/CXX/temp/temp.constr/temp.constr.atomic/constrant-satisfaction-conversions.cpp

Index: clang/test/CXX/temp/temp.constr/temp.constr.atomic/constrant-satisfaction-conversions.cpp
===
--- /dev/null
+++ clang/test/CXX/temp/temp.constr/temp.constr.atomic/constrant-satisfaction-conversions.cpp
@@ -0,0 +1,67 @@
+// RUN: %clang_cc1 -std=c++20 -x c++ -Wno-constant-logical-operand -verify %s
+
+template concept C =
+sizeof(T) == 4 && !true;  // requires atomic constraints sizeof(T) == 4 and !true
+
+template concept C2 = sizeof(T); // expected-error{{atomic constraint must be of type 'bool' (found }}
+
+template struct S {
+  constexpr operator bool() const { return true; }
+};
+
+// expected-error@+3{{atomic constraint must be of type 'bool' (found 'S')}}
+// expected-note@#FINST{{while checking constraint satisfaction}}
+// expected-note@#FINST{{in instantiation of function template specialization}}
+template requires (S{})
+void f(T);
+void f(int);
+
+// Ensure this applies to operator && as well.
+// expected-error@+3{{atomic constraint must be of type 'bool' (found 'S')}}
+// expected-note@#F2INST{{while checking constraint satisfaction}}
+// expected-note@#F2INST{{in instantiation of function template specialization}}
+template requires (S{} && true)
+void f2(T);
+void f2(int);
+
+template requires requires {
+  requires S{};
+  // expected-error@-1{{atomic constraint must be of type 'bool' (found 'S')}}
+  // expected-note@-2{{while checking the satisfaction}}
+  // expected-note@-3{{in instantiation of requirement}}
+  // expected-note@-4{{while checking the satisfaction}}
+  // expected-note@-6{{while substituting template arguments}}
+  // expected-note@#F3INST{{while checking constraint satisfaction}}
+  // expected-note@#F3INST{{in instantiation of function template specialization}}
+  //
+}
+void f3(T);
+void f3(int);
+
+// Doesn't diagnose, since this is no longer a compound requirement.
+template requires (bool(1 && 2))
+void f4(T);
+void f4(int);
+
+void g() {
+  f(0); // #FINST
+  f2(0); // #F2INST
+  f3(0); // #F3INST
+  f4(0);
+}
+
+template
+auto Nullptr = nullptr;
+
+template concept NullTy = Nullptr;
+// expected-error@-1{{atomic constraint must be of type 'bool' (found }}
+// expected-note@+1{{while checking the satisfaction}}
+static_assert(NullTy);
+
+template
+auto Struct = S{};
+
+template concept StructTy = Struct;
+// expected-error@-1{{atomic constraint must be of type 'bool' (found 'S')}}
+// expected-note@+1{{while checking the satisfaction}}
+static_assert(StructTy);
Index: clang/lib/Sema/SemaConcept.cpp
===
--- clang/lib/Sema/SemaConcept.cpp
+++ clang/lib/Sema/SemaConcept.cpp
@@ -329,14 +329,7 @@
   Sema::SFINAETrap Trap(S);
   SubstitutedExpression =
   S.SubstConstraintExpr(const_cast(AtomicExpr), MLTAL);
-  // Substitution might have stripped off a contextual conversion to
-  // bool if this is the operand of an '&&' or '||'. For example, we
-  // might lose an lvalue-to-rvalue conversion here. If so, put it back
-  // before we try to evaluate.
-  if (SubstitutedExpression.isUsable() &&
-  !SubstitutedExpression.isInvalid())
-SubstitutedExpression =
-S.PerformContextuallyConvertToBool(SubstitutedExpression.get());
+
   if (SubstitutedExpression.isInvalid() || Trap.hasErrorOccurred()) {
 // C++2a [temp.constr.atomic]p1
 //   ...If substitution results in an invalid type or expression, the
@@ -373,6 +366,22 @@
 if (!S.CheckConstraintExpression(SubstitutedExpression.get()))
   return ExprError();
 
+// [temp.constr.atomic]p3: To determine if an atomic constraint is
+// satisfied, the parameter mapping and template arguments are first
+// substituted into its expression.  If substitution results in an
+// invalid type or expression, the constraint is not satisfied.
+// Otherwise, the lvalue-to-rvalue conversion is performed if necessary,
+// and E shall be a constant expression of type bool.
+//
+// Perform the L to R Value conversion if necessary. We do so for all
+// non-PRValue categories, else we fail to extend the lifetime of
+// temporaries, and that fails the constant expression check.
+if (!SubstitutedExpression.get()->isPRValue())
+  SubstitutedExpression = ImplicitCastExpr::Create(
+  S.Context, SubstitutedExpression.get()->getType(),
+  CK_LValueToRValue

[PATCH] D136315: [clang][Darwin] Try to guess the SDK root with xcrun when unspecified

2023-01-19 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

In D136315#4065426 , @calebzulawski 
wrote:

> I don't think we necessarily need to revert due to the xcrun quirk since I 
> think it's harmless, though I can provide a follow up change if necessary.  I 
> just checked Rust's source as a comparison and it appears that for macOS 
> targets it will always attempt to invoke xcrun regardless of host as well.

Needlessly spawning additional processes doesn't seem "harmless" to me.

If you can fix quickly, sure, do that.

> I could see a macOS cross-compiler environment providing an xcrun 
> replacement, for example.

That's theoretically possible I suppose, but it doesn't exist. No mac cross 
compiling uses `xcrun`.

> The test failures are another issue but I still don't quite understand the 
> cause.

I can investigate a bit more. Which version of macOS are you running? Are you 
using system python3 or brew python3? I know that system python3 sets SDKROOT 
by default on macOS 13+ for some reason, so maybe that's related. (The bot runs 
macOS 13.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136315

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


[clang] c441f65 - [clang][dataflow] Add (initial) debug printing for `Value` and `Environment`.

2023-01-19 Thread Yitzhak Mandelbaum via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2023-01-19T14:33:32Z
New Revision: c441f65f9183a4d1d7f5ecc63b4e32a42e09367e

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

LOG: [clang][dataflow] Add (initial) debug printing for `Value` and 
`Environment`.

Also adds uses of the new printing in analysis inner loop.

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/include/clang/Analysis/FlowSensitive/Value.h
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
clang/lib/Analysis/FlowSensitive/Value.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 694dd0ea67d79..e457430a5e646 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -430,6 +430,7 @@ class Environment {
   }
 
   LLVM_DUMP_METHOD void dump() const;
+  LLVM_DUMP_METHOD void dump(raw_ostream &OS) const;
 
 private:
   /// Creates a value appropriate for `Type`, if `Type` is supported, otherwise

diff  --git a/clang/include/clang/Analysis/FlowSensitive/Value.h 
b/clang/include/clang/Analysis/FlowSensitive/Value.h
index 9012d3b00060c..32d10a3489483 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Value.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Value.h
@@ -19,6 +19,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 
@@ -310,6 +311,8 @@ class StructValue final : public Value {
   llvm::DenseMap Children;
 };
 
+raw_ostream &operator<<(raw_ostream &OS, const Value &Val);
+
 } // namespace dataflow
 } // namespace clang
 

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 37d200509e8d2..064d0f92e71a4 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -786,9 +786,29 @@ bool Environment::flowConditionImplies(BoolValue &Val) 
const {
   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
 }
 
-void Environment::dump() const {
+void Environment::dump(raw_ostream &OS) const {
+  // FIXME: add printing for remaining fields and allow caller to decide what
+  // fields are printed.
+  OS << "DeclToLoc:\n";
+  for (auto [D, L] : DeclToLoc)
+OS << "  [" << D->getName() << ", " << L << "]\n";
+
+  OS << "ExprToLoc:\n";
+  for (auto [E, L] : ExprToLoc)
+OS << "  [" << E << ", " << L << "]\n";
+
+  OS << "LocToVal:\n";
+  for (auto [L, V] : LocToVal) {
+OS << "  [" << L << ", " << V << ": " << *V << "]\n";
+  }
+
+  OS << "FlowConditionToken:\n";
   DACtx->dumpFlowCondition(*FlowConditionToken);
 }
 
+void Environment::dump() const {
+  dump(llvm::dbgs());
+}
+
 } // namespace dataflow
 } // namespace clang

diff  --git a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp 
b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
index dc923fe241975..b125701212c96 100644
--- a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -32,8 +32,10 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/Debug.h"
 #include "llvm/Support/Error.h"
-#include "llvm/Support/ErrorHandling.h"
+
+#define DEBUG_TYPE "clang-dataflow"
 
 namespace clang {
 namespace dataflow {
@@ -431,6 +433,8 @@ runTypeErasedDataflowAnalysis(
   std::min(RelativeMaxIterations, AbsoluteMaxIterations);
   uint32_t Iterations = 0;
   while (const CFGBlock *Block = Worklist.dequeue()) {
+LLVM_DEBUG(llvm::dbgs()
+   << "Processing Block " << Block->getBlockID() << "\n");
 if (++Iterations > MaxIterations) {
   return llvm::createStringError(std::errc::timed_out,
  "maximum number of iterations reached");
@@ -440,8 +444,16 @@ runTypeErasedDataflowAnalysis(
 BlockStates[Block->getBlockID()];
 TypeErasedDataflowAnalysisState NewBlockState =
 transferCFGBlock(*Block, AC);
+LLVM_DEBUG({
+  llvm::errs() << "New Env:\n";
+  NewBlockState.Env.dump();
+});
 
 if (OldBlockState) {
+  LLVM_DEBUG({
+llvm::errs() << "Old Env:\n";
+OldBlockState->Env.dump();
+  });
   if (isLoopHead(*Block)) {
 LatticeJoinEffect Effect1 = Analysis.widenTypeErased(
 NewBlockState.Lattice,

[PATCH] D141716: [clang][dataflow] Add (initial) debug printing for `Value` and `Environment`.

2023-01-19 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
ymandel marked an inline comment as done.
Closed by commit rGc441f65f9183: [clang][dataflow] Add (initial) debug printing 
for `Value` and `Environment`. (authored by ymandel).

Changed prior to commit:
  https://reviews.llvm.org/D141716?vs=490470&id=490496#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141716

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/Value.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/lib/Analysis/FlowSensitive/Value.cpp

Index: clang/lib/Analysis/FlowSensitive/Value.cpp
===
--- clang/lib/Analysis/FlowSensitive/Value.cpp
+++ clang/lib/Analysis/FlowSensitive/Value.cpp
@@ -11,6 +11,7 @@
 //===--===//
 
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Analysis/FlowSensitive/DebugSupport.h"
 #include "llvm/Support/Casting.h"
 
 namespace clang {
@@ -35,5 +36,21 @@
  areEquivalentIndirectionValues(Val1, Val2)));
 }
 
+raw_ostream &operator<<(raw_ostream &OS, const Value &Val) {
+  switch (Val.getKind()) {
+  case Value::Kind::Reference: {
+const auto *RV = cast(&Val);
+return OS << "Reference(" << &RV->getReferentLoc() << ")";
+  }
+  case Value::Kind::Pointer: {
+const auto *PV = dyn_cast(&Val);
+return OS << "Pointer(" << &PV->getPointeeLoc() << ")";
+  }
+  // FIXME: support remaining cases.
+  default:
+return OS << debugString(Val.getKind());
+  }
+}
+
 } // namespace dataflow
 } // namespace clang
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -32,8 +32,10 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/Debug.h"
 #include "llvm/Support/Error.h"
-#include "llvm/Support/ErrorHandling.h"
+
+#define DEBUG_TYPE "clang-dataflow"
 
 namespace clang {
 namespace dataflow {
@@ -431,6 +433,8 @@
   std::min(RelativeMaxIterations, AbsoluteMaxIterations);
   uint32_t Iterations = 0;
   while (const CFGBlock *Block = Worklist.dequeue()) {
+LLVM_DEBUG(llvm::dbgs()
+   << "Processing Block " << Block->getBlockID() << "\n");
 if (++Iterations > MaxIterations) {
   return llvm::createStringError(std::errc::timed_out,
  "maximum number of iterations reached");
@@ -440,8 +444,16 @@
 BlockStates[Block->getBlockID()];
 TypeErasedDataflowAnalysisState NewBlockState =
 transferCFGBlock(*Block, AC);
+LLVM_DEBUG({
+  llvm::errs() << "New Env:\n";
+  NewBlockState.Env.dump();
+});
 
 if (OldBlockState) {
+  LLVM_DEBUG({
+llvm::errs() << "Old Env:\n";
+OldBlockState->Env.dump();
+  });
   if (isLoopHead(*Block)) {
 LatticeJoinEffect Effect1 = Analysis.widenTypeErased(
 NewBlockState.Lattice, OldBlockState->Lattice);
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -786,9 +786,29 @@
   return DACtx->flowConditionImplies(*FlowConditionToken, Val);
 }
 
-void Environment::dump() const {
+void Environment::dump(raw_ostream &OS) const {
+  // FIXME: add printing for remaining fields and allow caller to decide what
+  // fields are printed.
+  OS << "DeclToLoc:\n";
+  for (auto [D, L] : DeclToLoc)
+OS << "  [" << D->getName() << ", " << L << "]\n";
+
+  OS << "ExprToLoc:\n";
+  for (auto [E, L] : ExprToLoc)
+OS << "  [" << E << ", " << L << "]\n";
+
+  OS << "LocToVal:\n";
+  for (auto [L, V] : LocToVal) {
+OS << "  [" << L << ", " << V << ": " << *V << "]\n";
+  }
+
+  OS << "FlowConditionToken:\n";
   DACtx->dumpFlowCondition(*FlowConditionToken);
 }
 
+void Environment::dump() const {
+  dump(llvm::dbgs());
+}
+
 } // namespace dataflow
 } // namespace clang
Index: clang/include/clang/Analysis/FlowSensitive/Value.h
===
--- clang/include/clang/Analysis/FlowSensitive/Value.h
+++ clang/include/clang/Analysis/FlowSensitive/Value.h
@@ -19,6 +19,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 
@@ -310,6 +311

[PATCH] D142113: [clang][nfc] refactor Module::Header to use OptionalFileEntryRef

2023-01-19 Thread Richard Howell via Phabricator via cfe-commits
rmaz created this revision.
Herald added a subscriber: ChuanqiXu.
Herald added a project: All.
rmaz requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Refactor the `Module::Header` class to use an `OptionalFileEntryRef` 
instead of a `FileEntry*`.

This is mostly based on https://reviews.llvm.org/D90497


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D142113

Files:
  clang/include/clang/Basic/Module.h
  clang/include/clang/Lex/ModuleMap.h
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Sema/SemaModule.cpp
  clang/lib/Serialization/ASTReader.cpp

Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -1947,7 +1947,7 @@
   Reader.ResolveImportedPath(M, Filename);
 // FIXME: NameAsWritten
 Module::Header H = {std::string(key.Filename), "",
-*FileMgr.getFile(Filename)};
+*FileMgr.getOptionalFileRef(Filename)};
 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
 HFI.isModuleHeader |= ModuleMap::isModular(HeaderRole);
   }
@@ -5661,7 +5661,7 @@
   //`Headers/`, so this path will never exist.
   std::string Filename = std::string(Blob);
   ResolveImportedPath(F, Filename);
-  if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
+  if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
 if (!CurrentModule->getUmbrellaHeader()) {
   // FIXME: NameAsWritten
   ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob, "");
Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -120,12 +120,12 @@
   // TODO: Make the C++20 header lookup independent.
   // When the input is pre-processed source, we need a file ref to the original
   // file for the header map.
-  auto F = SourceMgr.getFileManager().getFile(HUName);
+  auto F = SourceMgr.getFileManager().getOptionalFileRef(HUName);
   // For the sake of error recovery (if someone has moved the original header
   // after creating the pre-processed output) fall back to obtaining the file
   // ref for the input file, which must be present.
   if (!F)
-F = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
+F = SourceMgr.getFileEntryRefForID(SourceMgr.getMainFileID());
   assert(F && "failed to find the header unit source?");
   Module::Header H{HUName.str(), HUName.str(), *F};
   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -304,7 +304,7 @@
   // supplied by Clang. Find that builtin header.
   SmallString<128> Path;
   llvm::sys::path::append(Path, BuiltinIncludeDir->getName(), Header.FileName);
-  auto File = SourceMgr.getFileManager().getFile(Path);
+  auto File = SourceMgr.getFileManager().getOptionalFileRef(Path);
   if (!File)
 return false;
 
@@ -1024,7 +1024,7 @@
   // Look for an umbrella header.
   SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
   llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
-  auto UmbrellaHeader = FileMgr.getFile(UmbrellaName);
+  auto UmbrellaHeader = FileMgr.getOptionalFileRef(UmbrellaName);
 
   // FIXME: If there's no umbrella header, we could probably scan the
   // framework to load *everything*. But, it's not clear that this is a good
@@ -1136,14 +1136,14 @@
 }
 
 void ModuleMap::setUmbrellaHeader(
-Module *Mod, const FileEntry *UmbrellaHeader, const Twine &NameAsWritten,
+Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten,
 const Twine &PathRelativeToRootModuleDirectory) {
   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
-  Mod->Umbrella = UmbrellaHeader;
+  Mod->Umbrella = &UmbrellaHeader.getMapEntry();
   Mod->UmbrellaAsWritten = NameAsWritten.str();
   Mod->UmbrellaRelativeToRootModuleDirectory =
   PathRelativeToRootModuleDirectory.str();
-  UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
+  UmbrellaDirs[UmbrellaHeader.getDir()] = Mod;
 
   // Notify callbacks that we just added a new header.
   for (const auto &Cb : Callbacks)
@@ -2510,7 +2510,7 @@
 SourceMgr.getFileManager().getVirtualFileSystem();
 for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
  I != E && !EC; I.increment(EC)) {
-  if (auto FE = SourceMgr.getFileManager().getFile(I->path())) {
+  if (auto FE = SourceMgr.getFileManager().getOptionalFileRef(I->path())) {
 Module::Header Header = {"", std::string(I->path()), *FE};
 Headers.push_back(std::move(Header));
   }
Index: clang/lib/Frontend/Fron

[PATCH] D142028: [clang] remove SUBMODULE_TOPHEADER

2023-01-19 Thread Richard Howell via Phabricator via cfe-commits
rmaz abandoned this revision.
rmaz added a comment.

Its going to be less work to refactor TopheaderNames to use FileEntryRef, so 
went that way instead. First step is here: https://reviews.llvm.org/D142113


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142028

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


[PATCH] D142094: [Clang][Doc] Add release note for changes for the RVV intrinsics

2023-01-19 Thread Alex Bradbury via Phabricator via cfe-commits
asb added a comment.

In D142094#4065175 , @eopXD wrote:

> @asb I just saw the cancellation of the sync-up call today. Regarding the 
> branch out on 01/24 I think it would be good to have these incompatible 
> changes into LLVM 16.

Sorry for missing there were open questions about this. I won't uncancel the 
meeting at this point as I think that will just cause more confusion.

What does GCC currently do about these intrinsics? I think the obvious concern 
would be that by continuing to alter these intrinsics across releases, we're 
extending the compatibility issue.

Though without RVV 1.0 being agreed yet, I don't see any options other than 
just documenting where we're at and noting that more changes are possible (as 
this change does), or alternatively moving the intrinsics to an experimental 
flag until they're unexperimental.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142094

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


[PATCH] D142001: [clang] Use FP options from AST for emitting code for casts

2023-01-19 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff updated this revision to Diff 490504.
sepavloff added a comment.

Use --implicit-check-not in tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142001

Files:
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/CodeGen/X86/avx512dq-builtins-constrained.c
  clang/test/CodeGen/aarch64-v8.2a-neon-intrinsics-constrained.c

Index: clang/test/CodeGen/aarch64-v8.2a-neon-intrinsics-constrained.c
===
--- clang/test/CodeGen/aarch64-v8.2a-neon-intrinsics-constrained.c
+++ clang/test/CodeGen/aarch64-v8.2a-neon-intrinsics-constrained.c
@@ -6,7 +6,7 @@
 // RUN: -ffp-exception-behavior=maytrap -DEXCEPT=1 \
 // RUN: -flax-vector-conversions=none -S -disable-O0-optnone -emit-llvm -o - %s \
 // RUN: | opt -S -passes=mem2reg \
-// RUN: | FileCheck --check-prefix=COMMON --check-prefix=COMMONIR --check-prefix=CONSTRAINED %s
+// RUN: | FileCheck --check-prefix=COMMON --check-prefix=COMMONIR --check-prefix=CONSTRAINED --implicit-check-not=fpexcept.maytrap %s
 // RUN: %clang_cc1 -triple arm64-none-linux-gnu -target-feature +neon -target-feature +fullfp16 -target-feature +v8.2a\
 // RUN: -flax-vector-conversions=none -S -disable-O0-optnone -emit-llvm -o - %s \
 // RUN: | opt -S -passes=mem2reg | llc -o=- - \
@@ -15,13 +15,13 @@
 // RUN: -ffp-exception-behavior=maytrap -DEXCEPT=1 \
 // RUN: -flax-vector-conversions=none -S -disable-O0-optnone -emit-llvm -o - %s \
 // RUN: | opt -S -passes=mem2reg | llc -o=- - \
-// RUN: | FileCheck --check-prefix=COMMON --check-prefix=CHECK-ASM %s
+// RUN: | FileCheck --check-prefix=COMMON --check-prefix=CHECK-ASM --implicit-check-not=fpexcept.maytrap  %s
 
 // REQUIRES: aarch64-registered-target
 
 // Test that the constrained intrinsics are picking up the exception
 // metadata from the AST instead of the global default from the command line.
-// FIXME: All cases of "fpexcept.maytrap" in this test are wrong.
+// Any cases of "fpexcept.maytrap" in this test are clang bugs.
 
 #if EXCEPT
 #pragma float_control(except, on)
@@ -31,7 +31,7 @@
 
 // COMMON-LABEL: test_vsqrt_f16
 // UNCONSTRAINED:  [[SQR:%.*]] = call <4 x half> @llvm.sqrt.v4f16(<4 x half> %a)
-// CONSTRAINED:[[SQR:%.*]] = call <4 x half> @llvm.experimental.constrained.sqrt.v4f16(<4 x half> %a, metadata !"round.tonearest", metadata !"fpexcept.maytrap")
+// CONSTRAINED:[[SQR:%.*]] = call <4 x half> @llvm.experimental.constrained.sqrt.v4f16(<4 x half> %a, metadata !"round.tonearest", metadata !"fpexcept.strict")
 // CHECK-ASM:  fsqrt v{{[0-9]+}}.4h, v{{[0-9]+}}.4h
 // COMMONIR:   ret <4 x half> [[SQR]]
 float16x4_t test_vsqrt_f16(float16x4_t a) {
@@ -40,7 +40,7 @@
 
 // COMMON-LABEL: test_vsqrtq_f16
 // UNCONSTRAINED:  [[SQR:%.*]] = call <8 x half> @llvm.sqrt.v8f16(<8 x half> %a)
-// CONSTRAINED:[[SQR:%.*]] = call <8 x half> @llvm.experimental.constrained.sqrt.v8f16(<8 x half> %a, metadata !"round.tonearest", metadata !"fpexcept.maytrap")
+// CONSTRAINED:[[SQR:%.*]] = call <8 x half> @llvm.experimental.constrained.sqrt.v8f16(<8 x half> %a, metadata !"round.tonearest", metadata !"fpexcept.strict")
 // CHECK-ASM:  fsqrt v{{[0-9]+}}.8h, v{{[0-9]+}}.8h
 // COMMONIR:   ret <8 x half> [[SQR]]
 float16x8_t test_vsqrtq_f16(float16x8_t a) {
@@ -49,7 +49,7 @@
 
 // COMMON-LABEL: test_vfma_f16
 // UNCONSTRAINED:  [[ADD:%.*]] = call <4 x half> @llvm.fma.v4f16(<4 x half> %b, <4 x half> %c, <4 x half> %a)
-// CONSTRAINED:[[ADD:%.*]] = call <4 x half> @llvm.experimental.constrained.fma.v4f16(<4 x half> %b, <4 x half> %c, <4 x half> %a, metadata !"round.tonearest", metadata !"fpexcept.maytrap")
+// CONSTRAINED:[[ADD:%.*]] = call <4 x half> @llvm.experimental.constrained.fma.v4f16(<4 x half> %b, <4 x half> %c, <4 x half> %a, metadata !"round.tonearest", metadata !"fpexcept.strict")
 // CHECK-ASM:  fmla v{{[0-9]+}}.4h, v{{[0-9]+}}.4h, v{{[0-9]+}}.4h
 // COMMONIR:   ret <4 x half> [[ADD]]
 float16x4_t test_vfma_f16(float16x4_t a, float16x4_t b, float16x4_t c) {
@@ -58,7 +58,7 @@
 
 // COMMON-LABEL: test_vfmaq_f16
 // UNCONSTRAINED:  [[ADD:%.*]] = call <8 x half> @llvm.fma.v8f16(<8 x half> %b, <8 x half> %c, <8 x half> %a)
-// CONSTRAINED:[[ADD:%.*]] = call <8 x half> @llvm.experimental.constrained.fma.v8f16(<8 x half> %b, <8 x half> %c, <8 x half> %a, metadata !"round.tonearest", metadata !"fpexcept.maytrap")
+// CONSTRAINED:[[ADD:%.*]] = call <8 x half> @llvm.experimental.constrained.fma.v8f16(<8 x half> %b, <8 x half> %c, <8 x half> %a, metadata !"round.tonearest", metadata !"fpexcept.strict")
 // CHECK-ASM:  fmla v{{[0-9]+}}.8h, v{{[0-9]+}}.8h, v{{[0-9]+}}.8h
 // COMMONIR:   ret <8 x half> [[ADD]]
 float16x8_t test_vfmaq_f16(float16x8_t a, float16x8_t b, float16x8_t c) {
@@ -68,7 +68,7 @@
 // COMMON-LABEL: test_vfms_f16
 // COMMONIR:   [[SUB:%.*]] = fneg <4 x half> %b
 // UNCONSTRAINED:  [[ADD:%.*]] = call <4 x half> @llvm.fma.v4

[PATCH] D139921: [include-cleaner] Ranking of providers based on hints

2023-01-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.
Herald added a subscriber: ChuanqiXu.

LG, just nits really!




Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h:133
+
+  Header(std::in_place_t, decltype(Storage) Sentinel)
+  : Storage(std::move(Sentinel)) {}

this is a bit confusing... kind of the opposite of what `std::in_place` means?
(All of the other constructors build the state in-place in some sense, but this 
one doesn't)

Maybe just a private `struct Sentinel{};` instead of in_place_t?

Symbol does this without any sentinel at all, if that's causing ambiguity then 
it might be worth fixing both to be the same.



Comment at: clang-tools-extra/include-cleaner/lib/AnalysisInternal.h:86
+///
+/// Hints represents the properties of the edges touched when finding headers
+/// that satisfy an AST node (AST node => symbols => locations => headers).

nit: touched => traversed? Since you haven't explicitly mentioned a graph here 
(which is fine), hint at it more specifically



Comment at: clang-tools-extra/include-cleaner/lib/AnalysisInternal.h:91
+/// to merge hints. These hints are merged by taking the union of all the
+/// properties along all the paths, hence these are all expressed positively.
+///

"positive" makes intuitive sense, but not *quite* the right concept. 
(existential vs universal quantification)

Maybe just give an example:
```
We choose the boolean sense accordingly, e.g. "Public" rather than "Private",
because a header is good if it provides any public definition, even if it also 
provides private ones.
```



Comment at: clang-tools-extra/include-cleaner/lib/AnalysisInternal.h:94
+/// Hints are sorted in ascending order of relevance.
+enum class Hint : uint8_t {
+  None = 0x00,

nit: maybe `Hints` over `Hint` to indicate it's a bitset



Comment at: clang-tools-extra/include-cleaner/lib/AnalysisInternal.h:110
+LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
+/// A wrapper to augment types with hints.
+template  struct Hinted : public T {

nit: augment **values** with hints? (or "augment types with `Hint`", but I 
think values is clearer)



Comment at: clang-tools-extra/include-cleaner/lib/AnalysisInternal.h:84
 
+/// Represents properties of a symbol provider.
+enum class Hint : uint8_t {

kadircet wrote:
> sammccall wrote:
> > along with `SymbolLocation`, I think mixing our fundamental types and 
> > analysis functions in this header makes the structure harder to understand 
> > and think they both belong in `Types.h`
> i still don't feel great about exposing these types as public API. would it 
> help if I moved these into a `TypesInternal.h` ?
`AnalysisInternal` < `TypesInternal` < `Types` I think, so yes

(I think separating the concepts/data structures from the 
algorithm/implementation is the important concern here. I don't think 
defensively minimizing surface area is important as the library simply won't 
have many users, and that exposing these is a net win because it makes the 
structure of the system easier for human readers to understand. Anyway, up to 
you)



Comment at: clang-tools-extra/include-cleaner/lib/AnalysisInternal.h:95
+  /// Declaration is explicitly marked as canonical, e.g. with a IWYU private
+  /// pragma that points at this provider.
+  Canonical = 0x04,

sammccall wrote:
> hokein wrote:
> > This comment is hard to follow, it doesn't explain the `Canonical`. From 
> > the design doc, it means `NameMatch` and `Annotated` headers, I think it 
> > would be nice to document them in the comment.
> > 
> > I'd suggest avoid using the `Canonical` name, it remains me too much about 
> > the canonical decl in clang. Maybe `Preferred`?
> +1 to Preferred and also documenting the conditions when a signal is set here 
> in some detail (also for Public and Complete).
> 
> I think we really have to understand what the signal is quite precisely to 
> make correct use of it.
nit: the conditions seem well-documented now, but I think we should drop the 
`e.g.` these should be the actual definitions, not just examples.



Comment at: clang-tools-extra/include-cleaner/lib/FindHeaders.cpp:38
+llvm::SmallVector ranked(llvm::SmallVector> Headers) {
+  llvm::stable_sort(Headers,
+[](const Hinted &LHS, const Hinted &RHS) {

just stable_sort(reverse(Headers))?

(reverse() returns an rbegin/rend view which should DTRT)



Comment at: clang-tools-extra/include-cleaner/lib/FindHeaders.cpp:46
+llvm::SmallVector>
+nameMatch(llvm::StringRef DeclName, llvm::SmallVector> Headers) 
{
+  for (auto &H : Headers) {

this signature seems unneccesarily complicated/hard to understand

what about `n

[PATCH] D136315: [clang][Darwin] Try to guess the SDK root with xcrun when unspecified

2023-01-19 Thread Caleb Zulawski via Phabricator via cfe-commits
calebzulawski added a comment.

In D136315#4065481 , @thakis wrote:

> In D136315#4065426 , @calebzulawski 
> wrote:
>
>> I don't think we necessarily need to revert due to the xcrun quirk since I 
>> think it's harmless, though I can provide a follow up change if necessary.  
>> I just checked Rust's source as a comparison and it appears that for macOS 
>> targets it will always attempt to invoke xcrun regardless of host as well.
>
> Needlessly spawning additional processes doesn't seem "harmless" to me.
>
> If you can fix quickly, sure, do that.
>
>> I could see a macOS cross-compiler environment providing an xcrun 
>> replacement, for example.
>
> That's theoretically possible I suppose, but it doesn't exist. No mac cross 
> compiling uses `xcrun`.

Sorry, I agree that we shouldn't do things needlessly, but xcrun is only 
invoked if the compiler otherwise can't figure out the sysroot.  I just tried 
using `--target=x86_64-apple-macos` on its own on Linux and sure enough the 
sysroot included `/usr/include` etc, which is surely also wrong.  I suspect any 
existing cross-compiler environments either set SDKROOT or pass a sysroot flag, 
otherwise they wouldn't work (and this change doesn't affect them).

It seems osxcross does provide an xcrun replacement: 
https://github.com/tpoechtrager/osxcross/blob/master/wrapper/programs/xcrun.cpp

>> The test failures are another issue but I still don't quite understand the 
>> cause.
>
> I can investigate a bit more. Which version of macOS are you running? Are you 
> using system python3 or brew python3? I know that system python3 sets SDKROOT 
> by default on macOS 13+ for some reason, so maybe that's related. (The bot 
> runs macOS 13.)

I'm using 13.1 and I do have brew python installed.  I see what you're 
describing, system python has SDKROOT set.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136315

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


[clang] ee700de - [AArch64] Armv9-A implies FP16

2023-01-19 Thread David Green via cfe-commits

Author: David Green
Date: 2023-01-19T15:37:50Z
New Revision: ee700dec052a0336798fb2570faec31719b53f8d

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

LOG: [AArch64] Armv9-A implies FP16

As Armv9-a implies SVE2 it implies SVE (added in D141411) and so it
should also imply FP16, which this patch adds. This helps get the target
features correct when using `target("arch=armv9-a")` attributes.

There is also an adjustment to AssertSameExtensionFlags in this patch to
make it print cpu names, useful when the TargetParser unit tests are run
through lit to distinguish which cpu is failing.

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

Added: 


Modified: 
clang/test/CodeGen/aarch64-targetattr-arch.c
clang/test/CodeGen/aarch64-targetattr.c
llvm/include/llvm/TargetParser/AArch64TargetParser.h
llvm/unittests/TargetParser/TargetParserTest.cpp

Removed: 




diff  --git a/clang/test/CodeGen/aarch64-targetattr-arch.c 
b/clang/test/CodeGen/aarch64-targetattr-arch.c
index d70d68c6e6a21..86ddeac0b9e62 100644
--- a/clang/test/CodeGen/aarch64-targetattr-arch.c
+++ b/clang/test/CodeGen/aarch64-targetattr-arch.c
@@ -8,6 +8,7 @@
 #endif
 
 #include 
+#include 
 #include 
 
 __attribute__((target("arch=armv8.1-a")))
@@ -22,6 +23,12 @@ svint8_t test_svadd_attr(svbool_t pg, svint8_t op1, svint8_t 
op2)
   return svadd_s8_z(pg, op1, op2);
 }
 
+__attribute__((target("arch=armv9-a")))
+float16_t test_fp16_on_v9(float16_t x, float16_t y)
+{
+  return vabdh_f16(x, y);
+}
+
 void test_errors()
 {
 #ifdef HAS8

diff  --git a/clang/test/CodeGen/aarch64-targetattr.c 
b/clang/test/CodeGen/aarch64-targetattr.c
index 8730ecfbd1343..6ce3c72c44b72 100644
--- a/clang/test/CodeGen/aarch64-targetattr.c
+++ b/clang/test/CodeGen/aarch64-targetattr.c
@@ -93,7 +93,7 @@ void nosimd() {}
 // CHECK: attributes #1 = { {{.*}} 
"target-features"="+crc,+fp-armv8,+fullfp16,+lse,+neon,+ras,+rdm,+sve,+v8.1a,+v8.2a,+v8a"
 }
 // CHECK: attributes #2 = { {{.*}} 
"target-features"="+crc,+fp-armv8,+fullfp16,+lse,+neon,+ras,+rdm,+sve,+sve2,+v8.1a,+v8.2a,+v8a"
 }
 // CHECK: attributes #3 = { {{.*}} 
"target-features"="+aes,+bf16,+crc,+dotprod,+fp-armv8,+fullfp16,+i8mm,+lse,+neon,+ras,+rcpc,+rdm,+sha2,+sha3,+sm4,+sve,+sve2,+v8.1a,+v8.2a,+v8.3a,+v8.4a,+v8.5a,+v8.6a,+v8a"
 }
-// CHECK: attributes #4 = { {{.*}} "target-cpu"="cortex-a710" 
"target-features"="+bf16,+crc,+dotprod,+flagm,+fp-armv8,+fp16fml,+i8mm,+lse,+mte,+neon,+pauth,+ras,+rcpc,+rdm,+sb,+sve,+sve2,+sve2-bitperm"
 }
+// CHECK: attributes #4 = { {{.*}} "target-cpu"="cortex-a710" 
"target-features"="+bf16,+crc,+dotprod,+flagm,+fp-armv8,+fp16fml,+fullfp16,+i8mm,+lse,+mte,+neon,+pauth,+ras,+rcpc,+rdm,+sb,+sve,+sve2,+sve2-bitperm"
 }
 // CHECK: attributes #5 = { {{.*}} "tune-cpu"="cortex-a710" }
 // CHECK: attributes #6 = { {{.*}} "target-cpu"="generic" }
 // CHECK: attributes #7 = { {{.*}} "tune-cpu"="generic" }

diff  --git a/llvm/include/llvm/TargetParser/AArch64TargetParser.h 
b/llvm/include/llvm/TargetParser/AArch64TargetParser.h
index 3c416e4576e56..ff6a629c8faa0 100644
--- a/llvm/include/llvm/TargetParser/AArch64TargetParser.h
+++ b/llvm/include/llvm/TargetParser/AArch64TargetParser.h
@@ -314,7 +314,7 @@ inline constexpr ArchInfo ARMV8_6A  = { VersionTuple{8, 6}, 
AProfile, "armv8.6-a
 inline constexpr ArchInfo ARMV8_7A  = { VersionTuple{8, 7}, AProfile, 
"armv8.7-a", "+v8.7a", (ARMV8_6A.DefaultExts)};
 inline constexpr ArchInfo ARMV8_8A  = { VersionTuple{8, 8}, AProfile, 
"armv8.8-a", "+v8.8a", (ARMV8_7A.DefaultExts | AArch64::AEK_MOPS | 
AArch64::AEK_HBC)};
 inline constexpr ArchInfo ARMV8_9A  = { VersionTuple{8, 9}, AProfile, 
"armv8.9-a", "+v8.9a", (ARMV8_8A.DefaultExts)};
-inline constexpr ArchInfo ARMV9A= { VersionTuple{9, 0}, AProfile, 
"armv9-a", "+v9a", (BaseNoCrypto | AArch64::AEK_SVE | AArch64::AEK_SVE2)};
+inline constexpr ArchInfo ARMV9A= { VersionTuple{9, 0}, AProfile, 
"armv9-a", "+v9a", (BaseNoCrypto | AArch64::AEK_FP16 | AArch64::AEK_SVE | 
AArch64::AEK_SVE2)};
 inline constexpr ArchInfo ARMV9_1A  = { VersionTuple{9, 1}, AProfile, 
"armv9.1-a", "+v9.1a", (ARMV9A.DefaultExts | AArch64::AEK_BF16 | 
AArch64::AEK_I8MM)};
 inline constexpr ArchInfo ARMV9_2A  = { VersionTuple{9, 2}, AProfile, 
"armv9.2-a", "+v9.2a", (ARMV9_1A.DefaultExts)};
 inline constexpr ArchInfo ARMV9_3A  = { VersionTuple{9, 3}, AProfile, 
"armv9.3-a", "+v9.3a", (ARMV9_2A.DefaultExts | AArch64::AEK_MOPS | 
AArch64::AEK_HBC)};
@@ -509,4 +509,4 @@ uint64_t getCpuSupportsMask(ArrayRef 
FeatureStrs);
 } // namespace AArch64
 } // namespace llvm
 
-#endif
\ No newline at end of file
+#endif

diff  --git a/llvm/unittests/TargetParser/TargetParserTest.cpp 
b/llvm/unittests/TargetParser/TargetParserTest.cpp
index 7bf20ef87436b..39de9e25c8cca 100644
--- a/llvm/unittests/

[PATCH] D142087: [AArch64] Armv9-A implies FP16

2023-01-19 Thread Dave Green 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 rGee700dec052a: [AArch64] Armv9-A implies FP16 (authored by 
dmgreen).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D142087?vs=490391&id=490510#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142087

Files:
  clang/test/CodeGen/aarch64-targetattr-arch.c
  clang/test/CodeGen/aarch64-targetattr.c
  llvm/include/llvm/TargetParser/AArch64TargetParser.h
  llvm/unittests/TargetParser/TargetParserTest.cpp

Index: llvm/unittests/TargetParser/TargetParserTest.cpp
===
--- llvm/unittests/TargetParser/TargetParserTest.cpp
+++ llvm/unittests/TargetParser/TargetParserTest.cpp
@@ -68,19 +68,26 @@
   return llvm::join(Features, ", ");
 }
 
-template 
-testing::AssertionResult
-AssertSameExtensionFlags(const char *m_expr, const char *n_expr,
- uint64_t ExpectedFlags, uint64_t GotFlags) {
-  if (ExpectedFlags == GotFlags)
-return testing::AssertionSuccess();
-
-  return testing::AssertionFailure() << llvm::formatv(
- "Expected extension flags: {0} ({1:x})\n"
- " Got extension flags: {2} ({3:x})\n",
- FormatExtensionFlags(ExpectedFlags), ExpectedFlags,
- FormatExtensionFlags(GotFlags), GotFlags);
-}
+template  struct AssertSameExtensionFlags {
+  AssertSameExtensionFlags(StringRef CPUName) : CPUName(CPUName) {}
+
+  testing::AssertionResult operator()(const char *m_expr, const char *n_expr,
+  uint64_t ExpectedFlags,
+  uint64_t GotFlags) {
+if (ExpectedFlags == GotFlags)
+  return testing::AssertionSuccess();
+
+return testing::AssertionFailure() << llvm::formatv(
+   "CPU: {4}\n"
+   "Expected extension flags: {0} ({1:x})\n"
+   " Got extension flags: {2} ({3:x})\n",
+   FormatExtensionFlags(ExpectedFlags), ExpectedFlags,
+   FormatExtensionFlags(GotFlags), GotFlags, CPUName);
+  }
+
+private:
+  StringRef CPUName;
+};
 
 struct ARMCPUTestParams {
   ARMCPUTestParams(StringRef CPUName, StringRef ExpectedArch,
@@ -116,8 +123,9 @@
   EXPECT_EQ(params.ExpectedFPU, ARM::getFPUName(FPUKind));
 
   uint64_t default_extensions = ARM::getDefaultExtensions(params.CPUName, AK);
-  EXPECT_PRED_FORMAT2(AssertSameExtensionFlags,
-  params.ExpectedFlags, default_extensions);
+  EXPECT_PRED_FORMAT2(
+  AssertSameExtensionFlags(params.CPUName),
+  params.ExpectedFlags, default_extensions);
 
   EXPECT_EQ(params.CPUAttr, ARM::getCPUAttr(AK));
 }
@@ -958,8 +966,9 @@
 
   uint64_t default_extensions =
   AArch64::getDefaultExtensions(params.CPUName, AI);
-  EXPECT_PRED_FORMAT2(AssertSameExtensionFlags,
-  params.ExpectedFlags, default_extensions);
+  EXPECT_PRED_FORMAT2(
+  AssertSameExtensionFlags(params.CPUName),
+  params.ExpectedFlags, default_extensions);
 }
 
 INSTANTIATE_TEST_SUITE_P(
@@ -997,7 +1006,8 @@
  AArch64::AEK_SVE | AArch64::AEK_SVE2 |
  AArch64::AEK_SVE2BITPERM | AArch64::AEK_PAUTH |
  AArch64::AEK_MTE | AArch64::AEK_SSBS |
- AArch64::AEK_FP16FML | AArch64::AEK_SB,
+ AArch64::AEK_FP16 | AArch64::AEK_FP16FML |
+ AArch64::AEK_SB,
  "9-A"),
 ARMCPUTestParams("cortex-a57", "armv8-a", "crypto-neon-fp-armv8",
  AArch64::AEK_CRC | AArch64::AEK_CRYPTO |
@@ -1076,17 +1086,16 @@
  AArch64::AEK_PROFILE | AArch64::AEK_FLAGM |
  AArch64::AEK_PAUTH | AArch64::AEK_FP16FML,
  "8.2-A"),
-ARMCPUTestParams("cortex-a710", "armv9-a", "neon-fp-armv8",
- AArch64::AEK_CRC | AArch64::AEK_FP |
- AArch64::AEK_SIMD | AArch64::AEK_RAS |
- AArch64::AEK_LSE | AArch64::AEK_RDM |
- AArch64::AEK_RCPC | AArch64::AEK_DOTPROD |
- AArch64::AEK_MTE | AArch64::AEK_FP16FML |
- AArch64::AEK_SVE | AArch64::AEK_SVE2 |
- AArch64::AEK_SVE2BITPERM | AArch64::AEK_PAUTH |
- AArch64::AEK_FLAGM | AArch64::AEK_SB |
- AArch64::AEK_I8MM | AArch64::AEK_BF16,
- "9-A"),
+ARMCPUTestParams(
+"cortex-a710", "armv9-a", "neon-fp-armv8",
+AArch64::AEK_CRC | AArch64::AEK_FP | AArch64::AEK_SIMD |
+AArch64::AEK_RAS

[PATCH] D142118: [HIP] Unbundler allows missing host entry

2023-01-19 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added a reviewer: tra.
Herald added a project: All.
yaxunl requested review of this revision.
Herald added subscribers: sstefan1, MaskRay.
Herald added a reviewer: jdoerfert.

clang-offload-bundler should allow missing host entry when unbundling with 
option
--allow-missing-bundles specified.

This is for the use cases where users want to link device-only bundles with
bundles containing both device and host entries.


https://reviews.llvm.org/D142118

Files:
  clang/lib/Driver/OffloadBundler.cpp
  clang/test/Driver/clang-offload-bundler.c


Index: clang/test/Driver/clang-offload-bundler.c
===
--- clang/test/Driver/clang-offload-bundler.c
+++ clang/test/Driver/clang-offload-bundler.c
@@ -224,8 +224,11 @@
 // RUN: diff %t.empty %t.res.tgt2
 
 // Check that bindler prints an error if given host bundle does not exist in 
the fat binary.
-// RUN: not clang-offload-bundler -type=s 
-targets=host-amdgcn-xxx-linux-gnu,openmp-powerpc64le-ibm-linux-gnu 
-output=%t.res.s -output=%t.res.tgt1 -input=%t.bundle3.s -unbundle 
-allow-missing-bundles 2>&1 | FileCheck %s --check-prefix CK-NO-HOST-BUNDLE
-// CK-NO-HOST-BUNDLE: error: Can't find bundle for the host target
+// RUN: not clang-offload-bundler -type=s 
-targets=host-amdgcn-xxx-linux-gnu,openmp-powerpc64le-ibm-linux-gnu 
-output=%t.res.s -output=%t.res.tgt1 -input=%t.bundle3.s -unbundle 2>&1 | 
FileCheck %s --check-prefix CK-NO-HOST-BUNDLE
+// CK-NO-HOST-BUNDLE: error: Can't find bundles for host-amdgcn-xxx-linux-gnu
+
+// Check missing host entry is allowed with -allow-missing-bundles
+// RUN: clang-offload-bundler -type=s 
-targets=host-amdgcn-xxx-linux-gnu,openmp-powerpc64le-ibm-linux-gnu 
-output=%t.res.s -output=%t.res.tgt1 -input=%t.bundle3.s -unbundle 
-allow-missing-bundles
 
 //
 // Check binary bundle/unbundle. The content that we have before bundling must 
be the same we have after unbundling.
Index: clang/lib/Driver/OffloadBundler.cpp
===
--- clang/lib/Driver/OffloadBundler.cpp
+++ clang/lib/Driver/OffloadBundler.cpp
@@ -1060,7 +1060,7 @@
 
   // If we found elements, we emit an error if none of those were for the host
   // in case host bundle name was provided in command line.
-  if (!FoundHostBundle && BundlerConfig.HostInputIndex != ~0u)
+  if (!FoundHostBundle && BundlerConfig.HostInputIndex != ~0u && 
!BundlerConfig.AllowMissingBundles)
 return createStringError(inconvertibleErrorCode(),
  "Can't find bundle for the host target");
 


Index: clang/test/Driver/clang-offload-bundler.c
===
--- clang/test/Driver/clang-offload-bundler.c
+++ clang/test/Driver/clang-offload-bundler.c
@@ -224,8 +224,11 @@
 // RUN: diff %t.empty %t.res.tgt2
 
 // Check that bindler prints an error if given host bundle does not exist in the fat binary.
-// RUN: not clang-offload-bundler -type=s -targets=host-amdgcn-xxx-linux-gnu,openmp-powerpc64le-ibm-linux-gnu -output=%t.res.s -output=%t.res.tgt1 -input=%t.bundle3.s -unbundle -allow-missing-bundles 2>&1 | FileCheck %s --check-prefix CK-NO-HOST-BUNDLE
-// CK-NO-HOST-BUNDLE: error: Can't find bundle for the host target
+// RUN: not clang-offload-bundler -type=s -targets=host-amdgcn-xxx-linux-gnu,openmp-powerpc64le-ibm-linux-gnu -output=%t.res.s -output=%t.res.tgt1 -input=%t.bundle3.s -unbundle 2>&1 | FileCheck %s --check-prefix CK-NO-HOST-BUNDLE
+// CK-NO-HOST-BUNDLE: error: Can't find bundles for host-amdgcn-xxx-linux-gnu
+
+// Check missing host entry is allowed with -allow-missing-bundles
+// RUN: clang-offload-bundler -type=s -targets=host-amdgcn-xxx-linux-gnu,openmp-powerpc64le-ibm-linux-gnu -output=%t.res.s -output=%t.res.tgt1 -input=%t.bundle3.s -unbundle -allow-missing-bundles
 
 //
 // Check binary bundle/unbundle. The content that we have before bundling must be the same we have after unbundling.
Index: clang/lib/Driver/OffloadBundler.cpp
===
--- clang/lib/Driver/OffloadBundler.cpp
+++ clang/lib/Driver/OffloadBundler.cpp
@@ -1060,7 +1060,7 @@
 
   // If we found elements, we emit an error if none of those were for the host
   // in case host bundle name was provided in command line.
-  if (!FoundHostBundle && BundlerConfig.HostInputIndex != ~0u)
+  if (!FoundHostBundle && BundlerConfig.HostInputIndex != ~0u && !BundlerConfig.AllowMissingBundles)
 return createStringError(inconvertibleErrorCode(),
  "Can't find bundle for the host target");
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D139774: [libclang] Add API to set temporary directory location

2023-01-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D139774#4063131 , @vedgy wrote:

> After a discussion under the corresponding KDevelop merge request, I can see 
> 4-6 alternative ways to address the temporary directory issue:
>
> 1. Add an option to store the //preamble-*.pch// files in RAM instead of /tmp 
> and add a corresponding option in KDevelop configuration UI. This would work 
> perfectly for me, provided I don't change my mind and decide to turn this 
> option off, in which case I'll be back to square one.
> 2. Add an option to store the //preamble-*.pch// files in a custom directory 
> instead of a general temporary directory. The option could be named generally 
> (2a: overrideTemporaryDirectory) or specially (2b: setPreambleStoragePath). 
> If the option is named generally, other temporary files created by libclang 
> could be identified in the future and placed in the same directory without 
> changing the API.
> 3. 1 and 2 - the options can be propagated between identical end points 
> together, so this combination is natural.
> 4. The current patch. This is the easiest (already implemented) and most 
> reliable (the temporary directory is definitely and completely overridden) 
> approach. But there are thread safety concerns due to the introduction of 
> global state.
>
> If the 4th option is unacceptable, I lean towards the option 3a (1 and 2a), 
> because the amount of implementation work should not be much greater than 1 
> alone or 2a alone. If the 4th option is unacceptable, I suppose a separate 
> review request based on the current LLVM main branch should be created and 
> this one closed, right?

From a design perspective, my preference is to not add new APIs at the file 
system support layer in LLVM to override the temporary directory but instead 
allow individual components to override the decision where to put files. 
Overriding a system directory at the LLVM support level feels unclean to me 
because 1) threading concerns (mostly related to lock performance), 2) 
consistency concerns (put files in temp directory, override temp directory, put 
additional files in the new directory), 3) principle of least surprise. To me, 
the LLVM layer is responsible for interfacing with the system and asking for 
the system temp directory should get you the same answer as querying for that 
from the OS directly.

So my preference is for components to have an option to pick a different 
location as part of their API layer, rather than at the lower level. Based on 
that, I'm definitely in support of #1, and I'm in support of one of the options 
for #2. I lean towards #2b over #2a due to wanting individual overrides rather 
than a blanket override (e.g., we should be able to put preamble files in a 
different location than we put, say, crash logs).

@dblaikie does that sound reasonable to you?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139774

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


[PATCH] D140875: [clangd] prototype: Implement unused include warnings with include-cleaner library.

2023-01-19 Thread Christian Kandeler via Phabricator via cfe-commits
ckandeler added a comment.

With this, I now get:
FAILED: bin/clangd-fuzzer 
: && /usr/lib/icecream/libexec/icecc/bin/c++ -fPIC -fno-semantic-interposition 
-fvisibility-inlines-hidden -Werror=date-time -Wall -Wextra 
-Wno-unused-parameter -Wwrite-strings -Wcast-qual 
-Wno-missing-field-initializers -pedantic -Wno-long-long -Wimplicit-fallthrough 
-Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move 
-Wno-pessimizing-move -Wno-noexcept-type -Wdelete-non-virtual-dtor 
-Wsuggest-override -Wno-comment -Wno-misleading-indentation 
-Wctad-maybe-unsupported -fdiagnostics-color -ffunction-sections 
-fdata-sections -fno-common -Woverloaded-virtual -fno-strict-aliasing -O2 -g 
-DNDEBUG -fuse-ld=lld -Wl,--color-diagnostics-Wl,--gc-sections 
tools/clang/tools/extra/clangd/fuzzer/CMakeFiles/clangd-fuzzer.dir/FuzzerClangdMain.cpp.o
 
tools/clang/tools/extra/clangd/fuzzer/CMakeFiles/clangd-fuzzer.dir/clangd-fuzzer.cpp.o
 -o bin/clangd-fuzzer  -Wl,-rpath,"\$ORIGIN/../lib"  lib/libclangDaemon.a  
lib/libclangdSupport.a  lib/libclangPseudo.a  lib/libclangPseudoGrammar.a  
lib/libclangTidyAndroidModule.a  lib/libclangTidyAbseilModule.a  
lib/libclangTidyAlteraModule.a  lib/libclangTidyBoostModule.a  
lib/libclangTidyCERTModule.a  lib/libclangTidyConcurrencyModule.a  
lib/libclangTidyDarwinModule.a  lib/libclangTidyFuchsiaModule.a  
lib/libclangTidyHICPPModule.a  lib/libclangTidyBugproneModule.a  
lib/libclangTidyCppCoreGuidelinesModule.a  lib/libclangTidyGoogleModule.a  
lib/libclangTidyLinuxKernelModule.a  lib/libclangTidyLLVMModule.a  
lib/libclangTidyLLVMLibcModule.a  lib/libclangTidyMiscModule.a  
lib/libclangAnalysis.a  lib/libclangASTMatchers.a  lib/libclangAST.a  
lib/libclangLex.a  lib/libclangBasic.a  lib/libclangTidyModernizeModule.a  
lib/libclangTidyObjCModule.a  lib/libclangTidyOpenMPModule.a  
lib/libclangTidyPerformanceModule.a  lib/libclangTidyPortabilityModule.a  
lib/libclangTidyReadabilityModule.a  lib/libclangTidyZirconModule.a  
lib/libclangTidyMPIModule.a  lib/libclangTidyUtils.a  lib/libclangTidy.a  
lib/libclang-cpp.so.16git  lib/libLLVM-16git.so && :
ld.lld: error: undefined symbol: 
clang::include_cleaner::walkUsed(llvm::ArrayRef, 
llvm::ArrayRef, 
clang::include_cleaner::PragmaIncludes const*, clang::SourceManager const&, 
llvm::function_ref)>)

>>> referenced by IncludeCleaner.cpp:504 
>>> (/sda/home/christian/dev/llvm/clang-tools-extra/clangd/IncludeCleaner.cpp:504)
>>>
>>>   
>>> IncludeCleaner.cpp.o:(clang::clangd::computeUnusedIncludesExperimental(clang::clangd::ParsedAST&)
>>>  (.localalias)) in archive lib/libclangDaemon.a


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140875

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


  1   2   3   >