[PATCH] D112534: [PoC][RISCV] Use an attribute to declare C intrinsics with different policy.

2021-12-16 Thread Hsiangkai Wang via Phabricator via cfe-commits
HsiangKai updated this revision to Diff 394766.
HsiangKai added a comment.

Fix build errors.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112534

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/riscv_vector.td
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/RISCV/rvv-intrinsics/vadd-policy.c
  clang/utils/TableGen/RISCVVEmitter.cpp

Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -204,6 +204,10 @@
   // Emit the macros for mapping C/C++ intrinsic function to builtin functions.
   void emitIntrinsicFuncDef(raw_ostream &o) const;
 
+  // Emit the declarations for mapping C/C++ intrinsic function to builtin
+  // functions.
+  void emitIntrinsicWithPolicyFuncDef(raw_ostream &o) const;
+
   // Emit the mangled function definition.
   void emitMangledFuncDef(raw_ostream &o) const;
 };
@@ -835,9 +839,10 @@
   if (isMask()) {
 if (hasVL()) {
   OS << "  std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end() - 1);\n";
-  if (hasPolicy())
-OS << "  Ops.push_back(ConstantInt::get(Ops.back()->getType(),"
-   " TAIL_UNDISTURBED));\n";
+  if (hasPolicy()) {
+OS << "  Ops.push_back(ConstantInt::get(Ops.back()->getType(), "
+  "PolicyValue));\n";
+  }
 } else {
   OS << "  std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end());\n";
 }
@@ -865,12 +870,32 @@
   OS << "__builtin_rvv_" << getBuiltinName() << ")))\n";
   OS << OutputType->getTypeStr() << " " << getName() << "(";
   // Emit function arguments
-  if (!InputTypes.empty()) {
+  ListSeparator LS;
+  for (unsigned i = 0; i < InputTypes.size(); ++i)
+OS << LS << InputTypes[i]->getTypeStr();
+  OS << ");\n";
+}
+
+void RVVIntrinsic::emitIntrinsicWithPolicyFuncDef(raw_ostream &OS) const {
+  if (!isMask())
+return;
+
+  static const char *const PolicySuffix[] = {"tumu", "tamu", "tuma", "tama"};
+
+  for (auto Suffix : PolicySuffix) {
+OS << "__rvv_ai ";
+OS << "__attribute__((__clang_builtin_alias__(";
+OS << "__builtin_rvv_" << getBuiltinName() << ")))\n";
+OS << "__attribute__((rvv_policy(" << Suffix << ")))\n";
+StringRef IntrinsicName = getName().substr(0, getName().size() - 2);
+OS << OutputType->getTypeStr() << " " << IntrinsicName << "_" << Suffix
+   << "(";
+// Emit function arguments
 ListSeparator LS;
 for (unsigned i = 0; i < InputTypes.size(); ++i)
   OS << LS << InputTypes[i]->getTypeStr();
+OS << ");\n";
   }
-  OS << ");\n";
 }
 
 void RVVIntrinsic::emitMangledFuncDef(raw_ostream &OS) const {
@@ -878,11 +903,9 @@
   OS << "__builtin_rvv_" << getBuiltinName() << ")))\n";
   OS << OutputType->getTypeStr() << " " << getMangledName() << "(";
   // Emit function arguments
-  if (!InputTypes.empty()) {
-ListSeparator LS;
-for (unsigned i = 0; i < InputTypes.size(); ++i)
-  OS << LS << InputTypes[i]->getTypeStr();
-  }
+  ListSeparator LS;
+  for (unsigned i = 0; i < InputTypes.size(); ++i)
+OS << LS << InputTypes[i]->getTypeStr();
   OS << ");\n";
 }
 
@@ -989,6 +1012,10 @@
 Inst.emitIntrinsicFuncDef(OS);
   });
 
+  emitArchMacroAndBody(Defs, OS, [](raw_ostream &OS, const RVVIntrinsic &Inst) {
+Inst.emitIntrinsicWithPolicyFuncDef(OS);
+  });
+
   OS << "#undef __rvv_ai\n\n";
 
   OS << "#define __riscv_v_intrinsic_overloading 1\n";
Index: clang/test/CodeGen/RISCV/rvv-intrinsics/vadd-policy.c
===
--- /dev/null
+++ clang/test/CodeGen/RISCV/rvv-intrinsics/vadd-policy.c
@@ -0,0 +1,42 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// REQUIRES: riscv-registered-target
+// RUN: %clang_cc1 -triple riscv64 -target-feature +f -target-feature +d -target-feature +experimental-v \
+// RUN:   -target-feature +experimental-zfh -disable-O0-optnone -emit-llvm %s -o - | opt -S -mem2reg | FileCheck --check-prefix=CHECK-RV64 %s
+
+#include 
+
+// CHECK-RV64-LABEL: @test_vadd_vv_i8m1_tama(
+// CHECK-RV64-NEXT:  entry:
+// CHECK-RV64-NEXT:[[TMP0:%.*]] = call  @llvm.riscv.vadd.mask.nxv8i8.nxv8i8.i64( [[MASKEDOFF:%.*]],  [[OP1:%.*]],  [[OP2:%.*]],  [[MASK:%.*]], i64 [[VL:%.*]], i64 3)
+// CHECK-RV64-NEXT:ret  [[TMP0]]
+//
+vint8m1_t test_vadd_vv_i8m1_tama(vbool8_t mask, vint8m1_t maskedoff, vint8m1_t op1, vint8m1_t op2, size_t vl) {
+  return vadd_vv_i8m1_tama(mask, maskedoff, op1, op2, vl);
+}
+
+// CHECK-RV64-LABEL: @test_vadd_vv_i8m1_tamu(
+// CHECK-RV64-NEXT:  entry:
+// CHECK-RV64-NEXT:[[TMP0:%.*]] = call  @llvm.riscv.vadd.mask.nxv8i8.nxv8i8.i64( [[MASKEDOFF:%.*]],  [[OP1:%.*]],  [[OP2:%.*]],  [[MASK:%.*]], i64 [[VL:%.*]], i64 1)
+// CHECK-RV64-NEXT:ret  [[TMP

[clang] 6bca9a4 - [CodeGen] Store ElementType in LValue

2021-12-16 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2021-12-16T09:23:33+01:00
New Revision: 6bca9a428e32c598f793821e407d5c9d7bbe7cd8

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

LOG: [CodeGen] Store ElementType in LValue

Store the pointer element type inside LValue so that we can
preserve it when converting it back into an Address. Storing the
pointer element type might not be strictly required here in that
we could probably re-derive it from the QualType (which would
require CGF access though), but storing it seems like the simpler
solution.

The global register case is special and does not store an element
type, as the value is not a pointer type in that case and it's not
possible to create an Address from it.

This is the main remaining part from D103465.

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

Added: 


Modified: 
clang/lib/CodeGen/CGValue.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGValue.h b/clang/lib/CodeGen/CGValue.h
index 8e4f0604d6229..916f423ef5b88 100644
--- a/clang/lib/CodeGen/CGValue.h
+++ b/clang/lib/CodeGen/CGValue.h
@@ -175,6 +175,7 @@ class LValue {
   } LVType;
 
   llvm::Value *V;
+  llvm::Type *ElementType;
 
   union {
 // Index into a vector subscript: V[i]
@@ -230,6 +231,13 @@ class LValue {
   LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
 assert((!Alignment.isZero() || Type->isIncompleteType()) &&
"initializing l-value with zero alignment!");
+if (isGlobalReg())
+  assert(ElementType == nullptr && "Global reg does not store elem type");
+else
+  assert(llvm::cast(V->getType())
+ ->isOpaqueOrPointeeTypeMatches(ElementType) &&
+ "Pointer element type mismatch");
+
 this->Type = Type;
 this->Quals = Quals;
 const unsigned MaxAlign = 1U << 31;
@@ -327,17 +335,18 @@ class LValue {
 return V;
   }
   Address getAddress(CodeGenFunction &CGF) const {
-return Address(getPointer(CGF), getAlignment());
+return Address(getPointer(CGF), ElementType, getAlignment());
   }
   void setAddress(Address address) {
 assert(isSimple());
 V = address.getPointer();
+ElementType = address.getElementType();
 Alignment = address.getAlignment().getQuantity();
   }
 
   // vector elt lvalue
   Address getVectorAddress() const {
-return Address(getVectorPointer(), getAlignment());
+return Address(getVectorPointer(), ElementType, getAlignment());
   }
   llvm::Value *getVectorPointer() const {
 assert(isVectorElt());
@@ -349,7 +358,7 @@ class LValue {
   }
 
   Address getMatrixAddress() const {
-return Address(getMatrixPointer(), getAlignment());
+return Address(getMatrixPointer(), ElementType, getAlignment());
   }
   llvm::Value *getMatrixPointer() const {
 assert(isMatrixElt());
@@ -362,7 +371,7 @@ class LValue {
 
   // extended vector elements.
   Address getExtVectorAddress() const {
-return Address(getExtVectorPointer(), getAlignment());
+return Address(getExtVectorPointer(), ElementType, getAlignment());
   }
   llvm::Value *getExtVectorPointer() const {
 assert(isExtVectorElt());
@@ -375,7 +384,7 @@ class LValue {
 
   // bitfield lvalue
   Address getBitFieldAddress() const {
-return Address(getBitFieldPointer(), getAlignment());
+return Address(getBitFieldPointer(), ElementType, getAlignment());
   }
   llvm::Value *getBitFieldPointer() const { assert(isBitField()); return V; }
   const CGBitFieldInfo &getBitFieldInfo() const {
@@ -395,6 +404,7 @@ class LValue {
 R.LVType = Simple;
 assert(address.getPointer()->getType()->isPointerTy());
 R.V = address.getPointer();
+R.ElementType = address.getElementType();
 R.Initialize(type, qs, address.getAlignment(), BaseInfo, TBAAInfo);
 return R;
   }
@@ -405,6 +415,7 @@ class LValue {
 LValue R;
 R.LVType = VectorElt;
 R.V = vecAddress.getPointer();
+R.ElementType = vecAddress.getElementType();
 R.VectorIdx = Idx;
 R.Initialize(type, type.getQualifiers(), vecAddress.getAlignment(),
  BaseInfo, TBAAInfo);
@@ -417,6 +428,7 @@ class LValue {
 LValue R;
 R.LVType = ExtVectorElt;
 R.V = vecAddress.getPointer();
+R.ElementType = vecAddress.getElementType();
 R.VectorElts = Elts;
 R.Initialize(type, type.getQualifiers(), vecAddress.getAlignment(),
  BaseInfo, TBAAInfo);
@@ -435,6 +447,7 @@ class LValue {
 LValue R;
 R.LVType = BitField;
 R.V = Addr.getPointer();
+R.ElementType = Addr.getElementType();
 R.BitFieldInfo = &Info;
 R.Initialize(type, type.getQualifiers(), Addr.getAlignment(), BaseInfo,
  TBAAInfo);
@@ -446,6 +459,7 @@ class LValue {
 LValue R;
 R.LVType = GlobalReg;
 R.V = V;
+R.ElementType = nu

[PATCH] D115791: [CodeGen] Store ElementType in LValue

2021-12-16 Thread Nikita Popov 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 rG6bca9a428e32: [CodeGen] Store ElementType in LValue 
(authored by nikic).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115791

Files:
  clang/lib/CodeGen/CGValue.h

Index: clang/lib/CodeGen/CGValue.h
===
--- clang/lib/CodeGen/CGValue.h
+++ clang/lib/CodeGen/CGValue.h
@@ -175,6 +175,7 @@
   } LVType;
 
   llvm::Value *V;
+  llvm::Type *ElementType;
 
   union {
 // Index into a vector subscript: V[i]
@@ -230,6 +231,13 @@
   LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
 assert((!Alignment.isZero() || Type->isIncompleteType()) &&
"initializing l-value with zero alignment!");
+if (isGlobalReg())
+  assert(ElementType == nullptr && "Global reg does not store elem type");
+else
+  assert(llvm::cast(V->getType())
+ ->isOpaqueOrPointeeTypeMatches(ElementType) &&
+ "Pointer element type mismatch");
+
 this->Type = Type;
 this->Quals = Quals;
 const unsigned MaxAlign = 1U << 31;
@@ -327,17 +335,18 @@
 return V;
   }
   Address getAddress(CodeGenFunction &CGF) const {
-return Address(getPointer(CGF), getAlignment());
+return Address(getPointer(CGF), ElementType, getAlignment());
   }
   void setAddress(Address address) {
 assert(isSimple());
 V = address.getPointer();
+ElementType = address.getElementType();
 Alignment = address.getAlignment().getQuantity();
   }
 
   // vector elt lvalue
   Address getVectorAddress() const {
-return Address(getVectorPointer(), getAlignment());
+return Address(getVectorPointer(), ElementType, getAlignment());
   }
   llvm::Value *getVectorPointer() const {
 assert(isVectorElt());
@@ -349,7 +358,7 @@
   }
 
   Address getMatrixAddress() const {
-return Address(getMatrixPointer(), getAlignment());
+return Address(getMatrixPointer(), ElementType, getAlignment());
   }
   llvm::Value *getMatrixPointer() const {
 assert(isMatrixElt());
@@ -362,7 +371,7 @@
 
   // extended vector elements.
   Address getExtVectorAddress() const {
-return Address(getExtVectorPointer(), getAlignment());
+return Address(getExtVectorPointer(), ElementType, getAlignment());
   }
   llvm::Value *getExtVectorPointer() const {
 assert(isExtVectorElt());
@@ -375,7 +384,7 @@
 
   // bitfield lvalue
   Address getBitFieldAddress() const {
-return Address(getBitFieldPointer(), getAlignment());
+return Address(getBitFieldPointer(), ElementType, getAlignment());
   }
   llvm::Value *getBitFieldPointer() const { assert(isBitField()); return V; }
   const CGBitFieldInfo &getBitFieldInfo() const {
@@ -395,6 +404,7 @@
 R.LVType = Simple;
 assert(address.getPointer()->getType()->isPointerTy());
 R.V = address.getPointer();
+R.ElementType = address.getElementType();
 R.Initialize(type, qs, address.getAlignment(), BaseInfo, TBAAInfo);
 return R;
   }
@@ -405,6 +415,7 @@
 LValue R;
 R.LVType = VectorElt;
 R.V = vecAddress.getPointer();
+R.ElementType = vecAddress.getElementType();
 R.VectorIdx = Idx;
 R.Initialize(type, type.getQualifiers(), vecAddress.getAlignment(),
  BaseInfo, TBAAInfo);
@@ -417,6 +428,7 @@
 LValue R;
 R.LVType = ExtVectorElt;
 R.V = vecAddress.getPointer();
+R.ElementType = vecAddress.getElementType();
 R.VectorElts = Elts;
 R.Initialize(type, type.getQualifiers(), vecAddress.getAlignment(),
  BaseInfo, TBAAInfo);
@@ -435,6 +447,7 @@
 LValue R;
 R.LVType = BitField;
 R.V = Addr.getPointer();
+R.ElementType = Addr.getElementType();
 R.BitFieldInfo = &Info;
 R.Initialize(type, type.getQualifiers(), Addr.getAlignment(), BaseInfo,
  TBAAInfo);
@@ -446,6 +459,7 @@
 LValue R;
 R.LVType = GlobalReg;
 R.V = V;
+R.ElementType = nullptr;
 R.Initialize(type, type.getQualifiers(), alignment,
  LValueBaseInfo(AlignmentSource::Decl), TBAAAccessInfo());
 return R;
@@ -457,6 +471,7 @@
 LValue R;
 R.LVType = MatrixElt;
 R.V = matAddress.getPointer();
+R.ElementType = matAddress.getElementType();
 R.VectorIdx = Idx;
 R.Initialize(type, type.getQualifiers(), matAddress.getAlignment(),
  BaseInfo, TBAAInfo);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 27818f0 - [clang-format] Fix tabs when using BreakBeforeTernaryOperators=false.

2021-12-16 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2021-12-16T09:28:00+01:00
New Revision: 27818f01fec2dd8f18325281f97646aed5ca9c89

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

LOG: [clang-format] Fix tabs when using BreakBeforeTernaryOperators=false.

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

This is rather a workaround than a correct fix. To properly fix it, we'd need 
to find a better way to tell when not to decrease the StartOfTokenColumn.

Reviewed By: MyDeveloperDay, owenpan

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

Added: 


Modified: 
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index fae8a1c3fdc66..96a66da0f82ba 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1282,9 +1282,12 @@ void WhitespaceManager::generateChanges() {
  C.EscapedNewlineColumn);
   else
 appendNewlineText(ReplacementText, C.NewlinesBefore);
+  // FIXME: This assert should hold if we computed the column correctly.
+  // assert((int)C.StartOfTokenColumn >= C.Spaces);
   appendIndentText(
   ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces),
-  C.StartOfTokenColumn - std::max(0, C.Spaces), C.IsAligned);
+  std::max((int)C.StartOfTokenColumn, C.Spaces) - std::max(0, 
C.Spaces),
+  C.IsAligned);
   ReplacementText.append(C.CurrentLinePrefix);
   storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
 }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index f54139227e871..37d08d2d91292 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -13452,6 +13452,25 @@ TEST_F(FormatTest, ConfigurableUseOfTab) {
"}",
Tab));
 
+  verifyFormat("void f() {\n"
+   "\treturn true ? aa\n"
+   "\t: bb\n"
+   "}",
+   Tab);
+  FormatStyle TabNoBreak = Tab;
+  TabNoBreak.BreakBeforeTernaryOperators = false;
+  verifyFormat("void f() {\n"
+   "\treturn true ? aa :\n"
+   "\t  bb\n"
+   "}",
+   TabNoBreak);
+  verifyFormat("void f() {\n"
+   "\treturn true ?\n"
+   "\t    :\n"
+   "\t   \n"
+   "}",
+   TabNoBreak);
+
   Tab.UseTab = FormatStyle::UT_Never;
   EXPECT_EQ("/*\n"
 "  a\t\tcomment\n"



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


[PATCH] D115803: [clang-format] Fix tabs when using BreakBeforeTernaryOperators=false.

2021-12-16 Thread Marek Kurdej 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 rG27818f01fec2: [clang-format] Fix tabs when using 
BreakBeforeTernaryOperators=false. (authored by curdeius).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115803

Files:
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -13452,6 +13452,25 @@
"}",
Tab));
 
+  verifyFormat("void f() {\n"
+   "\treturn true ? aa\n"
+   "\t: bb\n"
+   "}",
+   Tab);
+  FormatStyle TabNoBreak = Tab;
+  TabNoBreak.BreakBeforeTernaryOperators = false;
+  verifyFormat("void f() {\n"
+   "\treturn true ? aa :\n"
+   "\t  bb\n"
+   "}",
+   TabNoBreak);
+  verifyFormat("void f() {\n"
+   "\treturn true ?\n"
+   "\t    :\n"
+   "\t   \n"
+   "}",
+   TabNoBreak);
+
   Tab.UseTab = FormatStyle::UT_Never;
   EXPECT_EQ("/*\n"
 "  a\t\tcomment\n"
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -1282,9 +1282,12 @@
  C.EscapedNewlineColumn);
   else
 appendNewlineText(ReplacementText, C.NewlinesBefore);
+  // FIXME: This assert should hold if we computed the column correctly.
+  // assert((int)C.StartOfTokenColumn >= C.Spaces);
   appendIndentText(
   ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces),
-  C.StartOfTokenColumn - std::max(0, C.Spaces), C.IsAligned);
+  std::max((int)C.StartOfTokenColumn, C.Spaces) - std::max(0, 
C.Spaces),
+  C.IsAligned);
   ReplacementText.append(C.CurrentLinePrefix);
   storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
 }


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -13452,6 +13452,25 @@
"}",
Tab));
 
+  verifyFormat("void f() {\n"
+   "\treturn true ? aa\n"
+   "\t: bb\n"
+   "}",
+   Tab);
+  FormatStyle TabNoBreak = Tab;
+  TabNoBreak.BreakBeforeTernaryOperators = false;
+  verifyFormat("void f() {\n"
+   "\treturn true ? aa :\n"
+   "\t  bb\n"
+   "}",
+   TabNoBreak);
+  verifyFormat("void f() {\n"
+   "\treturn true ?\n"
+   "\t    :\n"
+   "\t   \n"
+   "}",
+   TabNoBreak);
+
   Tab.UseTab = FormatStyle::UT_Never;
   EXPECT_EQ("/*\n"
 "  a\t\tcomment\n"
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -1282,9 +1282,12 @@
  C.EscapedNewlineColumn);
   else
 appendNewlineText(ReplacementText, C.NewlinesBefore);
+  // FIXME: This assert should hold if we computed the column correctly.
+  // assert((int)C.StartOfTokenColumn >= C.Spaces);
   appendIndentText(
   ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces),
-  C.StartOfTokenColumn - std::max(0, C.Spaces), C.IsAligned);
+  std::max((int)C.StartOfTokenColumn, C.Spaces) - std::max(0, C.Spaces),
+  C.IsAligned);
   ReplacementText.append(C.CurrentLinePrefix);
   storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D115856: [syntax][pseudo] Introduce the spec C++ grammar.

2021-12-16 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added a subscriber: mgorny.
hokein requested review of this revision.
Herald added a project: clang.

Also, add a dummy clang-pseudo tool (right now it accepts and parses the
grammar file).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115856

Files:
  clang/lib/Tooling/Syntax/Pseudo/cxx.bnf
  clang/tools/CMakeLists.txt
  clang/tools/clang-pseudo/CMakeLists.txt
  clang/tools/clang-pseudo/ClangPseudo.cpp

Index: clang/tools/clang-pseudo/ClangPseudo.cpp
===
--- /dev/null
+++ clang/tools/clang-pseudo/ClangPseudo.cpp
@@ -0,0 +1,44 @@
+//===-- ClangPseudo.cpp - Clang pseudo parser tool ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Syntax/Pseudo/Grammar.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/MemoryBuffer.h"
+
+using clang::syntax::pseudo::Grammar;
+using llvm::cl::desc;
+using llvm::cl::init;
+using llvm::cl::opt;
+
+static opt
+GrammarFile("grammar", desc("grammar file to parse"),
+init("clang/lib/Tooling/Syntax/Pseudo/cxx.bnf"));
+
+int main(int argc, char *argv[]) {
+  llvm::cl::ParseCommandLineOptions(argc, argv, "");
+
+  llvm::ErrorOr> Text =
+  llvm::MemoryBuffer::getFile(GrammarFile);
+  if (std::error_code EC = Text.getError()) {
+llvm::errs() << "Error: can't read grammar '" << GrammarFile
+ << "': " << EC.message() << "\n";
+return 1;
+  }
+
+  auto RSpecs = Grammar::RuleSpec::parseAll(Text.get()->getBuffer());
+  if (!RSpecs) {
+llvm::errs() << llvm::toString(RSpecs.takeError());
+return 1;
+  }
+
+  auto Diagnostics = Grammar::build(*RSpecs).diagnose();
+  llvm::errs() << (Diagnostics.empty() ? "Parse grammar successfully!\n"
+   : llvm::join(Diagnostics, "\n"));
+  return 0;
+}
Index: clang/tools/clang-pseudo/CMakeLists.txt
===
--- /dev/null
+++ clang/tools/clang-pseudo/CMakeLists.txt
@@ -0,0 +1,15 @@
+set(LLVM_LINK_COMPONENTS support)
+
+add_clang_tool(clang-pseudo
+  ClangPseudo.cpp
+  )
+
+set(CLANG_SOUP_LIB_DEPS
+  clangBasic
+  clangToolingPseudo
+  )
+
+clang_target_link_libraries(clang-pseudo
+  PRIVATE
+  ${CLANG_SOUP_LIB_DEPS}
+  )
\ No newline at end of file
Index: clang/tools/CMakeLists.txt
===
--- clang/tools/CMakeLists.txt
+++ clang/tools/CMakeLists.txt
@@ -12,6 +12,7 @@
 add_clang_subdirectory(clang-offload-bundler)
 add_clang_subdirectory(clang-offload-wrapper)
 add_clang_subdirectory(clang-scan-deps)
+add_clang_subdirectory(clang-pseudo)
 add_clang_subdirectory(clang-repl)
 
 add_clang_subdirectory(c-index-test)
Index: clang/lib/Tooling/Syntax/Pseudo/cxx.bnf
===
--- /dev/null
+++ clang/lib/Tooling/Syntax/Pseudo/cxx.bnf
@@ -0,0 +1,745 @@
+
+# This is a C++ grammar from the C++ standard [1].
+#
+# The grammar is a superset of the true grammar requring semantic constraints to
+# resolve ambiguties. The grammar is context-free and ambiguous (beyond the
+# limit of LR(k)). We use general parsing algorithm (e.g GLR) to handle the
+# grammar and generate a transition table which is used to drive the parsing.
+#
+# It aims to align with the ISO C++ grammar as much as possible. We adjust it
+# to fit the need for the grammar-based parser:
+#  - attributes are omitted, which will be handled as comments;
+#  - we don't allow nullable non-terminal symbols (except translation-unit).
+#There are few nullable non-terminals in the spec grammar, they are adjust
+#to be non-nullable;
+#  - the file merely describes the core C++ grammar. Preprocessor directives and
+#lexical conversions are omitted as we reuse clang's lexer and run a fake
+#preprocessor;
+#
+# Guidelines:
+#   - non-terminals are lower_case; terminals (aka tokens) correspond to
+# clang::TokenKind, written as "IDENTIFIER", "USING", "::" etc;
+#   - optional symbols are supported, with a _opt suffix;
+#
+# [1] https://isocpp.org/files/papers/N4860.pdf
+#
+# FIXME:
+#   - support annotations (lazy parsing, contextual identifiers)
+#   - empty input should be parsed successfully (special-case it?)
+#
+# start symbols
+_ := translation-unit
+
+# A.1 gram.key
+typedef-name := IDENTIFIER
+typedef-name := simple-template-id
+namespace-name := IDENTIFIER
+namespace-name := namespace-alias
+namespace-alias := IDENTIFIER
+class-name := IDENTIFIER
+class-name := simple-template-id
+enum-name := IDENTIFIER
+template-name := IDENTIFI

[PATCH] D114251: [AST] Add a sugar type for types found via UsingDecl

2021-12-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 394780.
sammccall added a comment.

Make hasDeclaration look through UsingType, and throughUsingDecl work on
UsingType too. This is more ergonomic, more similar to existing behavior
that matchers rely on, and similar in spirit to DeclRefExpr.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114251

Files:
  clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
  clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/PropertiesBase.td
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/TextNodeDumper.h
  clang/include/clang/AST/Type.h
  clang/include/clang/AST/TypeLoc.h
  clang/include/clang/AST/TypeProperties.td
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/include/clang/ASTMatchers/ASTMatchersInternal.h
  clang/include/clang/Basic/TypeNodes.td
  clang/include/clang/Serialization/TypeBitCodes.def
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTDiagnostic.cpp
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/QualTypeNames.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaCXXScopeSpec.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/AST/ast-dump-using.cpp
  clang/tools/libclang/CIndex.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp

Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -2581,6 +2581,7 @@
 case clang::Type::Typedef:
 case clang::Type::TypeOf:
 case clang::Type::TypeOfExpr:
+case clang::Type::Using:
   type = type->getLocallyUnqualifiedSingleStepDesugaredType();
   break;
 default:
@@ -4063,6 +4064,7 @@
   case clang::Type::Paren:
   case clang::Type::TypeOf:
   case clang::Type::TypeOfExpr:
+  case clang::Type::Using:
 llvm_unreachable("Handled in RemoveWrappingTypes!");
   case clang::Type::UnaryTransform:
 break;
@@ -4722,6 +4724,7 @@
   case clang::Type::Typedef:
   case clang::Type::TypeOf:
   case clang::Type::TypeOfExpr:
+  case clang::Type::Using:
 llvm_unreachable("Handled in RemoveWrappingTypes!");
 
   case clang::Type::UnaryTransform:
@@ -5104,6 +5107,7 @@
   case clang::Type::Typedef:
   case clang::Type::TypeOf:
   case clang::Type::TypeOfExpr:
+  case clang::Type::Using:
 llvm_unreachable("Handled in RemoveWrappingTypes!");
   case clang::Type::UnaryTransform:
 break;
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1666,6 +1666,8 @@
   return Visit(TL.getPointeeLoc());
 }
 
+bool CursorVisitor::VisitUsingTypeLoc(UsingTypeLoc TL) { return false; }
+
 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
   return Visit(TL.getModifiedLoc());
 }
Index: clang/test/AST/ast-dump-using.cpp
===
--- /dev/null
+++ clang/test/AST/ast-dump-using.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ast-dump %s | FileCheck -strict-whitespace %s
+
+namespace a {
+struct S;
+}
+namespace b {
+using a::S;
+// CHECK:  UsingDecl {{.*}} a::S
+// CHECK-NEXT: UsingShadowDecl {{.*}} implicit CXXRecord {{.*}} 'S'
+// CHECK-NEXT: `-RecordType {{.*}} 'a::S'
+typedef S f; // to dump the introduced type
+// CHECK:  TypedefDecl
+// CHECK-NEXT: `-UsingType {{.*}} 'a::S' sugar
+// CHECK-NEXT:   |-UsingShadow {{.*}} 'S'
+// CHECK-NEXT:   `-RecordType {{.*}} 'a::S'
+}
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -396,6 +396,8 @@
   Record.AddSourceLocation(TL.getNameLoc());
 }
 
+void TypeLocWriter::VisitUsingTypeLoc(UsingTypeLoc TL) {}
+
 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
   Record.AddSourceLocation(TL.getNameLoc());
 }
Index: clang/lib/Serialization/ASTReader.cpp
===

[clang] f668034 - [clang][deps] Squash caches for original and minimized files

2021-12-16 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-12-16T09:57:21+01:00
New Revision: f66803457ec7f88fa86376d9aef677dea107818c

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

LOG: [clang][deps] Squash caches for original and minimized files

The minimizing and caching filesystem used by the dependency scanner keeps 
minimized and original files in separate caches.

This setup is not well suited for dealing with files that are sometimes 
minimized and sometimes not. Such files are being stat-ed and read twice, which 
is wasteful and also means the two versions of the file can get "out of sync".

This patch squashes the two caches together. When a file is stat-ed or read, 
its original contents are populated. If a file needs to be minimized, we give 
the minimizer the already loaded contents instead of reading the file again.

Reviewed By: dexonsmith

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

Added: 


Modified: 

clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
clang/unittests/Tooling/DependencyScannerTest.cpp
llvm/include/llvm/Support/VirtualFileSystem.h
llvm/lib/Support/VirtualFileSystem.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
index 4e770bb2e7898..3981ccfd98c06 100644
--- 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -26,27 +26,31 @@ namespace dependencies {
 /// the dependency scanning filesystem.
 ///
 /// It represents one of the following:
-/// - an opened source file with minimized contents and a stat value.
-/// - an opened source file with original contents and a stat value.
-/// - a directory entry with its stat value.
-/// - an error value to represent a file system error.
+/// - opened file with original contents and a stat value,
+/// - opened file with original contents, minimized contents and a stat value,
+/// - directory entry with its stat value,
+/// - filesystem error,
 /// - uninitialized entry with unknown status.
 class CachedFileSystemEntry {
 public:
   /// Creates an uninitialized entry.
-  CachedFileSystemEntry() : MaybeStat(llvm::vfs::Status()) {}
+  CachedFileSystemEntry()
+  : MaybeStat(llvm::vfs::Status()), MinimizedContentsAccess(nullptr) {}
 
   /// Initialize the cached file system entry.
   void init(llvm::ErrorOr &&MaybeStatus, StringRef Filename,
-llvm::vfs::FileSystem &FS, bool ShouldMinimize = true);
+llvm::vfs::FileSystem &FS);
 
   /// Initialize the entry as file with minimized or original contents.
   ///
   /// The filesystem opens the file even for `stat` calls open to avoid the
   /// issues with stat + open of minimized files that might lead to a
   /// mismatching size of the file.
-  llvm::ErrorOr
-  initFile(StringRef Filename, llvm::vfs::FileSystem &FS, bool Minimize = 
true);
+  llvm::ErrorOr initFile(StringRef Filename,
+llvm::vfs::FileSystem &FS);
+
+  /// Minimize contents of the file.
+  void minimizeFile();
 
   /// \returns True if the entry is initialized.
   bool isInitialized() const {
@@ -56,13 +60,38 @@ class CachedFileSystemEntry {
   /// \returns True if the current entry points to a directory.
   bool isDirectory() const { return MaybeStat && MaybeStat->isDirectory(); }
 
-  /// \returns The error or the file's contents.
-  llvm::ErrorOr getContents() const {
+  /// \returns The error or the file's original contents.
+  llvm::ErrorOr getOriginalContents() const {
+if (!MaybeStat)
+  return MaybeStat.getError();
+assert(!MaybeStat->isDirectory() && "not a file");
+assert(isInitialized() && "not initialized");
+assert(OriginalContents && "not read");
+return OriginalContents->getBuffer();
+  }
+
+  /// \returns The error or the file's minimized contents.
+  llvm::ErrorOr getMinimizedContents() const {
 if (!MaybeStat)
   return MaybeStat.getError();
 assert(!MaybeStat->isDirectory() && "not a file");
 assert(isInitialized() && "not initialized");
-return Contents->getBuffer();
+llvm::MemoryBuffer *Buffer = MinimizedContentsAccess.load();
+assert(Buffer && "not minimized");
+return Buffer->getBuffer();
+  }
+
+  /// \returns True if this entry represents a file that can be read.
+  bool isReadable() const { return MaybeStat && !MaybeStat->isDirectory(); }
+
+  /// \returns True if this cached entry needs to be updated.
+  bool needsUpdate(bool ShouldBeMinimized) const {
+return isReadable() && needsMinimiza

[PATCH] D115346: [clang][deps] Squash caches for original and minimized files

2021-12-16 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
jansvoboda11 marked an inline comment as done.
Closed by commit rGf66803457ec7: [clang][deps] Squash caches for original and 
minimized files (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D115346?vs=394585&id=394781#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115346

Files:
  clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
  clang/unittests/Tooling/DependencyScannerTest.cpp
  llvm/include/llvm/Support/VirtualFileSystem.h
  llvm/lib/Support/VirtualFileSystem.cpp

Index: llvm/lib/Support/VirtualFileSystem.cpp
===
--- llvm/lib/Support/VirtualFileSystem.cpp
+++ llvm/lib/Support/VirtualFileSystem.cpp
@@ -75,6 +75,12 @@
 : Name(Name.str()), UID(UID), MTime(MTime), User(User), Group(Group),
   Size(Size), Type(Type), Perms(Perms) {}
 
+Status Status::copyWithNewSize(const Status &In, uint64_t NewSize) {
+  return Status(In.getName(), In.getUniqueID(), In.getLastModificationTime(),
+In.getUser(), In.getGroup(), NewSize, In.getType(),
+In.getPermissions());
+}
+
 Status Status::copyWithNewName(const Status &In, const Twine &NewName) {
   return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
Index: llvm/include/llvm/Support/VirtualFileSystem.h
===
--- llvm/include/llvm/Support/VirtualFileSystem.h
+++ llvm/include/llvm/Support/VirtualFileSystem.h
@@ -64,6 +64,8 @@
  uint64_t Size, llvm::sys::fs::file_type Type,
  llvm::sys::fs::perms Perms);
 
+  /// Get a copy of a Status with a different size.
+  static Status copyWithNewSize(const Status &In, uint64_t NewSize);
   /// Get a copy of a Status with a different name.
   static Status copyWithNewName(const Status &In, const Twine &NewName);
   static Status copyWithNewName(const llvm::sys::fs::file_status &In,
Index: clang/unittests/Tooling/DependencyScannerTest.cpp
===
--- clang/unittests/Tooling/DependencyScannerTest.cpp
+++ clang/unittests/Tooling/DependencyScannerTest.cpp
@@ -205,32 +205,46 @@
 }
 
 namespace dependencies {
-TEST(DependencyScanningFilesystem, IgnoredFilesHaveSeparateCache) {
+TEST(DependencyScanningFilesystem, IgnoredFilesAreCachedSeparately1) {
   auto VFS = llvm::makeIntrusiveRefCnt();
-  VFS->addFile("/mod.h", 0, llvm::MemoryBuffer::getMemBuffer("// hi there!\n"));
+  VFS->addFile("/mod.h", 0,
+   llvm::MemoryBuffer::getMemBuffer("#include \n"
+"// hi there!\n"));
 
   DependencyScanningFilesystemSharedCache SharedCache;
   auto Mappings = std::make_unique();
   DependencyScanningWorkerFilesystem DepFS(SharedCache, VFS, Mappings.get());
 
+  DepFS.enableMinimizationOfAllFiles(); // Let's be explicit for clarity.
   auto StatusMinimized0 = DepFS.status("/mod.h");
   DepFS.disableMinimization("/mod.h");
   auto StatusFull1 = DepFS.status("/mod.h");
-  DepFS.enableMinimizationOfAllFiles();
-
-  auto StatusMinimized2 = DepFS.status("/mod.h");
-  DepFS.disableMinimization("/mod.h");
-  auto StatusFull3 = DepFS.status("/mod.h");
 
   EXPECT_TRUE(StatusMinimized0);
-  EXPECT_EQ(StatusMinimized0->getSize(), 0u);
   EXPECT_TRUE(StatusFull1);
-  EXPECT_EQ(StatusFull1->getSize(), 13u);
+  EXPECT_EQ(StatusMinimized0->getSize(), 17u);
+  EXPECT_EQ(StatusFull1->getSize(), 30u);
+}
+
+TEST(DependencyScanningFilesystem, IgnoredFilesAreCachedSeparately2) {
+  auto VFS = llvm::makeIntrusiveRefCnt();
+  VFS->addFile("/mod.h", 0,
+   llvm::MemoryBuffer::getMemBuffer("#include \n"
+"// hi there!\n"));
+
+  DependencyScanningFilesystemSharedCache SharedCache;
+  auto Mappings = std::make_unique();
+  DependencyScanningWorkerFilesystem DepFS(SharedCache, VFS, Mappings.get());
+
+  DepFS.disableMinimization("/mod.h");
+  auto StatusFull0 = DepFS.status("/mod.h");
+  DepFS.enableMinimizationOfAllFiles();
+  auto StatusMinimized1 = DepFS.status("/mod.h");
 
-  EXPECT_TRUE(StatusMinimized2);
-  EXPECT_EQ(StatusMinimized2->getSize(), 0u);
-  EXPECT_TRUE(StatusFull3);
-  EXPECT_EQ(StatusFull3->getSize(), 13u);
+  EXPECT_TRUE(StatusFull0);
+  EXPECT_TRUE(StatusMinimized1);
+  EXPECT_EQ(StatusFull0->getSize(), 30u);
+  EXPECT_EQ(StatusMinimized1->getSize(), 17u);
 }
 
 } // end namespace dependencies
Index: clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
===
--- clang/lib/Tooling/Dependen

[PATCH] D112534: [PoC][RISCV] Use an attribute to declare C intrinsics with different policy.

2021-12-16 Thread Hsiangkai Wang via Phabricator via cfe-commits
HsiangKai updated this revision to Diff 394782.
HsiangKai added a comment.
Herald added a subscriber: jdoerfert.

Update attribute test cases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112534

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/riscv_vector.td
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/RISCV/rvv-intrinsics/vadd-policy.c
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/utils/TableGen/RISCVVEmitter.cpp

Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -204,6 +204,10 @@
   // Emit the macros for mapping C/C++ intrinsic function to builtin functions.
   void emitIntrinsicFuncDef(raw_ostream &o) const;
 
+  // Emit the declarations for mapping C/C++ intrinsic function to builtin
+  // functions.
+  void emitIntrinsicWithPolicyFuncDef(raw_ostream &o) const;
+
   // Emit the mangled function definition.
   void emitMangledFuncDef(raw_ostream &o) const;
 };
@@ -835,9 +839,10 @@
   if (isMask()) {
 if (hasVL()) {
   OS << "  std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end() - 1);\n";
-  if (hasPolicy())
-OS << "  Ops.push_back(ConstantInt::get(Ops.back()->getType(),"
-   " TAIL_UNDISTURBED));\n";
+  if (hasPolicy()) {
+OS << "  Ops.push_back(ConstantInt::get(Ops.back()->getType(), "
+  "PolicyValue));\n";
+  }
 } else {
   OS << "  std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end());\n";
 }
@@ -865,12 +870,32 @@
   OS << "__builtin_rvv_" << getBuiltinName() << ")))\n";
   OS << OutputType->getTypeStr() << " " << getName() << "(";
   // Emit function arguments
-  if (!InputTypes.empty()) {
+  ListSeparator LS;
+  for (unsigned i = 0; i < InputTypes.size(); ++i)
+OS << LS << InputTypes[i]->getTypeStr();
+  OS << ");\n";
+}
+
+void RVVIntrinsic::emitIntrinsicWithPolicyFuncDef(raw_ostream &OS) const {
+  if (!isMask())
+return;
+
+  static const char *const PolicySuffix[] = {"tumu", "tamu", "tuma", "tama"};
+
+  for (auto Suffix : PolicySuffix) {
+OS << "__rvv_ai ";
+OS << "__attribute__((__clang_builtin_alias__(";
+OS << "__builtin_rvv_" << getBuiltinName() << ")))\n";
+OS << "__attribute__((rvv_policy(" << Suffix << ")))\n";
+StringRef IntrinsicName = getName().substr(0, getName().size() - 2);
+OS << OutputType->getTypeStr() << " " << IntrinsicName << "_" << Suffix
+   << "(";
+// Emit function arguments
 ListSeparator LS;
 for (unsigned i = 0; i < InputTypes.size(); ++i)
   OS << LS << InputTypes[i]->getTypeStr();
+OS << ");\n";
   }
-  OS << ");\n";
 }
 
 void RVVIntrinsic::emitMangledFuncDef(raw_ostream &OS) const {
@@ -878,11 +903,9 @@
   OS << "__builtin_rvv_" << getBuiltinName() << ")))\n";
   OS << OutputType->getTypeStr() << " " << getMangledName() << "(";
   // Emit function arguments
-  if (!InputTypes.empty()) {
-ListSeparator LS;
-for (unsigned i = 0; i < InputTypes.size(); ++i)
-  OS << LS << InputTypes[i]->getTypeStr();
-  }
+  ListSeparator LS;
+  for (unsigned i = 0; i < InputTypes.size(); ++i)
+OS << LS << InputTypes[i]->getTypeStr();
   OS << ");\n";
 }
 
@@ -989,6 +1012,10 @@
 Inst.emitIntrinsicFuncDef(OS);
   });
 
+  emitArchMacroAndBody(Defs, OS, [](raw_ostream &OS, const RVVIntrinsic &Inst) {
+Inst.emitIntrinsicWithPolicyFuncDef(OS);
+  });
+
   OS << "#undef __rvv_ai\n\n";
 
   OS << "#define __riscv_v_intrinsic_overloading 1\n";
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -148,6 +148,7 @@
 // CHECK-NEXT: PassObjectSize (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: PatchableFunctionEntry (SubjectMatchRule_function, SubjectMatchRule_objc_method)
 // CHECK-NEXT: Pointer (SubjectMatchRule_record_not_is_union)
+// CHECK-NEXT: RISCVVPolicy (SubjectMatchRule_function)
 // CHECK-NEXT: ReleaseHandle (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: RenderScriptKernel (SubjectMatchRule_function)
 // CHECK-NEXT: ReqdWorkGroupSize (SubjectMatchRule_function)
Index: clang/test/CodeGen/RISCV/rvv-intrinsics/vadd-policy.c
===
--- /dev/null
+++ clang/test/CodeGen/RISCV/rvv-intrinsics/vadd-policy.c
@@ -0,0 +1,42 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// REQUIRES: riscv-registered-target
+// RUN: %clang_cc1 -triple riscv64 -target-feature +f -target-feature +d -target-feature +experimental-v \
+// RUN:   

[PATCH] D115346: [clang][deps] Squash caches for original and minimized files

2021-12-16 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

Committed with the writes swapped and explanation in the comment. Thanks for 
the review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115346

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


[PATCH] D113622: [analyzer] support ignoring use-after-free checking with reference_counted attribute

2021-12-16 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D113622#3195985 , @NoQ wrote:

> In D113622#3194580 , @steakhal 
> wrote:
>
>> Could you please share the results to have look? How can I reproduce and 
>> evaluate the effect of this change?
>
> ...

Ah, I see. Thank you for the detailed motivation, and future plans.


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

https://reviews.llvm.org/D113622

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


[PATCH] D115792: [Modules] Incorrect ODR detection for unresolved using type

2021-12-16 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 394786.
ChuanqiXu added a comment.

Address comments.


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

https://reviews.llvm.org/D115792

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/TypeProperties.td
  clang/lib/AST/ASTContext.cpp
  clang/test/Modules/Inputs/odr_using_dependent_name/X.cppm
  clang/test/Modules/Inputs/odr_using_dependent_name/foo.h
  clang/test/Modules/odr_using_dependent_name.cppm

Index: clang/test/Modules/odr_using_dependent_name.cppm
===
--- /dev/null
+++ clang/test/Modules/odr_using_dependent_name.cppm
@@ -0,0 +1,9 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: %clang -std=c++20 %S/Inputs/odr_using_dependent_name/X.cppm --precompile -o %t/X.pcm
+// RUN: %clang -std=c++20 -I%S/Inputs/odr_using_dependent_name -fprebuilt-module-path=%t %s --precompile -c
+// expected-no-diagnostics
+module;
+#include "foo.h"
+export module Y;
+import X;
Index: clang/test/Modules/Inputs/odr_using_dependent_name/foo.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/odr_using_dependent_name/foo.h
@@ -0,0 +1,9 @@
+template 
+struct bar {
+  using Ty = int;
+};
+template 
+struct foo : public bar {
+  using typename bar::Ty;
+  void baz(Ty);
+};
Index: clang/test/Modules/Inputs/odr_using_dependent_name/X.cppm
===
--- /dev/null
+++ clang/test/Modules/Inputs/odr_using_dependent_name/X.cppm
@@ -0,0 +1,3 @@
+module;
+#include "foo.h"
+export module X;
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -4568,9 +4568,7 @@
 assert(Enum->isFirstDecl() && "enum has previous declaration");
 return getEnumType(Enum);
   } else if (const auto *Using = dyn_cast(Decl)) {
-Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
-Decl->TypeForDecl = newType;
-Types.push_back(newType);
+return getUnresolvedUsingType(Using);
   } else
 llvm_unreachable("TypeDecl without a type?");
 
@@ -4619,6 +4617,22 @@
   return QualType(newType, 0);
 }
 
+QualType ASTContext::getUnresolvedUsingType(
+const UnresolvedUsingTypenameDecl *Decl) const {
+  if (Decl->TypeForDecl)
+return QualType(Decl->TypeForDecl, 0);
+
+  if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
+  Decl->getCanonicalDecl())
+if (CanonicalDecl->TypeForDecl)
+  return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
+
+  Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl);
+  Decl->TypeForDecl = newType;
+  Types.push_back(newType);
+  return QualType(newType, 0);
+}
+
 QualType ASTContext::getAttributedType(attr::Kind attrKind,
QualType modifiedType,
QualType equivalentType) {
Index: clang/include/clang/AST/TypeProperties.td
===
--- clang/include/clang/AST/TypeProperties.td
+++ clang/include/clang/AST/TypeProperties.td
@@ -358,7 +358,7 @@
   }
 
   def : Creator<[{
-return ctx.getTypeDeclType(cast(declaration));
+return ctx.getUnresolvedUsingType(cast(declaration));
   }]>;
 }
 
Index: clang/include/clang/AST/ASTContext.h
===
--- clang/include/clang/AST/ASTContext.h
+++ clang/include/clang/AST/ASTContext.h
@@ -1564,6 +1564,9 @@
 
   QualType getEnumType(const EnumDecl *Decl) const;
 
+  QualType
+  getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const;
+
   QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
 
   QualType getAttributedType(attr::Kind attrKind,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D110622: [HIPSPV][3/4] Enable SPIR-V emission for HIP

2021-12-16 Thread Henry Linjamäki via Phabricator via cfe-commits
linjamaki updated this revision to Diff 394789.
linjamaki added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110622

Files:
  clang/include/clang/Basic/Cuda.h
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Cuda.cpp
  clang/lib/Basic/Targets/NVPTX.cpp
  clang/lib/Basic/Targets/NVPTX.h
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/Inputs/hipspv-dev-lib/a/a.bc
  clang/test/Driver/Inputs/hipspv-dev-lib/b/b.bc
  clang/test/Driver/Inputs/hipspv-dev-lib/hipspv-spirv64.bc
  clang/test/Driver/Inputs/hipspv/bin/.hipVersion
  clang/test/Driver/Inputs/hipspv/lib/hip-device-lib/hipspv-spirv64.bc
  clang/test/Driver/Inputs/hipspv/lib/libLLVMHipSpvPasses.so
  clang/test/Driver/Inputs/pass-plugin.so
  clang/test/Driver/hipspv-device-libs.hip
  clang/test/Driver/hipspv-pass-plugin.hip
  clang/test/Driver/hipspv-toolchain-rdc.hip
  clang/test/Driver/hipspv-toolchain.hip
  clang/test/Driver/invalid-offload-options.cpp

Index: clang/test/Driver/invalid-offload-options.cpp
===
--- /dev/null
+++ clang/test/Driver/invalid-offload-options.cpp
@@ -0,0 +1,31 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// UNSUPPORTED: system-windows
+
+// RUN: %clang -### -x hip -target x86_64-linux-gnu --offload= \
+// RUN:   --hip-path=%S/Inputs/hipspv -nogpuinc -nogpulib %s \
+// RUN: 2>&1 | FileCheck --check-prefix=INVALID-TARGET %s
+// RUN: %clang -### -x hip -target x86_64-linux-gnu --offload=foo \
+// RUN:   --hip-path=%S/Inputs/hipspv -nogpuinc -nogpulib %s \
+// RUN: 2>&1 | FileCheck --check-prefix=INVALID-TARGET %s
+
+// INVALID-TARGET: error: Invalid or unsupported offload target: '{{.*}}'
+
+// In the future we should be able to specify multiple targets for HIP
+// compilation but currently it is not supported.
+//
+// RUN: %clang -### -x hip -target x86_64-linux-gnu --offload=foo,bar \
+// RUN:   --hip-path=%S/Inputs/hipspv -nogpuinc -nogpulib %s \
+// RUN: 2>&1 | FileCheck --check-prefix=TOO-MANY-TARGETS %s
+// RUN: %clang -### -x hip -target x86_64-linux-gnu \
+// RUN:   --offload=foo --offload=bar \
+// RUN:   --hip-path=%S/Inputs/hipspv -nogpuinc -nogpulib %s \
+// RUN: 2>&1 | FileCheck --check-prefix=TOO-MANY-TARGETS %s
+
+// TOO-MANY-TARGETS: error: Only one offload target is supported in HIP.
+
+// RUN: %clang -### -x hip -target x86_64-linux-gnu -nogpuinc -nogpulib \
+// RUN:   --offload=amdgcn-amd-amdhsa --offload-arch=gfx900 %s \
+// RUN: 2>&1 | FileCheck --check-prefix=OFFLOAD-ARCH-MIX %s
+
+// OFFLOAD-ARCH-MIX: error: option '--offload-arch' cannot be specified with '--offload'
Index: clang/test/Driver/hipspv-toolchain.hip
===
--- /dev/null
+++ clang/test/Driver/hipspv-toolchain.hip
@@ -0,0 +1,37 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// UNSUPPORTED: system-windows
+
+// RUN: %clang -### -target x86_64-linux-gnu --offload=spirv64 \
+// RUN:   --hip-path=%S/Inputs/hipspv -nohipwrapperinc %s \
+// RUN: 2>&1 | FileCheck %s
+
+// CHECK: [[CLANG:".*clang.*"]] "-cc1" "-triple" "spirv64"
+// CHECK-SAME: "-aux-triple" "{{.*}}" "-emit-llvm-bc"
+// CHECK-SAME: "-fcuda-is-device"
+// CHECK-SAME: "-fcuda-allow-variadic-functions"
+// CHECK-SAME: "-mlink-builtin-bitcode" {{".*/hipspv/lib/hip-device-lib/hipspv-spirv64.bc"}}
+// CHECK-SAME: "-isystem" {{".*/hipspv/include"}}
+// CHECK-SAME: "-fhip-new-launch-api"
+// CHECK-SAME: "-o" [[DEV_BC:".*bc"]]
+// CHECK-SAME: "-x" "hip"
+
+// CHECK: {{".*llvm-link"}} [[DEV_BC]] "-o" [[LINK_BC:".*bc"]]
+
+// CHECK: {{".*opt"}} [[LINK_BC]] "-load-pass-plugin"
+// CHECK-SAME: {{".*/hipspv/lib/libLLVMHipSpvPasses.so"}}
+// CHECK-SAME: "-passes=hip-post-link-passes" "-o" [[LOWER_BC:".*bc"]]
+
+// CHECK: {{".*llvm-spirv"}} "--spirv-max-version=1.1" "--spirv-ext=+all"
+// CHECK-SAME: [[LOWER_BC]] "-o" "[[SPIRV_OUT:.*out]]"
+
+// CHECK: {{".*clang-offload-bundler"}} "-type=o" "-bundle-align=4096"
+// CHECK-SAME: "-targets=host-x86_64-unknown-linux,hip-spirv64generic"
+// CHECK-SAME: "-inputs={{.*}},[[SPIRV_OUT]]" "-outputs=[[BUNDLE:.*hipfb]]"
+
+// CHECK: [[CLANG]] "-cc1" "-triple" {{".*"}} "-aux-triple" "spirv64"
+// CHECK-SAME: "-emit-obj"
+// CHECK-SAME: "-fcuda-include-gpubinary" "[[BUNDLE]]"
+// CHECK-SAME: "-o" [[OBJ_HOST:".*o"]] "-x" "hip"
+
+// CHECK: {{".*ld.*"}} {{.*}}[[OBJ_HOST]]
Index: clang/test/Driver/hipspv-toolchain-rdc.hip
===
--- /dev/null
+++ clang/test/Driver/hipspv-toolchain-rdc.hip
@@ -0,0 +1,63 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// UNSUPPORTED: system-windows
+
+// RUN: %clang -### -x hip -target x86_64-linux-gnu --offload=spirv64 \
+// RUN:   -fgpu-rdc --h

[PATCH] D115865: [clang-format] add support for branch attribute macros

2021-12-16 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay created this revision.
MyDeveloperDay added reviewers: curdeius, HazardyKnusperkeks, owenpan.
MyDeveloperDay added projects: clang, clang-format.
MyDeveloperDay requested review of this revision.

https://github.com/llvm/llvm-project/issues/49184

clang-format doesn't handle the use of AttributeMacros where `[[unlikely]]` / 
`[[likely]]` could be used in `if` statements

  if (StartIndex == End)
  BRANCH_UNLIKELY
  return npos;

Give better support via

  if (StartIndex == End) [[unlikely]]
return npos;
  
  if (StartIndex == End) [[unlikely]] {
return npos;
  }
  
  if (StartIndex == End) UNLIKELY
return npos;
  
  if (StartIndex == End) UNLIKELY {
return npos;
  }

Fixes #49184


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115865

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -22180,6 +22180,42 @@
"  return 29;\n"
"}",
Style);
+
+  verifyFormat("if (argc > 5) [[unlikely]]\n"
+   "  return 29;\n",
+   Style);
+  verifyFormat("if (argc > 5) [[likely]]\n"
+   "  return 29;\n",
+   Style);
+
+  Style.AttributeMacros.push_back("UNLIKELY");
+  Style.AttributeMacros.push_back("LIKELY");
+  verifyFormat("if (argc > 5) UNLIKELY\n"
+   "  return 29;\n",
+   Style);
+
+  verifyFormat("if (argc > 5) UNLIKELY {\n"
+   "  return 29;\n"
+   "}",
+   Style);
+  verifyFormat("if (argc > 5) UNLIKELY {\n"
+   "  return 29;\n"
+   "} else [[likely]] {\n"
+   "  return 42;\n"
+   "}\n",
+   Style);
+  verifyFormat("if (argc > 5) UNLIKELY {\n"
+   "  return 29;\n"
+   "} else LIKELY {\n"
+   "  return 42;\n"
+   "}\n",
+   Style);
+  verifyFormat("if (argc > 5) [[unlikely]] {\n"
+   "  return 29;\n"
+   "} else LIKELY {\n"
+   "  return 42;\n"
+   "}\n",
+   Style);
 }
 
 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2166,6 +2166,9 @@
 nextToken();
   if (FormatTok->Tok.is(tok::l_paren))
 parseParens();
+  // handle  AttributeMacro  if (x) UNLIKELY
+  if (FormatTok->is(TT_AttributeMacro))
+nextToken();
   // handle [[likely]] / [[unlikely]]
   if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute())
 parseSquare();
@@ -2185,6 +2188,9 @@
   }
   if (FormatTok->Tok.is(tok::kw_else)) {
 nextToken();
+// handle  AttributeMacro  else UNLIKELY
+if (FormatTok->is(TT_AttributeMacro))
+  nextToken();
 // handle [[likely]] / [[unlikely]]
 if (FormatTok->Tok.is(tok::l_square) && tryToParseSimpleAttribute())
   parseSquare();


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -22180,6 +22180,42 @@
"  return 29;\n"
"}",
Style);
+
+  verifyFormat("if (argc > 5) [[unlikely]]\n"
+   "  return 29;\n",
+   Style);
+  verifyFormat("if (argc > 5) [[likely]]\n"
+   "  return 29;\n",
+   Style);
+
+  Style.AttributeMacros.push_back("UNLIKELY");
+  Style.AttributeMacros.push_back("LIKELY");
+  verifyFormat("if (argc > 5) UNLIKELY\n"
+   "  return 29;\n",
+   Style);
+
+  verifyFormat("if (argc > 5) UNLIKELY {\n"
+   "  return 29;\n"
+   "}",
+   Style);
+  verifyFormat("if (argc > 5) UNLIKELY {\n"
+   "  return 29;\n"
+   "} else [[likely]] {\n"
+   "  return 42;\n"
+   "}\n",
+   Style);
+  verifyFormat("if (argc > 5) UNLIKELY {\n"
+   "  return 29;\n"
+   "} else LIKELY {\n"
+   "  return 42;\n"
+   "}\n",
+   Style);
+  verifyFormat("if (argc > 5) [[unlikely]] {\n"
+   "  return 29;\n"
+   "} else LIKELY {\n"
+   "  return 42;\n"
+   "}\n",
+   Style);
 }
 
 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2166,6 +2166,9 @@
 nextToken();
   if (FormatTok->Tok.is(tok::l_paren

[PATCH] D102669: [analyzer][ctu] Fix wrong 'multiple definitions' errors caused by space characters in lookup names when parsing the ctu index file

2021-12-16 Thread Ella Ma via Phabricator via cfe-commits
OikawaKirie added a comment.

It seems this patch has nothing to do with the failure in the Linux build. I 
think it is now ready to land.
Thanks a lot for your suggestions during the revision.

Could you please commit this patch on my behalf? Thanks.
Ella Ma 


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

https://reviews.llvm.org/D102669

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


[PATCH] D115231: [Clang] Add __builtin_reduce_xor

2021-12-16 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

In D115231#3194439 , @junaire wrote:

> In D115231#3194372 , @RKSimon wrote:
>
>> Any reason not to handle __builtin_reduce_xor + __builtin_reduce_or as well 
>> in the same patch since they are very similar?
>
> Hi, thanks for take a look at this.
> Yes, you're right. The reason I split them is that I'm a beginner, so I want 
> to send a "experimental patch" first, this will make review work a little bit 
> easier if I mess something up. I think it's reasonable to add all similar 
> builtins if currently nothing wrong about this one.

That's fine - I'm happy to see these addressed as follow up patches - cheers!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115231

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


[PATCH] D113779: [Clang] Add mfp16, mfp16fml and mdotprod flags for ARM target features.

2021-12-16 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.

In D113779#3192009 , @SjoerdMeijer 
wrote:

> Ok, fair enough, perhaps adding features is a valid use-case.
>
> I will refrain from commenting on "things are terribly broken".  I agree it 
> is broken, but in a different way than suggested in previous comments. 
> If others also think this makes sense, then here a few follow up remarks from 
> my side:
>
> - First of all, this (really) sets precedent for setting options in a 
> different way. This needs documentation and release noting.
> - If we are going to do this, this should be the first patch in a series to 
> fix this for all features. We can't just do a few of them.

Agreed.

> - There was a suggestion to allow adding features with -march=+feature. Was 
> this dismissed in favour of how things works for x86 and be consistent with 
> that?

This would be the easiest way to implement this, *but* it would require either 
to allow not specify an architecture version with `-march` (which seems a bit 
odd) or perhaps adding a `default` architecture version which just uses the 
default set. For our users, either would work, so I'd be happy to go with what 
seems most compelling to others.

But compatibility with X86 is IMO also valuable for people porting from 
X86->AArch64.

> It would be really good if we keep options consistent/compatible across the 
> GCC and Clang toolchains. Any possibility to check with GCC community if they 
> are open for this?

If anybody has contacts to GCC that would be very helpful. Unfortunately I 
don't think I will be able to drive this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113779

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


[PATCH] D115231: [Clang] Add __builtin_reduce_xor

2021-12-16 Thread Florian Hahn via Phabricator via cfe-commits
fhahn accepted this revision.
fhahn added a comment.

LGTM, thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115231

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


[PATCH] D115867: [C++20] [Coroutines] Warning for always_inline coroutine

2021-12-16 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu created this revision.
ChuanqiXu added reviewers: rjmccall, lxfind.
ChuanqiXu added a project: clang.
ChuanqiXu requested review of this revision.
Herald added a subscriber: cfe-commits.

See the discussion in https://reviews.llvm.org/D100282.  Since coroutine 
couldn't be **properly** inlined as user imaged, it is suggested to warn for 
the case a coroutine is marked with `always_inline`


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115867

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaCoroutine.cpp
  clang/test/SemaCXX/coroutines.cpp


Index: clang/test/SemaCXX/coroutines.cpp
===
--- clang/test/SemaCXX/coroutines.cpp
+++ clang/test/SemaCXX/coroutines.cpp
@@ -1443,3 +1443,7 @@
   co_await missing_await_suspend{}; // expected-error {{no member named 
'await_suspend' in 'missing_await_suspend'}}
   co_await missing_await_resume{}; // expected-error {{no member named 
'await_resume' in 'missing_await_resume'}}
 }
+
+__attribute__((__always_inline__)) void warn_always_inline() { // 
expected-warning {{A coroutine marked always_inline might not be inlined 
properly}}
+  co_await suspend_always{};
+}
Index: clang/lib/Sema/SemaCoroutine.cpp
===
--- clang/lib/Sema/SemaCoroutine.cpp
+++ clang/lib/Sema/SemaCoroutine.cpp
@@ -1062,6 +1062,12 @@
 return;
   }
 
+  // The coroutine marked always inline might not be inlined properly in 
current
+  // compiler support. Only the ramp function is guarantted to be inlined. It 
might
+  // be different to what users expects to. Emit a warning to tell it.
+  if (FD->hasAttr())
+Diag(FD->getLocation(), diag::warn_always_inline_coroutine);
+
   // Coroutines [stmt.return]p1:
   //   A return statement shall not appear in a coroutine.
   if (Fn->FirstReturnLoc.isValid()) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11099,6 +11099,10 @@
 def note_coroutine_function_declare_noexcept : Note<
   "must be declared with 'noexcept'"
 >;
+def warn_always_inline_coroutine : Warning<
+  "A coroutine marked always_inline might not be inlined properly."
+  >,
+  InGroup;
 } // end of coroutines issue category
 
 let CategoryName = "Documentation Issue" in {
Index: clang/include/clang/Basic/DiagnosticGroups.td
===
--- clang/include/clang/Basic/DiagnosticGroups.td
+++ clang/include/clang/Basic/DiagnosticGroups.td
@@ -58,7 +58,9 @@
   DiagGroup<"deprecated-experimental-coroutine">;
 def DeprecatedCoroutine :
   DiagGroup<"deprecated-coroutine", [DeprecatedExperimentalCoroutine]>;
-def Coroutine : DiagGroup<"coroutine", [CoroutineMissingUnhandledException, 
DeprecatedCoroutine]>;
+def AlwaysInlineCoroutine :
+  DiagGroup<"always-inline-coroutine">;
+def Coroutine : DiagGroup<"coroutine", [CoroutineMissingUnhandledException, 
DeprecatedCoroutine, AlwaysInlineCoroutine]>;
 def ObjCBoolConstantConversion : DiagGroup<"objc-bool-constant-conversion">;
 def ConstantConversion : DiagGroup<"constant-conversion",
[BitFieldConstantConversion,


Index: clang/test/SemaCXX/coroutines.cpp
===
--- clang/test/SemaCXX/coroutines.cpp
+++ clang/test/SemaCXX/coroutines.cpp
@@ -1443,3 +1443,7 @@
   co_await missing_await_suspend{}; // expected-error {{no member named 'await_suspend' in 'missing_await_suspend'}}
   co_await missing_await_resume{}; // expected-error {{no member named 'await_resume' in 'missing_await_resume'}}
 }
+
+__attribute__((__always_inline__)) void warn_always_inline() { // expected-warning {{A coroutine marked always_inline might not be inlined properly}}
+  co_await suspend_always{};
+}
Index: clang/lib/Sema/SemaCoroutine.cpp
===
--- clang/lib/Sema/SemaCoroutine.cpp
+++ clang/lib/Sema/SemaCoroutine.cpp
@@ -1062,6 +1062,12 @@
 return;
   }
 
+  // The coroutine marked always inline might not be inlined properly in current
+  // compiler support. Only the ramp function is guarantted to be inlined. It might
+  // be different to what users expects to. Emit a warning to tell it.
+  if (FD->hasAttr())
+Diag(FD->getLocation(), diag::warn_always_inline_coroutine);
+
   // Coroutines [stmt.return]p1:
   //   A return statement shall not appear in a coroutine.
   if (Fn->FirstReturnLoc.isValid()) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11099,6 +11

[PATCH] D115231: [Clang] Add __builtin_reduce_xor

2021-12-16 Thread Jun Zhang via Phabricator via cfe-commits
junaire added a comment.

Thanks for accepting this patch! I would appreciate it if someone is willing to 
commit this for me since I don't have commit access ;D

You can use:
Jun Zhang 
j...@junz.org


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115231

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


[clang] 9fa15e0 - [CodeGen] Remove an unused MakeAddrLValue() overload (NFC)

2021-12-16 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2021-12-16T11:49:20+01:00
New Revision: 9fa15e0073b97dc2aa3482f297c13cb9509238e4

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

LOG: [CodeGen] Remove an unused MakeAddrLValue() overload (NFC)

This is unused and we should prefer the overloads accepting Address.

Added: 


Modified: 
clang/lib/CodeGen/CodeGenFunction.h

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index bb60e22e4368..6b310d32e28b 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -2498,12 +2498,6 @@ class CodeGenFunction : public CodeGenTypeCache {
 LValueBaseInfo(Source), CGM.getTBAAAccessInfo(T));
   }
 
-  LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
-LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
-return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
-BaseInfo, TBAAInfo);
-  }
-
   LValue
   MakeAddrLValueWithoutTBAA(Address Addr, QualType T,
 AlignmentSource Source = AlignmentSource::Type) {



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


[PATCH] D115790: [Coroutines] Set presplit attribute in Clang

2021-12-16 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 394801.
ChuanqiXu retitled this revision from "[Coroutines] Run CoroEarly Pass in front 
of AlwaysInliner in O0 pass and warn for always_inline coroutine" to 
"[Coroutines] Set presplit attribute in Clang".
ChuanqiXu edited the summary of this revision.
ChuanqiXu added a comment.
Herald added a subscriber: jdoerfert.

Address the comments to set the attribute in frontend.


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

https://reviews.llvm.org/D115790

Files:
  clang/lib/CodeGen/CGCoroutine.cpp
  clang/test/CodeGenCoroutines/coro-attributes.cpp
  llvm/docs/Coroutines.rst
  llvm/lib/Transforms/Coroutines/CoroEarly.cpp
  llvm/lib/Transforms/Coroutines/CoroInternal.h
  llvm/test/Transforms/Coroutines/coro-debug-O2.ll
  llvm/test/Transforms/Coroutines/coro-debug-coro-frame.ll
  llvm/test/Transforms/Coroutines/coro-debug-dbg.values-not_used_in_frame.ll
  llvm/test/Transforms/Coroutines/coro-debug-dbg.values.ll
  llvm/test/Transforms/Coroutines/coro-debug-frame-variable.ll
  llvm/test/Transforms/Coroutines/coro-split-01.ll
  llvm/test/Transforms/Coroutines/coro-split-recursive.ll
  llvm/test/Transforms/Coroutines/ex0.ll
  llvm/test/Transforms/Coroutines/ex1.ll
  llvm/test/Transforms/Coroutines/ex2.ll
  llvm/test/Transforms/Coroutines/ex3.ll
  llvm/test/Transforms/Coroutines/ex4.ll
  llvm/test/Transforms/Coroutines/ex5.ll
  llvm/test/Transforms/Coroutines/phi-coro-end.ll
  llvm/test/Transforms/Coroutines/restart-trigger.ll

Index: llvm/test/Transforms/Coroutines/restart-trigger.ll
===
--- llvm/test/Transforms/Coroutines/restart-trigger.ll
+++ llvm/test/Transforms/Coroutines/restart-trigger.ll
@@ -10,7 +10,7 @@
 ; CHECK-NEWPM-NOT:  CoroSplit: Processing coroutine 'f' state: 1
 
 
-define void @f() {
+define void @f() "coroutine.presplit"="0" {
   %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
   %size = call i32 @llvm.coro.size.i32()
   %alloc = call i8* @malloc(i32 %size)
Index: llvm/test/Transforms/Coroutines/phi-coro-end.ll
===
--- llvm/test/Transforms/Coroutines/phi-coro-end.ll
+++ llvm/test/Transforms/Coroutines/phi-coro-end.ll
@@ -1,7 +1,7 @@
 ; Verify that we correctly handle suspend when the coro.end block contains phi
 ; RUN: opt < %s -aa-pipeline=basic-aa -passes='default' -enable-coroutines -S | FileCheck %s
 
-define i8* @f(i32 %n) {
+define i8* @f(i32 %n) "coroutine.presplit"="0" {
 entry:
   %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
   %size = call i32 @llvm.coro.size.i32()
Index: llvm/test/Transforms/Coroutines/ex5.ll
===
--- llvm/test/Transforms/Coroutines/ex5.ll
+++ llvm/test/Transforms/Coroutines/ex5.ll
@@ -1,7 +1,7 @@
 ; Fifth example from Doc/Coroutines.rst (final suspend)
 ; RUN: opt < %s -aa-pipeline=basic-aa -passes='default' -enable-coroutines -preserve-alignment-assumptions-during-inlining=false -S | FileCheck %s
 
-define i8* @f(i32 %n) {
+define i8* @f(i32 %n) "coroutine.presplit"="0" {
 entry:
   %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
   %size = call i32 @llvm.coro.size.i32()
Index: llvm/test/Transforms/Coroutines/ex4.ll
===
--- llvm/test/Transforms/Coroutines/ex4.ll
+++ llvm/test/Transforms/Coroutines/ex4.ll
@@ -1,7 +1,7 @@
 ; Fourth example from Doc/Coroutines.rst (coroutine promise)
 ; RUN: opt < %s -passes='default' -enable-coroutines -S | FileCheck %s
 
-define i8* @f(i32 %n) {
+define i8* @f(i32 %n) "coroutine.presplit"="0" {
 entry:
   %promise = alloca i32
   %pv = bitcast i32* %promise to i8*
Index: llvm/test/Transforms/Coroutines/ex3.ll
===
--- llvm/test/Transforms/Coroutines/ex3.ll
+++ llvm/test/Transforms/Coroutines/ex3.ll
@@ -1,7 +1,7 @@
 ; Third example from Doc/Coroutines.rst (two suspend points)
 ; RUN: opt < %s -aa-pipeline=basic-aa -passes='default' -enable-coroutines -S | FileCheck %s
 
-define i8* @f(i32 %n) {
+define i8* @f(i32 %n) "coroutine.presplit"="0" {
 entry:
   %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
   %size = call i32 @llvm.coro.size.i32()
Index: llvm/test/Transforms/Coroutines/ex2.ll
===
--- llvm/test/Transforms/Coroutines/ex2.ll
+++ llvm/test/Transforms/Coroutines/ex2.ll
@@ -1,7 +1,7 @@
 ; Second example from Doc/Coroutines.rst (custom alloc and free functions)
 ; RUN: opt < %s -passes='default' -enable-coroutines -S | FileCheck %s
 
-define i8* @f(i32 %n) {
+define i8* @f(i32 %n) "coroutine.presplit"="0" {
 entry:
   %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
   %need.dyn.alloc = call i1 @llvm.coro.alloc(token %id)
Index: llvm/test/Transforms/Coroutines/ex1.ll
==

[PATCH] D115738: [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-16 Thread Peter Stys via Phabricator via cfe-commits
peterstys updated this revision to Diff 394802.

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

https://reviews.llvm.org/D115738

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTestCSharp.cpp

Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -759,6 +759,128 @@
GoogleStyle);
 }
 
+TEST_F(FormatTestCSharp, CSharpLambdasDontBreakFollowingCodeAlignment) {
+  FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
+  FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(//
+public class Sample {
+  public void Test() {
+while (true) {
+  preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+  CodeThatFollowsLambda();
+  IsWellAligned();
+}
+  }
+})",
+   GoogleStyle);
+
+  verifyFormat(R"(//
+public class Sample
+{
+public void Test()
+{
+while (true)
+{
+preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+CodeThatFollowsLambda();
+IsWellAligned();
+}
+}
+})",
+   MicrosoftStyle);
+}
+
+TEST_F(FormatTestCSharp, CSharpLambdasComplexLambdasDontBreakAlignment) {
+  FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
+  FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(//
+public class Test
+{
+private static void ComplexLambda(BuildReport protoReport)
+{
+allSelectedScenes =
+veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds.Where(scene => scene.enabled)
+.Select(scene => scene.path)
+.ToArray();
+if (allSelectedScenes.Count == 0)
+{
+return;
+}
+Functions();
+AreWell();
+Aligned();
+AfterLambdaBlock();
+}
+})",
+   MicrosoftStyle);
+
+  verifyFormat(R"(//
+public class Test {
+  private static void ComplexLambda(BuildReport protoReport) {
+allSelectedScenes = veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds
+.Where(scene => scene.enabled)
+.Select(scene => scene.path)
+.ToArray();
+if (allSelectedScenes.Count == 0) {
+  return;
+}
+Functions();
+AreWell();
+Aligned();
+AfterLambdaBlock();
+  }
+})",
+   GoogleStyle);
+}
+
+TEST_F(FormatTestCSharp, CSharpLambdasMulipleLambdasDontBreakAlignment) {
+  FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
+  FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(//
+public class Test
+{
+private static void MultipleLambdas(BuildReport protoReport)
+{
+allSelectedScenes =
+veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds.Where(scene => scene.enabled)
+.Select(scene => scene.path)
+.ToArray();
+preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+if (allSelectedScenes.Count == 0)
+{
+return;
+}
+Functions();
+AreWell();
+Aligned();
+AfterLambdaBlock();
+}
+})",
+   MicrosoftStyle);
+
+  verifyFormat(R"(//
+public class Test {
+  private static void MultipleLambdas(BuildReport protoReport) {
+allSelectedScenes = veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds
+.Where(scene => scene.enabled)
+.Select(scene => scene.path)
+.ToArray();
+preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+if (allSelectedScenes.Count == 0) {
+  return;
+}
+Functions();
+AreWell();
+Aligned();
+AfterLambdaBlock();
+  }
+})",
+   GoogleStyle);
+}
+
 TEST_F(FormatTestCSharp, CSharpObjectInitializers) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 
Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -138,6 +138,7 @@
   // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
   void parseCSharpGenericTypeConstraint();
   bool tryToParseLambda();
+  bool tryToParseCSharpLambda();
   bool tryToParseLambdaIntroducer();
   bool tryToParsePropertyAccessor();
   void tryToParseJSFunction();
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Forma

[PATCH] D115738: [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-16 Thread Peter Stys via Phabricator via cfe-commits
peterstys marked 4 inline comments as done.
peterstys added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1870
   // C# may break after => if the next character is a newline.
   if (Style.isCSharp() && Style.BraceWrapping.AfterFunction == true) {
 // calling `addUnwrappedLine()` here causes odd parsing errors.

owenpan wrote:
> Let's fix this too while we are at it. In the future, we may want to factor 
> lines 1862-1874 and 2004-2009.
I extracted the C# lambda parsing block into a separate function to avoid 
repeating the same logic twice. Hope that is alright.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1872
 // calling `addUnwrappedLine()` here causes odd parsing errors.
 FormatTok->MustBreakBefore = true;
   }

MyDeveloperDay wrote:
> part of me thinks the MustBreakBefore should be handled separately in 
> TokenAnnotator::mustBreakBefore() and let it do its stuff. 
I used MustBreakBefore = true because the same method was used for the FatArrow 
processing on the lines 1862-1874 and it did the right thing i.e. added a new 
line before the block. 

If you want me to change the code to use TokenAnnotator::mustBreakBefore() 
please provide more details on how to do it, or point me to some examples. I 
failed to find any good references, I'm afraid.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1872
 // calling `addUnwrappedLine()` here causes odd parsing errors.
 FormatTok->MustBreakBefore = true;
   }

owenpan wrote:
> peterstys wrote:
> > MyDeveloperDay wrote:
> > > part of me thinks the MustBreakBefore should be handled separately in 
> > > TokenAnnotator::mustBreakBefore() and let it do its stuff. 
> > I used MustBreakBefore = true because the same method was used for the 
> > FatArrow processing on the lines 1862-1874 and it did the right thing i.e. 
> > added a new line before the block. 
> > 
> > If you want me to change the code to use TokenAnnotator::mustBreakBefore() 
> > please provide more details on how to do it, or point me to some examples. 
> > I failed to find any good references, I'm afraid.
> Yes, but we can take care of it in a separate patch.
ACK



Comment at: clang/unittests/Format/FormatTestCSharp.cpp:766
+
+  verifyFormat(R"(//
+public class Sample {

MyDeveloperDay wrote:
> Nit: (only my preference) but I don't like the use of RawStrings in these 
> tests (I know others have let them creep in) but I find them more unreadable 
> because we lose the indentation.. I think I'm just so used to the other style 
> that this just crates a little.
> 
> Just my personal preference (you can ignore)
I used the RawStrings as it was very easy to copy snippet of code to a separate 
file so I could run clang-format on it to check all was working well. I also 
copied snippets to my local IDE to check if the file was building, or at least 
structurally okay (which I appreciate is not a requirements as clang-format 
does not build a complete AST of the code). 

For example, I was surprised to see some sample code in unit tests missing 
braces after catch (Exception) statement (line 694) (which may have been 
intended). I find it slightly more difficult to read those code snippets if 
they are decorated with \n. 

On the other hand, you're right, raw string break the indentation which is not 
great. Also, I'd rather follow the leading preferences (and wasn't sure which 
ones where they before your comment). I'm happy to update this to your style if 
that is the preference.


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

https://reviews.llvm.org/D115738

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


[clang] 34eb715 - [CodeGen] Avoid more pointer element type accesses

2021-12-16 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2021-12-16T12:03:11+01:00
New Revision: 34eb715f61991cd3abd19b02af689b84409363f1

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

LOG: [CodeGen] Avoid more pointer element type accesses

Added: 


Modified: 
clang/lib/CodeGen/CGExprAgg.cpp
clang/lib/CodeGen/CGExprScalar.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntime.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprAgg.cpp b/clang/lib/CodeGen/CGExprAgg.cpp
index cc7a333d6290..980d6095b3a5 100644
--- a/clang/lib/CodeGen/CGExprAgg.cpp
+++ b/clang/lib/CodeGen/CGExprAgg.cpp
@@ -513,7 +513,8 @@ void AggExprEmitter::EmitArrayInit(Address DestPtr, 
llvm::ArrayType *AType,
   Emitter.finalize(GV);
   CharUnits Align = CGM.getContext().getTypeAlignInChars(ArrayQTy);
   GV->setAlignment(Align.getAsAlign());
-  EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GV, ArrayQTy, Align));
+  Address GVAddr(GV, GV->getValueType(), Align);
+  EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GVAddr, ArrayQTy));
   return;
 }
   }

diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index f1ee56531378..4998d343e5f5 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -3531,7 +3531,7 @@ static Value *emitPointerArithmetic(CodeGenFunction &CGF,
 return CGF.Builder.CreateBitCast(result, pointer->getType());
   }
 
-  llvm::Type *elemTy = pointer->getType()->getPointerElementType();
+  llvm::Type *elemTy = CGF.ConvertTypeForMem(elementType);
   if (CGF.getLangOpts().isSignedOverflowDefined())
 return CGF.Builder.CreateGEP(elemTy, pointer, index, "add.ptr");
 

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 2e26fb18ab2f..7bd7d97da43a 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -2017,12 +2017,13 @@ Address 
CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
   StringRef Name) {
   std::string Suffix = getName({"artificial", ""});
   llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
-  llvm::Value *GAddr =
+  llvm::GlobalVariable *GAddr =
   getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
   if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPUseTLS &&
   CGM.getTarget().isTLSSupported()) {
-cast(GAddr)->setThreadLocal(/*Val=*/true);
-return Address(GAddr, CGM.getContext().getTypeAlignInChars(VarType));
+GAddr->setThreadLocal(/*Val=*/true);
+return Address(GAddr, GAddr->getValueType(),
+   CGM.getContext().getTypeAlignInChars(VarType));
   }
   std::string CacheSuffix = getName({"cache", ""});
   llvm::Value *Args[] = {
@@ -2177,7 +2178,7 @@ Address 
CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
   return ThreadIDTemp;
 }
 
-llvm::Constant *CGOpenMPRuntime::getOrCreateInternalVariable(
+llvm::GlobalVariable *CGOpenMPRuntime::getOrCreateInternalVariable(
 llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
   SmallString<256> Buffer;
   llvm::raw_svector_ostream Out(Buffer);
@@ -2185,7 +2186,7 @@ llvm::Constant 
*CGOpenMPRuntime::getOrCreateInternalVariable(
   StringRef RuntimeName = Out.str();
   auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
   if (Elem.second) {
-assert(Elem.second->getType()->getPointerElementType() == Ty &&
+assert(Elem.second->getType()->isOpaqueOrPointeeTypeMatches(Ty) &&
"OMP internal variable has 
diff erent type than requested");
 return &*Elem.second;
   }
@@ -12684,12 +12685,11 @@ void 
CGOpenMPRuntime::emitLastprivateConditionalUpdate(CodeGenFunction &CGF,
 
   // Last value of the lastprivate conditional.
   // decltype(priv_a) last_a;
-  llvm::Constant *Last = getOrCreateInternalVariable(
+  llvm::GlobalVariable *Last = getOrCreateInternalVariable(
   CGF.ConvertTypeForMem(LVal.getType()), UniqueDeclName);
-  cast(Last)->setAlignment(
-  LVal.getAlignment().getAsAlign());
-  LValue LastLVal =
-  CGF.MakeAddrLValue(Last, LVal.getType(), LVal.getAlignment());
+  Last->setAlignment(LVal.getAlignment().getAsAlign());
+  LValue LastLVal = CGF.MakeAddrLValue(
+  Address(Last, Last->getValueType(), LVal.getAlignment()), 
LVal.getType());
 
   // Global loop counter. Required to handle inner parallel-for regions.
   // iv
@@ -12862,7 +12862,8 @@ void 
CGOpenMPRuntime::emitLastprivateConditionalFinalUpdate(
   if (!GV)
 return;
   LValue LPLVal = CGF.MakeAddrLValue(
-  GV, PrivLVal.getType().getNonReferenceType(), PrivLVal.getAlignment());
+  Address(GV, GV->getValueType(), PrivLVal.getAlignment()),
+  

[PATCH] D115790: [Coroutines] Set presplit attribute in Clang

2021-12-16 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

@ezhulenev hi, we are discussing if we should set the coroutine attributes  in 
middle-end or front-end. Now in this revision, it would set the 
`coroutine.presplit` attribute in frontend, which would break the MLIR test.  I 
have tried to implement it myself today. But I found that it is really not easy 
to edit MLIR's code. I found that you introduced the Coroutines intrinsic into 
MLIR.  How do you think about set the attribute in the frontend of MLIR? And if 
you approve this, could you help to add the attributes in MLIR? We could still 
add the attribute in CoroEarly pass for a short time to make things consistent.


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

https://reviews.llvm.org/D115790

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


[PATCH] D114251: [AST] Add a sugar type for types found via UsingDecl

2021-12-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 394806.
sammccall added a comment.

Fix serialization (found with msan)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114251

Files:
  clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
  clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/PropertiesBase.td
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/TextNodeDumper.h
  clang/include/clang/AST/Type.h
  clang/include/clang/AST/TypeLoc.h
  clang/include/clang/AST/TypeProperties.td
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/include/clang/ASTMatchers/ASTMatchersInternal.h
  clang/include/clang/Basic/TypeNodes.td
  clang/include/clang/Serialization/TypeBitCodes.def
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTDiagnostic.cpp
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/QualTypeNames.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaCXXScopeSpec.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/AST/ast-dump-using.cpp
  clang/tools/libclang/CIndex.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp

Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -2581,6 +2581,7 @@
 case clang::Type::Typedef:
 case clang::Type::TypeOf:
 case clang::Type::TypeOfExpr:
+case clang::Type::Using:
   type = type->getLocallyUnqualifiedSingleStepDesugaredType();
   break;
 default:
@@ -4063,6 +4064,7 @@
   case clang::Type::Paren:
   case clang::Type::TypeOf:
   case clang::Type::TypeOfExpr:
+  case clang::Type::Using:
 llvm_unreachable("Handled in RemoveWrappingTypes!");
   case clang::Type::UnaryTransform:
 break;
@@ -4722,6 +4724,7 @@
   case clang::Type::Typedef:
   case clang::Type::TypeOf:
   case clang::Type::TypeOfExpr:
+  case clang::Type::Using:
 llvm_unreachable("Handled in RemoveWrappingTypes!");
 
   case clang::Type::UnaryTransform:
@@ -5104,6 +5107,7 @@
   case clang::Type::Typedef:
   case clang::Type::TypeOf:
   case clang::Type::TypeOfExpr:
+  case clang::Type::Using:
 llvm_unreachable("Handled in RemoveWrappingTypes!");
   case clang::Type::UnaryTransform:
 break;
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1666,6 +1666,8 @@
   return Visit(TL.getPointeeLoc());
 }
 
+bool CursorVisitor::VisitUsingTypeLoc(UsingTypeLoc TL) { return false; }
+
 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
   return Visit(TL.getModifiedLoc());
 }
Index: clang/test/AST/ast-dump-using.cpp
===
--- /dev/null
+++ clang/test/AST/ast-dump-using.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ast-dump %s | FileCheck -strict-whitespace %s
+
+namespace a {
+struct S;
+}
+namespace b {
+using a::S;
+// CHECK:  UsingDecl {{.*}} a::S
+// CHECK-NEXT: UsingShadowDecl {{.*}} implicit CXXRecord {{.*}} 'S'
+// CHECK-NEXT: `-RecordType {{.*}} 'a::S'
+typedef S f; // to dump the introduced type
+// CHECK:  TypedefDecl
+// CHECK-NEXT: `-UsingType {{.*}} 'a::S' sugar
+// CHECK-NEXT:   |-UsingShadow {{.*}} 'S'
+// CHECK-NEXT:   `-RecordType {{.*}} 'a::S'
+}
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -396,6 +396,10 @@
   Record.AddSourceLocation(TL.getNameLoc());
 }
 
+void TypeLocWriter::VisitUsingTypeLoc(UsingTypeLoc TL) {
+  Record.AddSourceLocation(TL.getNameLoc());
+}
+
 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
   Record.AddSourceLocation(TL.getNameLoc());
 }
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTRead

[PATCH] D115865: [clang-format] add support for branch attribute macros

2021-12-16 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

LGTM!

Tested locally.
Has Bolt landed? It seems that the CI adds bolt as the project but it isn't 
recognized...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115865

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


[PATCH] D110742: [OpenCL] Add pure attributes to vload builtins

2021-12-16 Thread Stuart Brady via Phabricator via cfe-commits
stuart added a comment.

In D110742#3194608 , @svenvh wrote:

> Apologies for the late reply...  I'd prefer to get the langref updated first, 
> for the sake of consistency and to ensure other stakeholders agree with the 
> interpretation.  You can still go ahead with the `__attribute__((pure))` 
> changes of course.

Thanks!  I have updated the review to use `__attribute__((pure))` only (i.e. it 
no longer uses `__attribute__((const))`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110742

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


[PATCH] D115738: [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-16 Thread Peter Stys via Phabricator via cfe-commits
peterstys marked an inline comment as done.
peterstys added inline comments.



Comment at: clang/unittests/Format/FormatTestCSharp.cpp:766
+
+  verifyFormat(R"(//
+public class Sample {

peterstys wrote:
> MyDeveloperDay wrote:
> > Nit: (only my preference) but I don't like the use of RawStrings in these 
> > tests (I know others have let them creep in) but I find them more 
> > unreadable because we lose the indentation.. I think I'm just so used to 
> > the other style that this just crates a little.
> > 
> > Just my personal preference (you can ignore)
> I used the RawStrings as it was very easy to copy snippet of code to a 
> separate file so I could run clang-format on it to check all was working 
> well. I also copied snippets to my local IDE to check if the file was 
> building, or at least structurally okay (which I appreciate is not a 
> requirements as clang-format does not build a complete AST of the code). 
> 
> For example, I was surprised to see some sample code in unit tests missing 
> braces after catch (Exception) statement (line 694) (which may have been 
> intended). I find it slightly more difficult to read those code snippets if 
> they are decorated with \n. 
> 
> On the other hand, you're right, raw string break the indentation which is 
> not great. Also, I'd rather follow the leading preferences (and wasn't sure 
> which ones where they before your comment). I'm happy to update this to your 
> style if that is the preference.
I tried to apply your preferred style but after running clang-format on the 
test file, many files were split which made it look much less readable, in my 
opinion. Here's an example:

  verifyFormat(
  "public class Test\n"
  "{\n"
  "private static void ComplexLambda(BuildReport protoReport)\n"
  "{\n"
  "allSelectedScenes =\n"
  ""
  "veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds.Where("
  "scene => scene.enabled)\n"
  ".Select(scene => scene.path)\n"
  ".ToArray();\n"
  "if (allSelectedScenes.Count == 0)\n"
  "{\n"
  "return;\n"
  "}\n"
  "Functions();\n"
  "AreWell();\n"
  "Aligned();\n"
  "AfterLambdaBlock();\n"
  "}\n"
  "}",
  MicrosoftStyle);


I think it makes it look cleaner and more readable if we stick to the raw 
string literals for my tests. WDYT?


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

https://reviews.llvm.org/D115738

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


[PATCH] D114718: [analyzer] Implement a new checker for Strict Aliasing Rule.

2021-12-16 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

I haven't checked the code, but only the tests and expectations for scalar 
values.
I'll dive deeper if we settled on those.

A couple of remarks:

1. I would rather use top-level function parameters of the given type instead 
of declaring an instance of that type and taking the address of that object. I 
think it would reflect more a real-world scenario when we don't see the 
allocation of the object, thus we don't know the dynamic/effective type of that 
object.
2. Using an alias or the underlying type does not matter in this context; You 
should not duplicate the tests for this reason. A single test demonstrating 
that the checker is able to look through type aliases (by using the canonical 
type) is enough.
3. Marking signed an already signed type won't introduce new coverage. unlike 
for `char` you can be sure that `short`, `int`, `long`, `long long` are 
`signed` by default.
4. Constness does not matter in this context, since type similarity effectively 
removes any CVR anyway. I would rather remove those test cases, and leave a 
single one demonstrating that we thought about them and it works the same way 
as without `const`.
5. Please, also test when you have two pointers with a different number of 
indirections: `long *` and `long **`; `gcc` expects `*p` and `*q` not aliasing.
6. Consider adding all the test cases from Detecting Strict Aliasing Violations 
in the Wild 
 paper by 
Pascal Cuoq et al.

They cover a lot of really interesting cases. BTW in the paper, they already 
set up the godbolt links demonstrating their findings: 
https://godbolt.org/g/ggZzQo

I think if we are done with these, we can move on to the more complicated cases 
involving standard layout types with/without inheritance, unions with common 
prefixes, and other interesting cases like function pointers, pointers to 
members, pointers to arrays.

---

The test expectations for `(int, Class)`, `(int, ClassInt)`, `(int, 
UnionUchar)`, `(int, UnionInt)`, `(int, std::byte)`, `(int, std::OtherByte)`, 
`(int, EnumInt)`, `(int, char)`, `(int, unsigned char)`, `(int, signed char)`, 
`(int, short)`, `(int, unsigned short)`, `(int, int)`, `(int, volatile unsigned 
int)`, `(int, long)`, `(int, unsigned long)`, `(int, long long)`, `(int, 
unsigned long long)`, `(int, float)`, `(int, double)`, `(int, long double)`, 
`(int, unsigned)`, look right.

I'll continue the review when I can spare some time for this.

I would like to see this as an `alpha.core` checker displayed as two checkers: 
`StrictAliasingModeling` and `StrictAliasingChecker`. You could implement this 
as a single checker, similarly to how the `CStringChecker` does for example. Do 
the reporting only if the `StrictAliasingChecker` is enabled, but emit the sink 
node unconditionally, restricting the exploration space.
To get this checker into the `core` package we will need a couple of checker 
options, relaxing the strict-aliasing rules for //unions// and for example the 
//signed char// as well; since it seems like both `gcc` and `clang` respects 
aliasing involving them via extensions.

Lastly, I'd like to thank you for working on this. I'm really excited about 
covering these types of issues.




Comment at: 
clang/test/Analysis/Checkers/StrictAliasingChecker/strict-aliasing.cpp:2
+// RUN: %clang_cc1 -std=c++20 -analyze -analyzer-config eagerly-assume=false 
-analyzer-checker=debug.ExprInspection,alpha.core.StrictAliasing -verify %s
+// NOTE: -relaxed-aliasing flag disables StrictAliasing checker.
+

I think `fno-strict-aliasing` should achieve this, by which the driver should 
transform that flag into the `-relaxed-aliasing` flag consumed by the backend.


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

https://reviews.llvm.org/D114718

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


[PATCH] D115738: [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-16 Thread Peter Stys via Phabricator via cfe-commits
peterstys added inline comments.



Comment at: clang/unittests/Format/FormatTestCSharp.cpp:766
+
+  verifyFormat(R"(//
+public class Sample {

peterstys wrote:
> peterstys wrote:
> > MyDeveloperDay wrote:
> > > Nit: (only my preference) but I don't like the use of RawStrings in these 
> > > tests (I know others have let them creep in) but I find them more 
> > > unreadable because we lose the indentation.. I think I'm just so used to 
> > > the other style that this just crates a little.
> > > 
> > > Just my personal preference (you can ignore)
> > I used the RawStrings as it was very easy to copy snippet of code to a 
> > separate file so I could run clang-format on it to check all was working 
> > well. I also copied snippets to my local IDE to check if the file was 
> > building, or at least structurally okay (which I appreciate is not a 
> > requirements as clang-format does not build a complete AST of the code). 
> > 
> > For example, I was surprised to see some sample code in unit tests missing 
> > braces after catch (Exception) statement (line 694) (which may have been 
> > intended). I find it slightly more difficult to read those code snippets if 
> > they are decorated with \n. 
> > 
> > On the other hand, you're right, raw string break the indentation which is 
> > not great. Also, I'd rather follow the leading preferences (and wasn't sure 
> > which ones where they before your comment). I'm happy to update this to 
> > your style if that is the preference.
> I tried to apply your preferred style but after running clang-format on the 
> test file, many files were split which made it look much less readable, in my 
> opinion. Here's an example:
> 
>   verifyFormat(
>   "public class Test\n"
>   "{\n"
>   "private static void ComplexLambda(BuildReport protoReport)\n"
>   "{\n"
>   "allSelectedScenes =\n"
>   ""
>   
> "veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds.Where("
>   "scene => scene.enabled)\n"
>   ".Select(scene => scene.path)\n"
>   ".ToArray();\n"
>   "if (allSelectedScenes.Count == 0)\n"
>   "{\n"
>   "return;\n"
>   "}\n"
>   "Functions();\n"
>   "AreWell();\n"
>   "Aligned();\n"
>   "AfterLambdaBlock();\n"
>   "}\n"
>   "}",
>   MicrosoftStyle);
> 
> 
> I think it makes it look cleaner and more readable if we stick to the raw 
> string literals for my tests. WDYT?
by "many files" I meant "many code snippets".


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

https://reviews.llvm.org/D115738

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


[PATCH] D106120: [PowerPC] Implement vector bool/pixel initialization under -faltivec-src-compat=xl

2021-12-16 Thread Nemanja Ivanovic via Phabricator via cfe-commits
nemanjai added a comment.

In D106120#3196010 , @q66 wrote:

> On x86_64, the program predictably prints `Dv4_i`.

The semantics here are not new, but the warning is emitted for generic vector 
types as a result of https://reviews.llvm.org/D103615. This is perhaps an 
oversight that should change (i.e. only emit the warning from 
`CheckVectorCompareOperands()` if the operands are `vector bool/vector pixel`).
@stefanp What do you think?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106120

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


[PATCH] D115804: [CodeGen] use saturating FP casts when compiling with "no-strict-float-cast-overflow"

2021-12-16 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

In D115804#3195158 , @spatel wrote:

> In D115804#3195002 , @nikic wrote:
>
>> Looks reasonable. Making float to int cast well defined is exactly why these 
>> intrinsics exist. Should we also drop the "string-float-cast-overflow" 
>> attribute, as UB is now prevented in a different way?
>
> Yes, that sounds like a good enhancement. The only in-tree use of the 
> attribute is in DAGCombiner. Make that a follow-up patch or two since it 
> crosses into LLVM?

Followup sounds good.


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

https://reviews.llvm.org/D115804

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


[PATCH] D115738: [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-16 Thread Owen Pan via Phabricator via cfe-commits
owenpan accepted this revision.
owenpan added a comment.

Thanks! LGTM other than the extraneous braces on lines 1859-1861. (See 
https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements.)




Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1859
+  nextToken();
+  if (FormatTok->isNot(tok::l_brace)) {
+return false;

Remove braces.


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

https://reviews.llvm.org/D115738

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


[PATCH] D106120: [PowerPC] Implement vector bool/pixel initialization under -faltivec-src-compat=xl

2021-12-16 Thread Daniel Kolesa via Phabricator via cfe-commits
q66 added a comment.

Well, I'm more concerned about the actual semantics - as I see it, when using 
generic vectors, they should be unaffected by the comparison behavior of 
AltiVec vectors, which is not the case when you set the mode to `xl`. If the 
semantics are affected, it means creating a massive pain for libraries that use 
generic vectors without caring what platform they are in (since they will get a 
vector as a result of comparison on x86_64, but a bool on PowerPC). And since 
the behavior can be switched with a compiler flag, they don't even have a 
reasonable way to make this conditional in the code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106120

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


[PATCH] D115738: [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-16 Thread Peter Stys via Phabricator via cfe-commits
peterstys updated this revision to Diff 394814.

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

https://reviews.llvm.org/D115738

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTestCSharp.cpp

Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -759,6 +759,128 @@
GoogleStyle);
 }
 
+TEST_F(FormatTestCSharp, CSharpLambdasDontBreakFollowingCodeAlignment) {
+  FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
+  FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(//
+public class Sample
+{
+public void Test()
+{
+while (true)
+{
+preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+CodeThatFollowsLambda();
+IsWellAligned();
+}
+}
+})",
+   MicrosoftStyle);
+
+  verifyFormat(R"(//
+public class Sample {
+  public void Test() {
+while (true) {
+  preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+  CodeThatFollowsLambda();
+  IsWellAligned();
+}
+  }
+})",
+   GoogleStyle);
+}
+
+TEST_F(FormatTestCSharp, CSharpLambdasComplexLambdasDontBreakAlignment) {
+  FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
+  FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(//
+public class Test
+{
+private static void ComplexLambda(BuildReport protoReport)
+{
+allSelectedScenes =
+veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds.Where(scene => scene.enabled)
+.Select(scene => scene.path)
+.ToArray();
+if (allSelectedScenes.Count == 0)
+{
+return;
+}
+Functions();
+AreWell();
+Aligned();
+AfterLambdaBlock();
+}
+})",
+   MicrosoftStyle);
+
+  verifyFormat(R"(//
+public class Test {
+  private static void ComplexLambda(BuildReport protoReport) {
+allSelectedScenes = veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds
+.Where(scene => scene.enabled)
+.Select(scene => scene.path)
+.ToArray();
+if (allSelectedScenes.Count == 0) {
+  return;
+}
+Functions();
+AreWell();
+Aligned();
+AfterLambdaBlock();
+  }
+})",
+   GoogleStyle);
+}
+
+TEST_F(FormatTestCSharp, CSharpLambdasMulipleLambdasDontBreakAlignment) {
+  FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
+  FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(//
+public class Test
+{
+private static void MultipleLambdas(BuildReport protoReport)
+{
+allSelectedScenes =
+veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds.Where(scene => scene.enabled)
+.Select(scene => scene.path)
+.ToArray();
+preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+if (allSelectedScenes.Count == 0)
+{
+return;
+}
+Functions();
+AreWell();
+Aligned();
+AfterLambdaBlock();
+}
+})",
+   MicrosoftStyle);
+
+  verifyFormat(R"(//
+public class Test {
+  private static void MultipleLambdas(BuildReport protoReport) {
+allSelectedScenes = veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds
+.Where(scene => scene.enabled)
+.Select(scene => scene.path)
+.ToArray();
+preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+if (allSelectedScenes.Count == 0) {
+  return;
+}
+Functions();
+AreWell();
+Aligned();
+AfterLambdaBlock();
+  }
+})",
+   GoogleStyle);
+}
+
 TEST_F(FormatTestCSharp, CSharpObjectInitializers) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 
Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -138,6 +138,7 @@
   // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
   void parseCSharpGenericTypeConstraint();
   bool tryToParseLambda();
+  bool tryToParseCSharpLambda();
   bool tryToParseLambdaIntroducer();
   bool tryToParsePropertyAccessor();
   void tryToParseJSFunction();
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Forma

[PATCH] D110742: [OpenCL] Add pure attributes to vload builtins

2021-12-16 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh accepted this revision.
svenvh added a comment.
This revision is now accepted and ready to land.

In D110742#3197183 , @stuart wrote:

> Thanks!  I have updated the review to use `__attribute__((pure))` only (i.e. 
> it no longer uses `__attribute__((const))`.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110742

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


[PATCH] D115640: [OpenCL] Add support of __opencl_c_device_enqueue feature macro.

2021-12-16 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

> This feature requires support of opencl_c_generic_address_space and

opencl_c_program_scope_global_variables so diagnostics for that is provided as 
well.

Do we have a spec issue for it or a PR? It would be good to list it here since 
it is not yet published in the registry.




Comment at: clang/lib/Sema/Sema.cpp:329
+if (OCLCompatibleVersion >= 200) {
+  if ((OCLCompatibleVersion == 200) ||
+  (OCLCompatibleVersion == 300 && getLangOpts().Blocks)) {

Here it should be sufficient to just check `getLangOpts().Blocks` only wothout 
the versions.



Comment at: clang/test/Misc/opencl-c-3.0.incorrect_options.cl:21
+
 // CHECK-FP64: error: options cl_khr_fp64 and __opencl_c_fp64 are set to 
different values
 

I can't remember if we have discussed this already, but could we use `-verify` 
for these errors?



Comment at: clang/test/SemaOpenCL/invalid-device-enqueue-types-cl3.0.cl:5
+void f() {
+  clk_event_t e;
+  queue_t q;

I know that many test have prefix "invalid" but I feel we have failed to 
establish the meaning for it because most of the tests in Sema are testing some 
sort of invalid behavior. But also here I feel that we should test that 
`enqueue_kernel` is not supported?

Do you think we chould merge this testing together with 
`SemaOpenCL/cl20-device-side-enqueue.cl` with some filename renaming?

Technically we should do the same testing even for CL1.x versions...



Comment at: clang/test/SemaOpenCL/storageclass.cl:2
 // RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL1.2
-// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL3.0 
-cl-ext=-__opencl_c_program_scope_global_variables,-__opencl_c_generic_address_space,-__opencl_c_pipes
-// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL3.0 
-cl-ext=+__opencl_c_program_scope_global_variables,-__opencl_c_generic_address_space,-__opencl_c_pipes
-// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL3.0 
-cl-ext=-__opencl_c_program_scope_global_variables,+__opencl_c_generic_address_space
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL3.0 
-cl-ext=-__opencl_c_program_scope_global_variables,-__opencl_c_generic_address_space,-__opencl_c_pipes,-__opencl_c_device_enqueue
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL3.0 
-cl-ext=+__opencl_c_program_scope_global_variables,-__opencl_c_generic_address_space,-__opencl_c_pipes,-__opencl_c_device_enqueue

These lines are getting a bit longer. Do we actually need to set 
`-__opencl_c_device_enqueue` for this test? Same for some other tests...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115640

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


[PATCH] D112410: [SPIR-V] Add a toolchain for SPIR-V in clang

2021-12-16 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh accepted this revision.
svenvh added a comment.
This revision is now accepted and ready to land.

Mostly some minor comments that you can address at commit time.

It would be good to get approval from another reviewer.




Comment at: clang/docs/UsersManual.rst:3538
+`_
+for more details. Clang will expects the ``llvm-spirv`` executable to
+be present in the ``PATH`` environment variable. Clang uses ``llvm-spirv``





Comment at: clang/test/Driver/spirv-toolchain.cl:10
+// SPV64-SAME: "-o" [[BC:".*bc"]]
+// SPV64: {{".*llvm-spirv.*"}} [[BC]] "-o" {{".*o"}}
+

svenvh wrote:
> Anastasia wrote:
> > svenvh wrote:
> > > Any reason to not just check for `llvm-spirv{{.*}}`, for consistency with 
> > > the clang check above?
> > Good question, apparently some tools get some target prefixes like if you 
> > look at `Driver::generatePrefixedToolNames`:
> > https://clang.llvm.org/doxygen/Driver_8cpp_source.html#l05169
> > 
> > But perhaps it doesn't happen for `llvm-spirv` and we can safely omit the 
> > prefix?
> Having a target prefix for llvm-spirv seems a bit redundant indeed.  
> `Driver::generatePrefixedToolNames` seems to add both a prefixed and 
> non-prefixed tool name.
I see you have taken out the checking of the prefix; my suggestion was to write 
`llvm-spirv{{.*}}`, to align with the clang check above.


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

https://reviews.llvm.org/D112410

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


[clang] a1879e5 - Fix crash on invalid code involving late parsed inline methods

2021-12-16 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-12-16T07:58:51-05:00
New Revision: a1879e52e3ae9424b59747d9b837a7a87bcb996d

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

LOG: Fix crash on invalid code involving late parsed inline methods

When parsing the following construct, we parse it as an erroneous
deduction guide declaration and correctly diagnose the issues with it.

template struct B;
struct A { B() noexcept(false); };

However, we then go on to finish late parsing the declaration and this
expects that what we've parsed is a CXXMethodDecl. A
CXXDeductionGuideDecl is not a CXXMethodDecl (it's a FunctionDecl), and
so we assert on the cast.

This fixes the crash by switching from cast<> to dyn_cast<> and not
setting up a "this" scope when the declaration is not a CXXMethodDecl.

This fixes PR49735.

Added: 


Modified: 
clang/lib/Parse/ParseCXXInlineMethods.cpp
clang/test/Parser/cxx1z-class-template-argument-deduction.cpp

Removed: 




diff  --git a/clang/lib/Parse/ParseCXXInlineMethods.cpp 
b/clang/lib/Parse/ParseCXXInlineMethods.cpp
index 116724a0d50ba..19cddc69ebfc7 100644
--- a/clang/lib/Parse/ParseCXXInlineMethods.cpp
+++ b/clang/lib/Parse/ParseCXXInlineMethods.cpp
@@ -452,13 +452,14 @@ void 
Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
 CXXMethodDecl *Method;
 if (FunctionTemplateDecl *FunTmpl
   = dyn_cast(LM.Method))
-  Method = cast(FunTmpl->getTemplatedDecl());
+  Method = dyn_cast(FunTmpl->getTemplatedDecl());
 else
-  Method = cast(LM.Method);
+  Method = dyn_cast(LM.Method);
 
-Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
- Method->getMethodQualifiers(),
- getLangOpts().CPlusPlus11);
+Sema::CXXThisScopeRAII ThisScope(
+Actions, Method ? Method->getParent() : nullptr,
+Method ? Method->getMethodQualifiers() : Qualifiers{},
+Method && getLangOpts().CPlusPlus11);
 
 // Parse the exception-specification.
 SourceRange SpecificationRange;

diff  --git a/clang/test/Parser/cxx1z-class-template-argument-deduction.cpp 
b/clang/test/Parser/cxx1z-class-template-argument-deduction.cpp
index 532c893f2132f..2f0e948022fbf 100644
--- a/clang/test/Parser/cxx1z-class-template-argument-deduction.cpp
+++ b/clang/test/Parser/cxx1z-class-template-argument-deduction.cpp
@@ -230,3 +230,21 @@ namespace within_template_arg_list {
 
   template struct Z { Y y; };
 }
+
+namespace PR49735 {
+// Ensure that we do not crash when parsing code which looks like an invalid
+// deduction guide declaration.
+template struct B; // expected-note 2{{template is declared here}}
+struct A1 {
+  B() noexcept(false); // expected-error {{deduction guide must be declared in 
the same scope as template 'PR49735::B'}} \
+   // expected-error {{deduction guide declaration without 
trailing return type}}
+};
+
+struct A2 {
+  template  // expected-note {{non-deducible template parameter 
'Ty'}}
+  B() noexcept(false); // expected-error {{deduction guide must be declared in 
the same scope as template 'PR49735::B'}} \
+   // expected-error {{deduction guide template contains a 
template parameter that cannot be deduced}} \
+   // expected-error {{deduction guide declaration without 
trailing return type}}
+};
+
+}



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


[PATCH] D112616: Fix crash on invalid code involving late parsed inline methods

2021-12-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

Thanks, I've commit in a1879e52e3ae9424b59747d9b837a7a87bcb996d 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112616

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


[PATCH] D113943: Add `withIntrospection` matcher.

2021-12-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D113943#3184076 , @avogelsgesang 
wrote:

> Nit:
> Personally, I would prefer the name `withDebugOutput` over 
> `withIntrospection`, as it more clearly describes the intent of this matcher.
> At least to me, "introspection" is usually something done programatically, 
> i.e. the matcher somehow reflects about its own state, but in this case all 
> we are doing is printing some debug output to stderr.

FWIW, I tend to agree that "introspection" is a bit of an odd choice for naming 
here. `withDebugOutput` would be an improvement, but `withPrefixAndSuffix` or 
something along those lines would also work.




Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:3000-3001
+  const internal::Matcher &InnerMatcher) {
+  return internal::Matcher(new internal::WithIntrospectionMatcher(
+  BeforeTag, AfterTag, InnerMatcher));
+}

avogelsgesang wrote:
> std::move(BeforeTag), std::move(AfterTag)
> 
> No need to create additional copies of those strings. Here and other places
Alternatively, it'd be great if we can switch these to use `StringRef` to avoid 
copies.



Comment at: clang/include/clang/ASTMatchers/ASTMatchersInternal.h:1064-1066
+  explicit WithIntrospectionMatcher(std::string _BeforeTag,
+std::string _AfterTag,
+internal::Matcher _InnerMatcher)

All of those identifiers introduce UB because they're reserved, dropping the 
underscore solves the issue (and, oddly, matches our terrible coding style 
where we let ctor parameters shadow the names of member variables).



Comment at: clang/include/clang/ASTMatchers/ASTMatchersInternal.h:1784
+  internal::PolymorphicMatcher
+  _InnerMatcher)
+  : InnerMatcher(_InnerMatcher) {}




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113943

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


[clang-tools-extra] 9198d04 - Allow disabling integer to floating-point narrowing conversions for cppcoreguidelines-narrowing-conversions

2021-12-16 Thread Aaron Ballman via cfe-commits

Author: Paul Altin
Date: 2021-12-16T08:24:09-05:00
New Revision: 9198d04c06b561cd78d9407cedd50f7b995ee6d8

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

LOG: Allow disabling integer to floating-point narrowing conversions for 
cppcoreguidelines-narrowing-conversions

This change adds an option to disable warnings from the
cppcoreguidelines-narrowing-conversions check on integer to floating-
point conversions which may be narrowing.

An example of a case where this might be useful:
```
std::vector v = {1, 2, 3, 4};
double mean = std::accumulate(v.cbegin(), v.cend(), 0.0) / v.size();
```
The conversion from std::size_t to double is technically narrowing on
64-bit systems, but v almost certainly does not have enough elements
for this to be a problem.

This option would allow the cppcoreguidelines-narrowing-conversions
check to be enabled on codebases which might otherwise turn it off
because of cases like the above.

Added: 

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-narrowing-conversions-narrowingintegertofloatingpoint-option.cpp

Modified: 
clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.rst

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
index 4d67c33361c17..99965c9e5bb98 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
@@ -37,6 +37,8 @@ 
NarrowingConversionsCheck::NarrowingConversionsCheck(StringRef Name,
 : ClangTidyCheck(Name, Context),
   WarnOnIntegerNarrowingConversion(
   Options.get("WarnOnIntegerNarrowingConversion", true)),
+  WarnOnIntegerToFloatingPointNarrowingConversion(
+  Options.get("WarnOnIntegerToFloatingPointNarrowingConversion", 
true)),
   WarnOnFloatingPointNarrowingConversion(
   Options.get("WarnOnFloatingPointNarrowingConversion", true)),
   WarnWithinTemplateInstantiation(
@@ -49,6 +51,8 @@ void NarrowingConversionsCheck::storeOptions(
 ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "WarnOnIntegerNarrowingConversion",
 WarnOnIntegerNarrowingConversion);
+  Options.store(Opts, "WarnOnIntegerToFloatingPointNarrowingConversion",
+WarnOnIntegerToFloatingPointNarrowingConversion);
   Options.store(Opts, "WarnOnFloatingPointNarrowingConversion",
 WarnOnFloatingPointNarrowingConversion);
   Options.store(Opts, "WarnWithinTemplateInstantiation",
@@ -425,19 +429,21 @@ void NarrowingConversionsCheck::handleIntegralToBoolean(
 void NarrowingConversionsCheck::handleIntegralToFloating(
 const ASTContext &Context, SourceLocation SourceLoc, const Expr &Lhs,
 const Expr &Rhs) {
-  const BuiltinType *ToType = getBuiltinType(Lhs);
-  llvm::APSInt IntegerConstant;
-  if (getIntegerConstantExprValue(Context, Rhs, IntegerConstant)) {
-if (!isWideEnoughToHold(Context, IntegerConstant, *ToType))
-  diagNarrowIntegerConstant(SourceLoc, Lhs, Rhs, IntegerConstant);
-return;
-  }
+  if (WarnOnIntegerToFloatingPointNarrowingConversion) {
+const BuiltinType *ToType = getBuiltinType(Lhs);
+llvm::APSInt IntegerConstant;
+if (getIntegerConstantExprValue(Context, Rhs, IntegerConstant)) {
+  if (!isWideEnoughToHold(Context, IntegerConstant, *ToType))
+diagNarrowIntegerConstant(SourceLoc, Lhs, Rhs, IntegerConstant);
+  return;
+}
 
-  const BuiltinType *FromType = getBuiltinType(Rhs);
-  if (isWarningInhibitedByEquivalentSize(Context, *FromType, *ToType))
-return;
-  if (!isWideEnoughToHold(Context, *FromType, *ToType))
-diagNarrowType(SourceLoc, Lhs, Rhs);
+const BuiltinType *FromType = getBuiltinType(Rhs);
+if (isWarningInhibitedByEquivalentSize(Context, *FromType, *ToType))
+  return;
+if (!isWideEnoughToHold(Context, *FromType, *ToType))
+  diagNarrowType(SourceLoc, Lhs, Rhs);
+  }
 }
 
 void NarrowingConversionsCheck::handleFloatingToIntegral(

diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
index c6d087f867bda..36ced698e869f 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
@@ -98,6 +98,7 @@ class NarrowingConversionsCheck : public ClangTidyChec

[PATCH] D112410: [SPIR-V] Add a toolchain for SPIR-V in clang

2021-12-16 Thread Henry Linjamäki via Phabricator via cfe-commits
linjamaki added a comment.

If I understand correctly, the default optimization level is `-O2` for the 
OpenCL and OpenCL++ language mode (according to 
CompilerInvocation.cpp:getOptimizationLevel()). Since higher than `-O0` may not 
work with the translator, should the SPIR-V tool chain override this default 
and set it to -O0 (unless a user passes some -O option)?


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

https://reviews.llvm.org/D112410

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


[PATCH] D112881: [clang-tidy] Allow disabling integer to floating-point narrowing conversions for cppcoreguidelines-narrowing-conversions

2021-12-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

In D112881#3181082 , @paulaltin wrote:

>> Thanks! Do you need someone to commit on your behalf? If so, what name and 
>> email address would you like used for patch attribution?
>
> That would be great, thanks! You can use "Paul Altin 
> " for the attribution.

Thanks! I landed this as 9198d04c06b561cd78d9407cedd50f7b995ee6d8 
 this 
morning (sorry for the slight delay in getting this landed).


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

https://reviews.llvm.org/D112881

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


[PATCH] D112110: [OpenCL] queue_t and ndrange_t can't be defined in program scope.

2021-12-16 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:6853
+if (R->isReserveIDT() || R->isClkEventT() || R->isEventT() ||
+R.getUnqualifiedType().getAsString() == "ndrange_t" || R->isQueueT()) {
   Se.Diag(NewVD->getLocation(),

cycheng wrote:
> Anastasia wrote:
> > Suggest swapping those as string comparisons are more costly.
> > 
> > However, does it work if there is a typedef of `ndrange_t` to some other 
> > name? Although it feels like the same issue might apply to other types 
> > diagnosed here...
> > does it work if there is a typedef of ndrange_t to some other name?
> No, should we recursively check it?
> Or do we have better way to handle this?
We should be able to do this by using canonical type in the checks:
https://clang.llvm.org/doxygen/classclang_1_1QualType.html#a900520b154ba282febbaa7267020ca3f


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

https://reviews.llvm.org/D112110

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


[PATCH] D112410: [SPIR-V] Add a toolchain for SPIR-V in clang

2021-12-16 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D112410#3197441 , @linjamaki wrote:

> If I understand correctly, the default optimization level is `-O2` for the 
> OpenCL and OpenCL++ language mode (according to 
> CompilerInvocation.cpp:getOptimizationLevel()). Since higher than `-O0` may 
> not work with the translator, should the SPIR-V tool chain override this 
> default and set it to -O0 (unless a user passes some -O option)?

We could do that, although I also find it a bit confusing if one target behaves 
differently from the rest. I believe `-O2` is clang's default, not specific to 
a particular language...

Also I have an impression that translating optimised IR mostly works.

And another aspect to consider is that we are also integrating the SPIR-V 
backend in parallel which should be supporting the optimizations fully. So I 
would prefer not to tailor the clang architecture to the use of the translator 
too much as it is only a temporary solution...


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

https://reviews.llvm.org/D112410

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


[clang] 8561e15 - [clang][dataflow] Fix unused-variable warning.

2021-12-16 Thread Yitzhak Mandelbaum via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2021-12-16T13:37:17Z
New Revision: 8561e15c5befd84542637493a76c8f2de25d08b9

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

LOG: [clang][dataflow] Fix unused-variable warning.

Added: 


Modified: 
clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp

Removed: 




diff  --git 
a/clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
index 60b345ef9fce..c2ba3b965004 100644
--- 
a/clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
+++ 
b/clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
@@ -165,7 +165,7 @@ class ConstantPropagationAnalysis
 // Any assignment involving the expression itself resets the variable to
 // "unknown". A more advanced analysis could try to evaluate the compound
 // assignment. For example, `x += 0` need not invalidate `x`.
-if (const auto *E = Nodes.getNodeAs(kAssignment))
+if (Nodes.getNodeAs(kAssignment))
   return ConstantPropagationLattice::top();
 
 llvm_unreachable("expected at least one bound identifier");



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


[PATCH] D114317: [clang-tidy][WIP] Do not run perfect alias checks

2021-12-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a reviewer: alexfh.
aaron.ballman added a subscriber: alexfh.
aaron.ballman added a comment.

In D114317#3169067 , @carlosgalvezp 
wrote:

> Kind ping to reviewers, I mostly want to know if you agree with the general 
> direction so I can go ahead and implement the rest of the patch. It's a big 
> change (replace all check registrations with the macro) so I'd like to avoid 
> extra work if you are strongly against it.
>
> @aaron.ballman I understand you are super busy and don't want to take any 
> more time than needed from you. I'd just love to hear your thoughts about the 
> two missing points that we discussed in the RFC. Nobody else seems to have 
> raised similar concerns about it.
>
> Really appreciate your time!

Sorry about the lack of response! Taking (effectively) two weeks off put me 
pretty far behind on reviews (I'm down to "only" ~30 reviews in my queue as of 
this morning), and I head out for another vacation starting tomorrow until the 
end of the year. So please anticipate further delays from me, sorry!

> It would be desirable to still keep the diagnostic/fixit for the alias 
> checks. I don't know how to implement this in practice. It would require each 
> check to call the diag() function in a loop for all alias checks. This would 
> be very disruptive for check developers. I cannot implement this in the 
> ClangTidyCheck class because the diag() function returns an object, so I 
> can't put a loop there.

I'd like to make sure I'm on the same page as you. What you mean here is that 
you want the diagnostic to be something like: `error: forgot to frobble the 
quux [bugprone-frobble-quux, cert-quux45-cpp]` instead of error: forgot to 
frobble the quux [bugprone-frobble-quux]`? Or do you mean something else?

> Ideally, it would be nice to show "CACHED - 0 seconds" or "SKIPPED - 0 
> seconds" in the profiling output (currently, the alias check just doesn't 
> show up). Again, I don't know how to implement this feature in a 
> non-intrusive way that makes sense.

That would be handy, but I think is totally reasonable for a follow-up.

> I see, thanks for the input! I took configuration into account due to the 
> concerns raised in previous patch attempts and in the RFC. I believe both use 
> cases are valid so it makes sense to me to support both as independent opt-in 
> flags. What do you think, @aaron.ballman ?

Eh, I'm less convinced of this, but I'm also not certain I'm strongly opposed 
(mostly weakly opposed at this point). Aliases with different configuration 
options are positioned to users as being separate checks. For example, we could 
have one check that decides to convert all punctuators it can to be alternate 
tokens (`and` instead of `&&`, etc) and there could be an alias check that 
converts all alternative tokens back into punctuators but is implemented as an 
alias. The fact that it's an alias is an implementation detail that should not 
matter to the user, and being able to disable *all* checks regardless of their 
configuration strikes me as making these kinds of situations confusing to users 
and I think it closes a development door we don't really want to close. I'd 
want to have buy-in from @alexfh as code owner for that option. However, I 
think it'd be good to ensure that the design can support such an option in the 
future (at least, support as much as reasonable) so we can do it as follow-up 
work without extra effort.




Comment at: clang-tools-extra/clang-tidy/ClangTidyModule.h:25-26
 
+#define CLANG_TIDY_REGISTER_CHECK(Factory, CheckType, CheckName)   
\
+  Factory.registerCheck(CheckName, #CheckType)
+

I'm not 100% sold that this macro carries its weight. I almost think the 
registration code is easier to read without it, but not enough to suggest a 
change yet. Curious if others have feelings here.


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

https://reviews.llvm.org/D114317

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


[PATCH] D115694: [ARM] Introduce an empty "armv8.8-a" architecture.

2021-12-16 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson accepted this revision.
tmatheson 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/D115694/new/

https://reviews.llvm.org/D115694

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


[clang] 8c7f2a4 - [CodeGen] use saturating FP casts when compiling with "no-strict-float-cast-overflow"

2021-12-16 Thread Sanjay Patel via cfe-commits

Author: Sanjay Patel
Date: 2021-12-16T09:10:12-05:00
New Revision: 8c7f2a4f871928d8734ee3f03e67d09086850b60

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

LOG: [CodeGen] use saturating FP casts when compiling with 
"no-strict-float-cast-overflow"

We got an unintended consequence of the optimizer getting smarter when
compiling in a non-standard mode, and there's no good way to inhibit
those optimizations at a later stage. The test is based on an example
linked from D92270.

We allow the "no-strict-float-cast-overflow" exception to normal C
cast rules to preserve legacy code that does not expect overflowing
casts from FP to int to produce UB. See D46236 for details.

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

Added: 


Modified: 
clang/lib/CodeGen/CGExprScalar.cpp
clang/test/CodeGen/no-junk-ftrunc.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 4998d343e5f5e..d34cf7f36f678 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -1240,7 +1240,18 @@ Value *ScalarExprEmitter::EmitScalarCast(Value *Src, 
QualType SrcType,
 
   if (isa(DstElementTy)) {
 assert(SrcElementTy->isFloatingPointTy() && "Unknown real conversion");
-if (DstElementType->isSignedIntegerOrEnumerationType())
+bool IsSigned = DstElementType->isSignedIntegerOrEnumerationType();
+
+// If we can't recognize overflow as undefined behavior, assume that
+// overflow saturates. This protects against normal optimizations if we are
+// compiling with non-standard FP semantics.
+if (!CGF.CGM.getCodeGenOpts().StrictFloatCastOverflow) {
+  llvm::Intrinsic::ID IID =
+  IsSigned ? llvm::Intrinsic::fptosi_sat : llvm::Intrinsic::fptoui_sat;
+  return Builder.CreateCall(CGF.CGM.getIntrinsic(IID, {DstTy, SrcTy}), 
Src);
+}
+
+if (IsSigned)
   return Builder.CreateFPToSI(Src, DstTy, "conv");
 return Builder.CreateFPToUI(Src, DstTy, "conv");
   }

diff  --git a/clang/test/CodeGen/no-junk-ftrunc.c 
b/clang/test/CodeGen/no-junk-ftrunc.c
index 2ab4d8c25a39c..6ae6d30fca434 100644
--- a/clang/test/CodeGen/no-junk-ftrunc.c
+++ b/clang/test/CodeGen/no-junk-ftrunc.c
@@ -1,14 +1,22 @@
 // RUN: %clang_cc1 -S -fno-strict-float-cast-overflow %s -emit-llvm -o - | 
FileCheck %s --check-prefix=NOSTRICT
+
+// When compiling with non-standard semantics, use intrinsics to inhibit the 
optimizer.
+
 // NOSTRICT-LABEL: main
+// NOSTRICT: call i32 @llvm.fptosi.sat.i32.f64
+// NOSTRICT: call i32 @llvm.fptoui.sat.i32.f64
 // NOSTRICT: attributes #0 = {{.*}}"strict-float-cast-overflow"="false"{{.*}}
 
 // The workaround attribute is not applied by default.
 
 // RUN: %clang_cc1 -S %s -emit-llvm -o - | FileCheck %s --check-prefix=STRICT
 // STRICT-LABEL: main
+// STRICT: = fptosi
+// STRICT: = fptoui
 // STRICT-NOT: strict-float-cast-overflow
 
+
 int main() {
-  return 0;
+  double d = 1e20;
+  return (int)d != 1e20 && (unsigned)d != 1e20;
 }
-



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


[PATCH] D115804: [CodeGen] use saturating FP casts when compiling with "no-strict-float-cast-overflow"

2021-12-16 Thread Sanjay Patel 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 rG8c7f2a4f8719: [CodeGen] use saturating FP casts when 
compiling with "no-strict-float-cast… (authored by spatel).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D115804?vs=394571&id=394850#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115804

Files:
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/CodeGen/no-junk-ftrunc.c


Index: clang/test/CodeGen/no-junk-ftrunc.c
===
--- clang/test/CodeGen/no-junk-ftrunc.c
+++ clang/test/CodeGen/no-junk-ftrunc.c
@@ -1,14 +1,22 @@
 // RUN: %clang_cc1 -S -fno-strict-float-cast-overflow %s -emit-llvm -o - | 
FileCheck %s --check-prefix=NOSTRICT
+
+// When compiling with non-standard semantics, use intrinsics to inhibit the 
optimizer.
+
 // NOSTRICT-LABEL: main
+// NOSTRICT: call i32 @llvm.fptosi.sat.i32.f64
+// NOSTRICT: call i32 @llvm.fptoui.sat.i32.f64
 // NOSTRICT: attributes #0 = {{.*}}"strict-float-cast-overflow"="false"{{.*}}
 
 // The workaround attribute is not applied by default.
 
 // RUN: %clang_cc1 -S %s -emit-llvm -o - | FileCheck %s --check-prefix=STRICT
 // STRICT-LABEL: main
+// STRICT: = fptosi
+// STRICT: = fptoui
 // STRICT-NOT: strict-float-cast-overflow
 
+
 int main() {
-  return 0;
+  double d = 1e20;
+  return (int)d != 1e20 && (unsigned)d != 1e20;
 }
-
Index: clang/lib/CodeGen/CGExprScalar.cpp
===
--- clang/lib/CodeGen/CGExprScalar.cpp
+++ clang/lib/CodeGen/CGExprScalar.cpp
@@ -1240,7 +1240,18 @@
 
   if (isa(DstElementTy)) {
 assert(SrcElementTy->isFloatingPointTy() && "Unknown real conversion");
-if (DstElementType->isSignedIntegerOrEnumerationType())
+bool IsSigned = DstElementType->isSignedIntegerOrEnumerationType();
+
+// If we can't recognize overflow as undefined behavior, assume that
+// overflow saturates. This protects against normal optimizations if we are
+// compiling with non-standard FP semantics.
+if (!CGF.CGM.getCodeGenOpts().StrictFloatCastOverflow) {
+  llvm::Intrinsic::ID IID =
+  IsSigned ? llvm::Intrinsic::fptosi_sat : llvm::Intrinsic::fptoui_sat;
+  return Builder.CreateCall(CGF.CGM.getIntrinsic(IID, {DstTy, SrcTy}), 
Src);
+}
+
+if (IsSigned)
   return Builder.CreateFPToSI(Src, DstTy, "conv");
 return Builder.CreateFPToUI(Src, DstTy, "conv");
   }


Index: clang/test/CodeGen/no-junk-ftrunc.c
===
--- clang/test/CodeGen/no-junk-ftrunc.c
+++ clang/test/CodeGen/no-junk-ftrunc.c
@@ -1,14 +1,22 @@
 // RUN: %clang_cc1 -S -fno-strict-float-cast-overflow %s -emit-llvm -o - | FileCheck %s --check-prefix=NOSTRICT
+
+// When compiling with non-standard semantics, use intrinsics to inhibit the optimizer.
+
 // NOSTRICT-LABEL: main
+// NOSTRICT: call i32 @llvm.fptosi.sat.i32.f64
+// NOSTRICT: call i32 @llvm.fptoui.sat.i32.f64
 // NOSTRICT: attributes #0 = {{.*}}"strict-float-cast-overflow"="false"{{.*}}
 
 // The workaround attribute is not applied by default.
 
 // RUN: %clang_cc1 -S %s -emit-llvm -o - | FileCheck %s --check-prefix=STRICT
 // STRICT-LABEL: main
+// STRICT: = fptosi
+// STRICT: = fptoui
 // STRICT-NOT: strict-float-cast-overflow
 
+
 int main() {
-  return 0;
+  double d = 1e20;
+  return (int)d != 1e20 && (unsigned)d != 1e20;
 }
-
Index: clang/lib/CodeGen/CGExprScalar.cpp
===
--- clang/lib/CodeGen/CGExprScalar.cpp
+++ clang/lib/CodeGen/CGExprScalar.cpp
@@ -1240,7 +1240,18 @@
 
   if (isa(DstElementTy)) {
 assert(SrcElementTy->isFloatingPointTy() && "Unknown real conversion");
-if (DstElementType->isSignedIntegerOrEnumerationType())
+bool IsSigned = DstElementType->isSignedIntegerOrEnumerationType();
+
+// If we can't recognize overflow as undefined behavior, assume that
+// overflow saturates. This protects against normal optimizations if we are
+// compiling with non-standard FP semantics.
+if (!CGF.CGM.getCodeGenOpts().StrictFloatCastOverflow) {
+  llvm::Intrinsic::ID IID =
+  IsSigned ? llvm::Intrinsic::fptosi_sat : llvm::Intrinsic::fptoui_sat;
+  return Builder.CreateCall(CGF.CGM.getIntrinsic(IID, {DstTy, SrcTy}), Src);
+}
+
+if (IsSigned)
   return Builder.CreateFPToSI(Src, DstTy, "conv");
 return Builder.CreateFPToUI(Src, DstTy, "conv");
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 58c8c53 - [CodeGen] Avoid more pointer element type accesses

2021-12-16 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2021-12-16T15:26:21+01:00
New Revision: 58c8c5326329bb55df6b9d4f7f8f43a2c82e67c1

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

LOG: [CodeGen] Avoid more pointer element type accesses

Added: 


Modified: 
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGDecl.cpp
clang/lib/CodeGen/CGExpr.cpp
clang/lib/CodeGen/CGExprScalar.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/CodeGen/TargetInfo.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 79442d7f51c4..8ecef6ab9782 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -4964,8 +4964,7 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
   Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
   Src = TempAlloca;
 } else {
-  Src = Builder.CreateBitCast(Src,
-  
STy->getPointerTo(Src.getAddressSpace()));
+  Src = Builder.CreateElementBitCast(Src, STy);
 }
 
 assert(NumIRArgs == STy->getNumElements());

diff  --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index 97ca3a1e1db1..f6b758ba30a0 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -405,7 +405,8 @@ void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
 
   // Store into LocalDeclMap before generating initializer to handle
   // circular references.
-  setAddrOfLocalVar(&D, Address(addr, alignment));
+  setAddrOfLocalVar(
+  &D, Address(addr, ConvertTypeForMem(D.getType()), alignment));
 
   // We can't have a VLA here, but we can have a pointer to a VLA,
   // even though that doesn't really make any sense.

diff  --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index f22c09a09e3e..635ae8a70334 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1099,7 +1099,7 @@ Address CodeGenFunction::EmitPointerWithAlignment(const 
Expr *E,
   if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
 if (BaseInfo)
   BaseInfo->mergeForCast(TargetTypeBaseInfo);
-Addr = Address(Addr.getPointer(), Align);
+Addr = Address(Addr.getPointer(), Addr.getElementType(), Align);
   }
 }
 
@@ -,10 +,12 @@ Address CodeGenFunction::EmitPointerWithAlignment(const 
Expr *E,
   CodeGenFunction::CFITCK_UnrelatedCast,
   CE->getBeginLoc());
 }
-return CE->getCastKind() != CK_AddressSpaceConversion
-   ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
-   : Builder.CreateAddrSpaceCast(Addr,
- ConvertType(E->getType()));
+
+if (CE->getCastKind() == CK_AddressSpaceConversion)
+ return Builder.CreateAddrSpaceCast(Addr, ConvertType(E->getType()));
+
+llvm::Type *ElemTy = ConvertTypeForMem(E->getType()->getPointeeType());
+return Builder.CreateElementBitCast(Addr, ElemTy);
   }
   break;
 
@@ -2527,7 +2529,7 @@ static LValue EmitGlobalVarDeclLValue(CodeGenFunction 
&CGF,
   llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
   CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
-  Address Addr(V, Alignment);
+  Address Addr(V, RealVarTy, Alignment);
   // Emit reference to the private copy of the variable if it is an OpenMP
   // threadprivate variable.
   if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
@@ -2705,7 +2707,7 @@ LValue CodeGenFunction::EmitDeclRefLValue(const 
DeclRefExpr *E) {
 /* BaseInfo= */ nullptr,
 /* TBAAInfo= */ nullptr,
 /* forPointeeType= */ true);
-Addr = Address(Val, Alignment);
+Addr = Address(Val, ConvertTypeForMem(E->getType()), Alignment);
   }
   return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
 }
@@ -2782,9 +2784,10 @@ LValue CodeGenFunction::EmitDeclRefLValue(const 
DeclRefExpr *E) {
 // Otherwise, it might be static local we haven't emitted yet for
 // some reason; most likely, because it's in an outer function.
 } else if (VD->isStaticLocal()) {
-  addr = Address(CGM.getOrCreateStaticVarDecl(
-  *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false)),
- getContext().getDeclAlign(VD));
+  llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
+  *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false));
+  addr = Address(
+ 

[clang] a0cf066 - [CodeGen] Store element type in ParamValue

2021-12-16 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2021-12-16T15:31:55+01:00
New Revision: a0cf066eac8aa55782a6dd2deb90adc89a707a8b

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

LOG: [CodeGen] Store element type in ParamValue

ParamValue is basically a union between an Address and a Value*.
To be able to reconstruct the Address, we now need to store the
pointer element type.

Added: 


Modified: 
clang/lib/CodeGen/CodeGenFunction.h

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index 411a36a26332..679c720f7bd7 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -3130,15 +3130,18 @@ class CodeGenFunction : public CodeGenTypeCache {
 
   class ParamValue {
 llvm::Value *Value;
+llvm::Type *ElementType;
 unsigned Alignment;
-ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
+ParamValue(llvm::Value *V, llvm::Type *T, unsigned A)
+: Value(V), ElementType(T), Alignment(A) {}
   public:
 static ParamValue forDirect(llvm::Value *value) {
-  return ParamValue(value, 0);
+  return ParamValue(value, nullptr, 0);
 }
 static ParamValue forIndirect(Address addr) {
   assert(!addr.getAlignment().isZero());
-  return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
+  return ParamValue(addr.getPointer(), addr.getElementType(),
+addr.getAlignment().getQuantity());
 }
 
 bool isIndirect() const { return Alignment != 0; }
@@ -3151,7 +3154,7 @@ class CodeGenFunction : public CodeGenTypeCache {
 
 Address getIndirectAddress() const {
   assert(isIndirect());
-  return Address(Value, CharUnits::fromQuantity(Alignment));
+  return Address(Value, ElementType, CharUnits::fromQuantity(Alignment));
 }
   };
 



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


[clang] 1a376bc - [OpenCL] Add pure attribute to vload builtins

2021-12-16 Thread Stuart Brady via cfe-commits

Author: Stuart Brady
Date: 2021-12-16T14:55:31Z
New Revision: 1a376bc285358037a5edc48b0d125f91bf5a69ca

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

LOG: [OpenCL] Add pure attribute to vload builtins

Use the "pure" attribute (or "readonly") for the vload, vload_half and
vloada_half builtins.

Reviewed By: svenvh

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

Added: 


Modified: 
clang/lib/Headers/opencl-c.h
clang/lib/Sema/OpenCLBuiltins.td

Removed: 




diff  --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h
index 32af848a94c4f..77a7a8b9bb3a1 100644
--- a/clang/lib/Headers/opencl-c.h
+++ b/clang/lib/Headers/opencl-c.h
@@ -11190,305 +11190,305 @@ half16 __ovld __cnfn select(half16 a, half16 b, 
ushort16 c);
  * 64-bit aligned if gentype is long, ulong, double.
  */
 
-char2 __ovld vload2(size_t offset, const __constant char *p);
-uchar2 __ovld vload2(size_t offset, const __constant uchar *p);
-short2 __ovld vload2(size_t offset, const __constant short *p);
-ushort2 __ovld vload2(size_t offset, const __constant ushort *p);
-int2 __ovld vload2(size_t offset, const __constant int *p);
-uint2 __ovld vload2(size_t offset, const __constant uint *p);
-long2 __ovld vload2(size_t offset, const __constant long *p);
-ulong2 __ovld vload2(size_t offset, const __constant ulong *p);
-float2 __ovld vload2(size_t offset, const __constant float *p);
-char3 __ovld vload3(size_t offset, const __constant char *p);
-uchar3 __ovld vload3(size_t offset, const __constant uchar *p);
-short3 __ovld vload3(size_t offset, const __constant short *p);
-ushort3 __ovld vload3(size_t offset, const __constant ushort *p);
-int3 __ovld vload3(size_t offset, const __constant int *p);
-uint3 __ovld vload3(size_t offset, const __constant uint *p);
-long3 __ovld vload3(size_t offset, const __constant long *p);
-ulong3 __ovld vload3(size_t offset, const __constant ulong *p);
-float3 __ovld vload3(size_t offset, const __constant float *p);
-char4 __ovld vload4(size_t offset, const __constant char *p);
-uchar4 __ovld vload4(size_t offset, const __constant uchar *p);
-short4 __ovld vload4(size_t offset, const __constant short *p);
-ushort4 __ovld vload4(size_t offset, const __constant ushort *p);
-int4 __ovld vload4(size_t offset, const __constant int *p);
-uint4 __ovld vload4(size_t offset, const __constant uint *p);
-long4 __ovld vload4(size_t offset, const __constant long *p);
-ulong4 __ovld vload4(size_t offset, const __constant ulong *p);
-float4 __ovld vload4(size_t offset, const __constant float *p);
-char8 __ovld vload8(size_t offset, const __constant char *p);
-uchar8 __ovld vload8(size_t offset, const __constant uchar *p);
-short8 __ovld vload8(size_t offset, const __constant short *p);
-ushort8 __ovld vload8(size_t offset, const __constant ushort *p);
-int8 __ovld vload8(size_t offset, const __constant int *p);
-uint8 __ovld vload8(size_t offset, const __constant uint *p);
-long8 __ovld vload8(size_t offset, const __constant long *p);
-ulong8 __ovld vload8(size_t offset, const __constant ulong *p);
-float8 __ovld vload8(size_t offset, const __constant float *p);
-char16 __ovld vload16(size_t offset, const __constant char *p);
-uchar16 __ovld vload16(size_t offset, const __constant uchar *p);
-short16 __ovld vload16(size_t offset, const __constant short *p);
-ushort16 __ovld vload16(size_t offset, const __constant ushort *p);
-int16 __ovld vload16(size_t offset, const __constant int *p);
-uint16 __ovld vload16(size_t offset, const __constant uint *p);
-long16 __ovld vload16(size_t offset, const __constant long *p);
-ulong16 __ovld vload16(size_t offset, const __constant ulong *p);
-float16 __ovld vload16(size_t offset, const __constant float *p);
+char2 __ovld __purefn vload2(size_t offset, const __constant char *p);
+uchar2 __ovld __purefn vload2(size_t offset, const __constant uchar *p);
+short2 __ovld __purefn vload2(size_t offset, const __constant short *p);
+ushort2 __ovld __purefn vload2(size_t offset, const __constant ushort *p);
+int2 __ovld __purefn vload2(size_t offset, const __constant int *p);
+uint2 __ovld __purefn vload2(size_t offset, const __constant uint *p);
+long2 __ovld __purefn vload2(size_t offset, const __constant long *p);
+ulong2 __ovld __purefn vload2(size_t offset, const __constant ulong *p);
+float2 __ovld __purefn vload2(size_t offset, const __constant float *p);
+char3 __ovld __purefn vload3(size_t offset, const __constant char *p);
+uchar3 __ovld __purefn vload3(size_t offset, const __constant uchar *p);
+short3 __ovld __purefn vload3(size_t offset, const __constant short *p);
+ushort3 __ovld __purefn vload3(size_t offset, const __constant ushort *p);
+int3 __ovld __purefn vload3(size_t offset, const __constant int *p);
+uint3 __ovld __purefn 

[PATCH] D110742: [OpenCL] Add pure attributes to vload builtins

2021-12-16 Thread Stuart Brady 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 rG1a376bc28535: [OpenCL] Add pure attribute to vload builtins 
(authored by stuart).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110742

Files:
  clang/lib/Headers/opencl-c.h
  clang/lib/Sema/OpenCLBuiltins.td

Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -806,17 +806,17 @@
   foreach AS = addrspaces in {
 foreach VSize = [2, 3, 4, 8, 16] in {
   foreach name = ["vload" # VSize] in {
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
   }
   if defStores then {
 foreach name = ["vstore" # VSize] in {
@@ -848,10 +848,10 @@
 
 multiclass VloadVstoreHalf addrspaces, bit defStores> {
   foreach AS = addrspaces in {
-def : Builtin<"vload_half", [Float, Size, PointerType, AS>]>;
+def : Builtin<"vload_half", [Float, Size, PointerType, AS>], Attr.Pure>;
 foreach VSize = [2, 3, 4, 8, 16] in {
   foreach name = ["vload_half" # VSize, "vloada_half" # VSize] in {
-def : Builtin, Size, PointerType, AS>]>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
   }
 }
 if defStores then {
@@ -877,7 +877,7 @@
 let MinVersion = CL20 in {
   defm : VloadVstoreHalf<[GenericAS], 1>;
 }
-// vload with constant address space is available regardless of version.
+// vload_half and vloada_half with constant address space are available regardless of version.
 defm : VloadVstoreHalf<[ConstantAS], 0>;
 
 // OpenCL v3.0 s6.15.8 - Synchronization Functions.
Index: clang/lib/Headers/opencl-c.h
===
--- clang/lib/Headers/opencl-c.h
+++ clang/lib/Headers/opencl-c.h
@@ -11190,305 +11190,305 @@
  * 64-bit aligned if gentype is long, ulong, double.
  */
 
-char2 __ovld vload2(size_t offset, const __constant char *p);
-uchar2 __ovld vload2(size_t offset, const __constant uchar *p);
-short2 __ovld vload2(size_t offset, const __constant short *p);
-ushort2 __ovld vload2(size_t offset, const __constant ushort *p);
-int2 __ovld vload2(size_t offset, const __constant int *p);
-uint2 __ovld vload2(size_t offset, const __constant uint *p);
-long2 __ovld vload2(size_t offset, const __constant long *p);
-ulong2 __ovld vload2(size_t offset, const __constant ulong *p);
-float2 __ovld vload2(size_t offset, const __constant float *p);
-char3 __ovld vload3(size_t offset, const __constant char *p);
-uchar3 __ovld vload3(size_t offset, const __constant uchar *p);
-short3 __ovld vload3(size_t offset, const __constant short *p);
-ushort3 __ovld vload3(size_t offset, const __constant ushort *p);
-int3 __ovld vload3(size_t offset, const __constant int *p);
-uint3 __ovld vload3(size_t offset, const __constant uint *p);
-long3 __ovld vload3(size_t offset, const __constant long *p);
-ulong3 __ovld vload3(size_t offset, const __constant ulong *p);
-float3 __ovld vload3(size_t offset, const __constant float *p);
-char4 __ovld vload4(size_t offset, const __constant char *p);
-uchar4 __ovld vload4(size_t offset, const __constant uchar *p);
-short4 __ovld vload4(size_t offset, const __constant short *p);
-ushort4 __ovld vload4(size_t offset, const __constant ushort *p);
-int4 __ovld vload4(size_t offset, const __constant int *p);
-uint4 __ovld vload4(size_t offset, const __constant uint *p);
-long4 __ovld vload4(size_t offset, const __constant long *p);
-ulong4 __ovld vload4(size_t offset, const __constant ulong *p);
-float4 __ovld vload4(size_t offset, const __constant float *p);
-char8 __ovld vload8(size_t offset, const __co

[PATCH] D110742: [OpenCL] Add pure attributes to vload builtins

2021-12-16 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

looks like this broke tests: http://45.33.8.238/linux/63308/step_7.txt

Please take a look, and revert for now if it takes a while to fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110742

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


[clang] 5aefb1d - Revert "[OpenCL] Add pure attribute to vload builtins"

2021-12-16 Thread Stuart Brady via cfe-commits

Author: Stuart Brady
Date: 2021-12-16T15:16:41Z
New Revision: 5aefb1dc1eabd9286da9511b5227aa83443091b9

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

LOG: Revert "[OpenCL] Add pure attribute to vload builtins"

This reverts commit 1a376bc285358037a5edc48b0d125f91bf5a69ca.

This broke clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl

Added: 


Modified: 
clang/lib/Headers/opencl-c.h
clang/lib/Sema/OpenCLBuiltins.td

Removed: 




diff  --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h
index 77a7a8b9bb3a1..32af848a94c4f 100644
--- a/clang/lib/Headers/opencl-c.h
+++ b/clang/lib/Headers/opencl-c.h
@@ -11190,305 +11190,305 @@ half16 __ovld __cnfn select(half16 a, half16 b, 
ushort16 c);
  * 64-bit aligned if gentype is long, ulong, double.
  */
 
-char2 __ovld __purefn vload2(size_t offset, const __constant char *p);
-uchar2 __ovld __purefn vload2(size_t offset, const __constant uchar *p);
-short2 __ovld __purefn vload2(size_t offset, const __constant short *p);
-ushort2 __ovld __purefn vload2(size_t offset, const __constant ushort *p);
-int2 __ovld __purefn vload2(size_t offset, const __constant int *p);
-uint2 __ovld __purefn vload2(size_t offset, const __constant uint *p);
-long2 __ovld __purefn vload2(size_t offset, const __constant long *p);
-ulong2 __ovld __purefn vload2(size_t offset, const __constant ulong *p);
-float2 __ovld __purefn vload2(size_t offset, const __constant float *p);
-char3 __ovld __purefn vload3(size_t offset, const __constant char *p);
-uchar3 __ovld __purefn vload3(size_t offset, const __constant uchar *p);
-short3 __ovld __purefn vload3(size_t offset, const __constant short *p);
-ushort3 __ovld __purefn vload3(size_t offset, const __constant ushort *p);
-int3 __ovld __purefn vload3(size_t offset, const __constant int *p);
-uint3 __ovld __purefn vload3(size_t offset, const __constant uint *p);
-long3 __ovld __purefn vload3(size_t offset, const __constant long *p);
-ulong3 __ovld __purefn vload3(size_t offset, const __constant ulong *p);
-float3 __ovld __purefn vload3(size_t offset, const __constant float *p);
-char4 __ovld __purefn vload4(size_t offset, const __constant char *p);
-uchar4 __ovld __purefn vload4(size_t offset, const __constant uchar *p);
-short4 __ovld __purefn vload4(size_t offset, const __constant short *p);
-ushort4 __ovld __purefn vload4(size_t offset, const __constant ushort *p);
-int4 __ovld __purefn vload4(size_t offset, const __constant int *p);
-uint4 __ovld __purefn vload4(size_t offset, const __constant uint *p);
-long4 __ovld __purefn vload4(size_t offset, const __constant long *p);
-ulong4 __ovld __purefn vload4(size_t offset, const __constant ulong *p);
-float4 __ovld __purefn vload4(size_t offset, const __constant float *p);
-char8 __ovld __purefn vload8(size_t offset, const __constant char *p);
-uchar8 __ovld __purefn vload8(size_t offset, const __constant uchar *p);
-short8 __ovld __purefn vload8(size_t offset, const __constant short *p);
-ushort8 __ovld __purefn vload8(size_t offset, const __constant ushort *p);
-int8 __ovld __purefn vload8(size_t offset, const __constant int *p);
-uint8 __ovld __purefn vload8(size_t offset, const __constant uint *p);
-long8 __ovld __purefn vload8(size_t offset, const __constant long *p);
-ulong8 __ovld __purefn vload8(size_t offset, const __constant ulong *p);
-float8 __ovld __purefn vload8(size_t offset, const __constant float *p);
-char16 __ovld __purefn vload16(size_t offset, const __constant char *p);
-uchar16 __ovld __purefn vload16(size_t offset, const __constant uchar *p);
-short16 __ovld __purefn vload16(size_t offset, const __constant short *p);
-ushort16 __ovld __purefn vload16(size_t offset, const __constant ushort *p);
-int16 __ovld __purefn vload16(size_t offset, const __constant int *p);
-uint16 __ovld __purefn vload16(size_t offset, const __constant uint *p);
-long16 __ovld __purefn vload16(size_t offset, const __constant long *p);
-ulong16 __ovld __purefn vload16(size_t offset, const __constant ulong *p);
-float16 __ovld __purefn vload16(size_t offset, const __constant float *p);
+char2 __ovld vload2(size_t offset, const __constant char *p);
+uchar2 __ovld vload2(size_t offset, const __constant uchar *p);
+short2 __ovld vload2(size_t offset, const __constant short *p);
+ushort2 __ovld vload2(size_t offset, const __constant ushort *p);
+int2 __ovld vload2(size_t offset, const __constant int *p);
+uint2 __ovld vload2(size_t offset, const __constant uint *p);
+long2 __ovld vload2(size_t offset, const __constant long *p);
+ulong2 __ovld vload2(size_t offset, const __constant ulong *p);
+float2 __ovld vload2(size_t offset, const __constant float *p);
+char3 __ovld vload3(size_t offset, const __constant char *p);
+uchar3 __ovld vload3(size_t offset, con

[PATCH] D114251: [AST] Add a sugar type for types found via UsingDecl

2021-12-16 Thread David Rector via Phabricator via cfe-commits
davrec added a comment.

`throughUsingDecl` seems like a good solution, though I defer to regular 
ASTMatchers users.

One other thought: can we add diagnostic notes using this new information, e.g.

  struct A1 {
  protected:
using IntType = char;
  };
  
  struct A2 {
  protected:
using IntType = unsigned long;
  };
  
  struct B : A1, A2 {
using A1::IntType;
  };
  
  struct C : B {
IntType foo;
void setFoo(IntType V) {
  foo = V;
}
  };
  
  
  int main() {
D d;
d.setFoo((unsigned long)-1); // warning: implicit conversion loses info 
  }

It would be nice to add a note pointing to `using A1::IntType` saying 
"introduced here".


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114251

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


[clang] 5fbe21a - [clang] p2085 out-of-class comparison operator defaulting

2021-12-16 Thread Nathan Sidwell via cfe-commits

Author: Nathan Sidwell
Date: 2021-12-16T07:22:46-08:00
New Revision: 5fbe21a7748f91adbd1b16c95bbfe180642320a3

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

LOG: [clang] p2085 out-of-class comparison operator defaulting

This implements p2085, allowing out-of-class defaulting of comparison
operators, primarily so they need not be inline, IIUC intent. this was
mostly straigh forward, but required reimplementing
Sema::CheckExplicitlyDefaultedComparison, as now there's a case where
we have no a priori clue as to what class a defaulted comparison may
be for. We have to inspect the parameter types to find out. Eg:

class X { ... };
bool operator==(X, X) = default;

Thus reimplemented the parameter type checking, and added 'is this a
friend' functionality for the above case.

Reviewed By: mizvekov

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

Added: 
clang/test/CodeGenCXX/p2085.cpp

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
clang/www/cxx_status.html

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 038067521559c..29e7c5b447140 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9151,15 +9151,22 @@ def warn_cxx17_compat_defaulted_comparison : Warning<
   "before C++20">, InGroup, DefaultIgnore;
 def err_defaulted_comparison_template : Error<
   "comparison operator template cannot be defaulted">;
-def err_defaulted_comparison_out_of_class : Error<
-  "%sub{select_defaulted_comparison_kind}0 can only be defaulted in a class "
-  "definition">;
+def err_defaulted_comparison_num_args : Error<
+  "%select{non-member|member}0 %sub{select_defaulted_comparison_kind}1"
+  " comparison operator must have %select{2|1}0 parameters">;
 def err_defaulted_comparison_param : Error<
   "invalid parameter type for defaulted 
%sub{select_defaulted_comparison_kind}0"
   "; found %1, expected %2%select{| or %4}3">;
+def err_defaulted_comparison_param_unknown : Error<
+  "invalid parameter type for non-member defaulted"
+  " %sub{select_defaulted_comparison_kind}0"
+  "; found %1, expected class or reference to a constant class">;
 def err_defaulted_comparison_param_mismatch : Error<
   "parameters for defaulted %sub{select_defaulted_comparison_kind}0 "
   "must have the same type%
diff { (found $ vs $)|}1,2">;
+def err_defaulted_comparison_not_friend : Error<
+  "%sub{select_defaulted_comparison_kind}0 is not a friend of"
+  " %select{|incomplete class }1%2">;
 def err_defaulted_comparison_non_const : Error<
   "defaulted member %sub{select_defaulted_comparison_kind}0 must be "
   "const-qualified">;

diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 3f6bde1b9ed6a..119cdf2a3d3c0 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -8435,9 +8435,6 @@ bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, 
FunctionDecl *FD,
   DefaultedComparisonKind DCK) {
   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
 
-  CXXRecordDecl *RD = dyn_cast(FD->getLexicalDeclContext());
-  assert(RD && "defaulted comparison is not defaulted in a class");
-
   // Perform any unqualified lookups we're going to need to default this
   // function.
   if (S) {
@@ -8455,43 +8452,17 @@ bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, 
FunctionDecl *FD,
   //   const C&, or
   //-- a friend of C having two parameters of type const C& or two
   //   parameters of type C.
-  QualType ExpectedParmType1 = Context.getRecordType(RD);
-  QualType ExpectedParmType2 =
-  Context.getLValueReferenceType(ExpectedParmType1.withConst());
-  if (isa(FD))
-ExpectedParmType1 = ExpectedParmType2;
-  for (const ParmVarDecl *Param : FD->parameters()) {
-if (!Param->getType()->isDependentType() &&
-!Context.hasSameType(Param->getType(), ExpectedParmType1) &&
-!Context.hasSameType(Param->getType(), ExpectedParmType2)) {
-  // Don't diagnose an implicit 'operator=='; we will have diagnosed the
-  // corresponding defaulted 'operator<=>' already.
-  if (!FD->isImplicit()) {
-Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
-<< (int)DCK << Param->getType() << ExpectedParmType1
-<< !isa(FD)
-<< ExpectedParmType2 << Param->getSourceRange();
-  }
-  return true;
-}
-  }
-  if (FD->getNumParams() == 2 &&
-  !Context.hasSameType(FD->getParamDecl(0)->getType(),
-   FD->getParamDec

[PATCH] D104478: [clang] p2085 out-of-class comparison operator defaulting

2021-12-16 Thread Nathan Sidwell via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5fbe21a7748f: [clang] p2085 out-of-class comparison operator 
defaulting (authored by urnathan).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D104478?vs=387283&id=394873#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104478

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
  clang/test/CodeGenCXX/p2085.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1006,7 +1006,7 @@
   
   
 https://wg21.link/p2085r0";>P2085R0
-No
+Clang 14
   
 
   Access checking on specializations
Index: clang/test/CodeGenCXX/p2085.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/p2085.cpp
@@ -0,0 +1,38 @@
+// RUN: %clang_cc1 --std=c++20 %s -emit-llvm -o - -triple x86_64-linux | FileCheck %s
+
+namespace std {
+struct strong_ordering {
+  int n;
+  constexpr operator int() const { return n; }
+  static const strong_ordering equal, greater, less;
+};
+constexpr inline strong_ordering strong_ordering::equal = {0};
+constexpr inline strong_ordering strong_ordering::greater = {1};
+constexpr inline strong_ordering strong_ordering::less = {-1};
+} // namespace std
+
+struct Space {
+  int i, j;
+
+  std::strong_ordering operator<=>(Space const &other) const;
+  bool operator==(Space const &other) const;
+};
+
+// Make sure these cause emission
+std::strong_ordering Space::operator<=>(Space const &other) const = default;
+// CHECK-LABEL: define{{.*}} @_ZNK5SpacessERKS_
+bool Space::operator==(Space const &) const = default;
+// CHECK-LABEL: define{{.*}} @_ZNK5SpaceeqERKS_
+
+struct Water {
+  int i, j;
+
+  std::strong_ordering operator<=>(Water const &other) const;
+  bool operator==(Water const &other) const;
+};
+
+// Make sure these do not cause emission
+inline std::strong_ordering Water::operator<=>(Water const &other) const = default;
+// CHECK-NOT: define{{.*}} @_ZNK5WaterssERKS_
+inline bool Water::operator==(Water const &) const = default;
+// CHECK-NOT: define{{.*}} @_ZNK5WatereqERKS_
Index: clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
===
--- clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
+++ clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
@@ -1,15 +1,13 @@
 // RUN: %clang_cc1 -std=c++2a -verify %s
 
 struct B {};
-bool operator==(const B&, const B&) = default; // expected-error {{equality comparison operator can only be defaulted in a class definition}} expected-note {{candidate}}
-bool operator<=>(const B&, const B&) = default; // expected-error {{three-way comparison operator can only be defaulted in a class definition}}
 
 template
   bool operator<(const B&, const B&) = default; // expected-error {{comparison operator template cannot be defaulted}}
 
 struct A {
   friend bool operator==(const A&, const A&) = default;
-  friend bool operator!=(const A&, const B&) = default; // expected-error {{invalid parameter type for defaulted equality comparison operator; found 'const B &', expected 'A' or 'const A &'}}
+  friend bool operator!=(const A&, const B&) = default; // expected-error {{parameters for defaulted equality comparison operator must have the same type (found 'const A &' vs 'const B &')}}
   friend bool operator!=(const B&, const B&) = default; // expected-error {{invalid parameter type for defaulted equality comparison}}
   friend bool operator<(const A&, const A&);
   friend bool operator<(const B&, const B&) = default; // expected-error {{invalid parameter type for defaulted relational comparison}}
@@ -29,11 +27,6 @@
 bool operator==(const A&) const = default; // expected-error {{comparison operator template cannot be defaulted}}
 };
 
-// FIXME: The wording is not clear as to whether these are valid, but the
-// intention is that they are not.
-bool operator<(const A&, const A&) = default; // expected-error {{relational comparison operator can only be defaulted in a class definition}}
-bool A::operator<(const A&) const = default; // expected-error {{can only be defaulted in a class definition}}
-
 template struct Dependent {
   using U = typename T::type;
   bool operator==(U) const = default; // expected-error {{found 'Dependent::U'}}
@@ -132,3 +125,41 @@
 friend bool operator==(const B&, const B&) = default; // expected-warning {{deleted}}
   };
 }
+
+namespace p2085 {
+// out-of-class defaulting
+
+struct S1 {
+  bool operator==(S1 const &) const;
+};
+
+bool S1::operator==(

[PATCH] D115879: [clang-format] extern with new line brace without indentation

2021-12-16 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay created this revision.
MyDeveloperDay added reviewers: HazardyKnusperkeks, curdeius, owenpan, 
MarcusJohnson91.
MyDeveloperDay added projects: clang, clang-format.
MyDeveloperDay requested review of this revision.

https://github.com/llvm/llvm-project/issues/49804

Interaction between IndentExternBlock and AfterExternBlock means you cannot 
have AfterExternBlock = true and IndentExternBlock = NoIndent/Indent

This patch resolves that

  BraceWrapping:
AfterExternBlock: true
  IndentExternBlock: AfterExternBlock

Fixes: #49804


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115879

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3811,6 +3811,26 @@
"int foo16();\n"
"}",
Style);
+
+  Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterExternBlock = true;
+  Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
+  verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
+  verifyFormat("extern \"C\"\n{\n"
+   "int foo14();\n"
+   "}",
+   Style);
+
+  Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterExternBlock = true;
+  Style.IndentExternBlock = FormatStyle::IEBS_Indent;
+  verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
+  verifyFormat("extern \"C\"\n{\n"
+   "  int foo14();\n"
+   "}",
+   Style);
 }
 
 TEST_F(FormatTest, FormatsInlineASM) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1282,10 +1282,10 @@
 if (FormatTok->Tok.is(tok::string_literal)) {
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
+if (Style.BraceWrapping.AfterExternBlock) {
+  addUnwrappedLine();
+}
 if (!Style.IndentExternBlock) {
-  if (Style.BraceWrapping.AfterExternBlock) {
-addUnwrappedLine();
-  }
   unsigned AddLevels = Style.BraceWrapping.AfterExternBlock ? 1u : 0u;
   parseBlock(/*MustBeDeclaration=*/true, AddLevels);
 } else {


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3811,6 +3811,26 @@
"int foo16();\n"
"}",
Style);
+
+  Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterExternBlock = true;
+  Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
+  verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
+  verifyFormat("extern \"C\"\n{\n"
+   "int foo14();\n"
+   "}",
+   Style);
+
+  Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterExternBlock = true;
+  Style.IndentExternBlock = FormatStyle::IEBS_Indent;
+  verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
+  verifyFormat("extern \"C\"\n{\n"
+   "  int foo14();\n"
+   "}",
+   Style);
 }
 
 TEST_F(FormatTest, FormatsInlineASM) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1282,10 +1282,10 @@
 if (FormatTok->Tok.is(tok::string_literal)) {
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
+if (Style.BraceWrapping.AfterExternBlock) {
+  addUnwrappedLine();
+}
 if (!Style.IndentExternBlock) {
-  if (Style.BraceWrapping.AfterExternBlock) {
-addUnwrappedLine();
-  }
   unsigned AddLevels = Style.BraceWrapping.AfterExternBlock ? 1u : 0u;
   parseBlock(/*MustBeDeclaration=*/true, AddLevels);
 } else {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8285522 - [CodeGen] Always update map entry after adding initializer

2021-12-16 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2021-12-16T16:29:35+01:00
New Revision: 828552201420720ff52c9a27ea4e8f3697f1abc1

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

LOG: [CodeGen] Always update map entry after adding initializer

With opaque pointers the pointer cast may be a no-op, such that
var and castedAddr are the same. However, we still need to update
the map entry as the underlying global changed. We could explicitly
check whether the global was replaced, but we may as well just
always update the entry.

Added: 


Modified: 
clang/lib/CodeGen/CGDecl.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index f6b758ba30a0..2d1f229108d6 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -405,8 +405,8 @@ void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
 
   // Store into LocalDeclMap before generating initializer to handle
   // circular references.
-  setAddrOfLocalVar(
-  &D, Address(addr, ConvertTypeForMem(D.getType()), alignment));
+  llvm::Type *elemTy = ConvertTypeForMem(D.getType());
+  setAddrOfLocalVar(&D, Address(addr, elemTy, alignment));
 
   // We can't have a VLA here, but we can have a pointer to a VLA,
   // even though that doesn't really make any sense.
@@ -459,8 +459,7 @@ void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
   // RAUW's the GV uses of this constant will be invalid.
   llvm::Constant *castedAddr =
 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
-  if (var != castedAddr)
-LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
+  LocalDeclMap.find(&D)->second = Address(castedAddr, elemTy, alignment);
   CGM.setStaticLocalDeclAddress(&D, castedAddr);
 
   CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);



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


[clang] bbc690c - Define __STDC_NO_THREADS__ when targeting windows-msvc (PR48704)

2021-12-16 Thread Hans Wennborg via cfe-commits

Author: Hans Wennborg
Date: 2021-12-16T16:30:06+01:00
New Revision: bbc690c57213054907284d8964dc0487d38fc57a

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

LOG: Define __STDC_NO_THREADS__ when targeting windows-msvc (PR48704)

MSVC's libc doesn't provide thread.h, so we should set the macro to
indicate that.

We could just set it in C mode, but I noticed that Darwin sets it
unconditionally, so perhaps we should do the same here.

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

Added: 


Modified: 
clang/lib/Basic/Targets/OSTargets.cpp
clang/test/Preprocessor/init.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/OSTargets.cpp 
b/clang/lib/Basic/Targets/OSTargets.cpp
index 695cbafe36557..f8f12daaa0722 100644
--- a/clang/lib/Basic/Targets/OSTargets.cpp
+++ b/clang/lib/Basic/Targets/OSTargets.cpp
@@ -203,6 +203,7 @@ static void addVisualCDefines(const LangOptions &Opts, 
MacroBuilder &Builder) {
   }
 
   Builder.defineMacro("_INTEGRAL_MAX_BITS", "64");
+  Builder.defineMacro("__STDC_NO_THREADS__");
 
   // Starting with VS 2022 17.1, MSVC predefines the below macro to inform
   // users of the execution character set defined at compile time.

diff  --git a/clang/test/Preprocessor/init.c b/clang/test/Preprocessor/init.c
index 52c33d9b8b7a5..7d838413b8513 100644
--- a/clang/test/Preprocessor/init.c
+++ b/clang/test/Preprocessor/init.c
@@ -195,6 +195,7 @@
 // MSEXT-NOT:#define _NATIVE_WCHAR_T_DEFINED 1
 // MSEXT-NOT:#define _WCHAR_T_DEFINED 1
 // MSEXT:#define _MSVC_EXECUTION_CHARACTER_SET 65001
+// MSEXT:#define __STDC_NO_THREADS__ 1
 //
 //
 // RUN: %clang_cc1 -x c++ -fms-extensions -triple i686-pc-win32 -E -dM < 
/dev/null | FileCheck -match-full-lines -check-prefix MSEXT-CXX %s



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


[PATCH] D112081: Define __STDC_NO_THREADS__ when targeting windows-msvc (PR48704)

2021-12-16 Thread Hans Wennborg via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbbc690c57213: Define __STDC_NO_THREADS__ when targeting 
windows-msvc (PR48704) (authored by hans).

Changed prior to commit:
  https://reviews.llvm.org/D112081?vs=380704&id=394877#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112081

Files:
  clang/lib/Basic/Targets/OSTargets.cpp
  clang/test/Preprocessor/init.c


Index: clang/test/Preprocessor/init.c
===
--- clang/test/Preprocessor/init.c
+++ clang/test/Preprocessor/init.c
@@ -195,6 +195,7 @@
 // MSEXT-NOT:#define _NATIVE_WCHAR_T_DEFINED 1
 // MSEXT-NOT:#define _WCHAR_T_DEFINED 1
 // MSEXT:#define _MSVC_EXECUTION_CHARACTER_SET 65001
+// MSEXT:#define __STDC_NO_THREADS__ 1
 //
 //
 // RUN: %clang_cc1 -x c++ -fms-extensions -triple i686-pc-win32 -E -dM < 
/dev/null | FileCheck -match-full-lines -check-prefix MSEXT-CXX %s
Index: clang/lib/Basic/Targets/OSTargets.cpp
===
--- clang/lib/Basic/Targets/OSTargets.cpp
+++ clang/lib/Basic/Targets/OSTargets.cpp
@@ -203,6 +203,7 @@
   }
 
   Builder.defineMacro("_INTEGRAL_MAX_BITS", "64");
+  Builder.defineMacro("__STDC_NO_THREADS__");
 
   // Starting with VS 2022 17.1, MSVC predefines the below macro to inform
   // users of the execution character set defined at compile time.


Index: clang/test/Preprocessor/init.c
===
--- clang/test/Preprocessor/init.c
+++ clang/test/Preprocessor/init.c
@@ -195,6 +195,7 @@
 // MSEXT-NOT:#define _NATIVE_WCHAR_T_DEFINED 1
 // MSEXT-NOT:#define _WCHAR_T_DEFINED 1
 // MSEXT:#define _MSVC_EXECUTION_CHARACTER_SET 65001
+// MSEXT:#define __STDC_NO_THREADS__ 1
 //
 //
 // RUN: %clang_cc1 -x c++ -fms-extensions -triple i686-pc-win32 -E -dM < /dev/null | FileCheck -match-full-lines -check-prefix MSEXT-CXX %s
Index: clang/lib/Basic/Targets/OSTargets.cpp
===
--- clang/lib/Basic/Targets/OSTargets.cpp
+++ clang/lib/Basic/Targets/OSTargets.cpp
@@ -203,6 +203,7 @@
   }
 
   Builder.defineMacro("_INTEGRAL_MAX_BITS", "64");
+  Builder.defineMacro("__STDC_NO_THREADS__");
 
   // Starting with VS 2022 17.1, MSVC predefines the below macro to inform
   // users of the execution character set defined at compile time.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D112081: Define __STDC_NO_THREADS__ when targeting windows-msvc (PR48704)

2021-12-16 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

Thanks for the reminder! Landed now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112081

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


[PATCH] D110742: [OpenCL] Add pure attributes to vload builtins

2021-12-16 Thread Stuart Brady via Phabricator via cfe-commits
stuart updated this revision to Diff 394878.
stuart added a comment.

I've updated the review to include test changes that are required for 
check-clang-semaopencl to pass.


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

https://reviews.llvm.org/D110742

Files:
  clang/lib/Headers/opencl-c.h
  clang/lib/Sema/OpenCLBuiltins.td
  clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl

Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -46,12 +46,19 @@
 typedef char char2 __attribute__((ext_vector_type(2)));
 typedef char char4 __attribute__((ext_vector_type(4)));
 typedef uchar uchar4 __attribute__((ext_vector_type(4)));
+typedef uchar uchar16 __attribute__((ext_vector_type(16)));
 typedef float float4 __attribute__((ext_vector_type(4)));
+typedef float float16 __attribute__((ext_vector_type(16)));
 typedef half half4 __attribute__((ext_vector_type(4)));
 typedef int int2 __attribute__((ext_vector_type(2)));
 typedef int int4 __attribute__((ext_vector_type(4)));
+typedef uint uint2 __attribute__((ext_vector_type(2)));
 typedef uint uint4 __attribute__((ext_vector_type(4)));
 typedef long long2 __attribute__((ext_vector_type(2)));
+typedef long long8 __attribute__((ext_vector_type(8)));
+typedef ulong ulong4 __attribute__((ext_vector_type(4)));
+typedef short short16 __attribute__((ext_vector_type(16)));
+typedef ushort ushort3 __attribute__((ext_vector_type(3)));
 
 typedef int clk_profiling_info;
 #define CLK_PROFILING_COMMAND_EXEC_TIME 0x1
@@ -284,18 +291,27 @@
   global void *global_p;
   private void *private_p;
   size_t s;
+  ulong4 ul4;
+  short16 s16;
+#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
+  ushort3 us3;
+  uchar16 uc16;
+#endif
+  long8 l8;
+  uint2 ui2;
+  float16 f16;
 
-  vload4(s, (const __constant ulong *) constant_p);
-  vload16(s, (const __constant short *) constant_p);
+  ul4 = vload4(s, (const __constant ulong *) constant_p);
+  s16 = vload16(s, (const __constant short *) constant_p);
 
 #if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
-  vload3(s, (const __generic ushort *) generic_p);
-  vload16(s, (const __generic uchar *) generic_p);
+  us3 = vload3(s, (const __generic ushort *) generic_p);
+  uc16 = vload16(s, (const __generic uchar *) generic_p);
 #endif
 
-  vload8(s, (const __global long *) global_p);
-  vload2(s, (const __local uint *) local_p);
-  vload16(s, (const __private float *) private_p);
+  l8 = vload8(s, (const __global long *) global_p);
+  ui2 = vload2(s, (const __local uint *) local_p);
+  f16 = vload16(s, (const __private float *) private_p);
 }
 
 kernel void basic_work_item() {
Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -806,17 +806,17 @@
   foreach AS = addrspaces in {
 foreach VSize = [2, 3, 4, 8, 16] in {
   foreach name = ["vload" # VSize] in {
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
   }
   if defStores then {
 foreach name = ["vstore" # VSize] in {
@@ -848,10 +848,10 @@
 
 multiclass VloadVstoreHalf addrspaces, bit defStores> {
   foreach AS = addrspaces in {
-def : Builtin<"vload_half", [Float, Size, PointerType, AS>]>;
+def : Builtin<"vload_half", [Float, Size, PointerType, AS>], Attr.Pure>;
 foreach VSize = [2, 3, 4, 8, 16] in {
   foreach name = ["vload_half" # VSize, "vloada_half" # VSize] in {
-def : Builtin, Size, PointerType, AS>]>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
   }
 }
 if defStores then {
@@ -877,7 +877,7 @@
 let MinVersion = CL20 in {
   defm : VloadVstoreHalf<[Gene

[clang] 2d89382 - [CodeGen] Avoid more pointer element type accesses

2021-12-16 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2021-12-16T16:34:09+01:00
New Revision: 2d89382b5a21423180c7860163bb0e4cd3082e4b

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

LOG: [CodeGen] Avoid more pointer element type accesses

This is enough to build sqlite3 with opaque pointers.

Added: 


Modified: 
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGDecl.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 8ecef6ab9782..28fc75ba466e 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -2686,8 +2686,8 @@ void CodeGenFunction::EmitFunctionProlog(const 
CGFunctionInfo &FI,
 case ABIArgInfo::Indirect:
 case ABIArgInfo::IndirectAliased: {
   assert(NumIRArgs == 1);
-  Address ParamAddr =
-  Address(Fn->getArg(FirstIRArg), ArgI.getIndirectAlign());
+  Address ParamAddr = Address(Fn->getArg(FirstIRArg), 
ConvertTypeForMem(Ty),
+  ArgI.getIndirectAlign());
 
   if (!hasScalarEvaluationKind(Ty)) {
 // Aggregates and complex variables are accessed by reference. All we
@@ -4869,7 +4869,8 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
   I->copyInto(*this, AI);
 } else {
   // Skip the extra memcpy call.
-  auto *T = V->getType()->getPointerElementType()->getPointerTo(
+  auto *T = llvm::PointerType::getWithSamePointeeType(
+  cast(V->getType()),
   CGM.getDataLayout().getAllocaAddrSpace());
   IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
   *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,

diff  --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index 2d1f229108d6..e09279c1d455 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -1193,7 +1193,7 @@ static void emitStoresForConstant(CodeGenModule &CGM, 
const VarDecl &D,
 bool valueAlreadyCorrect =
 constant->isNullValue() || isa(constant);
 if (!valueAlreadyCorrect) {
-  Loc = Builder.CreateBitCast(Loc, 
Ty->getPointerTo(Loc.getAddressSpace()));
+  Loc = Builder.CreateElementBitCast(Loc, Ty);
   emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
   IsAutoInit);
 }



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


[PATCH] D110742: [OpenCL] Add pure attributes to vload builtins

2021-12-16 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Thanks! Bots look happy again :)


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

https://reviews.llvm.org/D110742

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


[PATCH] D114317: [clang-tidy][WIP] Do not run perfect alias checks

2021-12-16 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

> me pretty far behind on reviews

Wow, that's a lot to review! I will keep it in mind and hopefully only ping you 
when I have a nice final design ready to go. Really appreciate your early 
feedback!

> I'd like to make sure I'm on the same page as you.

Yes, exactly, from the RFC we agreed that the desired outcome of this patch 
would be that the same diagnostics and fixits are emitted, regardless of the 
alias checks actually running. I.e. this patch should not have any visible 
effects towards the user (other than faster runtime). The patch, as it is right 
now _will_ eliminate those diagnostics (since the alias checks are removed from 
the list), which to my understanding are not desirable. In order to implement 
this, the primary check needs to emit copies of the same diagnostic as if it 
were the alias check.


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

https://reviews.llvm.org/D114317

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


[PATCH] D114317: [clang-tidy][WIP] Do not run perfect alias checks

2021-12-16 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added inline comments.



Comment at: clang-tools-extra/clang-tidy/ClangTidyModule.h:25-26
 
+#define CLANG_TIDY_REGISTER_CHECK(Factory, CheckType, CheckName)   
\
+  Factory.registerCheck(CheckName, #CheckType)
+

aaron.ballman wrote:
> I'm not 100% sold that this macro carries its weight. I almost think the 
> registration code is easier to read without it, but not enough to suggest a 
> change yet. Curious if others have feelings here.
I'm not loving it either, to be honest, but I couldn't think of anything better 
that wouldn't cause developer friction. I've looked into RTTI (banned in LLVM) 
and hand-made LLVM RRTI, which I think would be quite a burden for check 
developers since they'd need to add a new enum to the list, implement a 
getClass() method, etc (IIUC).

Previous attempts as this problem created a different register function like:

```
Factory.registerCheck("foo-check", misc::PrimaryCheck, "misc-check")
```

Which I don't like much because the developer needs to spend time digging 
through the code and docs to see what is the name of the check it's aliasing, 
which is error-prone and can easily get out of sync in the future. 

With this macro, all of this is automated and always in sync. But again, if 
someone has some cleverer magic that would work here I'd love to bring it in :) 

Since replacing existing lines with the macro is a pretty big change, I'll wait 
until I get OK from reviewers to avoid spending time if in the end we go for 
another solution.


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

https://reviews.llvm.org/D114317

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


[PATCH] D99134: Lambdas are not necessarily locals. This resolves DR48250.

2021-12-16 Thread David Stone via Phabricator via cfe-commits
davidstone added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D99134

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


[PATCH] D91000: [clang-tidy] Add cert-msc24-c checker.

2021-12-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thanks for this new check!

In terms of whether we should expose the check in C++: I think we shouldn't. 
Annex K *could* be supported by a C++ library implementation 
(http://eel.is/c++draft/library#headers-10), but none of the identifiers are 
added to namespace `std` and there's not a lot of Annex K support in C so I 
imagine there's even less support in C++. We can always revisit the decision 
later and expand support for C++ once we know what that support should look 
like.

I think we should probably also not enable the check when the user compiles in 
C99 or earlier mode, because there is no Annex K available to provide 
replacement functions.

We should also circle back with the CERT authors for updates on missing entries 
in their tables once we've figured out what is missing, and on the terminology 
concerns of referring to these as "deprecated or obsolescent" functions.




Comment at: clang-tools-extra/clang-tidy/cert/ObsolescentFunctionsCheck.cpp:33
+  "::wcsrtombs", "::wcstok", "::wcstombs", "::wctomb", "::wmemcpy",
+  "::wmemmove", "::wprintf", "::wscanf", "::strlen"));
+  Finder->addMatcher(

steakhal wrote:
> Why is `strlen` an //obsolescent// function? I don't feel it justified, even 
> if there was a [[ 
> https://wiki.sei.cmu.edu/confluence/display/c/MSC24-C.+Do+not+use+deprecated+or+obsolescent+functions?focusedCommentId=88019519#comment-88019519
>  | comment ]] about it on the cert page.
I think its exclusion from the CERT page was an oversight. `strlen_s()` is a 
secure replacement for `strlen()` and it would be weird to leave it off the 
list.



Comment at: 
clang-tools-extra/clang-tidy/cert/ObsolescentFunctionsCheck.cpp:41-42
+
+  // Matching the `gets` deprecated function without replacement.
+  auto DeprecatedFunctionNamesMatcher = hasAnyName("::gets");
+

This comment is not accurate. `gets_s()` is a secure replacement for `gets()`.



Comment at: 
clang-tools-extra/clang-tidy/cert/ObsolescentFunctionsCheck.cpp:49-59
+  "::asctime", "::bsearch", "::ctime", "::fopen", "::fprintf", "::freopen",
+  "::fscanf", "::fwprintf", "::fwscanf", "::getenv", "::gmtime",
+  "::localtime", "::mbsrtowcs", "::mbstowcs", "::memcpy", "::memmove",
+  "::printf", "::qsort", "::snprintf", "::sprintf", "::sscanf", "::strcat",
+  "::strcpy", "::strerror", "::strncat", "::strncpy", "::strtok",
+  "::swprintf", "::swscanf", "::vfprintf", "::vfscanf", "::vfwprintf",
+  "::vfwscanf", "::vprintf", "::vscanf", "::vsnprintf", "::vsprintf",

This list appears to be missing quite a few functions with secure replacements 
in Annex K. For example: `tmpfile_s`, `tmpnam_s`, `strerrorlen_s`, 
`strlen_s`... can you check the list against the actual Annex K, as it seems 
the CERT recommendation is still out of date.



Comment at: 
clang-tools-extra/clang-tidy/cert/ObsolescentFunctionsCheck.cpp:84-86
+diag(Range.getBegin(),
+ "function '%0' is deprecated as of C99, removed from C11.")
+<< Deprecated->getName() << Range;

Fixed a few nits with the code, but `gets()` was never deprecated, so the 
message is not correct (it was present in C99 and removed in C11 with no 
deprecation period). I think it may be better to say "function %0 was removed 
in C11".



Comment at: clang-tools-extra/clang-tidy/cert/ObsolescentFunctionsCheck.cpp:103
+
+  diag(Range.getBegin(), "function '%0' %1; '%2' should be used instead.")
+  << FunctionName << getRationale(FunctionName)





Comment at: clang-tools-extra/clang-tidy/cert/ObsolescentFunctionsCheck.h:18
+
+/// Checks for deprecated and obsolescent function listed in
+/// CERT C Coding Standard Recommendation MSC24 - C. For the listed functions,

The terminology used in the CERT recommendation is pretty unfortunate and I 
don't think we should replicate it. Many of these are *not* deprecated or 
obsolescent functions and calling them that will confuse users. The crux of the 
CERT recommendation is that these functions have better replacements in more 
modern versions of C. So I would probably try to focus our diagnostics and 
documentation around modernization rather than deprecation.

FWIW, this is feedback that should also go onto the CERT recommendation itself. 
I noticed someone already observed the same thing: 
https://wiki.sei.cmu.edu/confluence/display/c/MSC24-C.+Do+not+use+deprecated+or+obsolescent+functions?focusedCommentId=215482395#comment-215482395


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

https://reviews.llvm.org/D91000

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


[clang] 2d0bf14 - [clang] Cleanup unneeded Function nullptr checks [NFC]

2021-12-16 Thread Mike Rice via cfe-commits

Author: Mike Rice
Date: 2021-12-16T08:28:10-08:00
New Revision: 2d0bf14397276d1ece9db1eb1858a644aad77ff2

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

LOG: [clang] Cleanup unneeded Function nullptr checks [NFC]

Add an assert and avoid unneeded checks of Fn in
CodeGenFunction::GenerateCode.

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

Added: 


Modified: 
clang/lib/CodeGen/CodeGenFunction.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index ed43adfab954..f14e4c33e91a 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1298,47 +1298,44 @@ QualType 
CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
 
 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
const CGFunctionInfo &FnInfo) {
+  assert(Fn && "generating code for null Function");
   const FunctionDecl *FD = cast(GD.getDecl());
   CurGD = GD;
 
   FunctionArgList Args;
   QualType ResTy = BuildFunctionArgList(GD, Args);
 
-  // When generating code for a builtin with an inline declaration, use a
-  // mangled name to hold the actual body, while keeping an external definition
-  // in case the function pointer is referenced somewhere.
-  if (Fn) {
-if (FD->isInlineBuiltinDeclaration()) {
-  std::string FDInlineName = (Fn->getName() + ".inline").str();
-  llvm::Module *M = Fn->getParent();
-  llvm::Function *Clone = M->getFunction(FDInlineName);
-  if (!Clone) {
-Clone = llvm::Function::Create(Fn->getFunctionType(),
-   llvm::GlobalValue::InternalLinkage,
-   Fn->getAddressSpace(), FDInlineName, M);
-Clone->addFnAttr(llvm::Attribute::AlwaysInline);
-  }
-  Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
-  Fn = Clone;
+  if (FD->isInlineBuiltinDeclaration()) {
+// When generating code for a builtin with an inline declaration, use a
+// mangled name to hold the actual body, while keeping an external
+// definition in case the function pointer is referenced somewhere.
+std::string FDInlineName = (Fn->getName() + ".inline").str();
+llvm::Module *M = Fn->getParent();
+llvm::Function *Clone = M->getFunction(FDInlineName);
+if (!Clone) {
+  Clone = llvm::Function::Create(Fn->getFunctionType(),
+ llvm::GlobalValue::InternalLinkage,
+ Fn->getAddressSpace(), FDInlineName, M);
+  Clone->addFnAttr(llvm::Attribute::AlwaysInline);
 }
-
+Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
+Fn = Clone;
+  } else {
 // Detect the unusual situation where an inline version is shadowed by a
 // non-inline version. In that case we should pick the external one
 // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
 // to detect that situation before we reach codegen, so do some late
 // replacement.
-else {
-  for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
-   PD = PD->getPreviousDecl()) {
-if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
-  std::string FDInlineName = (Fn->getName() + ".inline").str();
-  llvm::Module *M = Fn->getParent();
-  if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
-Clone->replaceAllUsesWith(Fn);
-Clone->eraseFromParent();
-  }
-  break;
+for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
+ PD = PD->getPreviousDecl()) {
+  if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
+std::string FDInlineName = (Fn->getName() + ".inline").str();
+llvm::Module *M = Fn->getParent();
+if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
+  Clone->replaceAllUsesWith(Fn);
+  Clone->eraseFromParent();
 }
+break;
   }
 }
   }
@@ -1347,8 +1344,7 @@ void CodeGenFunction::GenerateCode(GlobalDecl GD, 
llvm::Function *Fn,
   if (FD->hasAttr()) {
 // Clear non-distinct debug info that was possibly attached to the function
 // due to an earlier declaration without the nodebug attribute
-if (Fn)
-  Fn->setSubprogram(nullptr);
+Fn->setSubprogram(nullptr);
 // Disable debug info indefinitely for this function
 DebugInfo = nullptr;
   }



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


[PATCH] D115817: [clang] Cleanup unneeded Function nullptr checks [NFC]

2021-12-16 Thread Mike Rice 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 rG2d0bf1439727: [clang] Cleanup unneeded Function nullptr 
checks [NFC] (authored by mikerice).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115817

Files:
  clang/lib/CodeGen/CodeGenFunction.cpp


Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1298,47 +1298,44 @@
 
 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
const CGFunctionInfo &FnInfo) {
+  assert(Fn && "generating code for null Function");
   const FunctionDecl *FD = cast(GD.getDecl());
   CurGD = GD;
 
   FunctionArgList Args;
   QualType ResTy = BuildFunctionArgList(GD, Args);
 
-  // When generating code for a builtin with an inline declaration, use a
-  // mangled name to hold the actual body, while keeping an external definition
-  // in case the function pointer is referenced somewhere.
-  if (Fn) {
-if (FD->isInlineBuiltinDeclaration()) {
-  std::string FDInlineName = (Fn->getName() + ".inline").str();
-  llvm::Module *M = Fn->getParent();
-  llvm::Function *Clone = M->getFunction(FDInlineName);
-  if (!Clone) {
-Clone = llvm::Function::Create(Fn->getFunctionType(),
-   llvm::GlobalValue::InternalLinkage,
-   Fn->getAddressSpace(), FDInlineName, M);
-Clone->addFnAttr(llvm::Attribute::AlwaysInline);
-  }
-  Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
-  Fn = Clone;
+  if (FD->isInlineBuiltinDeclaration()) {
+// When generating code for a builtin with an inline declaration, use a
+// mangled name to hold the actual body, while keeping an external
+// definition in case the function pointer is referenced somewhere.
+std::string FDInlineName = (Fn->getName() + ".inline").str();
+llvm::Module *M = Fn->getParent();
+llvm::Function *Clone = M->getFunction(FDInlineName);
+if (!Clone) {
+  Clone = llvm::Function::Create(Fn->getFunctionType(),
+ llvm::GlobalValue::InternalLinkage,
+ Fn->getAddressSpace(), FDInlineName, M);
+  Clone->addFnAttr(llvm::Attribute::AlwaysInline);
 }
-
+Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
+Fn = Clone;
+  } else {
 // Detect the unusual situation where an inline version is shadowed by a
 // non-inline version. In that case we should pick the external one
 // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
 // to detect that situation before we reach codegen, so do some late
 // replacement.
-else {
-  for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
-   PD = PD->getPreviousDecl()) {
-if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
-  std::string FDInlineName = (Fn->getName() + ".inline").str();
-  llvm::Module *M = Fn->getParent();
-  if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
-Clone->replaceAllUsesWith(Fn);
-Clone->eraseFromParent();
-  }
-  break;
+for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
+ PD = PD->getPreviousDecl()) {
+  if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
+std::string FDInlineName = (Fn->getName() + ".inline").str();
+llvm::Module *M = Fn->getParent();
+if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
+  Clone->replaceAllUsesWith(Fn);
+  Clone->eraseFromParent();
 }
+break;
   }
 }
   }
@@ -1347,8 +1344,7 @@
   if (FD->hasAttr()) {
 // Clear non-distinct debug info that was possibly attached to the function
 // due to an earlier declaration without the nodebug attribute
-if (Fn)
-  Fn->setSubprogram(nullptr);
+Fn->setSubprogram(nullptr);
 // Disable debug info indefinitely for this function
 DebugInfo = nullptr;
   }


Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1298,47 +1298,44 @@
 
 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
const CGFunctionInfo &FnInfo) {
+  assert(Fn && "generating code for null Function");
   const FunctionDecl *FD = cast(GD.getDecl());
   CurGD = GD;
 
   FunctionArgList Args;
   QualType ResTy = BuildFunctionArgList(GD, Args);
 
-  // When generating code for a builtin with an inline declaration, use a

[PATCH] D114966: [clang][deps] Split stat and file content caches

2021-12-16 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: 
clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp:200-210
+  // FIXME: This read can fail.
+  // In that case, we should probably update `CacheEntry::MaybeStat`.
+  // However, that is concurrently read at the start of this function
+  // (`needsUpdate` -> `isReadable`), leading to a data race. If we try
+  // to avoid the data race by returning an `error_code` here (without
+  // updating the entry stat value, we can end up attempting to read 
the
+  // file again in the future, which breaks the consistency guarantees

dexonsmith wrote:
> dexonsmith wrote:
> > I'm not quite following this logic. I think it's safe (and important!) to 
> > modify MaybeStat if `read()` fails.
> > 
> > We're in a critical section that either creates and partially initializes 
> > the entry, or incrementally updates it.
> > 
> > In the "creates and partially initializes" case:
> > - All other workers will get nullptr for `Cache.getEntry()` and try to 
> > enter the critical section.
> > - We have just seen a successful MaybeStat value.
> > - `needsRead()` will be `true` since we have not read contents before. We 
> > will immediately try to read.
> > - `read()` should open the original contents and can safely:
> > - on success, update the value for MaybeStat to match the observed size
> > - on failure, drop the value and set the error for MaybeStat to the 
> > observed error
> > - When we leave the critical section, either:
> > - MaybeStat stores an error; no thread will enter the critical section 
> > again
> > - OriginalContents are initialized and `needsRead()` returns false
> > 
> > In the "incrementally updates" case:
> > - `needsRead()` returns false so `read()` will not be called
> > 
> The key property being the last bullet of the first case: that the "create 
> and partially initializes" case guarantees that either `MaybeStat` stores an 
> error (`isReadable()` is false) or `OriginalContents` is initialized 
> (`needsRead()` returns false).
> 
> 
> 
> I think I've found the part I was missing: that this critical section is for 
> a SharedCacheFileEntry (associated with a filename), but the 
> `OriginalContents` is a field on a CachedFileContents which could apply to 
> other UIDs (and `SharedCache.getFileContents()` is actually "get or create"). 
> Since this commit creates the UID map, seems like maybe the race gets worse 
> in this commit? (Not sure)
> 
> 
> 
> Another problem: the UID can change between the first stat above (call to 
> `getUnderlyingFS().status(Filename)`) and the one inside `read()` if another 
> process is writing at the same time. We can't trust the UID mapping from the 
> first `status()` call unless content already exists for that UID.
> 
> I think to avoid this race you need to delay creating "UID to content" map 
> entry until there is the result of a successful `read()` to store.
> 
> I'll describe an algorithm that I think is fairly clean that handles this. 
> I'm using different data structure names to avoid confusion since I've broken 
> it down a little differently:
> - ReadResult: stat (for directories) OR error and uid (failed read) OR stat 
> and content (and optional minimized content and pp ranges, and a way to 
> update them atomically))
> - FilenameMap: map from Filename to `ReadResult*` (shared and sharded; 
> mirrored locally in each worker)
> - UIDMap: map from UID to `ReadResult*` (shared and sharded; probably no 
> local mirror)
> 
> And here's the algorithm:
> ```
> lang=c++
> // Top-level API: get the entry/result for some filename.
> ErrorOr getOrCreateResult(StringRef Filename) {
>   if (ReadResult *Result = lookupEntryForFilename(Filename))
> return minimizeIfNecessary(*Result, ShouldMinimize);
>   if (ErrorOr Result = computeAndStoreResult(Filename))
> return minimizeIfNecessary(*Result, ShouldMinimize);
>   else
> return Result.getError();
> }
> // Compute and store an entry/result for some filename. Returned result
> // has in-sync stat+read info (assuming read was successful).
> ErrorOr computeAndStoreResult(StringRef Filename) {
>   ErrorOr Stat = UnderlyingFS->status(Filename);
>   if (!Stat)
> return Stat.getError(); // Can't cache missing files.
>   if (ReadResult *Result = lookupEntryForUID(Stat->UID))
> return storeFilenameEntry(Filename, *Result); // UID already known.
>   // UID not known. Compute a ReadResult.
>   //
>   // Unless this is a directory (where we don't need to go back to the FS),
>   // ignore existing 'Stat' because without an open file descriptor the UID
>   // could change.
>   Optional Result;
>   if (Stat->isDirectory())
> Result = ReadResult(*Stat);
>   else if (ErrorOr MaybeResult = computeReadResult(Filename))
> Result = std::move(*MaybeResult);
>   else
> return MaybeResult.getError(); // File disappeared...
>   // Store t

[clang] 333d66b - [analyzer][ctu] Fix wrong 'multiple definitions' errors caused by space characters in lookup names when parsing the ctu index file

2021-12-16 Thread Balazs Benics via cfe-commits

Author: Ella Ma
Date: 2021-12-16T17:47:59+01:00
New Revision: 333d66b09494b7ebc1a89f2befa79128a56f77e3

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

LOG: [analyzer][ctu] Fix wrong 'multiple definitions' errors caused by space 
characters in lookup names when parsing the ctu index file

This error was found when analyzing MySQL with CTU enabled.

When there are space characters in the lookup name, the current
delimiter searching strategy will make the file path wrongly parsed.
And when two lookup names have the same prefix before their first space
characters, a 'multiple definitions' error will be wrongly reported.

e.g. The lookup names for the two lambda exprs in the test case are
`c:@S@G@F@G#@Sa@F@operator int (*)(char)#1` and
`c:@S@G@F@G#@Sa@F@operator bool (*)(char)#1` respectively. And their
prefixes are both `c:@S@G@F@G#@Sa@F@operator` when using the first space
character as the delimiter.

Solving the problem by adding a length for the lookup name, making the
index items in the format of `USR-Length:USR File-Path`.

Reviewed By: steakhal

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

Added: 
clang/test/Analysis/Inputs/ctu-lookup-name-with-space.cpp
clang/test/Analysis/ctu-lookup-name-with-space.cpp

Modified: 
clang/docs/analyzer/user-docs/CrossTranslationUnit.rst
clang/include/clang/Basic/DiagnosticCrossTUKinds.td
clang/lib/CrossTU/CrossTranslationUnit.cpp
clang/test/Analysis/Inputs/ctu-import.c.externalDefMap.ast-dump.txt
clang/test/Analysis/Inputs/ctu-other.c.externalDefMap.ast-dump.txt
clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.ast-dump.txt

clang/test/Analysis/Inputs/plist-macros-with-expansion-ctu.c.externalDefMap.txt
clang/test/Analysis/ctu-inherited-default-ctor.cpp
clang/test/Analysis/func-mapping-test.cpp
clang/unittests/CrossTU/CrossTranslationUnitTest.cpp

Removed: 




diff  --git a/clang/docs/analyzer/user-docs/CrossTranslationUnit.rst 
b/clang/docs/analyzer/user-docs/CrossTranslationUnit.rst
index 0e0691b95d5d..0976c9a5b67a 100644
--- a/clang/docs/analyzer/user-docs/CrossTranslationUnit.rst
+++ b/clang/docs/analyzer/user-docs/CrossTranslationUnit.rst
@@ -81,12 +81,12 @@ of `foo.cpp`:
   $
 
 The next step is to create a CTU index file which holds the `USR` name and 
location of external definitions in the
-source files:
+source files in format `: `:
 
 .. code-block:: bash
 
   $ clang-extdef-mapping -p . foo.cpp
-  c:@F@foo# /path/to/your/project/foo.cpp
+  9:c:@F@foo# /path/to/your/project/foo.cpp
   $ clang-extdef-mapping -p . foo.cpp > externalDefMap.txt
 
 We have to modify `externalDefMap.txt` to contain the name of the `.ast` files 
instead of the source files:
@@ -278,12 +278,12 @@ The `invocation list`:
 
 We'd like to analyze `main.cpp` and discover the division by zero bug.
 As we are using On-demand mode, we only need to create a CTU index file which 
holds the `USR` name and location of
-external definitions in the source files:
+external definitions in the source files in format `: 
`:
 
 .. code-block:: bash
 
   $ clang-extdef-mapping -p . foo.cpp
-  c:@F@foo# /path/to/your/project/foo.cpp
+  9:c:@F@foo# /path/to/your/project/foo.cpp
   $ clang-extdef-mapping -p . foo.cpp > externalDefMap.txt
 
 Now everything is available for the CTU analysis.

diff  --git a/clang/include/clang/Basic/DiagnosticCrossTUKinds.td 
b/clang/include/clang/Basic/DiagnosticCrossTUKinds.td
index 4277a3173203..e6ea1956f98a 100644
--- a/clang/include/clang/Basic/DiagnosticCrossTUKinds.td
+++ b/clang/include/clang/Basic/DiagnosticCrossTUKinds.td
@@ -12,8 +12,8 @@ def err_ctu_error_opening : Error<
   "error opening '%0': required by the CrossTU functionality">;
 
 def err_extdefmap_parsing : Error<
-  "error parsing index file: '%0' line: %1 'UniqueID filename' format "
-  "expected">;
+  "error parsing index file: '%0' line: %1 ': ' "
+  "format expected">;
 
 def err_multiple_def_index : Error<
   "multiple definitions are found for the same key in index ">;

diff  --git a/clang/lib/CrossTU/CrossTranslationUnit.cpp 
b/clang/lib/CrossTU/CrossTranslationUnit.cpp
index 0aecad491ecc..cbe07acb76fb 100644
--- a/clang/lib/CrossTU/CrossTranslationUnit.cpp
+++ b/clang/lib/CrossTU/CrossTranslationUnit.cpp
@@ -149,6 +149,35 @@ std::error_code IndexError::convertToErrorCode() const {
   return std::error_code(static_cast(Code), *Category);
 }
 
+/// Parse one line of the input CTU index file.
+///
+/// @param[in]  LineRef The input CTU index item in format
+/// ": ".
+/// @param[out] LookupName  The lookup name in format ":".
+/// @param[out] FilePathThe file path "".
+static bool parseCrossTUIndexItem(StringRef LineRef, StringRef &LookupName,
+  St

[PATCH] D102669: [analyzer][ctu] Fix wrong 'multiple definitions' errors caused by space characters in lookup names when parsing the ctu index file

2021-12-16 Thread Balázs Benics 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 rG333d66b09494: [analyzer][ctu] Fix wrong 'multiple 
definitions' errors caused by space… (authored by OikawaKirie, committed 
by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102669

Files:
  clang/docs/analyzer/user-docs/CrossTranslationUnit.rst
  clang/include/clang/Basic/DiagnosticCrossTUKinds.td
  clang/lib/CrossTU/CrossTranslationUnit.cpp
  clang/test/Analysis/Inputs/ctu-import.c.externalDefMap.ast-dump.txt
  clang/test/Analysis/Inputs/ctu-lookup-name-with-space.cpp
  clang/test/Analysis/Inputs/ctu-other.c.externalDefMap.ast-dump.txt
  clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.ast-dump.txt
  
clang/test/Analysis/Inputs/plist-macros-with-expansion-ctu.c.externalDefMap.txt
  clang/test/Analysis/ctu-inherited-default-ctor.cpp
  clang/test/Analysis/ctu-lookup-name-with-space.cpp
  clang/test/Analysis/func-mapping-test.cpp
  clang/unittests/CrossTU/CrossTranslationUnitTest.cpp

Index: clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
===
--- clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
+++ clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
@@ -61,7 +61,7 @@
 ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("index", "txt", IndexFD,
 IndexFileName));
 llvm::ToolOutputFile IndexFile(IndexFileName, IndexFD);
-IndexFile.os() << "c:@F@f#I# " << ASTFileName << "\n";
+IndexFile.os() << "9:c:@F@f#I# " << ASTFileName << "\n";
 IndexFile.os().flush();
 EXPECT_TRUE(llvm::sys::fs::exists(IndexFileName));
 
Index: clang/test/Analysis/func-mapping-test.cpp
===
--- clang/test/Analysis/func-mapping-test.cpp
+++ clang/test/Analysis/func-mapping-test.cpp
@@ -3,10 +3,10 @@
 int f(int) {
   return 0;
 }
-// CHECK-DAG: c:@F@f#I#
+// CHECK-DAG: 9:c:@F@f#I#
 
 extern const int x = 5;
-// CHECK-DAG: c:@x
+// CHECK-DAG: 4:c:@x
 
 // Non-const variables should not be collected.
 int y = 5;
@@ -18,29 +18,29 @@
   int a;
 };
 extern S const s = {.a = 2};
-// CHECK-DAG: c:@s
+// CHECK-DAG: 4:c:@s
 
 struct SF {
   const int a;
 };
 SF sf = {.a = 2};
-// CHECK-DAG: c:@sf
+// CHECK-DAG: 5:c:@sf
 
 struct SStatic {
   static const int a = 4;
 };
 const int SStatic::a;
-// CHECK-DAG: c:@S@SStatic@a
+// CHECK-DAG: 14:c:@S@SStatic@a
 
 extern int const arr[5] = { 0, 1 };
-// CHECK-DAG: c:@arr
+// CHECK-DAG: 6:c:@arr
 
 union U {
   const int a;
   const unsigned int b;
 };
 U u = {.a = 6};
-// CHECK-DAG: c:@u
+// CHECK-DAG: 4:c:@u
 
 // No USR can be generated for this.
 // Check for no crash in this case.
@@ -48,3 +48,15 @@
   float uf;
   const int ui;
 };
+
+void f(int (*)(char));
+void f(bool (*)(char));
+
+struct G {
+  G() {
+f([](char) -> int { return 42; });
+// CHECK-DAG: 41:c:@S@G@F@G#@Sa@F@operator int (*)(char)#1
+f([](char) -> bool { return true; });
+// CHECK-DAG: 42:c:@S@G@F@G#@Sa@F@operator bool (*)(char)#1
+  }
+};
Index: clang/test/Analysis/ctu-lookup-name-with-space.cpp
===
--- /dev/null
+++ clang/test/Analysis/ctu-lookup-name-with-space.cpp
@@ -0,0 +1,21 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+
+// RUN: echo '"%/S/Inputs/ctu-lookup-name-with-space.cpp" : ["g++", "-c", "%/S/Inputs/ctu-lookup-name-with-space.cpp"]' > %t/invocations.yaml
+// RUN: %clang_extdef_map %S/Inputs/ctu-lookup-name-with-space.cpp -- > %t/externalDefMap.txt
+
+// RUN: cd %t && %clang_cc1 -fsyntax-only -analyze \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config experimental-enable-naive-ctu-analysis=true \
+// RUN:   -analyzer-config ctu-dir=. \
+// RUN:   -analyzer-config ctu-invocation-list=invocations.yaml \
+// RUN:   -verify %s
+
+void importee();
+
+void trigger() {
+  // Call an external function to trigger the parsing process of CTU index.
+  // Refer to file Inputs/ctu-lookup-name-with-space.cpp for more details.
+
+  importee(); // expected-no-diagnostics
+}
Index: clang/test/Analysis/ctu-inherited-default-ctor.cpp
===
--- clang/test/Analysis/ctu-inherited-default-ctor.cpp
+++ clang/test/Analysis/ctu-inherited-default-ctor.cpp
@@ -4,7 +4,7 @@
 // RUN: %clang_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
 // RUN:   -emit-pch -o %t/ctudir/ctu-inherited-default-ctor-other.cpp.ast \
 // RUN:%S/Inputs/ctu-inherited-default-ctor-other.cpp
-// RUN: echo "c:@N@clang@S@DeclContextLookupResult@SingleElementDummyList ctu-inherited-default-ctor-other.cpp.ast" \
+// RUN: echo "59:c:@N@clang@S@DeclContextLookupResult@SingleElementDummyList ctu-inherited-default-ctor-other.cpp.ast" \
 // RUN:   > %t/ctudir/ext

[PATCH] D114317: [clang-tidy][WIP] Do not run perfect alias checks

2021-12-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D114317#3197815 , @carlosgalvezp 
wrote:

>> me pretty far behind on reviews
>
> Wow, that's a lot to review! I will keep it in mind and hopefully only ping 
> you when I have a nice final design ready to go. Really appreciate your early 
> feedback!

Happy to help and I really appreciate your patience!

>> I'd like to make sure I'm on the same page as you.
>
> Yes, exactly, from the RFC we agreed that the desired outcome of this patch 
> would be that the same diagnostics and fixits are emitted, regardless of the 
> alias checks actually running. I.e. this patch should not have any visible 
> effects towards the user (other than faster runtime). The patch, as it is 
> right now _will_ eliminate those diagnostics (since the alias checks are 
> removed from the list), which to my understanding are not desirable. In order 
> to implement this, the primary check needs to emit copies of the same 
> diagnostic as if it were the alias check.

Okay, thank you for verifying! I keep reading "copies of the same diagnostic" 
as though you wanted:

  error: forgot to frobble the quux [bugprone-frobble-quux]
  error: forgot to frobble the quux [cert-quux45-cpp]

and going "no, I don't think that's quite what we want." :-)

If it turns out that producing output like `error: forgot to frobble the quux 
[bugprone-frobble-quux, cert-quux45-cpp]` is really difficult, I don't see it 
as being a deal breaker to only emit the primary check name. (Same goes for 
things like `LINT` comments naming the perfect alias vs naming the primary.)

The idea I had for supporting this was: we already register which check is the 
primary and all the names of the aliases, and so we don't need to really run 
the alias check to get its diagnostic output, we could thread some way to go 
from the diagnostics engine back to our registered lists of aliases, and then 
print the alias names manually when emitting the diagnostic for the primary. 
However, I've not tried this idea out and who knows what details I'm missing.




Comment at: clang-tools-extra/clang-tidy/ClangTidyModule.h:25-26
 
+#define CLANG_TIDY_REGISTER_CHECK(Factory, CheckType, CheckName)   
\
+  Factory.registerCheck(CheckName, #CheckType)
+

carlosgalvezp wrote:
> aaron.ballman wrote:
> > I'm not 100% sold that this macro carries its weight. I almost think the 
> > registration code is easier to read without it, but not enough to suggest a 
> > change yet. Curious if others have feelings here.
> I'm not loving it either, to be honest, but I couldn't think of anything 
> better that wouldn't cause developer friction. I've looked into RTTI (banned 
> in LLVM) and hand-made LLVM RRTI, which I think would be quite a burden for 
> check developers since they'd need to add a new enum to the list, implement a 
> getClass() method, etc (IIUC).
> 
> Previous attempts as this problem created a different register function like:
> 
> ```
> Factory.registerCheck("foo-check", misc::PrimaryCheck, "misc-check")
> ```
> 
> Which I don't like much because the developer needs to spend time digging 
> through the code and docs to see what is the name of the check it's aliasing, 
> which is error-prone and can easily get out of sync in the future. 
> 
> With this macro, all of this is automated and always in sync. But again, if 
> someone has some cleverer magic that would work here I'd love to bring it in 
> :) 
> 
> Since replacing existing lines with the macro is a pretty big change, I'll 
> wait until I get OK from reviewers to avoid spending time if in the end we go 
> for another solution.
> With this macro, all of this is automated and always in sync.

Yup, and this is the primary reason I'm not suggesting a change yet. This 
solves the problem we needed to solve, it's just a bit... crufty, maybe? I 
dunno. I would not spend time finding a replacement yet; if someone has a great 
idea, we can consider it then.


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

https://reviews.llvm.org/D114317

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


[PATCH] D112221: Mark ATOMIC_VAR_INIT and ATOMIC_FLAG_INIT as deprecated

2021-12-16 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

In D112221#3196740 , @tambre wrote:

> In D112221#3195955 , @ldionne wrote:
>
>> @tambre Any appetite for a libc++ patch? :)
>>
>> Otherwise, let me know and I'll put it in my list of things to fix up.
>
> Sure, I can take it up during the weekend.

Thanks a lot! Ping me and I'll review it quickly.


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

https://reviews.llvm.org/D112221

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


[PATCH] D115883: [analyzer][NFC] Change return value of StoreManager::attemptDownCast function from SVal to Optional

2021-12-16 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov created this revision.
ASDenysPetrov added reviewers: xazax.hun, steakhal, NoQ, martong, 
baloghadamsoftware.
ASDenysPetrov added a project: clang.
Herald added subscribers: manas, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet.
ASDenysPetrov requested review of this revision.
Herald added a subscriber: cfe-commits.

Refactor return value of `StoreManager::attemptDownCast` function by removing 
the last parameter `bool &Failed` and replace the return value `SVal` with 
`Optional`.  Make the function consistent with the family of 
`evalDerivedToBase` by renaming it to `evalBaseToDerived`. Aligned the code on 
the call side with these changes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115883

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp

Index: clang/lib/StaticAnalyzer/Core/Store.cpp
===
--- clang/lib/StaticAnalyzer/Core/Store.cpp
+++ clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -314,10 +314,7 @@
   return nullptr;
 }
 
-SVal StoreManager::attemptDownCast(SVal Base, QualType TargetType,
-   bool &Failed) {
-  Failed = false;
-
+Optional StoreManager::evalBaseToDerived(SVal Base, QualType TargetType) {
   const MemRegion *MR = Base.getAsRegion();
   if (!MR)
 return UnknownVal();
@@ -392,7 +389,9 @@
   }
 
   // We failed if the region we ended up with has perfect type info.
-  Failed = isa(MR);
+  if (isa(MR))
+return None;
+
   return UnknownVal();
 }
 
Index: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -439,14 +439,15 @@
 if (CastE->isGLValue())
   resultType = getContext().getPointerType(resultType);
 
-bool Failed = false;
-
-// Check if the value being cast evaluates to 0.
-if (val.isZeroConstant())
-  Failed = true;
-// Else, evaluate the cast.
-else
-  val = getStoreManager().attemptDownCast(val, T, Failed);
+bool Failed = true;
+
+// Check if the value being cast does not evaluates to 0.
+if (!val.isZeroConstant())
+  if (Optional V =
+  StateMgr.getStoreManager().evalBaseToDerived(val, T)) {
+val = *V;
+Failed = false;
+  }
 
 if (Failed) {
   if (T->isReferenceType()) {
@@ -478,14 +479,13 @@
 if (CastE->isGLValue())
   resultType = getContext().getPointerType(resultType);
 
-bool Failed = false;
-
 if (!val.isConstant()) {
-  val = getStoreManager().attemptDownCast(val, T, Failed);
+  Optional V = getStoreManager().evalBaseToDerived(val, T);
+  val = V ? *V : UnknownVal();
 }
 
 // Failed to cast or the result is unknown, fall back to conservative.
-if (Failed || val.isUnknown()) {
+if (val.isUnknown()) {
   val =
 svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
  currBldrCtx->blockCount());
Index: clang/lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -762,9 +762,9 @@
   QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
 
   // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
-  bool Failed;
-  ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, Failed);
-  if (Failed) {
+  Optional V =
+  StateMgr.getStoreManager().evalBaseToDerived(ThisVal, Ty);
+  if (!V.hasValue()) {
 // We might have suffered some sort of placement new earlier, so
 // we're constructing in a completely unexpected storage.
 // Fall back to a generic pointer cast for this-value.
@@ -772,7 +772,8 @@
 const CXXRecordDecl *StaticClass = StaticMD->getParent();
 QualType StaticTy = Ctx.getPointerType(Ctx.getRecordType(StaticClass));
 ThisVal = SVB.evalCast(ThisVal, Ty, StaticTy);
-  }
+  } else
+ThisVal = *V;
 }
 
 if (!ThisVal.isUnknown())
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
@@ -172,9 +172,9 @@
   ///dynamic_cast.
   ///  - We don't know (base is a symbolic region and we don't have
   ///enough info to determine if the cast will succeed at run time).
-  /// The function re

[PATCH] D115883: [analyzer][NFC] Change return value of StoreManager::attemptDownCast function from SVal to Optional

2021-12-16 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115883

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


[PATCH] D112903: [C++20] [Module] Fix bug47116 and implement [module.interface]/p6

2021-12-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/AST/DeclBase.h:616
 
+  bool isInExportDeclContext() const;
+

I think it would be good to add some comments to document the function (as done 
with surrounding code).



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:7793-7794
   "because namespace %1 does not enclose namespace %2">;
+def err_export_non_namespace_scope_name : Error<"cannot export %0 as it is "
+  "not at namespace scope.">;
+def err_redeclaration_non_exported : Error <"cannot export redeclaration %0 
here "





Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:7795-7796
+  "not at namespace scope.">;
+def err_redeclaration_non_exported : Error <"cannot export redeclaration %0 
here "
+  "since the previous declaration is not exported.">;
 def err_invalid_declarator_global_scope : Error<

Both of these tweak the formatting somewhat, but the important thing is 
dropping the trailing punctuation from the diagnostic text.



Comment at: clang/lib/AST/DeclBase.cpp:999
+bool Decl::isInExportDeclContext() const {
+  auto *DC = getLexicalDeclContext();
+





Comment at: clang/lib/Sema/SemaDecl.cpp:1622
 
+// [module.interface]p6:
+// A redeclaration of an entity X is implicitly exported if X was introduced by





Comment at: clang/lib/Sema/SemaDecl.cpp:1643-1645
+// A simple wrapper function to ease the call for
+// CheckRedeclarationModuleOwnership and CheckRedeclarationExported and any
+// other thing needed.





Comment at: clang/lib/Sema/SemaDecl.cpp:5789
+  if (!isa(DC))
+Diag(Loc, diag::err_export_non_namespace_scope_name) << Name;
+  else




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

https://reviews.llvm.org/D112903

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


[PATCH] D114995: clang-tidy: improve the 'modernize-use-default-member-init'

2021-12-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D114995#3183240 , @malcolm.parsons 
wrote:

> In D114995#3180475 , @aaron.ballman 
> wrote:
>
>> was there a reason we didn't cover that case originally or was it an 
>> oversight/left for future work?
>
> It was left for future work - by only considering the initializer list of the 
> default constructor, clang-tidy did not have to work out what to do when the 
> constructors don't agree on what value the member init should have.

Thank you for verifying! @oleg.smolsky -- this would be a very useful test case 
to add, btw.

In D114995#3181486 , @oleg.smolsky 
wrote:

> Sure, adding an option is easy, if that's the consensus. What would you call 
> it?

Since we left this for future work, I don't think we need to add a 
configuration option unless a user finds a need for one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114995

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


[PATCH] D115441: [X86][MS] Add 80bit long double support for Windows

2021-12-16 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

I see, thanks for the info.  Can you please add a targeted LLVM test for long 
double arguments? From what I can tell, the auto-generated 
update_llc_test_checks.py style tests are not a good fit for testing parameter 
passing because they pattern-match away the stack offsets which are relevant to 
the test.

I think it's also worth breaking this into LLVM and clang-side patches:

1. make clang emit x86_fp80 with -mlong-double-80
2. update LLVM datalayout (must affect clang via clang/lib/Basic/Targets/X86.h) 
to align fp80 to 16 bytes in the MSVC environment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115441

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


[PATCH] D115670: Implement some constexpr vector unary operators, fix boolean-ops

2021-12-16 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Note: I think I've done everything requested, so I'm hoping to commit this 
tomorrow 1st thing in order to have it in time for everyone's vacations (and so 
my downstream can get it before the new year), unless I hear objections from 
the other reviewers.


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

https://reviews.llvm.org/D115670

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


[PATCH] D110742: [OpenCL] Add pure attributes to vload builtins

2021-12-16 Thread Stuart Brady 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 rGceb80557e523: [OpenCL] Add pure attribute to vload builtins 
(authored by stuart).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110742

Files:
  clang/lib/Headers/opencl-c.h
  clang/lib/Sema/OpenCLBuiltins.td
  clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl

Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -46,12 +46,19 @@
 typedef char char2 __attribute__((ext_vector_type(2)));
 typedef char char4 __attribute__((ext_vector_type(4)));
 typedef uchar uchar4 __attribute__((ext_vector_type(4)));
+typedef uchar uchar16 __attribute__((ext_vector_type(16)));
 typedef float float4 __attribute__((ext_vector_type(4)));
+typedef float float16 __attribute__((ext_vector_type(16)));
 typedef half half4 __attribute__((ext_vector_type(4)));
 typedef int int2 __attribute__((ext_vector_type(2)));
 typedef int int4 __attribute__((ext_vector_type(4)));
+typedef uint uint2 __attribute__((ext_vector_type(2)));
 typedef uint uint4 __attribute__((ext_vector_type(4)));
 typedef long long2 __attribute__((ext_vector_type(2)));
+typedef long long8 __attribute__((ext_vector_type(8)));
+typedef ulong ulong4 __attribute__((ext_vector_type(4)));
+typedef short short16 __attribute__((ext_vector_type(16)));
+typedef ushort ushort3 __attribute__((ext_vector_type(3)));
 
 typedef int clk_profiling_info;
 #define CLK_PROFILING_COMMAND_EXEC_TIME 0x1
@@ -284,18 +291,27 @@
   global void *global_p;
   private void *private_p;
   size_t s;
+  ulong4 ul4;
+  short16 s16;
+#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
+  ushort3 us3;
+  uchar16 uc16;
+#endif
+  long8 l8;
+  uint2 ui2;
+  float16 f16;
 
-  vload4(s, (const __constant ulong *) constant_p);
-  vload16(s, (const __constant short *) constant_p);
+  ul4 = vload4(s, (const __constant ulong *) constant_p);
+  s16 = vload16(s, (const __constant short *) constant_p);
 
 #if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
-  vload3(s, (const __generic ushort *) generic_p);
-  vload16(s, (const __generic uchar *) generic_p);
+  us3 = vload3(s, (const __generic ushort *) generic_p);
+  uc16 = vload16(s, (const __generic uchar *) generic_p);
 #endif
 
-  vload8(s, (const __global long *) global_p);
-  vload2(s, (const __local uint *) local_p);
-  vload16(s, (const __private float *) private_p);
+  l8 = vload8(s, (const __global long *) global_p);
+  ui2 = vload2(s, (const __local uint *) local_p);
+  f16 = vload16(s, (const __private float *) private_p);
 }
 
 kernel void basic_work_item() {
Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -806,17 +806,17 @@
   foreach AS = addrspaces in {
 foreach VSize = [2, 3, 4, 8, 16] in {
   foreach name = ["vload" # VSize] in {
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
-def : Builtin, Size, PointerType, AS>]>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
   }
   if defStores then {
 foreach name = ["vstore" # VSize] in {
@@ -848,10 +848,10 @@
 
 multiclass VloadVstoreHalf addrspaces, bit defStores> {
   foreach AS = addrspaces in {
-def : Builtin<"vload_half", [Float, Size, PointerType, AS>]>;
+def : Builtin<"vload_half", [Float, Size, PointerType, AS>], Attr.Pure>;
 foreach VSize = [2, 3, 4, 8, 16] in {
   foreach name = ["vload_half" # VSize, "vloada_half" # VSize] in {
-def : Builtin, Size, PointerType, AS>]>;
+def : Builtin, Size, PointerType, AS>], Attr.Pure>;
   }
 }
 if

[clang] ceb8055 - [OpenCL] Add pure attribute to vload builtins

2021-12-16 Thread Stuart Brady via cfe-commits

Author: Stuart Brady
Date: 2021-12-16T18:30:58Z
New Revision: ceb80557e523f1894799ebadd5d985e11ee80461

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

LOG: [OpenCL] Add pure attribute to vload builtins

Use the "pure" attribute (or "readonly") for the vload, vload_half and
vloada_half builtins.

Includes test changes to SemaOpenCL/fdeclare-opencl-builtins.cl to avoid
triggering unused-result warnings.

Reviewed By: svenvh

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

Added: 


Modified: 
clang/lib/Headers/opencl-c.h
clang/lib/Sema/OpenCLBuiltins.td
clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl

Removed: 




diff  --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h
index 32af848a94c4f..77a7a8b9bb3a1 100644
--- a/clang/lib/Headers/opencl-c.h
+++ b/clang/lib/Headers/opencl-c.h
@@ -11190,305 +11190,305 @@ half16 __ovld __cnfn select(half16 a, half16 b, 
ushort16 c);
  * 64-bit aligned if gentype is long, ulong, double.
  */
 
-char2 __ovld vload2(size_t offset, const __constant char *p);
-uchar2 __ovld vload2(size_t offset, const __constant uchar *p);
-short2 __ovld vload2(size_t offset, const __constant short *p);
-ushort2 __ovld vload2(size_t offset, const __constant ushort *p);
-int2 __ovld vload2(size_t offset, const __constant int *p);
-uint2 __ovld vload2(size_t offset, const __constant uint *p);
-long2 __ovld vload2(size_t offset, const __constant long *p);
-ulong2 __ovld vload2(size_t offset, const __constant ulong *p);
-float2 __ovld vload2(size_t offset, const __constant float *p);
-char3 __ovld vload3(size_t offset, const __constant char *p);
-uchar3 __ovld vload3(size_t offset, const __constant uchar *p);
-short3 __ovld vload3(size_t offset, const __constant short *p);
-ushort3 __ovld vload3(size_t offset, const __constant ushort *p);
-int3 __ovld vload3(size_t offset, const __constant int *p);
-uint3 __ovld vload3(size_t offset, const __constant uint *p);
-long3 __ovld vload3(size_t offset, const __constant long *p);
-ulong3 __ovld vload3(size_t offset, const __constant ulong *p);
-float3 __ovld vload3(size_t offset, const __constant float *p);
-char4 __ovld vload4(size_t offset, const __constant char *p);
-uchar4 __ovld vload4(size_t offset, const __constant uchar *p);
-short4 __ovld vload4(size_t offset, const __constant short *p);
-ushort4 __ovld vload4(size_t offset, const __constant ushort *p);
-int4 __ovld vload4(size_t offset, const __constant int *p);
-uint4 __ovld vload4(size_t offset, const __constant uint *p);
-long4 __ovld vload4(size_t offset, const __constant long *p);
-ulong4 __ovld vload4(size_t offset, const __constant ulong *p);
-float4 __ovld vload4(size_t offset, const __constant float *p);
-char8 __ovld vload8(size_t offset, const __constant char *p);
-uchar8 __ovld vload8(size_t offset, const __constant uchar *p);
-short8 __ovld vload8(size_t offset, const __constant short *p);
-ushort8 __ovld vload8(size_t offset, const __constant ushort *p);
-int8 __ovld vload8(size_t offset, const __constant int *p);
-uint8 __ovld vload8(size_t offset, const __constant uint *p);
-long8 __ovld vload8(size_t offset, const __constant long *p);
-ulong8 __ovld vload8(size_t offset, const __constant ulong *p);
-float8 __ovld vload8(size_t offset, const __constant float *p);
-char16 __ovld vload16(size_t offset, const __constant char *p);
-uchar16 __ovld vload16(size_t offset, const __constant uchar *p);
-short16 __ovld vload16(size_t offset, const __constant short *p);
-ushort16 __ovld vload16(size_t offset, const __constant ushort *p);
-int16 __ovld vload16(size_t offset, const __constant int *p);
-uint16 __ovld vload16(size_t offset, const __constant uint *p);
-long16 __ovld vload16(size_t offset, const __constant long *p);
-ulong16 __ovld vload16(size_t offset, const __constant ulong *p);
-float16 __ovld vload16(size_t offset, const __constant float *p);
+char2 __ovld __purefn vload2(size_t offset, const __constant char *p);
+uchar2 __ovld __purefn vload2(size_t offset, const __constant uchar *p);
+short2 __ovld __purefn vload2(size_t offset, const __constant short *p);
+ushort2 __ovld __purefn vload2(size_t offset, const __constant ushort *p);
+int2 __ovld __purefn vload2(size_t offset, const __constant int *p);
+uint2 __ovld __purefn vload2(size_t offset, const __constant uint *p);
+long2 __ovld __purefn vload2(size_t offset, const __constant long *p);
+ulong2 __ovld __purefn vload2(size_t offset, const __constant ulong *p);
+float2 __ovld __purefn vload2(size_t offset, const __constant float *p);
+char3 __ovld __purefn vload3(size_t offset, const __constant char *p);
+uchar3 __ovld __purefn vload3(size_t offset, const __constant uchar *p);
+short3 __ovld __purefn vload3(size_t offset, const __constant short *p);
+ushor

[PATCH] D115456: Implement on-demand TLS initialization for Microsoft CXX ABI

2021-12-16 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

I probably don't have time to review this, so let me redirect to @hans.




Comment at: clang/lib/CodeGen/MicrosoftCXXABI.cpp:2400
 
+static llvm::GlobalValue *getTlsGuardVar(CodeGenModule &CGM) {
+  llvm::Type *VTy = llvm::Type::getInt8Ty(CGM.getLLVMContext());

My understanding is that every DLL has exactly one `__tls_guard` variable. All 
TLS variables in a DLL are initialized as soon as a thread accesses one TLS 
variable for a DLL. Is that accurate? Can you add comments about the way this 
is intended to work here?


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

https://reviews.llvm.org/D115456

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


[libunwind] 1c4867e - [libunwind] Provide a way to conveniently install libunwind headers

2021-12-16 Thread Louis Dionne via cfe-commits

Author: PoYao Chang
Date: 2021-12-16T13:32:40-05:00
New Revision: 1c4867e6fc507fe6e81cfc0e3c7148307b4b7433

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

LOG: [libunwind] Provide a way to conveniently install libunwind headers

This adds a CMake option (defaults to OFF to not be intrusive) to activate
2 new targets `install-unwind-headers` and `install-unwind-headers-stripped`.
So, for example:

  cmake -S runtimes -B build -G Ninja \
-DLLVM_ENABLE_RUNTIMES='libunwind' \
-DLIBUNWIND_INSTALL_HEADERS=ON

And then, `ninja -C build install-unwind` would install headers in addition
to good ol' dylibs and archives, i.e., targets `install-unwind*` `DEPENDS`
on `install-unwind-headers*`. On the other hand,
`ninja -C build install-unwind-headers` gives you headers only.

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

Added: 
libunwind/include/CMakeLists.txt

Modified: 
libunwind/CMakeLists.txt
libunwind/src/CMakeLists.txt

Removed: 




diff  --git a/libunwind/CMakeLists.txt b/libunwind/CMakeLists.txt
index a63dc453ffb6c..eb478e4e7730c 100644
--- a/libunwind/CMakeLists.txt
+++ b/libunwind/CMakeLists.txt
@@ -78,6 +78,7 @@ option(LIBUNWIND_INCLUDE_TESTS "Build the libunwind tests." 
${LLVM_INCLUDE_TESTS
 option(LIBUNWIND_IS_BAREMETAL "Build libunwind for baremetal targets." OFF)
 option(LIBUNWIND_USE_FRAME_HEADER_CACHE "Cache frame headers for unwinding. 
Requires locking dl_iterate_phdr." OFF)
 option(LIBUNWIND_REMEMBER_HEAP_ALLOC "Use heap instead of the stack for 
.cfi_remember_state." OFF)
+option(LIBUNWIND_INSTALL_HEADERS "Install the libunwind headers." OFF)
 
 set(LIBUNWIND_LIBDIR_SUFFIX "${LLVM_LIBDIR_SUFFIX}" CACHE STRING
 "Define suffix of library directory name (32/64)")
@@ -372,7 +373,7 @@ endif()
 # Setup Source Code
 
#===
 
-include_directories(include)
+add_subdirectory(include)
 
 add_subdirectory(src)
 

diff  --git a/libunwind/include/CMakeLists.txt 
b/libunwind/include/CMakeLists.txt
new file mode 100644
index 0..c3bb1dd0f69fa
--- /dev/null
+++ b/libunwind/include/CMakeLists.txt
@@ -0,0 +1,31 @@
+set(files
+__libunwind_config.h
+libunwind.h
+mach-o/compact_unwind_encoding.h
+unwind_arm_ehabi.h
+unwind_itanium.h
+unwind.h
+)
+
+add_library(unwind-headers INTERFACE)
+target_include_directories(unwind-headers INTERFACE 
${CMAKE_CURRENT_SOURCE_DIR})
+
+if(LIBUNWIND_INSTALL_HEADERS)
+  foreach(file ${files})
+get_filename_component(dir ${file} DIRECTORY)
+install(FILES ${file}
+  DESTINATION "include/${dir}"
+  COMPONENT unwind-headers
+  PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ
+)
+  endforeach()
+
+  if(NOT CMAKE_CONFIGURATION_TYPES)
+add_custom_target(install-unwind-headers
+  DEPENDS unwind-headers
+  COMMAND "${CMAKE_COMMAND}"
+  -DCMAKE_INSTALL_COMPONENT=unwind-headers
+  -P "${LIBUNWIND_BINARY_DIR}/cmake_install.cmake")
+add_custom_target(install-unwind-headers-stripped DEPENDS 
install-unwind-headers)
+  endif()
+endif()

diff  --git a/libunwind/src/CMakeLists.txt b/libunwind/src/CMakeLists.txt
index 41513ddfff1f5..710198550a061 100644
--- a/libunwind/src/CMakeLists.txt
+++ b/libunwind/src/CMakeLists.txt
@@ -133,7 +133,8 @@ if (LIBUNWIND_ENABLE_SHARED)
   else()
 target_compile_options(unwind_shared PRIVATE -fno-rtti)
   endif()
-  target_link_libraries(unwind_shared PRIVATE ${LIBUNWIND_LIBRARIES})
+  target_link_libraries(unwind_shared PRIVATE ${LIBUNWIND_LIBRARIES}
+  PRIVATE unwind-headers)
   set_target_properties(unwind_shared
 PROPERTIES
   CXX_EXTENSIONS OFF
@@ -160,7 +161,8 @@ if (LIBUNWIND_ENABLE_STATIC)
   else()
 target_compile_options(unwind_static PRIVATE -fno-rtti)
   endif()
-  target_link_libraries(unwind_static PRIVATE ${LIBUNWIND_LIBRARIES})
+  target_link_libraries(unwind_static PRIVATE ${LIBUNWIND_LIBRARIES}
+  PRIVATE unwind-headers)
   set_target_properties(unwind_static
 PROPERTIES
   CXX_EXTENSIONS OFF
@@ -207,4 +209,8 @@ if (NOT CMAKE_CONFIGURATION_TYPES AND 
LIBUNWIND_INSTALL_LIBRARY)
 -DCMAKE_INSTALL_COMPONENT=unwind
 -DCMAKE_INSTALL_DO_STRIP=1
 -P "${LIBUNWIND_BINARY_DIR}/cmake_install.cmake")
+  if(LIBUNWIND_INSTALL_HEADERS)
+add_dependencies(install-unwind install-unwind-headers)
+add_dependencies(install-unwind-stripped install-unwind-headers-stripped)
+  endif()
 endif()



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


[PATCH] D112453: [Sema] When dereferencing a pointer of dependent type, infer the result type.

2021-12-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:10546-10548
+  if (PointeeTy->isDependentType()) {
+return true;
+  }





Comment at: clang/lib/Sema/SemaExpr.cpp:13824
 SourceLocation OpLoc) {
-  if (Op->isTypeDependent())
+  if (Op->isTypeDependent() && !Op->getType()->isPointerType())
 return S.Context.DependentTy;

One thing that makes me a bit uncomfortable is that the logic for these used to 
be far more understandable when it was just checking for a dependent type. Now 
we need to sprinkle "and not a pointer type" in places, but it's not 
particularly clear as to why for a naïve reader of the code.

I wonder if we want some sort of type predicate `isDeferrablyDependentType()` 
or something along those lines, or whether that's not really plausible? 
Basically, I'm hoping to find a way that, as a code reviewer, I can more easily 
spot places where `isTypeDependent()` should really be caring about type 
dependent pointers as a special case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112453

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


[PATCH] D109885: [MLIR][[amdgpu-arch]][OpenMP] Remove direct dependency on /opt/rocm

2021-12-16 Thread Ethan Stewart via Phabricator via cfe-commits
estewart08 added a comment.

In D109885#3194819 , @ronlieb wrote:

> @estewart08 thoughts on a good CMAKE variable to allow users to define 
> equivalent of /opt/rocm  ?   and not use environment variable inside the 
> cmake file.

I would be ok with the following, without the check for ENV{ROCM_PATH}. The 
user has the option to set -DROCM_PATH=$ROCM_PATH or -DCMAKE_PREFIX_PATH.

  find_package(hsa-runtime64 QUIET 1.2.0 HINTS ${CMAKE_INSTALL_PREFIX} PATH 
${ROCM_PATH})


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109885

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


[PATCH] D109885: [MLIR][[amdgpu-arch]][OpenMP] Remove direct dependency on /opt/rocm

2021-12-16 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm requested changes to this revision.
arsenm added a comment.

Dropping the default install location from the default search hint is entirely 
unreasonable


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109885

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


[PATCH] D111100: enable plugins for clang-tidy

2021-12-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp:392-394
+  cl::Option *load_opt = cl::getRegisteredOptions().lookup("load");
+  if (load_opt)
+load_opt->addCategory(ClangTidyCategory);





Comment at: clang-tools-extra/docs/clang-tidy/Contributing.rst:421-424
+If you want to develop this out-of-tree, the steps above are the largely same.
+External to the clang-tidy build system, put all of the new code into a single
+shared library. Build and link it against llvm, while allowing some symbols to
+be undefined during linking, almost exactly as you would define a clang plugin.

I wordsmithed a bit and this should be similar to what you already had. I did 
remove the "while allowing some symbols to be undefined during linking" bit 
because I wasn't certain what that was about.



Comment at: clang-tools-extra/docs/clang-tidy/Contributing.rst:426-427
+
+Then we can run it by passing `-load` to `clang-tidy`, in addition to the name
+of our new checks.
+





Comment at: clang-tools-extra/docs/clang-tidy/index.rst:223
+ Load the dynamic object ``plugin``. This
+ object should register new static 
analyzer or clang-tidy passes. Once loaded, the object
+ will add new command line options to run





Comment at: clang-tools-extra/test/clang-tidy/CTTestTidyModule.cpp:24-25
+
+  //void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  //void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+

Shouldn't these functions be overloaded? We don't need it to be particularly 
functional, but the plugin should demonstrate that it works and can be run by 
clang-tidy (not just loaded and listed as a check).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D00

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


[PATCH] D109885: [MLIR][[amdgpu-arch]][OpenMP] Remove direct dependency on /opt/rocm

2021-12-16 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

In D109885#3198232 , @arsenm wrote:

> Dropping the default install location from the default search hint is 
> entirely unreasonable

That seems to be the feature request, though I haven't gone through the jira 
web to work out what's going on here.

We can either have opt-in to somewhere other than CMAKE_INSTALL_PREFIX, which I 
think Ethan's suggestion does (not clear whether PATH between the two variables 
is semantically important), or we could have opt-out for people who want to be 
sure they aren't picking up something in /opt/rocm.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109885

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


[PATCH] D109885: [MLIR][[amdgpu-arch]][OpenMP] Remove direct dependency on /opt/rocm

2021-12-16 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

In D109885#3198290 , @JonChesterfield 
wrote:

> In D109885#3198232 , @arsenm wrote:
>
>> Dropping the default install location from the default search hint is 
>> entirely unreasonable
>
> That seems to be the feature request, though I haven't gone through the jira 
> web to work out what's going on here.

This isn't a feature, it's the introduction of a bug. It degrades the usability 
of the build. If you want an explicit version, that's what the search order 
process is for.

> We can either have opt-in to somewhere other than CMAKE_INSTALL_PREFIX, which 
> I think Ethan's suggestion does (not clear whether PATH between the two 
> variables is semantically important), or we could have opt-out for people who 
> want to be sure they aren't picking up something in /opt/rocm.

This isn't how search paths work. By default, the fallback should always find 
the default location


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109885

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


[PATCH] D109885: [MLIR][[amdgpu-arch]][OpenMP] Remove direct dependency on /opt/rocm

2021-12-16 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/tools/amdgpu-arch/CMakeLists.txt:13
+
+find_package(hsa-runtime64 QUIET 1.2.0 HINTS ${CMAKE_INSTALL_PREFIX} PATH 
${ROCM_PATH})
 if (NOT ${hsa-runtime64_FOUND})

I also think CMAKE_INSTALL_PREFIX in the search hints is bad practice. I don't 
recall ever seeing a project do this. Depending on the install path for 
anything leads to flaky builds


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109885

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


[PATCH] D109885: [MLIR][[amdgpu-arch]][OpenMP] Remove direct dependency on /opt/rocm

2021-12-16 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

In D109885#3198296 , @arsenm wrote:

> This isn't a feature, it's the introduction of a bug.

It would regress people depending on the implicit pickup of /opt/rocm, leaving 
them with a straightforward workaround of setting the cmake variable.

The inverse, where we look in /opt/rocm unless that's overridden (perhaps by 
the empty string), achieves much the same effect without breaking anyone using 
trunk with a rocm install.

I'm very mistrusting of mixing a rocm toolchain with a trunk toolchain as 
they're both quite keen on runpath and LD_LIBRARY_PATH to find internal 
components. That makes it very easy to accidentally mix the two together into 
something that doesn't work so personal preference is to rip out the /opt/rocm 
search path for HSA entirely and encourage people to build it from source.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109885

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


  1   2   >