[clang] 7ff0bf5 - [RISCV][NFC] Refactor RISC-V vector intrinsic utils.

2022-05-16 Thread Kito Cheng via cfe-commits

Author: Kito Cheng
Date: 2022-05-16T15:13:05+08:00
New Revision: 7ff0bf576b841d5418c0fb1c4b94f16c6205e7d9

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

LOG: [RISCV][NFC] Refactor RISC-V vector intrinsic utils.

This patch is preparation for D111617, use class/struct/enum rather than 
char/StringRef to present internal information as possible, that provide more 
compact way to store those info and also easier to serialize/deserialize.

And also that improve readability of the code, e.g. "v" vs TypeProfile::Vector.

Reviewed By: khchen

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

Added: 


Modified: 
clang/include/clang/Support/RISCVVIntrinsicUtils.h
clang/lib/Support/RISCVVIntrinsicUtils.cpp
clang/utils/TableGen/RISCVVEmitter.cpp

Removed: 




diff  --git a/clang/include/clang/Support/RISCVVIntrinsicUtils.h 
b/clang/include/clang/Support/RISCVVIntrinsicUtils.h
index 1a4947d0c3df3..f1f06ba60786f 100644
--- a/clang/include/clang/Support/RISCVVIntrinsicUtils.h
+++ b/clang/include/clang/Support/RISCVVIntrinsicUtils.h
@@ -9,7 +9,10 @@
 #ifndef CLANG_SUPPORT_RISCVVINTRINSICUTILS_H
 #define CLANG_SUPPORT_RISCVVINTRINSICUTILS_H
 
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/BitmaskEnum.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include 
 #include 
@@ -18,9 +21,133 @@
 namespace clang {
 namespace RISCV {
 
-using BasicType = char;
 using VScaleVal = llvm::Optional;
 
+// Modifier for vector type.
+enum class VectorTypeModifier : uint8_t {
+  NoModifier,
+  Widening2XVector,
+  Widening4XVector,
+  Widening8XVector,
+  MaskVector,
+  Log2EEW3,
+  Log2EEW4,
+  Log2EEW5,
+  Log2EEW6,
+  FixedSEW8,
+  FixedSEW16,
+  FixedSEW32,
+  FixedSEW64,
+  LFixedLog2LMULN3,
+  LFixedLog2LMULN2,
+  LFixedLog2LMULN1,
+  LFixedLog2LMUL0,
+  LFixedLog2LMUL1,
+  LFixedLog2LMUL2,
+  LFixedLog2LMUL3,
+  SFixedLog2LMULN3,
+  SFixedLog2LMULN2,
+  SFixedLog2LMULN1,
+  SFixedLog2LMUL0,
+  SFixedLog2LMUL1,
+  SFixedLog2LMUL2,
+  SFixedLog2LMUL3,
+};
+
+// Similar to basic type but used to describe what's kind of type related to
+// basic vector type, used to compute type info of arguments.
+enum class BaseTypeModifier : uint8_t {
+  Invalid,
+  Scalar,
+  Vector,
+  Void,
+  SizeT,
+  Ptr
diff ,
+  UnsignedLong,
+  SignedLong,
+};
+
+// Modifier for type, used for both scalar and vector types.
+enum class TypeModifier : uint8_t {
+  NoModifier = 0,
+  Pointer = 1 << 0,
+  Const = 1 << 1,
+  Immediate = 1 << 2,
+  UnsignedInteger = 1 << 3,
+  SignedInteger = 1 << 4,
+  Float = 1 << 5,
+  // LMUL1 should be kind of VectorTypeModifier, but that might come with
+  // Widening2XVector for widening reduction.
+  // However that might require VectorTypeModifier become bitmask rather than
+  // simple enum, so we decide keek LMUL1 in TypeModifier for code size
+  // optimization of clang binary size.
+  LMUL1 = 1 << 6,
+  MaxOffset = 6,
+  LLVM_MARK_AS_BITMASK_ENUM(LMUL1),
+};
+
+// PrototypeDescriptor is used to compute type info of arguments or return
+// value.
+struct PrototypeDescriptor {
+  constexpr PrototypeDescriptor() = default;
+  constexpr PrototypeDescriptor(
+  BaseTypeModifier PT,
+  VectorTypeModifier VTM = VectorTypeModifier::NoModifier,
+  TypeModifier TM = TypeModifier::NoModifier)
+  : PT(static_cast(PT)), VTM(static_cast(VTM)),
+TM(static_cast(TM)) {}
+  constexpr PrototypeDescriptor(uint8_t PT, uint8_t VTM, uint8_t TM)
+  : PT(PT), VTM(VTM), TM(TM) {}
+
+  uint8_t PT = static_cast(BaseTypeModifier::Invalid);
+  uint8_t VTM = static_cast(VectorTypeModifier::NoModifier);
+  uint8_t TM = static_cast(TypeModifier::NoModifier);
+
+  bool operator!=(const PrototypeDescriptor &PD) const {
+return PD.PT != PT || PD.VTM != VTM || PD.TM != TM;
+  }
+  bool operator>(const PrototypeDescriptor &PD) const {
+return !(PD.PT <= PT && PD.VTM <= VTM && PD.TM <= TM);
+  }
+
+  static const PrototypeDescriptor Mask;
+  static const PrototypeDescriptor Vector;
+  static const PrototypeDescriptor VL;
+  static llvm::Optional
+  parsePrototypeDescriptor(llvm::StringRef PrototypeStr);
+};
+
+llvm::SmallVector
+parsePrototypes(llvm::StringRef Prototypes);
+
+// Basic type of vector type.
+enum class BasicType : uint8_t {
+  Unknown = 0,
+  Int8 = 1 << 0,
+  Int16 = 1 << 1,
+  Int32 = 1 << 2,
+  Int64 = 1 << 3,
+  Float16 = 1 << 4,
+  Float32 = 1 << 5,
+  Float64 = 1 << 6,
+  MaxOffset = 6,
+  LLVM_MARK_AS_BITMASK_ENUM(Float64),
+};
+
+// Type of vector type.
+enum ScalarTypeKind : uint8_t {
+  Void,
+  Size_t,
+  Ptr
diff _t,
+  UnsignedLong,
+  SignedLong,
+  Boolean,
+  SignedInteger,
+  UnsignedInteger,
+  Float,
+  Invalid,
+};
+
 // Exponential LMUL
 struct LMULType {
   int Log2LMUL;
@@ -

[PATCH] D124730: [RISCV][NFC] Refactor RISC-V vector intrinsic utils.

2022-05-16 Thread Kito Cheng via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7ff0bf576b84: [RISCV][NFC] Refactor RISC-V vector intrinsic 
utils. (authored by kito-cheng).

Changed prior to commit:
  https://reviews.llvm.org/D124730?vs=429184&id=429620#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124730

Files:
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  clang/utils/TableGen/RISCVVEmitter.cpp

Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -32,9 +32,6 @@
 class RVVEmitter {
 private:
   RecordKeeper &Records;
-  // Concat BasicType, LMUL and Proto as key
-  StringMap LegalTypes;
-  StringSet<> IllegalTypes;
 
 public:
   RVVEmitter(RecordKeeper &R) : Records(R) {}
@@ -48,20 +45,11 @@
   /// Emit all the information needed to map builtin -> LLVM IR intrinsic.
   void createCodeGen(raw_ostream &o);
 
-  std::string getSuffixStr(char Type, int Log2LMUL, StringRef Prototypes);
-
 private:
   /// Create all intrinsics and add them to \p Out
   void createRVVIntrinsics(std::vector> &Out);
   /// Print HeaderCode in RVVHeader Record to \p Out
   void printHeaderCode(raw_ostream &OS);
-  /// Compute output and input types by applying different config (basic type
-  /// and LMUL with type transformers). It also record result of type in legal
-  /// or illegal set to avoid compute the  same config again. The result maybe
-  /// have illegal RVVType.
-  Optional computeTypes(BasicType BT, int Log2LMUL, unsigned NF,
-  ArrayRef PrototypeSeq);
-  Optional computeType(BasicType BT, int Log2LMUL, StringRef Proto);
 
   /// Emit Acrh predecessor definitions and body, assume the element of Defs are
   /// sorted by extension.
@@ -73,14 +61,39 @@
   // non-empty string.
   bool emitMacroRestrictionStr(RISCVPredefinedMacroT PredefinedMacros,
raw_ostream &o);
-  // Slice Prototypes string into sub prototype string and process each sub
-  // prototype string individually in the Handler.
-  void parsePrototypes(StringRef Prototypes,
-   std::function Handler);
 };
 
 } // namespace
 
+static BasicType ParseBasicType(char c) {
+  switch (c) {
+  case 'c':
+return BasicType::Int8;
+break;
+  case 's':
+return BasicType::Int16;
+break;
+  case 'i':
+return BasicType::Int32;
+break;
+  case 'l':
+return BasicType::Int64;
+break;
+  case 'x':
+return BasicType::Float16;
+break;
+  case 'f':
+return BasicType::Float32;
+break;
+  case 'd':
+return BasicType::Float64;
+break;
+
+  default:
+return BasicType::Unknown;
+  }
+}
+
 void emitCodeGenSwitchBody(const RVVIntrinsic *RVVI, raw_ostream &OS) {
   if (!RVVI->getIRName().empty())
 OS << "  ID = Intrinsic::riscv_" + RVVI->getIRName() + ";\n";
@@ -202,24 +215,31 @@
   constexpr int Log2LMULs[] = {-3, -2, -1, 0, 1, 2, 3};
   // Print RVV boolean types.
   for (int Log2LMUL : Log2LMULs) {
-auto T = computeType('c', Log2LMUL, "m");
+auto T = RVVType::computeType(BasicType::Int8, Log2LMUL,
+  PrototypeDescriptor::Mask);
 if (T.hasValue())
   printType(T.getValue());
   }
   // Print RVV int/float types.
   for (char I : StringRef("csil")) {
+BasicType BT = ParseBasicType(I);
 for (int Log2LMUL : Log2LMULs) {
-  auto T = computeType(I, Log2LMUL, "v");
+  auto T = RVVType::computeType(BT, Log2LMUL, PrototypeDescriptor::Vector);
   if (T.hasValue()) {
 printType(T.getValue());
-auto UT = computeType(I, Log2LMUL, "Uv");
+auto UT = RVVType::computeType(
+BT, Log2LMUL,
+PrototypeDescriptor(BaseTypeModifier::Vector,
+VectorTypeModifier::NoModifier,
+TypeModifier::UnsignedInteger));
 printType(UT.getValue());
   }
 }
   }
   OS << "#if defined(__riscv_zvfh)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = computeType('x', Log2LMUL, "v");
+auto T = RVVType::computeType(BasicType::Float16, Log2LMUL,
+  PrototypeDescriptor::Vector);
 if (T.hasValue())
   printType(T.getValue());
   }
@@ -227,7 +247,8 @@
 
   OS << "#if defined(__riscv_f)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = computeType('f', Log2LMUL, "v");
+auto T = RVVType::computeType(BasicType::Float32, Log2LMUL,
+  PrototypeDescriptor::Vector);
 if (T.hasValue())
   printType(T.getValue());
   }
@@ -235,7 +256,8 @@
 
   OS << "#if defined(__riscv_d)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = computeType('d', Log2LMUL, "v");
+auto T = RVVType::computeType(BasicType::Float6

[PATCH] D122126: [LoopVectorize] Don't interleave when the number of runtime checks exceeds the threshold

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

Still LGTM, thanks! The remaining suggestion can be addressed directly before 
committing the patch.




Comment at: llvm/lib/Transforms/Vectorize/LoopVectorizationPlanner.h:324
+  /// Check if the number of runtime checks exceeds the threshold.
+  bool requiresTooManyRuntimeChecks();
+

nit: could be turned  into `const` if possible.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122126

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


[clang] e20bc89 - [clang-format] Fix PointerAlignment: Right not working with tab indentation.

2022-05-16 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-05-16T09:42:20+02:00
New Revision: e20bc892b6facc56fffc012929157888bb798bed

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

LOG: [clang-format] Fix PointerAlignment: Right not working with tab 
indentation.

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

Given configuration:
```
UseTab: Always
PointerAlignment: Right
AlignConsecutiveDeclarations: true
```

Before, the pointer was misaligned in this code:
```
void f() {
unsigned long long big;
char  *ptr; // misaligned
inti;
}
```

That was due to the fact that when handling right-aligned pointers, the Spaces 
were changed but StartOfTokenColumn was not.

Also, a tab was used not only for indentation but for spacing too when using 
`UseTab: ForIndentation` config option:
```
void f() {
unsigned long long big;
char  *ptr; // \t after char
inti;
}
```

Reviewed By: owenpan

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

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 8563312b45bb0..673af51d2daae 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -432,6 +432,7 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
--Previous) {
 Changes[Previous + 1].Spaces -= Shift;
 Changes[Previous].Spaces += Shift;
+Changes[Previous].StartOfTokenColumn += Shift;
   }
 }
   }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index e4fea9085b574..44da34001f990 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -14161,6 +14161,21 @@ TEST_F(FormatTest, ConfigurableUseOfTab) {
"int ; // x\n",
Tab);
 
+  FormatStyle TabAlignment = Tab;
+  TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("unsigned long long big;\n"
+   "char*\t\t   ptr;",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("unsigned long long big;\n"
+   "char *\t\t   ptr;",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("unsigned long long big;\n"
+   "char\t\t  *ptr;",
+   TabAlignment);
+
   Tab.TabWidth = 4;
   Tab.IndentWidth = 8;
   verifyFormat("class TabWidth4Indent8 {\n"
@@ -14203,6 +14218,26 @@ TEST_F(FormatTest, ConfigurableUseOfTab) {
" \t  */",
Tab));
 
+  TabAlignment.UseTab = FormatStyle::UT_ForIndentation;
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar*  ptr;\n"
+   "}",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar * ptr;\n"
+   "}",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar  *ptr;\n"
+   "}",
+   TabAlignment);
+
   Tab.UseTab = FormatStyle::UT_ForIndentation;
   verifyFormat("{\n"
"\t();\n"



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


[PATCH] D125528: [clang-format] Fix PointerAlignment: Right not working with tab indentation.

2022-05-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.
curdeius marked an inline comment as done.
Closed by commit rGe20bc892b6fa: [clang-format] Fix PointerAlignment: Right not 
working with tab indentation. (authored by curdeius).

Changed prior to commit:
  https://reviews.llvm.org/D125528?vs=429178&id=429629#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125528

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
@@ -14161,6 +14161,21 @@
"int ; // x\n",
Tab);
 
+  FormatStyle TabAlignment = Tab;
+  TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("unsigned long long big;\n"
+   "char*\t\t   ptr;",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("unsigned long long big;\n"
+   "char *\t\t   ptr;",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("unsigned long long big;\n"
+   "char\t\t  *ptr;",
+   TabAlignment);
+
   Tab.TabWidth = 4;
   Tab.IndentWidth = 8;
   verifyFormat("class TabWidth4Indent8 {\n"
@@ -14203,6 +14218,26 @@
" \t  */",
Tab));
 
+  TabAlignment.UseTab = FormatStyle::UT_ForIndentation;
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar*  ptr;\n"
+   "}",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar * ptr;\n"
+   "}",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar  *ptr;\n"
+   "}",
+   TabAlignment);
+
   Tab.UseTab = FormatStyle::UT_ForIndentation;
   verifyFormat("{\n"
"\t();\n"
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -432,6 +432,7 @@
--Previous) {
 Changes[Previous + 1].Spaces -= Shift;
 Changes[Previous].Spaces += Shift;
+Changes[Previous].StartOfTokenColumn += Shift;
   }
 }
   }


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -14161,6 +14161,21 @@
"int ; // x\n",
Tab);
 
+  FormatStyle TabAlignment = Tab;
+  TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("unsigned long long big;\n"
+   "char*\t\t   ptr;",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("unsigned long long big;\n"
+   "char *\t\t   ptr;",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("unsigned long long big;\n"
+   "char\t\t  *ptr;",
+   TabAlignment);
+
   Tab.TabWidth = 4;
   Tab.IndentWidth = 8;
   verifyFormat("class TabWidth4Indent8 {\n"
@@ -14203,6 +14218,26 @@
" \t  */",
Tab));
 
+  TabAlignment.UseTab = FormatStyle::UT_ForIndentation;
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar*  ptr;\n"
+   "}",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar * ptr;\n"
+   "}",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar  *ptr;\n"
+   "}",
+   TabAlignment);
+
   Tab.UseTab = FormatStyle::UT_ForIndentation;
   verifyFormat("{\n"
"\t();\n"
Index: clang/lib/Format/WhitespaceManager.cpp

[PATCH] D124688: [clangd] parse all make_unique-like functions in preamble

2022-05-16 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj updated this revision to Diff 429630.
upsj marked an inline comment as done.
upsj added a comment.

remove std::forward bodies from diagnostic tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124688

Files:
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Compiler.h
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/tool/Check.cpp
  clang-tools-extra/clangd/tool/ClangdMain.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp
  clang-tools-extra/clangd/unittests/TestTU.h

Index: clang-tools-extra/clangd/unittests/TestTU.h
===
--- clang-tools-extra/clangd/unittests/TestTU.h
+++ clang-tools-extra/clangd/unittests/TestTU.h
@@ -81,7 +81,7 @@
   // By default, build() will report Error diagnostics as GTest errors.
   // Suppress this behavior by adding an 'error-ok' comment to the code.
   // The result will always have getDiagnostics() populated.
-  ParsedAST build() const;
+  ParsedAST build(ParseOptions Opts = {}) const;
   std::shared_ptr
   preamble(PreambleParsedCallback PreambleCallback = nullptr) const;
   ParseInputs inputs(MockFS &FS) const;
Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -104,9 +104,10 @@
   /*StoreInMemory=*/true, PreambleCallback);
 }
 
-ParsedAST TestTU::build() const {
+ParsedAST TestTU::build(ParseOptions Opts) const {
   MockFS FS;
   auto Inputs = inputs(FS);
+  Inputs.Opts = Opts;
   StoreDiags Diags;
   auto CI = buildCompilerInvocation(Inputs, Diags);
   assert(CI && "Failed to build compilation invocation.");
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -389,7 +389,7 @@
 namespace std {
 // These mocks aren't quite right - we omit unique_ptr for simplicity.
 // forward is included to show its body is not needed to get the diagnostic.
-template  T&& forward(T& t) { return static_cast(t); }
+template  T&& forward(T& t);
 template  T* make_unique(A&&... args) {
return new T(std::forward(args)...);
 }
@@ -402,6 +402,31 @@
"no matching constructor for initialization of 'S'")));
 }
 
+TEST(DiagnosticTest, MakeShared) {
+  // We usually miss diagnostics from header functions as we don't parse them.
+  // std::make_shared is only parsed when --parse-forwarding-functions is set
+  Annotations Main(R"cpp(
+struct S { S(char*); };
+auto x = std::[[make_shared]](42); // error-ok
+  )cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.HeaderCode = R"cpp(
+namespace std {
+// These mocks aren't quite right - we omit shared_ptr for simplicity.
+// forward is included to show its body is not needed to get the diagnostic.
+template  T&& forward(T& t);
+template  T* make_shared(A&&... args) {
+   return new T(std::forward(args)...);
+}
+}
+  )cpp";
+  EXPECT_THAT(
+  *TU.build({/*PreambleParseForwardingFunctions=*/true}).getDiagnostics(),
+  UnorderedElementsAre(Diag(
+  Main.range(), "in template: "
+"no matching constructor for initialization of 'S'")));
+}
+
 TEST(DiagnosticTest, NoMultipleDiagnosticInFlight) {
   Annotations Main(R"cpp(
 template  struct Foo {
Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -498,6 +498,14 @@
   Hidden,
   init(ClangdServer::Options().UseDirtyHeaders)};
 
+opt PreambleParseForwardingFunctions{
+"parse-forwarding-functions",
+cat(Misc),
+desc("Parse all emplace-like functions in included headers"),
+Hidden,
+init(ParseOptions().PreambleParseForwardingFunctions),
+};
+
 #if defined(__GLIBC__) && CLANGD_MALLOC_TRIM
 opt EnableMallocTrim{
 "malloc-trim",
@@ -935,6 +943,7 @@
 Opts.ClangTidyProvider = ClangTidyOptProvider;
   }
   Opts.UseDirtyHeaders = UseDirtyHeaders;
+  Opts.PreambleParseForwardingFunctions = PreambleParseForwardingFunctions;
   Opts.QueryDriverGlobs = std::move(QueryDriverGlobs);
   Opts.TweakFilter = [&](const Tweak &T) {
 if (T.hidden() && !HiddenFeatures)
Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clan

[PATCH] D124688: [clangd] parse all make_unique-like functions in preamble

2022-05-16 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj added inline comments.



Comment at: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp:416
+// These mocks aren't quite right - we omit shared_ptr for simplicity.
+// forward is included to show its body is not needed to get the 
diagnostic.
+template  T&& forward(T& t) { return static_cast(t); }

nridge wrote:
> I'm confused about this line: you say "show its body is not needed" but 
> forward has a body here
Good catch, that was copy-pasted from std::make_unique above, but it doesn't 
seem to be necessary there either. I'll remove the bodies both.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124688

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


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

2022-05-16 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

Had a read through this. I'm still digesting it, but the high-level approach 
seems reasonable to me.

Could we add a test case for the recursive scenario that came up during chat:

  void foo();
  
  template 
  void foo(Head head, Tail... tail) {
foo(tail...);
  }
  
  int main() {
foo(1, 2, 3);
  }
  `

(even if the behaviour on this testcase isn't what we want yet, it's useful to 
have it in the test suite as a reminder)




Comment at: clang-tools-extra/clangd/InlayHints.cpp:344
+
+  const DeclRefExpr *unpackArgument(const Expr *E) {
+E = unpackImplicitCast(E);

unwrap? "unpack" sounds like something related to parameter packs



Comment at: clang-tools-extra/clangd/InlayHints.cpp:374
+  // have one in the definition, store this mapping here.
+  llvm::DenseMap ParamDeclToDef;
+};

I think it would be more readable if the state that persists across calls 
(TraversedFunctions, ForwardedParams, ParamDeclToDef) would be separate from 
the state that does not (UnresolvedParams, TraversalQueue).

A concrete suggestion:

 * Factor the first set out into a `ParameterMappingCache` struct
 * Do not keep a `ForwardingParameterVisitor` as a member of 
`InlayHintVisitor`, only the `ParameterMappingCache`
 * Create the `ForwardingParameterVisitor` as a local for each call, and pass 
it a reference to the `ParameterMappingCache` in the constructor


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

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


[PATCH] D125468: [clangd] Include Cleaner: ignore headers with IWYU export pragmas

2022-05-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Great! A few more nits




Comment at: clang-tools-extra/clangd/Headers.cpp:151
+  // will know that the next inclusion is behind the IWYU pragma.
+  if (!Text.consume_front(IWYUPragmaExport) &&
+  !Text.consume_front(IWYUPragmaKeep))

you never use Text again, so consume_front is unneccesary and confusing here, 
we can just use starts_with



Comment at: clang-tools-extra/clangd/Headers.cpp:151
+  // will know that the next inclusion is behind the IWYU pragma.
+  if (!Text.consume_front(IWYUPragmaExport) &&
+  !Text.consume_front(IWYUPragmaKeep))

sammccall wrote:
> you never use Text again, so consume_front is unneccesary and confusing here, 
> we can just use starts_with
add a FIXME that begin_export is not handled here (now that the other branch 
supports it)



Comment at: clang-tools-extra/clangd/Headers.h:148
 
+  bool hasIWYUPragmas(HeaderID ID) const {
+return HasIWYUPragmas.contains(ID);

hasIWYUExport?
(if the file contains non-export pragmas we need to return false)



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:274
+  // FIXME: Ignore the headers with IWYU export pragmas for now, remove this
+  // check when we have actual support for export pragmas.
+  if (AST.getIncludeStructure().hasIWYUPragmas(HID))

actual support for export pragmas => more precise tracking of exported headers?

(current wording doesn't really say what's missing)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125468

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


[PATCH] D125547: [analyzer][solver] Handle UnarySymExpr in SMTConv

2022-05-16 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 2 inline comments as done.
martong added inline comments.



Comment at: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h:258
 
+  static inline llvm::SMTExprRef fromUnary(llvm::SMTSolverRef &Solver,
+   ASTContext &Ctx,

steakhal wrote:
> I would prefer the `fromUnOp` similarly to how `fromBinOp` is called.
Yeah, very good point, I just realized that `fromUnOp` is already implemented!



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h:467-469
+  QualType FromTy;
+  llvm::SMTExprRef Exp =
+  getSymExpr(Solver, Ctx, USE->getOperand(), &FromTy, hasComparison);

steakhal wrote:
> If you discard the `FromTy`, you could have passed a nullptr there.
Ok, Changed it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125547

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


[PATCH] D125547: [analyzer][solver] Handle UnarySymExpr in SMTConv

2022-05-16 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 429633.
martong marked 2 inline comments as done.
martong added a comment.

- Use existing fromUnOp
- pass nullptr as FromTy


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125547

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
  clang/test/Analysis/z3-crosscheck.c


Index: clang/test/Analysis/z3-crosscheck.c
===
--- clang/test/Analysis/z3-crosscheck.c
+++ clang/test/Analysis/z3-crosscheck.c
@@ -14,6 +14,20 @@
   return 0;
 }
 
+int unary(int x, long l)
+{
+  int *z = 0;
+  int y = l;
+  if ((x & 1) && ((x & 1) ^ 1))
+if (-y)
+#ifdef NO_CROSSCHECK
+return *z; // expected-warning {{Dereference of null pointer (loaded 
from variable 'z')}}
+#else
+return *z; // no-warning
+#endif
+  return 0;
+}
+
 void g(int d);
 
 void f(int *a, int *b) {
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
@@ -446,6 +446,14 @@
   return getCastExpr(Solver, Ctx, Exp, FromTy, Sym->getType());
 }
 
+if (const UnarySymExpr *USE = dyn_cast(Sym)) {
+  if (RetTy)
+*RetTy = Sym->getType();
+  llvm::SMTExprRef Exp =
+  getSymExpr(Solver, Ctx, USE->getOperand(), nullptr, hasComparison);
+  return fromUnOp(Solver, USE->getOpcode(), Exp);
+}
+
 if (const BinarySymExpr *BSE = dyn_cast(Sym)) {
   llvm::SMTExprRef Exp =
   getSymBinExpr(Solver, Ctx, BSE, hasComparison, RetTy);


Index: clang/test/Analysis/z3-crosscheck.c
===
--- clang/test/Analysis/z3-crosscheck.c
+++ clang/test/Analysis/z3-crosscheck.c
@@ -14,6 +14,20 @@
   return 0;
 }
 
+int unary(int x, long l)
+{
+  int *z = 0;
+  int y = l;
+  if ((x & 1) && ((x & 1) ^ 1))
+if (-y)
+#ifdef NO_CROSSCHECK
+return *z; // expected-warning {{Dereference of null pointer (loaded from variable 'z')}}
+#else
+return *z; // no-warning
+#endif
+  return 0;
+}
+
 void g(int d);
 
 void f(int *a, int *b) {
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
@@ -446,6 +446,14 @@
   return getCastExpr(Solver, Ctx, Exp, FromTy, Sym->getType());
 }
 
+if (const UnarySymExpr *USE = dyn_cast(Sym)) {
+  if (RetTy)
+*RetTy = Sym->getType();
+  llvm::SMTExprRef Exp =
+  getSymExpr(Solver, Ctx, USE->getOperand(), nullptr, hasComparison);
+  return fromUnOp(Solver, USE->getOpcode(), Exp);
+}
+
 if (const BinarySymExpr *BSE = dyn_cast(Sym)) {
   llvm::SMTExprRef Exp =
   getSymBinExpr(Solver, Ctx, BSE, hasComparison, RetTy);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D94727: [clangd] Retire some flags for uncontroversial, stable features.

2022-05-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/tool/ClangdMain.cpp:762
 Opts.ResourceDir = ResourceDir;
-  Opts.BuildDynamicSymbolIndex = EnableIndex;
+  Opts.BuildDynamicSymbolIndex = true;
   Opts.CollectMainFileRefs = CollectMainFileRefs;

ivanmurashko wrote:
> @sammccall The option is always true, do we need it as an option?
It's false in tests, except when we're testing the index specifically.
On balance I think this is a good think because it allows us to reason about a 
simpler system when designing/debugging tests. In particular we don't have to 
worry about the AST-paths in tests "cheating" by looking at the index.

Seems sensible to make the struct default true and set it to false explicitly 
in optsForTest, though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94727

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


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

2022-05-16 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

Another test case that comes to mind is:

  void f1(int a, int b);
  void f2(int c, int d);
  
  template 
  void foo(Args... args) {
if (cond) {
  f1(args...);
} else {
  f2(args...);
}
  }
  
  int main() {
foo(1, 2);
  }

I guess in this case it will use the parameters names from `f1`, because that's 
the first call that appears in the function body in traversal order?

I think that's fine, functions written like this are probably not very common. 
Still good to add to the test suite to document the behaviour.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

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


[clang] 5bc469f - [RISCV][NFC] Fix build issue

2022-05-16 Thread Kito Cheng via cfe-commits

Author: Kito Cheng
Date: 2022-05-16T16:00:23+08:00
New Revision: 5bc469fd96192039bafe4bb9f74c85b37f63212e

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

LOG: [RISCV][NFC] Fix build issue

Added: 


Modified: 
clang/lib/Support/RISCVVIntrinsicUtils.cpp

Removed: 




diff  --git a/clang/lib/Support/RISCVVIntrinsicUtils.cpp 
b/clang/lib/Support/RISCVVIntrinsicUtils.cpp
index a0ca7b7c5166..9f5c1ffe2022 100644
--- a/clang/lib/Support/RISCVVIntrinsicUtils.cpp
+++ b/clang/lib/Support/RISCVVIntrinsicUtils.cpp
@@ -788,8 +788,6 @@ void RVVType::applyFixedLog2LMUL(int Log2LMUL, enum 
FixedLMULType Type) {
   return;
 }
 break;
-  default:
-llvm_unreachable("Unknown FixedLMULType??");
   }
 
   // Update new LMUL



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


[clang-tools-extra] 9902a09 - Add ThreadPriority::Low, and use QoS class Utility on Mac

2022-05-16 Thread Sam McCall via cfe-commits

Author: stk
Date: 2022-05-16T10:01:49+02:00
New Revision: 9902a0945d22cd5757b16ebe85fe07059723aa09

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

LOG: Add ThreadPriority::Low, and use QoS class Utility on Mac

On Apple Silicon Macs, using a Darwin thread priority of PRIO_DARWIN_BG seems to
map directly to the QoS class Background. With this priority, the thread is
confined to efficiency cores only, which makes background indexing take forever.

Introduce a new ThreadPriority "Low" that sits in the middle between Background
and Default, and maps to QoS class "Utility" on Mac. Make this new priority the
default for indexing. This makes the thread run on all cores, but still lowers
priority enough to keep the machine responsive, and not interfere with
user-initiated actions.

I didn't change the implementations for Windows and Linux; on these systems,
both ThreadPriority::Background and ThreadPriority::Low map to the same thread
priority. This could be changed as a followup (e.g. by using SCHED_BATCH for Low
on Linux).

See also https://github.com/clangd/clangd/issues/1119.

Reviewed By: sammccall, dgoldman

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

Added: 


Modified: 
clang-tools-extra/clangd/index/Background.h
clang/tools/libclang/CIndex.cpp
llvm/include/llvm/Support/Threading.h
llvm/lib/Support/Unix/Threading.inc
llvm/lib/Support/Windows/Threading.inc

Removed: 




diff  --git a/clang-tools-extra/clangd/index/Background.h 
b/clang-tools-extra/clangd/index/Background.h
index 040ca2d002bca..97f9095ed2c23 100644
--- a/clang-tools-extra/clangd/index/Background.h
+++ b/clang-tools-extra/clangd/index/Background.h
@@ -72,7 +72,7 @@ class BackgroundQueue {
 explicit Task(std::function Run) : Run(std::move(Run)) {}
 
 std::function Run;
-llvm::ThreadPriority ThreadPri = llvm::ThreadPriority::Background;
+llvm::ThreadPriority ThreadPri = llvm::ThreadPriority::Low;
 unsigned QueuePri = 0; // Higher-priority tasks will run first.
 std::string Tag;   // Allows priority to be boosted later.
 uint64_t Key = 0;  // If the key matches a previous task, drop this 
one.

diff  --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index 6df673fec4ada..235ca3e9c060b 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -9025,7 +9025,9 @@ void clang::setThreadBackgroundPriority() {
 return;
 
 #if LLVM_ENABLE_THREADS
-  llvm::set_thread_priority(llvm::ThreadPriority::Background);
+  // The function name setThreadBackgroundPriority is for historical reasons;
+  // Low is more appropriate.
+  llvm::set_thread_priority(llvm::ThreadPriority::Low);
 #endif
 }
 

diff  --git a/llvm/include/llvm/Support/Threading.h 
b/llvm/include/llvm/Support/Threading.h
index b158a57a1a21d..1e7e5f7b8f503 100644
--- a/llvm/include/llvm/Support/Threading.h
+++ b/llvm/include/llvm/Support/Threading.h
@@ -233,15 +233,20 @@ bool llvm_is_multithreaded();
   unsigned get_cpus();
 
   enum class ThreadPriority {
+/// Lower the current thread's priority as much as possible. Can be used
+/// for long-running tasks that are not time critical; more energy-
+/// efficient than Low.
 Background = 0,
-Default = 1,
+
+/// Lower the current thread's priority such that it does not affect
+/// foreground tasks significantly. This is a good default for long-
+/// running, latency-insensitive tasks to make sure cpu is not hogged
+/// by this task.
+Low = 1,
+
+/// Restore the current thread's priority to default scheduling priority.
+Default = 2,
   };
-  /// If priority is Background tries to lower current threads priority such
-  /// that it does not affect foreground tasks significantly. Can be used for
-  /// long-running, latency-insensitive tasks to make sure cpu is not hogged by
-  /// this task.
-  /// If the priority is default tries to restore current threads priority to
-  /// default scheduling priority.
   enum class SetThreadPriorityResult { FAILURE, SUCCESS };
   SetThreadPriorityResult set_thread_priority(ThreadPriority Priority);
 }

diff  --git a/llvm/lib/Support/Unix/Threading.inc 
b/llvm/lib/Support/Unix/Threading.inc
index 5de1cf071ba97..99f64b4f553d8 100644
--- a/llvm/lib/Support/Unix/Threading.inc
+++ b/llvm/lib/Support/Unix/Threading.inc
@@ -18,6 +18,7 @@
 #if defined(__APPLE__)
 #include 
 #include 
+#include 
 #endif
 
 #include 
@@ -258,27 +259,29 @@ SetThreadPriorityResult 
llvm::set_thread_priority(ThreadPriority Priority) {
   // SCHED_OTHER   the standard round-robin time-sharing policy;
   return !pthread_setschedparam(
  pthread_self(),
- Priority == ThreadPriority::Background ? SCHED_IDLE : SCHED_OTHER,
+

[PATCH] D124715: Add ThreadPriority::Low, and use QoS class Utility on Mac

2022-05-16 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9902a0945d22: Add ThreadPriority::Low, and use QoS class 
Utility on Mac (authored by stk , committed by 
sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124715

Files:
  clang-tools-extra/clangd/index/Background.h
  clang/tools/libclang/CIndex.cpp
  llvm/include/llvm/Support/Threading.h
  llvm/lib/Support/Unix/Threading.inc
  llvm/lib/Support/Windows/Threading.inc

Index: llvm/lib/Support/Windows/Threading.inc
===
--- llvm/lib/Support/Windows/Threading.inc
+++ llvm/lib/Support/Windows/Threading.inc
@@ -120,8 +120,10 @@
   // End background processing mode. The system restores the resource scheduling
   // priorities of the thread as they were before the thread entered background
   // processing mode.
+  //
+  // FIXME: consider THREAD_PRIORITY_BELOW_NORMAL for Low
   return SetThreadPriority(GetCurrentThread(),
-   Priority == ThreadPriority::Background
+   Priority != ThreadPriority::Default
? THREAD_MODE_BACKGROUND_BEGIN
: THREAD_MODE_BACKGROUND_END)
  ? SetThreadPriorityResult::SUCCESS
Index: llvm/lib/Support/Unix/Threading.inc
===
--- llvm/lib/Support/Unix/Threading.inc
+++ llvm/lib/Support/Unix/Threading.inc
@@ -18,6 +18,7 @@
 #if defined(__APPLE__)
 #include 
 #include 
+#include 
 #endif
 
 #include 
@@ -258,27 +259,29 @@
   // SCHED_OTHER   the standard round-robin time-sharing policy;
   return !pthread_setschedparam(
  pthread_self(),
- Priority == ThreadPriority::Background ? SCHED_IDLE : SCHED_OTHER,
+ // FIXME: consider SCHED_BATCH for Low
+ Priority == ThreadPriority::Default ? SCHED_OTHER : SCHED_IDLE,
  &priority)
  ? SetThreadPriorityResult::SUCCESS
  : SetThreadPriorityResult::FAILURE;
 #elif defined(__APPLE__)
-  // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpriority.2.html
-  // When setting a thread into background state the scheduling priority is set
-  // to lowest value, disk and network IO are throttled. Network IO will be
-  // throttled for any sockets the thread opens after going into background
-  // state. Any previously opened sockets are not affected.
-
-  // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/getiopolicy_np.3.html
-  // I/Os with THROTTLE policy are called THROTTLE I/Os. If a THROTTLE I/O
-  // request occurs within a small time window (usually a fraction of a second)
-  // of another NORMAL I/O request, the thread that issues the THROTTLE I/O is
-  // forced to sleep for a certain interval. This slows down the thread that
-  // issues the THROTTLE I/O so that NORMAL I/Os can utilize most of the disk
-  // I/O bandwidth.
-  return !setpriority(PRIO_DARWIN_THREAD, 0,
-  Priority == ThreadPriority::Background ? PRIO_DARWIN_BG
- : 0)
+  // https://developer.apple.com/documentation/apple-silicon/tuning-your-code-s-performance-for-apple-silicon
+  //
+  // Background - Applies to work that isn’t visible to the user and may take significant
+  // time to complete. Examples include indexing, backing up, or synchronizing data. This
+  // class emphasizes energy efficiency.
+  //
+  // Utility - Applies to work that takes anywhere from a few seconds to a few minutes to
+  // complete. Examples include downloading a document or importing data. This class
+  // offers a balance between responsiveness, performance, and energy efficiency.
+  const auto qosClass = [&](){
+switch (Priority) {
+  case ThreadPriority::Background: return QOS_CLASS_BACKGROUND;
+  case ThreadPriority::Low: return QOS_CLASS_UTILITY;
+  case ThreadPriority::Default: return QOS_CLASS_DEFAULT;
+}
+  }();
+  return !pthread_set_qos_class_self_np(qosClass, 0)
  ? SetThreadPriorityResult::SUCCESS
  : SetThreadPriorityResult::FAILURE;
 #endif
Index: llvm/include/llvm/Support/Threading.h
===
--- llvm/include/llvm/Support/Threading.h
+++ llvm/include/llvm/Support/Threading.h
@@ -233,15 +233,20 @@
   unsigned get_cpus();
 
   enum class ThreadPriority {
+/// Lower the current thread's priority as much as possible. Can be used
+/// for long-running tasks that are not time critical; more energy-
+/// efficient than Low.
 Background = 0,
-Default = 1,
+
+/// Lower the current thread's priority such that it does not affect
+/// foreground tasks significan

[PATCH] D124715: Add ThreadPriority::Low, and use QoS class Utility on Mac

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

In D124715#3510908 , @stefanhaller 
wrote:

> In D124715#3498846 , @sammccall 
> wrote:
>
>> Looks great! I'm happy to land it, will do so on Tuesday unless anyone has 
>> further comments.
>
> @sammccall Just a friendly ping, in case you forgot. 😄

Sorry about that! Landed now :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124715

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


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

2022-05-16 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added a subscriber: mgorny.
Herald added a project: All.
hokein requested review of this revision.
Herald added a subscriber: alextsao1999.
Herald added a project: clang-tools-extra.

The main idea is to compile the cxx grammar at build time, and construct
the core pieces (Grammar, LRTable) of the pseudoparse based on the compiled
data sources.

This is a tiny implementation, which is good for start:

- defines how the public API should look like;
- integrates the cxx grammar compilation workflow with the cmake system.
- onlynonterminal symbols of the C++ grammar are compiled, anything else are 
still doing the real compilation work at runtime, we can opt-in more bits in 
the future;
- splits the monolithic clangPsuedo library for better layering;


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125667

Files:
  clang-tools-extra/pseudo/CMakeLists.txt
  clang-tools-extra/pseudo/gen/CMakeLists.txt
  clang-tools-extra/pseudo/gen/Main.cpp
  clang-tools-extra/pseudo/gen/cxx_gen.cmake
  clang-tools-extra/pseudo/include/CMakeLists.txt
  clang-tools-extra/pseudo/include/clang-pseudo/cxx/cxx.h
  clang-tools-extra/pseudo/lib/CMakeLists.txt
  clang-tools-extra/pseudo/lib/cxx/cxx.cpp

Index: clang-tools-extra/pseudo/lib/cxx/cxx.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/lib/cxx/cxx.cpp
@@ -0,0 +1,34 @@
+//===--- cxx.cpp - Define public intefaces for C++ grammar ===//
+//
+// 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-pseudo/cxx/cxx.h"
+#include "clang-pseudo/LRTable.h"
+
+namespace clang {
+namespace pseudo {
+namespace cxx {
+
+static const char *CxxBNF =
+#include "CxxBNF.inc"
+;
+
+const Grammar &getGrammar() {
+  static std::vector Diags;
+  static std::unique_ptr G = Grammar::parseBNF(CxxBNF, Diags);
+  assert(Diags.empty());
+  return *G;
+}
+
+const LRTable &getLRTable() {
+  static LRTable Table = LRTable::buildSLR(getGrammar());
+  return Table;
+}
+
+} // namespace cxx
+} // namespace pseudo
+} // namespace clang
Index: clang-tools-extra/pseudo/lib/CMakeLists.txt
===
--- clang-tools-extra/pseudo/lib/CMakeLists.txt
+++ clang-tools-extra/pseudo/lib/CMakeLists.txt
@@ -1,6 +1,7 @@
 set(LLVM_LINK_COMPONENTS Support)
 
-add_clang_library(clangPseudo
+# Needed by LLVM's CMake checks because this file defines multiple targets.
+set(LLVM_OPTIONAL_SOURCES
   DirectiveTree.cpp
   Forest.cpp
   GLR.cpp
@@ -11,8 +12,42 @@
   LRTable.cpp
   LRTableBuild.cpp
   Token.cpp
+  )
+
+add_clang_library(clangPseudoGrammar
+  Grammar.cpp
+  GrammarBNF.cpp
+  LRGraph.cpp
+  LRTable.cpp
+  LRTableBuild.cpp
+
+  # FIXME: can we get rid of the clangBasic dependency? We need it for the
+  # clang::tok::getTokenName and clang::tok::getPunctuatorSpelling functions, we
+  # could consider remimplement these functions.
+  LINK_LIBS
+  clangBasic
+  )
+
+add_clang_library(clangPseudo
+  DirectiveTree.cpp
+  Forest.cpp
+  GLR.cpp
+  Lex.cpp
+  Token.cpp
 
   LINK_LIBS
   clangBasic
   clangLex
+  clangPseudoGrammar
+  )
+
+include(${CMAKE_CURRENT_SOURCE_DIR}/../gen/cxx_gen.cmake)
+add_clang_library(clangPseudoCxx
+  cxx/cxx.cpp
+
+  DEPENDS
+  cxx_gen
+
+  LINK_LIBS
+  clangPseudoGrammar
   )
Index: clang-tools-extra/pseudo/include/clang-pseudo/cxx/cxx.h
===
--- /dev/null
+++ clang-tools-extra/pseudo/include/clang-pseudo/cxx/cxx.h
@@ -0,0 +1,51 @@
+//===--- cxx.h - Public interfaces for the C++ grammar ---*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines public interfaces for the C++ grammar
+//  (pseudo/lib/cxx.bnf). It provides a fast way to access core building pieces
+//  of the LR parser, e.g. Grammar, LRTable, rather than parsing the grammar
+//  file at the runtime.
+//
+//  We do a compilation of the C++ BNF grammar at build time, and generate
+//  critical data sources. The implementation of the interfaces are based on the
+//  generated data sources.
+//
+//  FIXME: not everything is fully compiled yet. The implementation of the
+//  interfaces are still parsing the grammar file at the runtime.
+//
+//===--===//
+
+#ifndef CLANG_PSEUDO_CXX_CXX_H
+#define CLANG_PSEUDO_CXX_CXX_H
+
+#include "clang-pseudo/Grammar.h"

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

2022-05-16 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

This is a revised version of D125231 , based 
on our discussion. It has a narrow scope: only nonterminals of the grammar are 
compiled; and it mainly focuses on interfaces;


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125667

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


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

2022-05-16 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

One more testcase:

  template 
  void foo(Args...);
  
  template 
  void bar(Args... args) {
foo(args...);
  }
  
  template 
  void foo(Args... args) {
bar(args...);
  }
  
  int main() {
foo(1, 2);
  }

Sure, this is a stack overflow at runtime, but there's no excuse for it to be 
one in clangd :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

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


[PATCH] D125468: [clangd] Include Cleaner: ignore headers with IWYU export pragmas

2022-05-16 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 429637.
kbobyrev marked 4 inline comments as done.
kbobyrev added a comment.

Address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125468

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/HeadersTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -544,8 +544,7 @@
   EXPECT_TRUE(
   ReferencedFiles.User.contains(AST.getSourceManager().getMainFileID()));
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
-  auto Unused = computeUnusedIncludes(AST);
-  EXPECT_THAT(Unused, IsEmpty());
+  EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
 }
 
 TEST(IncludeCleaner, RecursiveInclusion) {
@@ -576,8 +575,34 @@
   findReferencedLocations(AST), AST.getIncludeStructure(),
   AST.getCanonicalIncludes(), AST.getSourceManager());
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
-  auto Unused = computeUnusedIncludes(AST);
-  EXPECT_THAT(Unused, IsEmpty());
+  EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
+}
+
+TEST(IncludeCleaner, IWYUPragmaExport) {
+  TestTU TU;
+  TU.Code = R"cpp(
+#include "foo.h"
+)cpp";
+  TU.AdditionalFiles["foo.h"] = R"cpp(
+#ifndef FOO_H
+#define FOO_H
+
+#include "bar.h" // IWYU pragma: export
+
+#endif
+  )cpp";
+  TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+void bar() {}
+  )cpp");
+  ParsedAST AST = TU.build();
+
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
+  // FIXME: This is not correct: foo.h is unused but is not diagnosed as such
+  // because we ignore headers with IWYU export pragmas for now.
+  EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
 }
 
 } // namespace
Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -406,7 +406,7 @@
   #define RECURSIVE_H
 
   #include "recursive.h"
-  
+
   #endif // RECURSIVE_H
 )cpp";
 
@@ -418,6 +418,33 @@
   EXPECT_FALSE(Includes.isSelfContained(getID("pp_depend.h", Includes)));
 }
 
+TEST_F(HeadersTest, HasIWYUPragmas) {
+  FS.Files[MainFile] = R"cpp(
+#include "export.h"
+#include "begin_exports.h"
+#include "none.h"
+)cpp";
+  FS.Files["export.h"] = R"cpp(
+#pragma once
+#include "none.h" // IWYU pragma: export
+)cpp";
+  FS.Files["begin_exports.h"] = R"cpp(
+#pragma once
+// IWYU pragma: begin_exports
+#include "none.h"
+// IWYU pragma: end_exports
+)cpp";
+  FS.Files["none.h"] = R"cpp(
+#pragma once
+// Not a pragma.
+)cpp";
+
+  auto Includes = collectIncludes();
+  EXPECT_TRUE(Includes.hasIWYUExport(getID("export.h", Includes)));
+  EXPECT_TRUE(Includes.hasIWYUExport(getID("begin_exports.h", Includes)));
+  EXPECT_FALSE(Includes.hasIWYUExport(getID("none.h", Includes)));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -268,13 +268,17 @@
   return true;
 return false;
   }
-  // Headers without include guards have side effects and are not
-  // self-contained, skip them.
   assert(Inc.HeaderID);
+  auto HID = static_cast(*Inc.HeaderID);
+  // FIXME: Ignore the headers with IWYU export pragmas for now, remove this
+  // check when we have more precise tracking of exported headers.
+  if (AST.getIncludeStructure().hasIWYUExport(HID))
+return false;
   auto FE = AST.getSourceManager().getFileManager().getFileRef(
-  AST.getIncludeStructure().getRealPath(
-  static_cast(*Inc.HeaderID)));
+  AST.getIncludeStructure().getRealPath(HID));
   assert(FE);
+  // Headers without include guards have side effects and are not
+  // self-contained, skip them.
   if (!AST.getPreprocessor().getHeaderSearchInfo().isFileMultipleIncludeGuarded(
   &FE->getFileEntry())) {
 dlog("{0} doesn't have header guard and will not be considered unused",
Index: clang-tools-extra/clangd/Headers.h
===
--- clang-tools-extra/clangd/Headers.h
+++ clang-tools-extra/clangd/Headers.h
@@ -145,6 +145,10 @@
 return !NonSelfContained.contains(ID);
   }
 
+  bool h

[clang-tools-extra] 40f361a - [clangd] Include Cleaner: ignore headers with IWYU export pragmas

2022-05-16 Thread Kirill Bobyrev via cfe-commits

Author: Kirill Bobyrev
Date: 2022-05-16T10:13:47+02:00
New Revision: 40f361ace3e9a9c24bd99300216aeabd49ad99bb

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

LOG: [clangd] Include Cleaner: ignore headers with IWYU export pragmas

Disable the warnings with `IWYU pragma: export` or `begin_exports` +
`end_exports` until we have support for these pragmas. There are too many
false-positive warnings for the headers that have the correct pragmas for now
and it makes the user experience very unpleasant.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/Headers.cpp
clang-tools-extra/clangd/Headers.h
clang-tools-extra/clangd/IncludeCleaner.cpp
clang-tools-extra/clangd/unittests/HeadersTests.cpp
clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Headers.cpp 
b/clang-tools-extra/clangd/Headers.cpp
index 9484bb7afa15b..6b934eae7b358 100644
--- a/clang-tools-extra/clangd/Headers.cpp
+++ b/clang-tools-extra/clangd/Headers.cpp
@@ -24,6 +24,7 @@ namespace clangd {
 
 const char IWYUPragmaKeep[] = "// IWYU pragma: keep";
 const char IWYUPragmaExport[] = "// IWYU pragma: export";
+const char IWYUPragmaBeginExports[] = "// IWYU pragma: begin_exports";
 
 class IncludeStructure::RecordHeaders : public PPCallbacks,
 public CommentHandler {
@@ -127,31 +128,45 @@ class IncludeStructure::RecordHeaders : public 
PPCallbacks,
 }
   }
 
-  // Given:
-  //
-  // #include "foo.h"
-  // #include "bar.h" // IWYU pragma: keep
-  //
-  // The order in which the callbacks will be triggered:
-  //
-  // 1. InclusionDirective("foo.h")
-  // 2. HandleComment("// IWYU pragma: keep")
-  // 3. InclusionDirective("bar.h")
-  //
-  // HandleComment will store the last location of "IWYU pragma: keep" (or
-  // export) comment in the main file, so that when InclusionDirective is
-  // called, it will know that the next inclusion is behind the IWYU pragma.
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
-if (!inMainFile() || Range.getBegin().isMacroID())
-  return false;
 bool Err = false;
 llvm::StringRef Text = SM.getCharacterData(Range.getBegin(), &Err);
-if (Err && !Text.consume_front(IWYUPragmaKeep) &&
-!Text.consume_front(IWYUPragmaExport))
+if (Err)
   return false;
-unsigned Offset = SM.getFileOffset(Range.getBegin());
-LastPragmaKeepInMainFileLine =
-SM.getLineNumber(SM.getFileID(Range.getBegin()), Offset) - 1;
+if (inMainFile()) {
+  // Given:
+  //
+  // #include "foo.h"
+  // #include "bar.h" // IWYU pragma: keep
+  //
+  // The order in which the callbacks will be triggered:
+  //
+  // 1. InclusionDirective("foo.h")
+  // 2. handleCommentInMainFile("// IWYU pragma: keep")
+  // 3. InclusionDirective("bar.h")
+  //
+  // This code stores the last location of "IWYU pragma: keep" (or export)
+  // comment in the main file, so that when InclusionDirective is called, 
it
+  // will know that the next inclusion is behind the IWYU pragma.
+  // FIXME: Support "IWYU pragma: begin_exports" and "IWYU pragma:
+  // end_exports".
+  if (!Text.startswith(IWYUPragmaExport) &&
+  !Text.startswith(IWYUPragmaKeep))
+return false;
+  unsigned Offset = SM.getFileOffset(Range.getBegin());
+  LastPragmaKeepInMainFileLine =
+  SM.getLineNumber(SM.getMainFileID(), Offset) - 1;
+} else {
+  // Memorize headers that that have export pragmas in them. Include 
Cleaner
+  // does not support them properly yet, so they will be not marked as
+  // unused.
+  // FIXME: Once IncludeCleaner supports export pragmas, remove this.
+  if (!Text.startswith(IWYUPragmaExport) &&
+  !Text.startswith(IWYUPragmaBeginExports))
+return false;
+  Out->HasIWYUPragmas.insert(
+  *Out->getID(SM.getFileEntryForID(SM.getFileID(Range.getBegin();
+}
 return false;
   }
 
@@ -237,8 +252,7 @@ IncludeStructure::getID(const FileEntry *Entry) const {
   return It->second;
 }
 
-IncludeStructure::HeaderID
-IncludeStructure::getOrCreateID(FileEntryRef Entry) {
+IncludeStructure::HeaderID IncludeStructure::getOrCreateID(FileEntryRef Entry) 
{
   // Main file's FileEntry was not known at IncludeStructure creation time.
   if (&Entry.getFileEntry() == MainFileEntry) {
 if (RealPathNames.front().empty())

diff  --git a/clang-tools-extra/clangd/Headers.h 
b/clang-tools-extra/clangd/Headers.h
index 5da0200afd1aa..b17107535e3d9 100644
--- a/clang-tools-extra/clangd/Headers.h
+++ b/clang-tools-extra/clangd/Headers.h
@@ -145,6 +145,10 @@

[PATCH] D125468: [clangd] Include Cleaner: ignore headers with IWYU export pragmas

2022-05-16 Thread Kirill Bobyrev 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 rG40f361ace3e9: [clangd] Include Cleaner: ignore headers with 
IWYU export pragmas (authored by kbobyrev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125468

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/HeadersTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -544,8 +544,7 @@
   EXPECT_TRUE(
   ReferencedFiles.User.contains(AST.getSourceManager().getMainFileID()));
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
-  auto Unused = computeUnusedIncludes(AST);
-  EXPECT_THAT(Unused, IsEmpty());
+  EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
 }
 
 TEST(IncludeCleaner, RecursiveInclusion) {
@@ -576,8 +575,34 @@
   findReferencedLocations(AST), AST.getIncludeStructure(),
   AST.getCanonicalIncludes(), AST.getSourceManager());
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
-  auto Unused = computeUnusedIncludes(AST);
-  EXPECT_THAT(Unused, IsEmpty());
+  EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
+}
+
+TEST(IncludeCleaner, IWYUPragmaExport) {
+  TestTU TU;
+  TU.Code = R"cpp(
+#include "foo.h"
+)cpp";
+  TU.AdditionalFiles["foo.h"] = R"cpp(
+#ifndef FOO_H
+#define FOO_H
+
+#include "bar.h" // IWYU pragma: export
+
+#endif
+  )cpp";
+  TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+void bar() {}
+  )cpp");
+  ParsedAST AST = TU.build();
+
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
+  // FIXME: This is not correct: foo.h is unused but is not diagnosed as such
+  // because we ignore headers with IWYU export pragmas for now.
+  EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
 }
 
 } // namespace
Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -406,7 +406,7 @@
   #define RECURSIVE_H
 
   #include "recursive.h"
-  
+
   #endif // RECURSIVE_H
 )cpp";
 
@@ -418,6 +418,33 @@
   EXPECT_FALSE(Includes.isSelfContained(getID("pp_depend.h", Includes)));
 }
 
+TEST_F(HeadersTest, HasIWYUPragmas) {
+  FS.Files[MainFile] = R"cpp(
+#include "export.h"
+#include "begin_exports.h"
+#include "none.h"
+)cpp";
+  FS.Files["export.h"] = R"cpp(
+#pragma once
+#include "none.h" // IWYU pragma: export
+)cpp";
+  FS.Files["begin_exports.h"] = R"cpp(
+#pragma once
+// IWYU pragma: begin_exports
+#include "none.h"
+// IWYU pragma: end_exports
+)cpp";
+  FS.Files["none.h"] = R"cpp(
+#pragma once
+// Not a pragma.
+)cpp";
+
+  auto Includes = collectIncludes();
+  EXPECT_TRUE(Includes.hasIWYUExport(getID("export.h", Includes)));
+  EXPECT_TRUE(Includes.hasIWYUExport(getID("begin_exports.h", Includes)));
+  EXPECT_FALSE(Includes.hasIWYUExport(getID("none.h", Includes)));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -268,13 +268,17 @@
   return true;
 return false;
   }
-  // Headers without include guards have side effects and are not
-  // self-contained, skip them.
   assert(Inc.HeaderID);
+  auto HID = static_cast(*Inc.HeaderID);
+  // FIXME: Ignore the headers with IWYU export pragmas for now, remove this
+  // check when we have more precise tracking of exported headers.
+  if (AST.getIncludeStructure().hasIWYUExport(HID))
+return false;
   auto FE = AST.getSourceManager().getFileManager().getFileRef(
-  AST.getIncludeStructure().getRealPath(
-  static_cast(*Inc.HeaderID)));
+  AST.getIncludeStructure().getRealPath(HID));
   assert(FE);
+  // Headers without include guards have side effects and are not
+  // self-contained, skip them.
   if (!AST.getPreprocessor().getHeaderSearchInfo().isFileMultipleIncludeGuarded(
   &FE->getFileEntry())) {
 dlog("{0} doesn't have header guard and will not be considered unused",
Index: clang-tools-extra/clangd/Headers.h
===
--- clang-tools-extra/clangd/Headers.h
+++ clang

[PATCH] D125669: Adding support for target in_reduction

2022-05-16 Thread Ritanya via Phabricator via cfe-commits
RitanyaB created this revision.
RitanyaB added reviewers: soumitra, koops, ssquare08, cchen, dreachem.
Herald added a project: All.
RitanyaB requested review of this revision.
Herald added a reviewer: jdoerfert.
Herald added subscribers: llvm-commits, cfe-commits, sstefan1.
Herald added projects: clang, LLVM.

Implementing target in_reduction by wrapping target task with host task with 
in_reduction and if clause. This is in compliance with OpenMP 5.0 section: 
2.19.5.6.
So, this

  #pragma omp target in_reduction(+:res)
for (int i=0; ihttps://reviews.llvm.org/D125669

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/Sema/SemaOpenMP.cpp
  clang/test/OpenMP/target_in_reduction_codegen.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -582,6 +582,7 @@
 VersionedClause,
 VersionedClause,
 VersionedClause,
+VersionedClause,
 VersionedClause,
 VersionedClause
   ];
Index: clang/test/OpenMP/target_in_reduction_codegen.cpp
===
--- /dev/null
+++ clang/test/OpenMP/target_in_reduction_codegen.cpp
@@ -0,0 +1,668 @@
+// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -verify -triple x86_64-apple-darwin10 -fopenmp -x c++ -emit-llvm %s -o - | FileCheck %s --check-prefix=CHECK1
+// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -fopenmp -x c++ -triple x86_64-apple-darwin10 -emit-pch -o %t %s
+// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -fopenmp -x c++ -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix=CHECK1
+// expected-no-diagnostics
+#ifndef HEADER
+#define HEADER
+
+struct S {
+  int a;
+  S() : a(0) {}
+  S(const S &) {}
+  S &operator=(const S &) { return *this; }
+  ~S() {}
+  friend S operator+(const S &a, const S &b) { return a; }
+};
+
+int main(int argc, char **argv) {
+  int a;
+  float b;
+  S c[5];
+  short d[argc];
+#pragma omp taskgroup task_reduction(+ \
+ : a, b, argc)
+  {
+#pragma omp taskgroup task_reduction(- \
+ : c, d)
+#pragma omp parallel
+#pragma omp target in_reduction(+ \
+: a)
+for (int i = 0; i < 5; i++)
+  a += d[a];
+  }
+  return 0;
+}
+
+#endif
+// CHECK1-LABEL: define {{[^@]+}}@main
+// CHECK1-SAME: (i32 [[ARGC:%.*]], i8** [[ARGV:%.*]]) #[[ATTR0:[0-9]+]] {
+// CHECK1-NEXT:  entry:
+// CHECK1-NEXT:[[RETVAL:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[ARGC_ADDR:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[ARGV_ADDR:%.*]] = alloca i8**, align 8
+// CHECK1-NEXT:[[A:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[B:%.*]] = alloca float, align 4
+// CHECK1-NEXT:[[C:%.*]] = alloca [5 x %struct.S], align 16
+// CHECK1-NEXT:[[SAVED_STACK:%.*]] = alloca i8*, align 8
+// CHECK1-NEXT:[[__VLA_EXPR0:%.*]] = alloca i64, align 8
+// CHECK1-NEXT:[[DOTRD_INPUT_:%.*]] = alloca [3 x %struct.kmp_taskred_input_t], align 8
+// CHECK1-NEXT:[[DOTTASK_RED_:%.*]] = alloca i8*, align 8
+// CHECK1-NEXT:[[DOTRD_INPUT_3:%.*]] = alloca [2 x %struct.kmp_taskred_input_t.0], align 8
+// CHECK1-NEXT:[[DOTTASK_RED_6:%.*]] = alloca i8*, align 8
+// CHECK1-NEXT:[[TMP0:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1:[0-9]+]])
+// CHECK1-NEXT:store i32 0, i32* [[RETVAL]], align 4
+// CHECK1-NEXT:store i32 [[ARGC]], i32* [[ARGC_ADDR]], align 4
+// CHECK1-NEXT:store i8** [[ARGV]], i8*** [[ARGV_ADDR]], align 8
+// CHECK1-NEXT:[[ARRAY_BEGIN:%.*]] = getelementptr inbounds [5 x %struct.S], [5 x %struct.S]* [[C]], i32 0, i32 0
+// CHECK1-NEXT:[[ARRAYCTOR_END:%.*]] = getelementptr inbounds [[STRUCT_S:%.*]], %struct.S* [[ARRAY_BEGIN]], i64 5
+// CHECK1-NEXT:br label [[ARRAYCTOR_LOOP:%.*]]
+// CHECK1:   arrayctor.loop:
+// CHECK1-NEXT:[[ARRAYCTOR_CUR:%.*]] = phi %struct.S* [ [[ARRAY_BEGIN]], [[ENTRY:%.*]] ], [ [[ARRAYCTOR_NEXT:%.*]], [[ARRAYCTOR_LOOP]] ]
+// CHECK1-NEXT:call void @_ZN1SC1Ev(%struct.S* nonnull align 4 dereferenceable(4) [[ARRAYCTOR_CUR]])
+// CHECK1-NEXT:[[ARRAYCTOR_NEXT]] = getelementptr inbounds [[STRUCT_S]], %struct.S* [[ARRAYCTOR_CUR]], i64 1
+// CHECK1-NEXT:[[ARRAYCTOR_DONE:%.*]] = icmp eq %struct.S* [[ARRAYCTOR_NEXT]], [[ARRAYCTOR_END]]
+// CHECK1-NEXT:br i1 [[ARRAYCTOR_DONE]], label [[ARRAYCTOR_CONT:%.*]], label [[ARRAYCTOR_LOOP]]
+// CHECK1:   arrayctor.cont:
+// CHECK1-NEXT:[[TMP1:%.*]] = load i32, i32* [[ARGC_ADDR]], align 4
+// CHECK1-NEXT:[[TMP2:%.*]] = zext i32 [[TMP1]] to i64
+// CHECK1-NEXT:[[TMP3:%.*]] = call i8* @llvm.stacksave()
+// CHECK1-NEXT:store i8* [[TMP3]], i8** [[

[clang-tools-extra] 106e63c - [clangd] NFC: Rename field to be compatible with the function name

2022-05-16 Thread Kirill Bobyrev via cfe-commits

Author: Kirill Bobyrev
Date: 2022-05-16T10:18:08+02:00
New Revision: 106e63ce47b5b00e376be9eef03a084c71c03f11

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

LOG: [clangd] NFC: Rename field to be compatible with the function name

Added: 


Modified: 
clang-tools-extra/clangd/Headers.cpp
clang-tools-extra/clangd/Headers.h

Removed: 




diff  --git a/clang-tools-extra/clangd/Headers.cpp 
b/clang-tools-extra/clangd/Headers.cpp
index 6b934eae7b35..cb7abac3e9f9 100644
--- a/clang-tools-extra/clangd/Headers.cpp
+++ b/clang-tools-extra/clangd/Headers.cpp
@@ -164,7 +164,7 @@ class IncludeStructure::RecordHeaders : public PPCallbacks,
   if (!Text.startswith(IWYUPragmaExport) &&
   !Text.startswith(IWYUPragmaBeginExports))
 return false;
-  Out->HasIWYUPragmas.insert(
+  Out->HasIWYUExport.insert(
   *Out->getID(SM.getFileEntryForID(SM.getFileID(Range.getBegin();
 }
 return false;

diff  --git a/clang-tools-extra/clangd/Headers.h 
b/clang-tools-extra/clangd/Headers.h
index b17107535e3d..ff3f06316832 100644
--- a/clang-tools-extra/clangd/Headers.h
+++ b/clang-tools-extra/clangd/Headers.h
@@ -146,7 +146,7 @@ class IncludeStructure {
   }
 
   bool hasIWYUExport(HeaderID ID) const {
-return HasIWYUPragmas.contains(ID);
+return HasIWYUExport.contains(ID);
   }
 
   // Return all transitively reachable files.
@@ -191,7 +191,7 @@ class IncludeStructure {
   llvm::DenseSet NonSelfContained;
   // Contains a set of headers that have either "IWYU pragma: export" or "IWYU
   // pragma: begin_exports".
-  llvm::DenseSet HasIWYUPragmas;
+  llvm::DenseSet HasIWYUExport;
 };
 
 // Calculates insertion edit for including a new header in a file.



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


[PATCH] D125604: [FileCheck] Catch missspelled directives.

2022-05-16 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev added a comment.

In D125604#3514983 , @jhenderson 
wrote:

> Are the TODO cases where the test fails if changing them?

Yes, this and where the fix is not perfectly obvious.




Comment at: llvm/test/FileCheck/missspelled-directive.txt:18
+
+P4_COUNT-2: foo
+CHECK4: error: misspelled directive 'P4_COUNT-2:'

jhenderson wrote:
> What about `P4-COUNT_2`? Is that case not really related?
Yeah, that's intentionally left for later. At the moment I don't even know how 
severe the problem with `COUNT_*` is, need to try and see.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125604

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


[clang] e57f578 - [clang-format] fix alignment w/o binpacked args

2022-05-16 Thread Marek Kurdej via cfe-commits

Author: Gregory Fong
Date: 2022-05-16T10:25:06+02:00
New Revision: e57f57841fbb0cd1d1dbd3237c2cbe6ce15984dd

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

LOG: [clang-format] fix alignment w/o binpacked args

The combination of

- AlignConsecutiveAssignments.Enabled = true
- BinPackArguments = false

would result in the first continuation line of a braced-init-list being
improperly indented (missing a shift) when in a continued function call.
Indentation was also wrong for braced-init-lists continuing a
direct-list-initialization.  Check for opening braced lists in
continuation and ensure that the correct shift occurs.

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

Reviewed By: curdeius

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

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 673af51d2daa..f20383800ab4 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -371,6 +371,9 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
 return false;
   if (Changes[ScopeStart].NewlinesBefore > 0)
 return false;
+  if (Changes[i].Tok->is(tok::l_brace) &&
+  Changes[i].Tok->is(BK_BracedInit))
+return true;
   return Style.BinPackArguments;
 }
 
@@ -387,6 +390,14 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
 Changes[i].Tok->Previous->is(TT_ConditionalExpr))
   return true;
 
+// Continued direct-list-initialization using braced list.
+if (ScopeStart > Start + 1 &&
+Changes[ScopeStart - 2].Tok->is(tok::identifier) &&
+Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
+Changes[i].Tok->is(tok::l_brace) &&
+Changes[i].Tok->is(BK_BracedInit))
+  return true;
+
 // Continued braced list.
 if (ScopeStart > Start + 1 &&
 Changes[ScopeStart - 2].Tok->isNot(tok::identifier) &&

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 44da34001f99..22c46a129403 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -17318,6 +17318,23 @@ TEST_F(FormatTest, AlignConsecutiveAssignments) {
   //  "ccc ? a : b,\n"
   //  "dd);",
   //  Alignment);
+
+  // Confirm proper handling of AlignConsecutiveAssignments with
+  // BinPackArguments.
+  // See https://llvm.org/PR55360
+  Alignment = getLLVMStyleWithColumns(50);
+  Alignment.AlignConsecutiveAssignments.Enabled = true;
+  Alignment.BinPackArguments = false;
+  verifyFormat("int a_long_name = 1;\n"
+   "auto b  = B({a_long_name, a_long_name},\n"
+   "{a_longer_name_for_wrap,\n"
+   " a_longer_name_for_wrap});",
+   Alignment);
+  verifyFormat("int a_long_name = 1;\n"
+   "auto b  = B{{a_long_name, a_long_name},\n"
+   "{a_longer_name_for_wrap,\n"
+   " a_longer_name_for_wrap}};",
+   Alignment);
 }
 
 TEST_F(FormatTest, AlignConsecutiveBitFields) {



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


[PATCH] D125162: [clang-format] fix alignment w/o binpacked args

2022-05-16 Thread Marek Kurdej via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe57f57841fbb: [clang-format] fix alignment w/o binpacked 
args (authored by cha5on, committed by curdeius).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125162

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
@@ -17318,6 +17318,23 @@
   //  "ccc ? a : b,\n"
   //  "dd);",
   //  Alignment);
+
+  // Confirm proper handling of AlignConsecutiveAssignments with
+  // BinPackArguments.
+  // See https://llvm.org/PR55360
+  Alignment = getLLVMStyleWithColumns(50);
+  Alignment.AlignConsecutiveAssignments.Enabled = true;
+  Alignment.BinPackArguments = false;
+  verifyFormat("int a_long_name = 1;\n"
+   "auto b  = B({a_long_name, a_long_name},\n"
+   "{a_longer_name_for_wrap,\n"
+   " a_longer_name_for_wrap});",
+   Alignment);
+  verifyFormat("int a_long_name = 1;\n"
+   "auto b  = B{{a_long_name, a_long_name},\n"
+   "{a_longer_name_for_wrap,\n"
+   " a_longer_name_for_wrap}};",
+   Alignment);
 }
 
 TEST_F(FormatTest, AlignConsecutiveBitFields) {
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -371,6 +371,9 @@
 return false;
   if (Changes[ScopeStart].NewlinesBefore > 0)
 return false;
+  if (Changes[i].Tok->is(tok::l_brace) &&
+  Changes[i].Tok->is(BK_BracedInit))
+return true;
   return Style.BinPackArguments;
 }
 
@@ -387,6 +390,14 @@
 Changes[i].Tok->Previous->is(TT_ConditionalExpr))
   return true;
 
+// Continued direct-list-initialization using braced list.
+if (ScopeStart > Start + 1 &&
+Changes[ScopeStart - 2].Tok->is(tok::identifier) &&
+Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
+Changes[i].Tok->is(tok::l_brace) &&
+Changes[i].Tok->is(BK_BracedInit))
+  return true;
+
 // Continued braced list.
 if (ScopeStart > Start + 1 &&
 Changes[ScopeStart - 2].Tok->isNot(tok::identifier) &&


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -17318,6 +17318,23 @@
   //  "ccc ? a : b,\n"
   //  "dd);",
   //  Alignment);
+
+  // Confirm proper handling of AlignConsecutiveAssignments with
+  // BinPackArguments.
+  // See https://llvm.org/PR55360
+  Alignment = getLLVMStyleWithColumns(50);
+  Alignment.AlignConsecutiveAssignments.Enabled = true;
+  Alignment.BinPackArguments = false;
+  verifyFormat("int a_long_name = 1;\n"
+   "auto b  = B({a_long_name, a_long_name},\n"
+   "{a_longer_name_for_wrap,\n"
+   " a_longer_name_for_wrap});",
+   Alignment);
+  verifyFormat("int a_long_name = 1;\n"
+   "auto b  = B{{a_long_name, a_long_name},\n"
+   "{a_longer_name_for_wrap,\n"
+   " a_longer_name_for_wrap}};",
+   Alignment);
 }
 
 TEST_F(FormatTest, AlignConsecutiveBitFields) {
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -371,6 +371,9 @@
 return false;
   if (Changes[ScopeStart].NewlinesBefore > 0)
 return false;
+  if (Changes[i].Tok->is(tok::l_brace) &&
+  Changes[i].Tok->is(BK_BracedInit))
+return true;
   return Style.BinPackArguments;
 }
 
@@ -387,6 +390,14 @@
 Changes[i].Tok->Previous->is(TT_ConditionalExpr))
   return true;
 
+// Continued direct-list-initialization using braced list.
+if (ScopeStart > Start + 1 &&
+Changes[ScopeStart - 2].Tok->is(tok::identifier) &&
+Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
+Changes[i].Tok->is(tok::l_brace) &&
+Changes[i].Tok->is(BK_BracedInit))
+  return true;
+
 // Continued braced list.
  

[PATCH] D122126: [LoopVectorize] Don't interleave when the number of runtime checks exceeds the threshold

2022-05-16 Thread Tiehu Zhang via Phabricator via cfe-commits
TiehuZhang added a comment.

In D122126#3515070 , @fhahn wrote:

> Still LGTM, thanks! The remaining suggestion can be addressed directly before 
> committing the patch.

Thanks, @fhahn! I'll add the precommit test  when committing the patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122126

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


[PATCH] D125006: [pseudo] Support parsing variant target symbols.

2022-05-16 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 429645.
hokein added a comment.

move the findNonterminal to Grammar.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125006

Files:
  clang-tools-extra/pseudo/benchmarks/Benchmark.cpp
  clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
  clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
  clang-tools-extra/pseudo/include/clang-pseudo/Grammar.h
  clang-tools-extra/pseudo/include/clang-pseudo/LRGraph.h
  clang-tools-extra/pseudo/include/clang-pseudo/LRTable.h
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/lib/Grammar.cpp
  clang-tools-extra/pseudo/lib/LRGraph.cpp
  clang-tools-extra/pseudo/lib/LRTable.cpp
  clang-tools-extra/pseudo/lib/LRTableBuild.cpp
  clang-tools-extra/pseudo/lib/cxx.bnf
  clang-tools-extra/pseudo/test/glr-variant-start.cpp
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp
  clang-tools-extra/pseudo/unittests/GLRTest.cpp
  clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Index: clang-tools-extra/pseudo/unittests/GrammarTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GrammarTest.cpp
+++ clang-tools-extra/pseudo/unittests/GrammarTest.cpp
@@ -112,7 +112,7 @@
 b := a
   )cpp");
 
-  EXPECT_EQ(G->startSymbol(), id("_"));
+  EXPECT_EQ(G->underscore(), id("_"));
   EXPECT_THAT(Diags, UnorderedElementsAre(
  "Rule '_ := ,_opt' has a nullable RHS",
  "Rule 'null := ' has a nullable RHS",
Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -344,7 +344,8 @@
   const TokenStream &Tokens = cook(lex("{ abc", LOptions), LOptions);
   auto LRTable = LRTable::buildSLR(*G);
 
-  const ForestNode &Parsed = glrParse(Tokens, {*G, LRTable, Arena, GSStack});
+  const ForestNode &Parsed =
+  glrParse(Tokens, {*G, LRTable, Arena, GSStack}, id("test"));
   // Verify that there is no duplicated sequence node of `expr := IDENTIFIER`
   // in the forest, see the `#1` and `=#1` in the dump string.
   EXPECT_EQ(Parsed.dumpRecursive(*G),
@@ -381,7 +382,8 @@
   const TokenStream &Tokens = cook(lex("IDENTIFIER", LOptions), LOptions);
   auto LRTable = LRTable::buildSLR(*G);
 
-  const ForestNode &Parsed = glrParse(Tokens, {*G, LRTable, Arena, GSStack});
+  const ForestNode &Parsed =
+  glrParse(Tokens, {*G, LRTable, Arena, GSStack}, id("test"));
   EXPECT_EQ(Parsed.dumpRecursive(*G),
 "[  0, end) test := \n"
 "[  0, end) ├─test := IDENTIFIER\n"
Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -43,6 +43,9 @@
 desc("Strip directives and select conditional sections"));
 static opt PrintStatistics("print-statistics", desc("Print GLR parser statistics"));
 static opt PrintForest("print-forest", desc("Print parse forest"));
+static opt StartSymbol("start-symbol",
+desc("specify the start symbol to parse"),
+init("translation-unit"));
 
 static std::string readOrDie(llvm::StringRef Path) {
   llvm::ErrorOr> Text =
@@ -110,9 +113,16 @@
 if (ParseableStream) {
   clang::pseudo::ForestArena Arena;
   clang::pseudo::GSS GSS;
-  auto &Root =
-  glrParse(*ParseableStream,
-   clang::pseudo::ParseParams{*G, LRTable, Arena, GSS});
+  llvm::Optional StartSymID =
+  G->findNonterminal(StartSymbol);
+  if (!StartSymID) {
+llvm::errs() << llvm::formatv(
+"The start symbol {0} doesn't exit in the grammar!\n", Grammar);
+return 2;
+  }
+  auto &Root = glrParse(*ParseableStream,
+clang::pseudo::ParseParams{*G, LRTable, Arena, GSS},
+*StartSymID);
   if (PrintForest)
 llvm::outs() << Root.dumpRecursive(*G, /*Abbreviated=*/true);
 
Index: clang-tools-extra/pseudo/test/glr-variant-start.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/glr-variant-start.cpp
@@ -0,0 +1,9 @@
+// RUN: clang-pseudo -grammar=%cxx-bnf-file -source=%s --start-symbol=statement-seq --print-forest | FileCheck %s
+
+a + a;
+// CHECK:  statement-seq~expression-statement := expression ;
+// CHECK-NEXT: ├─expression~additive-expression := additive-expression + multiplicative-expression
+// CHECK-NEXT: │ ├─additive-expression~IDENTIFIER :=
+// CHECK-NEXT: │ ├─+ :=
+// CHECK-NEXT: │ └─multiplicative-expression~IDENTIFIER :=
+// CHECK-NEXT: └─; :=
Index: clang-tools-extra/pseudo/lib/cxx.bnf
===

[clang-tools-extra] 1a65c49 - [pseudo] Support parsing variant target symbols.

2022-05-16 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-05-16T10:38:16+02:00
New Revision: 1a65c491be712f89b36af9d828b6ccce02de37db

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

LOG: [pseudo] Support parsing variant target symbols.

With this patch, we're able to parse smaller chunks of C++ code (statement,
declaration), rather than translation-unit.

The start symbol is listed in the grammar in a form of `_ :=
statement`, each start symbol has a dedicated state (`_ := • statement`).
We create and track all these separate states in the LRTable. When we
start parsing, we lookup the corresponding state to start the parser.

LR pasing table changes with this patch:
- number of states: 1467 -> 1471
- number of actions: 82891 -> 83578
- size of the table (bytes): 334248 -> 336996

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

Added: 
clang-tools-extra/pseudo/test/glr-variant-start.cpp

Modified: 
clang-tools-extra/pseudo/benchmarks/Benchmark.cpp
clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
clang-tools-extra/pseudo/include/clang-pseudo/Grammar.h
clang-tools-extra/pseudo/include/clang-pseudo/LRGraph.h
clang-tools-extra/pseudo/include/clang-pseudo/LRTable.h
clang-tools-extra/pseudo/lib/GLR.cpp
clang-tools-extra/pseudo/lib/Grammar.cpp
clang-tools-extra/pseudo/lib/LRGraph.cpp
clang-tools-extra/pseudo/lib/LRTable.cpp
clang-tools-extra/pseudo/lib/LRTableBuild.cpp
clang-tools-extra/pseudo/lib/cxx.bnf
clang-tools-extra/pseudo/tool/ClangPseudo.cpp
clang-tools-extra/pseudo/unittests/GLRTest.cpp
clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/benchmarks/Benchmark.cpp 
b/clang-tools-extra/pseudo/benchmarks/Benchmark.cpp
index 9568f76774af2..5518a51166593 100644
--- a/clang-tools-extra/pseudo/benchmarks/Benchmark.cpp
+++ b/clang-tools-extra/pseudo/benchmarks/Benchmark.cpp
@@ -103,10 +103,11 @@ static void runGLRParse(benchmark::State &State) {
   clang::LangOptions LangOpts = genericLangOpts();
   LRTable Table = clang::pseudo::LRTable::buildSLR(*G);
   TokenStream ParseableStream = parseableTokenStream();
+  SymbolID StartSymbol = *G->findNonterminal("translation-unit");
   for (auto _ : State) {
 pseudo::ForestArena Forest;
 pseudo::GSS GSS;
-glrParse(ParseableStream, ParseParams{*G, Table, Forest, GSS});
+glrParse(ParseableStream, ParseParams{*G, Table, Forest, GSS}, 
StartSymbol);
   }
   State.SetBytesProcessed(static_cast(State.iterations()) *
   SourceText->size());
@@ -116,10 +117,12 @@ BENCHMARK(runGLRParse);
 static void runParseOverall(benchmark::State &State) {
   clang::LangOptions LangOpts = genericLangOpts();
   LRTable Table = clang::pseudo::LRTable::buildSLR(*G);
+  SymbolID StartSymbol = *G->findNonterminal("translation-unit");
   for (auto _ : State) {
 pseudo::ForestArena Forest;
 pseudo::GSS GSS;
-glrParse(parseableTokenStream(), ParseParams{*G, Table, Forest, GSS});
+glrParse(parseableTokenStream(), ParseParams{*G, Table, Forest, GSS},
+ StartSymbol);
   }
   State.SetBytesProcessed(static_cast(State.iterations()) *
   SourceText->size());

diff  --git a/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp 
b/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
index 4907fc9f9c049..7b59eec30dbdf 100644
--- a/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
+++ b/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
@@ -58,8 +58,9 @@ class Fuzzer {
 
 clang::pseudo::ForestArena Arena;
 clang::pseudo::GSS GSS;
-auto &Root = glrParse(ParseableStream,
-  clang::pseudo::ParseParams{*G, T, Arena, GSS});
+auto &Root =
+glrParse(ParseableStream, clang::pseudo::ParseParams{*G, T, Arena, 
GSS},
+ *G->findNonterminal("translation-unit"));
 if (Print)
   llvm::outs() << Root.dumpRecursive(*G);
   }

diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
index f4eb424dd53fa..70d6e46e5aed3 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
@@ -122,13 +122,14 @@ struct ParseParams {
   ForestArena &Forest;  // Storage for the output forest.
   GSS &GSStack; // Storage for parsing stacks.
 };
-// Parse the given token stream with the GLR algorithm, and return a forest 
node
-// of the start symbol.
+// Parses the given token stream as the start symbol with the GLR algorithm,
+// and returns a forest node of the start symbol.
 //
-// If the parsing fails, we model it as an opaque node in the forest.
+// A rule `_ := StartSymbol` must exit for the chosen start symbol.
 //
-//

[PATCH] D125006: [pseudo] Support parsing variant target symbols.

2022-05-16 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
hokein marked 2 inline comments as done.
Closed by commit rG1a65c491be71: [pseudo] Support parsing variant target 
symbols. (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D125006?vs=429645&id=429647#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125006

Files:
  clang-tools-extra/pseudo/benchmarks/Benchmark.cpp
  clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
  clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
  clang-tools-extra/pseudo/include/clang-pseudo/Grammar.h
  clang-tools-extra/pseudo/include/clang-pseudo/LRGraph.h
  clang-tools-extra/pseudo/include/clang-pseudo/LRTable.h
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/lib/Grammar.cpp
  clang-tools-extra/pseudo/lib/LRGraph.cpp
  clang-tools-extra/pseudo/lib/LRTable.cpp
  clang-tools-extra/pseudo/lib/LRTableBuild.cpp
  clang-tools-extra/pseudo/lib/cxx.bnf
  clang-tools-extra/pseudo/test/glr-variant-start.cpp
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp
  clang-tools-extra/pseudo/unittests/GLRTest.cpp
  clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Index: clang-tools-extra/pseudo/unittests/GrammarTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GrammarTest.cpp
+++ clang-tools-extra/pseudo/unittests/GrammarTest.cpp
@@ -112,7 +112,7 @@
 b := a
   )cpp");
 
-  EXPECT_EQ(G->startSymbol(), id("_"));
+  EXPECT_EQ(G->underscore(), id("_"));
   EXPECT_THAT(Diags, UnorderedElementsAre(
  "Rule '_ := ,_opt' has a nullable RHS",
  "Rule 'null := ' has a nullable RHS",
Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -344,7 +344,8 @@
   const TokenStream &Tokens = cook(lex("{ abc", LOptions), LOptions);
   auto LRTable = LRTable::buildSLR(*G);
 
-  const ForestNode &Parsed = glrParse(Tokens, {*G, LRTable, Arena, GSStack});
+  const ForestNode &Parsed =
+  glrParse(Tokens, {*G, LRTable, Arena, GSStack}, id("test"));
   // Verify that there is no duplicated sequence node of `expr := IDENTIFIER`
   // in the forest, see the `#1` and `=#1` in the dump string.
   EXPECT_EQ(Parsed.dumpRecursive(*G),
@@ -381,7 +382,8 @@
   const TokenStream &Tokens = cook(lex("IDENTIFIER", LOptions), LOptions);
   auto LRTable = LRTable::buildSLR(*G);
 
-  const ForestNode &Parsed = glrParse(Tokens, {*G, LRTable, Arena, GSStack});
+  const ForestNode &Parsed =
+  glrParse(Tokens, {*G, LRTable, Arena, GSStack}, id("test"));
   EXPECT_EQ(Parsed.dumpRecursive(*G),
 "[  0, end) test := \n"
 "[  0, end) ├─test := IDENTIFIER\n"
Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -43,6 +43,9 @@
 desc("Strip directives and select conditional sections"));
 static opt PrintStatistics("print-statistics", desc("Print GLR parser statistics"));
 static opt PrintForest("print-forest", desc("Print parse forest"));
+static opt StartSymbol("start-symbol",
+desc("specify the start symbol to parse"),
+init("translation-unit"));
 
 static std::string readOrDie(llvm::StringRef Path) {
   llvm::ErrorOr> Text =
@@ -110,9 +113,16 @@
 if (ParseableStream) {
   clang::pseudo::ForestArena Arena;
   clang::pseudo::GSS GSS;
-  auto &Root =
-  glrParse(*ParseableStream,
-   clang::pseudo::ParseParams{*G, LRTable, Arena, GSS});
+  llvm::Optional StartSymID =
+  G->findNonterminal(StartSymbol);
+  if (!StartSymID) {
+llvm::errs() << llvm::formatv(
+"The start symbol {0} doesn't exit in the grammar!\n", Grammar);
+return 2;
+  }
+  auto &Root = glrParse(*ParseableStream,
+clang::pseudo::ParseParams{*G, LRTable, Arena, GSS},
+*StartSymID);
   if (PrintForest)
 llvm::outs() << Root.dumpRecursive(*G, /*Abbreviated=*/true);
 
Index: clang-tools-extra/pseudo/test/glr-variant-start.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/glr-variant-start.cpp
@@ -0,0 +1,9 @@
+// RUN: clang-pseudo -grammar=%cxx-bnf-file -source=%s --start-symbol=statement-seq --print-forest | FileCheck %s
+
+a + a;
+// CHECK:  statement-seq~expression-statement := expression ;
+// CHECK-NEXT: ├─expression~additive-expression := additive-expression + multiplicati

[PATCH] D124688: [clangd] parse all make_unique-like functions in preamble

2022-05-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Thanks, this looks good now! A last few nits here.

Would you like me to commit for you?
From your patches so far, I think it's appropriate to request commit access 
 if you 
want it.




Comment at: clang-tools-extra/clangd/ClangdServer.cpp:221
   std::string ActualVersion = DraftMgr.addDraft(File, Version, Contents);
-  ParseOptions Opts;
+  ParseOptions Opts{PreambleParseForwardingFunctions};
 

nit: rather assign
Opts.PreambleParseForwardingFunctions = PreambleParseForwardingFunctions

booleans in these opts structs are particularly prone to accidentally 
reordering and mis-assigning

One day we'll have designated initializers for this...



Comment at: clang-tools-extra/clangd/Preamble.cpp:140
 
+  bool isLikelyForwardingFunction(FunctionTemplateDecl *FT) {
+const auto *FD = FT->getTemplatedDecl();

nit: this can be static, and I think it'd be slightly clearer (e.g. that this 
doesn't interact with the policy flag)



Comment at: clang-tools-extra/clangd/Preamble.cpp:166
+// interesting overload resolution happens inside the forwarding
+// function's body. To provide more meaningful meaningful diagnostics,
+// code completion, and parameter hints we should parse (and later

nit: only one "meaningful" :-)



Comment at: clang-tools-extra/clangd/unittests/TestTU.h:84
   // The result will always have getDiagnostics() populated.
-  ParsedAST build() const;
+  ParsedAST build(ParseOptions Opts = {}) const;
   std::shared_ptr

Instead of adding a parameter here, we should add it to the TestTU struct and 
use it in inputs().

*many* things affect the behavior of build(), and tests would quickly become 
unreadable if we passed many of them as parameters. So we hold the line at zero 
:-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124688

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


[PATCH] D124435: [X86] Always extend the integer parameters in callee

2022-05-16 Thread LiuChen via Phabricator via cfe-commits
LiuChen3 added a comment.

Thanks, @rjmccall . I'm sorry I don't have much time on this patch recently. I 
will update it later.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124435

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


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

2022-05-16 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added inline comments.



Comment at: clang-tools-extra/clangd/InlayHints.cpp:208
+// If the parameter is part of an expanded pack and not yet resolved
+if (/*isExpandedParameter(Param) && */
+ForwardedParams.find(Param) == ForwardedParams.end()) {

upsj wrote:
> This needs to be fixed, see `ParameterHints.VariadicPlain` vs. 
> `ParameterHints.VariadicForwarded` if uncommented - I'd need some input from 
> somebody with more knowledge about the AST
It looks like `isExpandedParameter()` relies on the `SubstTemplateTypeParmType` 
type sugar being present in the ParmVarDecl's type, but in some cases, the 
ParmVarDecl's type points to the canonical type directly.

I'm not sure what sort of guarantees the AST intends to make about the presence 
of type sugar. Based on past experience with Eclipse CDT, it's very easy to 
lose type sugar and maintaining it in all the right places takes some effort.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

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


[PATCH] D125547: [analyzer][solver] Handle UnarySymExpr in SMTConv

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

Something is messed up with the diff. You refer to `fromUnOp()` but it's not 
defined anywhere.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125547

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


[PATCH] D125628: [flang][driver] Add support for generating executables on MacOSX/Darwin

2022-05-16 Thread Diana Picus via Phabricator via cfe-commits
rovka accepted this revision.
rovka added a comment.
This revision is now accepted and ready to land.

LGTM, I'll try to send one for Windows this week.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125628

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


[PATCH] D125318: [analyzer] Add UnarySymExpr

2022-05-16 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/test/Analysis/unary-sym-expr.c:35
+return;
+  clang_analyzer_eval(-(x + y) == -3); // expected-warning{{TRUE}}
+}

martong wrote:
> steakhal wrote:
> > Does it work if you swap x and y?
> No, that does not. And the reason of that is we cannot handle commutativity 
> (yet).
We could still test it, and put there a FIXME.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125318

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


[PATCH] D124688: [clangd] parse all make_unique-like functions in preamble

2022-05-16 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj updated this revision to Diff 429653.
upsj marked 4 inline comments as done.
upsj added a comment.

review updates


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124688

Files:
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Compiler.h
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/tool/Check.cpp
  clang-tools-extra/clangd/tool/ClangdMain.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp
  clang-tools-extra/clangd/unittests/TestTU.h

Index: clang-tools-extra/clangd/unittests/TestTU.h
===
--- clang-tools-extra/clangd/unittests/TestTU.h
+++ clang-tools-extra/clangd/unittests/TestTU.h
@@ -66,6 +66,9 @@
   // Simulate a header guard of the header (using an #import directive).
   bool ImplicitHeaderGuard = true;
 
+  // Parse options pass on to the ParseInputs
+  ParseOptions ParseOpts = {};
+
   // Whether to use overlay the TestFS over the real filesystem. This is
   // required for use of implicit modules.where the module file is written to
   // disk and later read back.
Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -107,6 +107,7 @@
 ParsedAST TestTU::build() const {
   MockFS FS;
   auto Inputs = inputs(FS);
+  Inputs.Opts = ParseOpts;
   StoreDiags Diags;
   auto CI = buildCompilerInvocation(Inputs, Diags);
   assert(CI && "Failed to build compilation invocation.");
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -389,7 +389,7 @@
 namespace std {
 // These mocks aren't quite right - we omit unique_ptr for simplicity.
 // forward is included to show its body is not needed to get the diagnostic.
-template  T&& forward(T& t) { return static_cast(t); }
+template  T&& forward(T& t);
 template  T* make_unique(A&&... args) {
return new T(std::forward(args)...);
 }
@@ -402,6 +402,32 @@
"no matching constructor for initialization of 'S'")));
 }
 
+TEST(DiagnosticTest, MakeShared) {
+  // We usually miss diagnostics from header functions as we don't parse them.
+  // std::make_shared is only parsed when --parse-forwarding-functions is set
+  Annotations Main(R"cpp(
+struct S { S(char*); };
+auto x = std::[[make_shared]](42); // error-ok
+  )cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.HeaderCode = R"cpp(
+namespace std {
+// These mocks aren't quite right - we omit shared_ptr for simplicity.
+// forward is included to show its body is not needed to get the diagnostic.
+template  T&& forward(T& t);
+template  T* make_shared(A&&... args) {
+   return new T(std::forward(args)...);
+}
+}
+  )cpp";
+  TU.ParseOpts.PreambleParseForwardingFunctions = true;
+  EXPECT_THAT(*TU.build().getDiagnostics(),
+  UnorderedElementsAre(
+  Diag(Main.range(),
+   "in template: "
+   "no matching constructor for initialization of 'S'")));
+}
+
 TEST(DiagnosticTest, NoMultipleDiagnosticInFlight) {
   Annotations Main(R"cpp(
 template  struct Foo {
Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -498,6 +498,14 @@
   Hidden,
   init(ClangdServer::Options().UseDirtyHeaders)};
 
+opt PreambleParseForwardingFunctions{
+"parse-forwarding-functions",
+cat(Misc),
+desc("Parse all emplace-like functions in included headers"),
+Hidden,
+init(ParseOptions().PreambleParseForwardingFunctions),
+};
+
 #if defined(__GLIBC__) && CLANGD_MALLOC_TRIM
 opt EnableMallocTrim{
 "malloc-trim",
@@ -935,6 +943,7 @@
 Opts.ClangTidyProvider = ClangTidyOptProvider;
   }
   Opts.UseDirtyHeaders = UseDirtyHeaders;
+  Opts.PreambleParseForwardingFunctions = PreambleParseForwardingFunctions;
   Opts.QueryDriverGlobs = std::move(QueryDriverGlobs);
   Opts.TweakFilter = [&](const Tweak &T) {
 if (T.hidden() && !HiddenFeatures)
Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -126,6 +126,8 @@
 Inputs.CompileCommand = Cmd;
 Inputs.TFS = &TFS;
 Inputs.ClangTidyProvider = Opts.ClangTidyProvider;
+Inputs

[PATCH] D124688: [clangd] parse all make_unique-like functions in preamble

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

@sammccall Feel free to merge with Author: Tobias Ribizel 
Thanks for the vote of confidence, I'll apply once the forwarding stuff is done 
:)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124688

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


[PATCH] D125673: [clangd] Add command-line flag to set background indexing thread priority.

2022-05-16 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added subscribers: usaxena95, arphaman.
Herald added a project: All.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

This is a followup to D124715 , which changed 
the default, and it anticipates
future patches raising the priority of Low (which is currently equal to
Background on Windows & Linux).
The main point is to allow users to restore the old behavior, which e.g.
allows efficiency cores to remain idle.

I did consider making this a config setting, this is a more complicated change:

- needs to touch queue priorities as well as thread priorities
- we don't know the priority until evaluating the config inside the task
- users would want the ability to prioritize background indexing tasks relative 
to each other without necessarily affecting thread priority, so using one 
option for both may be confusing

I don't really have a use case, so I prefer the simpler thing.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125673

Files:
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/Background.h
  clang-tools-extra/clangd/tool/ClangdMain.cpp


Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -169,6 +169,21 @@
 init(true),
 };
 
+opt BackgroundIndexPriority{
+"background-index-priority",
+cat(Features),
+desc("Thread priority for building the background index. "
+ "The effect of this flag is OS-specific."),
+values(clEnumValN(llvm::ThreadPriority::Background, "background",
+  "Minimum priority, runs on idle CPUs. "
+  "May leave 'performance' cores unused."),
+   clEnumValN(llvm::ThreadPriority::Low, "low",
+  "Reduced priority compared to interactive work."),
+   clEnumValN(llvm::ThreadPriority::Default, "normal",
+  "Same priority as other clangd work.")),
+init(llvm::ThreadPriority::Low),
+};
+
 opt EnableClangTidy{
 "clang-tidy",
 cat(Features),
@@ -868,6 +883,7 @@
   }
 #endif
   Opts.BackgroundIndex = EnableBackgroundIndex;
+  Opts.BackgroundIndexPriority = BackgroundIndexPriority;
   Opts.ReferencesLimit = ReferencesLimit;
   auto PAI = createProjectAwareIndex(loadExternalIndex, Sync);
   if (StaticIdx) {
Index: clang-tools-extra/clangd/index/Background.h
===
--- clang-tools-extra/clangd/index/Background.h
+++ clang-tools-extra/clangd/index/Background.h
@@ -136,6 +136,8 @@
 // Arbitrary value to ensure some concurrency in tests.
 // In production an explicit value is specified.
 size_t ThreadPoolSize = 4;
+// Thread priority when indexing files.
+llvm::ThreadPriority IndexingPriority = llvm::ThreadPriority::Low;
 // Callback that provides notifications as indexing makes progress.
 std::function OnProgress = nullptr;
 // Function called to obtain the Context to use while indexing the 
specified
@@ -194,6 +196,7 @@
   // configuration
   const ThreadsafeFS &TFS;
   const GlobalCompilationDatabase &CDB;
+  llvm::ThreadPriority IndexingPriority;
   std::function ContextProvider;
 
   llvm::Error index(tooling::CompileCommand);
Index: clang-tools-extra/clangd/index/Background.cpp
===
--- clang-tools-extra/clangd/index/Background.cpp
+++ clang-tools-extra/clangd/index/Background.cpp
@@ -92,6 +92,7 @@
 const ThreadsafeFS &TFS, const GlobalCompilationDatabase &CDB,
 BackgroundIndexStorage::Factory IndexStorageFactory, Options Opts)
 : SwapIndex(std::make_unique()), TFS(TFS), CDB(CDB),
+  IndexingPriority(Opts.IndexingPriority),
   ContextProvider(std::move(Opts.ContextProvider)),
   IndexedSymbols(IndexContents::All),
   Rebuilder(this, &IndexedSymbols, Opts.ThreadPoolSize),
@@ -165,6 +166,7 @@
   elog("Indexing {0} failed: {1}", Path, std::move(Error));
   });
   T.QueuePri = IndexFile;
+  T.ThreadPri = IndexingPriority;
   T.Tag = std::move(Tag);
   T.Key = Key;
   return T;
Index: clang-tools-extra/clangd/ClangdServer.h
===
--- clang-tools-extra/clangd/ClangdServer.h
+++ clang-tools-extra/clangd/ClangdServer.h
@@ -110,6 +110,7 @@
 /// If true, ClangdServer automatically indexes files in the current 
project
 /// on background threads. The index is stored in the project root.
 bool BackgroundIndex = false;
+llvm::ThreadPriority BackgroundIndexPriority = llvm::ThreadPriority::Low;
 
 /// If set, use this index to augment code complet

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

2022-05-16 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added inline comments.



Comment at: clang-tools-extra/clangd/InlayHints.cpp:208
+// If the parameter is part of an expanded pack and not yet resolved
+if (/*isExpandedParameter(Param) && */
+ForwardedParams.find(Param) == ForwardedParams.end()) {

nridge wrote:
> upsj wrote:
> > This needs to be fixed, see `ParameterHints.VariadicPlain` vs. 
> > `ParameterHints.VariadicForwarded` if uncommented - I'd need some input 
> > from somebody with more knowledge about the AST
> It looks like `isExpandedParameter()` relies on the 
> `SubstTemplateTypeParmType` type sugar being present in the ParmVarDecl's 
> type, but in some cases, the ParmVarDecl's type points to the canonical type 
> directly.
> 
> I'm not sure what sort of guarantees the AST intends to make about the 
> presence of type sugar. Based on past experience with Eclipse CDT, it's very 
> easy to lose type sugar and maintaining it in all the right places takes some 
> effort.
Upon further investigation, it looks like the ParmVarDecl is retaining the type 
sugar fine, it's the `getNonReferenceType()` call in `isExpandedParameter()` 
that loses it.

What happens with perfect forwarding when the argument is an lvalue is a bit 
subtle. In this testcase:

```
template 
void bar(Args&&... args) { return foo(std::forward(args)...); }
void baz() {
  int b;
  bar($param[[b]]);
}
```

the template argument that `bar()` is instantiated with is `Args = [int &]`. 
Substituting into `Args&&`, that then becomes `int& &&` which collapses into 
`int&`, leaving the instantiated parameter type an lvalue reference type.

Clang does in fact model this accurately, which means the type structure is:

```
BuiltinType
  ReferenceType
SubstTemplateTypeParmType
  ReferenceType
```

The outer reference type is the `&&` that's outside the `Args`, the 
`SubstTemplateTypeParmType` reflects the substitution `Args = int&`, and the 
inner `ReferenceType` is the `int&`.

The problem is, `getNonReferenceType()` unpacks _all_ the reference types, 
skipping past the `SubstTemplateTypeParmType` and giving you the `BuiltinType`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

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


[clang-tools-extra] 71cb8c8 - [clangd] parse all make_unique-like functions in preamble

2022-05-16 Thread Sam McCall via cfe-commits

Author: Tobias Ribizel
Date: 2022-05-16T11:17:25+02:00
New Revision: 71cb8c8cb9c162448159f2bffd2c77a8ee82d71f

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

LOG: [clangd] parse all make_unique-like functions in preamble

I am working on support for forwarding parameter names in make_unique-like 
functions, first for inlay hints, later maybe for signature help.
For that to work generically, I'd like to parse all of these functions in the 
preamble. Not sure how this impacts performance on large codebases though.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/ClangdServer.cpp
clang-tools-extra/clangd/ClangdServer.h
clang-tools-extra/clangd/Compiler.h
clang-tools-extra/clangd/Preamble.cpp
clang-tools-extra/clangd/tool/Check.cpp
clang-tools-extra/clangd/tool/ClangdMain.cpp
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
clang-tools-extra/clangd/unittests/TestTU.cpp
clang-tools-extra/clangd/unittests/TestTU.h

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index f9ac911aaf5a..80d7d5c5ece1 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -148,7 +148,9 @@ ClangdServer::ClangdServer(const GlobalCompilationDatabase 
&CDB,
 : FeatureModules(Opts.FeatureModules), CDB(CDB), TFS(TFS),
   DynamicIdx(Opts.BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
   ClangTidyProvider(Opts.ClangTidyProvider),
-  UseDirtyHeaders(Opts.UseDirtyHeaders), WorkspaceRoot(Opts.WorkspaceRoot),
+  UseDirtyHeaders(Opts.UseDirtyHeaders),
+  PreambleParseForwardingFunctions(Opts.PreambleParseForwardingFunctions),
+  WorkspaceRoot(Opts.WorkspaceRoot),
   Transient(Opts.ImplicitCancellation ? TUScheduler::InvalidateOnUpdate
   : TUScheduler::NoInvalidation),
   DirtyFS(std::make_unique(TFS, DraftMgr)) {
@@ -217,6 +219,7 @@ void ClangdServer::addDocument(PathRef File, 
llvm::StringRef Contents,
WantDiagnostics WantDiags, bool ForceRebuild) {
   std::string ActualVersion = DraftMgr.addDraft(File, Version, Contents);
   ParseOptions Opts;
+  Opts.PreambleParseForwardingFunctions = PreambleParseForwardingFunctions;
 
   // Compile command is set asynchronously during update, as it can be slow.
   ParseInputs Inputs;
@@ -910,7 +913,7 @@ void ClangdServer::getAST(PathRef File, 
llvm::Optional R,
   // It's safe to pass in the TU, as dumpAST() does not
   // deserialize the preamble.
   auto Node = DynTypedNode::create(
-*Inputs->AST.getASTContext().getTranslationUnitDecl());
+  *Inputs->AST.getASTContext().getTranslationUnitDecl());
   return CB(dumpAST(Node, Inputs->AST.getTokens(),
 Inputs->AST.getASTContext()));
 }

diff  --git a/clang-tools-extra/clangd/ClangdServer.h 
b/clang-tools-extra/clangd/ClangdServer.h
index a37b3c97d911..d1854c5f903e 100644
--- a/clang-tools-extra/clangd/ClangdServer.h
+++ b/clang-tools-extra/clangd/ClangdServer.h
@@ -164,6 +164,9 @@ class ClangdServer {
 /// If true, use the dirty buffer contents when building Preambles.
 bool UseDirtyHeaders = false;
 
+// If true, parse emplace-like functions in the preamble.
+bool PreambleParseForwardingFunctions = false;
+
 explicit operator TUScheduler::Options() const;
   };
   // Sensible default options for use in tests.
@@ -416,6 +419,8 @@ class ClangdServer {
 
   bool UseDirtyHeaders = false;
 
+  bool PreambleParseForwardingFunctions = false;
+
   // GUARDED_BY(CachedCompletionFuzzyFindRequestMutex)
   llvm::StringMap>
   CachedCompletionFuzzyFindRequestByFile;

diff  --git a/clang-tools-extra/clangd/Compiler.h 
b/clang-tools-extra/clangd/Compiler.h
index ca856a8bde9a..4ddb737c543e 100644
--- a/clang-tools-extra/clangd/Compiler.h
+++ b/clang-tools-extra/clangd/Compiler.h
@@ -39,7 +39,7 @@ class IgnoreDiagnostics : public DiagnosticConsumer {
 
 // Options to run clang e.g. when parsing AST.
 struct ParseOptions {
-  // (empty at present, formerly controlled recovery AST, include-fixer etc)
+  bool PreambleParseForwardingFunctions = false;
 };
 
 /// Information required to run clang, e.g. to parse AST or do code completion.

diff  --git a/clang-tools-extra/clangd/Preamble.cpp 
b/clang-tools-extra/clangd/Preamble.cpp
index 81d7c463ed7a..9fc249afcc22 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -66,9 +66,10 @@ class CppFilePreambleCallbacks : public PreambleCallbacks {
 public:
   CppFilePreambleCallbacks(
   PathRef File

[PATCH] D124688: [clangd] parse all make_unique-like functions in preamble

2022-05-16 Thread Sam McCall 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 rG71cb8c8cb9c1: [clangd] parse all make_unique-like functions 
in preamble (authored by upsj, committed by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124688

Files:
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Compiler.h
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/tool/Check.cpp
  clang-tools-extra/clangd/tool/ClangdMain.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp
  clang-tools-extra/clangd/unittests/TestTU.h

Index: clang-tools-extra/clangd/unittests/TestTU.h
===
--- clang-tools-extra/clangd/unittests/TestTU.h
+++ clang-tools-extra/clangd/unittests/TestTU.h
@@ -66,6 +66,9 @@
   // Simulate a header guard of the header (using an #import directive).
   bool ImplicitHeaderGuard = true;
 
+  // Parse options pass on to the ParseInputs
+  ParseOptions ParseOpts = {};
+
   // Whether to use overlay the TestFS over the real filesystem. This is
   // required for use of implicit modules.where the module file is written to
   // disk and later read back.
Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -109,6 +109,7 @@
 ParsedAST TestTU::build() const {
   MockFS FS;
   auto Inputs = inputs(FS);
+  Inputs.Opts = ParseOpts;
   StoreDiags Diags;
   auto CI = buildCompilerInvocation(Inputs, Diags);
   assert(CI && "Failed to build compilation invocation.");
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -389,7 +389,7 @@
 namespace std {
 // These mocks aren't quite right - we omit unique_ptr for simplicity.
 // forward is included to show its body is not needed to get the diagnostic.
-template  T&& forward(T& t) { return static_cast(t); }
+template  T&& forward(T& t);
 template  T* make_unique(A&&... args) {
return new T(std::forward(args)...);
 }
@@ -402,6 +402,32 @@
"no matching constructor for initialization of 'S'")));
 }
 
+TEST(DiagnosticTest, MakeShared) {
+  // We usually miss diagnostics from header functions as we don't parse them.
+  // std::make_shared is only parsed when --parse-forwarding-functions is set
+  Annotations Main(R"cpp(
+struct S { S(char*); };
+auto x = std::[[make_shared]](42); // error-ok
+  )cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.HeaderCode = R"cpp(
+namespace std {
+// These mocks aren't quite right - we omit shared_ptr for simplicity.
+// forward is included to show its body is not needed to get the diagnostic.
+template  T&& forward(T& t);
+template  T* make_shared(A&&... args) {
+   return new T(std::forward(args)...);
+}
+}
+  )cpp";
+  TU.ParseOpts.PreambleParseForwardingFunctions = true;
+  EXPECT_THAT(*TU.build().getDiagnostics(),
+  UnorderedElementsAre(
+  Diag(Main.range(),
+   "in template: "
+   "no matching constructor for initialization of 'S'")));
+}
+
 TEST(DiagnosticTest, NoMultipleDiagnosticInFlight) {
   Annotations Main(R"cpp(
 template  struct Foo {
Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -497,6 +497,14 @@
   Hidden,
   init(ClangdServer::Options().UseDirtyHeaders)};
 
+opt PreambleParseForwardingFunctions{
+"parse-forwarding-functions",
+cat(Misc),
+desc("Parse all emplace-like functions in included headers"),
+Hidden,
+init(ParseOptions().PreambleParseForwardingFunctions),
+};
+
 #if defined(__GLIBC__) && CLANGD_MALLOC_TRIM
 opt EnableMallocTrim{
 "malloc-trim",
@@ -934,6 +942,7 @@
 Opts.ClangTidyProvider = ClangTidyOptProvider;
   }
   Opts.UseDirtyHeaders = UseDirtyHeaders;
+  Opts.PreambleParseForwardingFunctions = PreambleParseForwardingFunctions;
   Opts.QueryDriverGlobs = std::move(QueryDriverGlobs);
   Opts.TweakFilter = [&](const Tweak &T) {
 if (T.hidden() && !HiddenFeatures)
Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp

[PATCH] D124749: [clang-format] Handle Verilog preprocessor directives

2022-05-16 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

In D124749#3514224 , @sstwcw wrote:

> The two parents of this revision change the same file, so the build bot says 
> patch does not apply.  Does that mean I have to submit the parent patches 
> with less context?

Maybe just wait until one of the parents has landed. We can make a review 
without the bot. :)
Or put the parents in relation.

In D124749#3490834 , @MyDeveloperDay 
wrote:

> You add significant number of keywords here but I don't see any of them being 
> tested? can you add a unit tests to cover what you are adding

I think this is still open?




Comment at: clang/lib/Format/FormatTokenLexer.cpp:1137
+  // normal lexer if there isn't one.
+  if (!(Style.isVerilog() && readRawTokenVerilogSpecific(Tok.Tok)))
+Lex->LexFromRawLexer(Tok.Tok);

As demonstrated by me, the parens can go under in a quick read.



Comment at: clang/lib/Format/FormatTokenLexer.cpp:1105
+  static const llvm::Regex VerilogToken(
+  "^(\'|``?|((\r?\n|\r)|[^[:space:]])*)");
+

sstwcw wrote:
> HazardyKnusperkeks wrote:
> > Consider a raw string, for a better reading.
> You mean like this?
> 
> static const llvm::Regex VerilogToken(R"re(^('|``?|\\(\\)re"
>   "(\r?\n|\r)|[^[:space:]])*)");
> 
I'd put it in one line, but basically yeah.



Comment at: clang/lib/Format/FormatTokenLexer.cpp:1129
 void FormatTokenLexer::readRawToken(FormatToken &Tok) {
-  Lex->LexFromRawLexer(Tok.Tok);
+  if (!(Style.isVerilog() && readRawTokenVerilogSpecific(Tok.Tok)))
+Lex->LexFromRawLexer(Tok.Tok);

sstwcw wrote:
> HazardyKnusperkeks wrote:
> > Otherwise I don't see why you change that.
> The function is only supposed to be used for Verilog, so `&&` is correct. If 
> you mean why this part is different from D121758, I changed the name from 
> `readRawTokenLanguageSpecific` to `readRawTokenVerilogSpecific` as suggested 
> by a reviewer. Then I moved the check for language out of that function like 
> what `tryParseJSRegexLiteral` does.
I think I missed the parens.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124749

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


[PATCH] D125026: [clang-tidy][NFC] Reimplement SimplifyBooleanExpr with RecursiveASTVisitors

2022-05-16 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 429659.
njames93 added a comment.

Tweak logic for detecting nested `if`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125026

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
  clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp
@@ -2,8 +2,6 @@
 #include "ClangTidyTest.h"
 #include "readability/BracesAroundStatementsCheck.h"
 #include "readability/NamespaceCommentCheck.h"
-#include "readability/SimplifyBooleanExprMatchers.h"
-#include "clang/ASTMatchers/ASTMatchers.h"
 #include "gtest/gtest.h"
 
 namespace clang {
@@ -14,91 +12,6 @@
 using readability::NamespaceCommentCheck;
 using namespace ast_matchers;
 
-TEST_P(ASTMatchersTest, HasCaseSubstatement) {
-  EXPECT_TRUE(matches(
-  "void f() { switch (1) { case 1: return; break; default: break; } }",
-  traverse(TK_AsIs, caseStmt(hasSubstatement(returnStmt());
-}
-
-TEST_P(ASTMatchersTest, HasDefaultSubstatement) {
-  EXPECT_TRUE(matches(
-  "void f() { switch (1) { case 1: return; break; default: break; } }",
-  traverse(TK_AsIs, defaultStmt(hasSubstatement(breakStmt());
-}
-
-TEST_P(ASTMatchersTest, HasLabelSubstatement) {
-  EXPECT_TRUE(
-  matches("void f() { while (1) { bar: break; foo: return; } }",
-  traverse(TK_AsIs, labelStmt(hasSubstatement(breakStmt());
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceSimple) {
-  const char *Text = "int f() { int x = 5; if (x < 0) return 1; return 0; }";
-  EXPECT_TRUE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
-  EXPECT_FALSE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), labelStmt();
-  EXPECT_FALSE(matches(
-  Text, compoundStmt(hasSubstatementSequence(returnStmt(), ifStmt();
-  EXPECT_FALSE(matches(
-  Text, compoundStmt(hasSubstatementSequence(switchStmt(), labelStmt();
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceAlmost) {
-  const char *Text = R"code(
-int f() {
-  int x = 5;
-  if (x < 10)
-;
-  if (x < 0)
-return 1;
-  return 0;
-}
-)code";
-  EXPECT_TRUE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
-  EXPECT_TRUE(
-  matches(Text, compoundStmt(hasSubstatementSequence(ifStmt(), ifStmt();
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceComplex) {
-  const char *Text = R"code(
-int f() {
-  int x = 5;
-  if (x < 10)
-x -= 10;
-  if (x < 0)
-return 1;
-  return 0;
-}
-)code";
-  EXPECT_TRUE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
-  EXPECT_FALSE(
-  matches(Text, compoundStmt(hasSubstatementSequence(ifStmt(), expr();
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceExpression) {
-  const char *Text = R"code(
-int f() {
-  return ({ int x = 5;
-  int result;
-  if (x < 10)
-x -= 10;
-  if (x < 0)
-result = 1;
-  else
-result = 0;
-  result;
-});
-  }
-)code";
-  EXPECT_TRUE(
-  matches(Text, stmtExpr(hasSubstatementSequence(ifStmt(), expr();
-  EXPECT_FALSE(
-  matches(Text, stmtExpr(hasSubstatementSequence(ifStmt(), returnStmt();
-}
-
 // Copied from ASTMatchersTests
 static std::vector allTestClangConfigs() {
   std::vector all_configs;
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
+++ /dev/null
@@ -1,68 +0,0 @@
-//===-- SimplifyBooleanExprMatchers.h - clang-tidy ===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-
-#include "clang/ASTMatchers/ASTMatchersInternal.h"
-#include "clang/ASTMatchers/ASTMatchersMacros.h"
-
-namespace clang {
-namespace ast_matchers {
-
-/// Matches the substatement associated with a case, default or label statement.
-///
-/// Given
-/// \code
-///   switch (1) { case 1: break; case 2: return; break; default: return; break;
-///   }
-///   foo: return;
-///   bar: break;
-/// \endcode
-///
-/// caseStmt(hasSubstatement(returnStmt()))
-///   matches "case 2: return;"
-/// defaultStmt(hasSubstatement(returnStmt()))
-///   matche

[PATCH] D124748: [clang-format] Fix whitespace counting stuff

2022-05-16 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/FormatTokenLexer.cpp:839
 
+void FormatTokenLexer::resizeToken(size_t NewLen) {
+  resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(

sstwcw wrote:
> HazardyKnusperkeks wrote:
> > Can you add some documentation?
> Is this comment enough?
Maybe some reasoning?

Also I think NewLen shouldn't be bigger than `FormatTok->TokenText.size()` 
should it? Add an assert and a comment on the restriction.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124748

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


[PATCH] D125547: [analyzer][solver] Handle UnarySymExpr in SMTConv

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

In D125547#3515259 , @steakhal wrote:

> Something is messed up with the diff. You refer to `fromUnOp()` but it's not 
> defined anywhere.

No. There is no mess up here, the diff is correct. `fromUnOp` had been 
implemented way before. I missed that when I created the initial patch. So, we 
just have to call that preexisting function in `getSymExpr`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125547

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


[PATCH] D125026: [clang-tidy][NFC] Reimplement SimplifyBooleanExpr with RecursiveASTVisitors

2022-05-16 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 429660.
njames93 added a comment.

Nit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125026

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
  clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp
@@ -2,8 +2,6 @@
 #include "ClangTidyTest.h"
 #include "readability/BracesAroundStatementsCheck.h"
 #include "readability/NamespaceCommentCheck.h"
-#include "readability/SimplifyBooleanExprMatchers.h"
-#include "clang/ASTMatchers/ASTMatchers.h"
 #include "gtest/gtest.h"
 
 namespace clang {
@@ -14,91 +12,6 @@
 using readability::NamespaceCommentCheck;
 using namespace ast_matchers;
 
-TEST_P(ASTMatchersTest, HasCaseSubstatement) {
-  EXPECT_TRUE(matches(
-  "void f() { switch (1) { case 1: return; break; default: break; } }",
-  traverse(TK_AsIs, caseStmt(hasSubstatement(returnStmt());
-}
-
-TEST_P(ASTMatchersTest, HasDefaultSubstatement) {
-  EXPECT_TRUE(matches(
-  "void f() { switch (1) { case 1: return; break; default: break; } }",
-  traverse(TK_AsIs, defaultStmt(hasSubstatement(breakStmt());
-}
-
-TEST_P(ASTMatchersTest, HasLabelSubstatement) {
-  EXPECT_TRUE(
-  matches("void f() { while (1) { bar: break; foo: return; } }",
-  traverse(TK_AsIs, labelStmt(hasSubstatement(breakStmt());
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceSimple) {
-  const char *Text = "int f() { int x = 5; if (x < 0) return 1; return 0; }";
-  EXPECT_TRUE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
-  EXPECT_FALSE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), labelStmt();
-  EXPECT_FALSE(matches(
-  Text, compoundStmt(hasSubstatementSequence(returnStmt(), ifStmt();
-  EXPECT_FALSE(matches(
-  Text, compoundStmt(hasSubstatementSequence(switchStmt(), labelStmt();
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceAlmost) {
-  const char *Text = R"code(
-int f() {
-  int x = 5;
-  if (x < 10)
-;
-  if (x < 0)
-return 1;
-  return 0;
-}
-)code";
-  EXPECT_TRUE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
-  EXPECT_TRUE(
-  matches(Text, compoundStmt(hasSubstatementSequence(ifStmt(), ifStmt();
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceComplex) {
-  const char *Text = R"code(
-int f() {
-  int x = 5;
-  if (x < 10)
-x -= 10;
-  if (x < 0)
-return 1;
-  return 0;
-}
-)code";
-  EXPECT_TRUE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
-  EXPECT_FALSE(
-  matches(Text, compoundStmt(hasSubstatementSequence(ifStmt(), expr();
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceExpression) {
-  const char *Text = R"code(
-int f() {
-  return ({ int x = 5;
-  int result;
-  if (x < 10)
-x -= 10;
-  if (x < 0)
-result = 1;
-  else
-result = 0;
-  result;
-});
-  }
-)code";
-  EXPECT_TRUE(
-  matches(Text, stmtExpr(hasSubstatementSequence(ifStmt(), expr();
-  EXPECT_FALSE(
-  matches(Text, stmtExpr(hasSubstatementSequence(ifStmt(), returnStmt();
-}
-
 // Copied from ASTMatchersTests
 static std::vector allTestClangConfigs() {
   std::vector all_configs;
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
+++ /dev/null
@@ -1,68 +0,0 @@
-//===-- SimplifyBooleanExprMatchers.h - clang-tidy ===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-
-#include "clang/ASTMatchers/ASTMatchersInternal.h"
-#include "clang/ASTMatchers/ASTMatchersMacros.h"
-
-namespace clang {
-namespace ast_matchers {
-
-/// Matches the substatement associated with a case, default or label statement.
-///
-/// Given
-/// \code
-///   switch (1) { case 1: break; case 2: return; break; default: return; break;
-///   }
-///   foo: return;
-///   bar: break;
-/// \endcode
-///
-/// caseStmt(hasSubstatement(returnStmt()))
-///   matches "case 2: return;"
-/// defaultStmt(hasSubstatement(returnStmt()))
-///   matches "default: return;"
-/// labelStm

[clang] 9dffab9 - [clang-format][NFC] Don't call mightFitOnOneLine() unnecessarily

2022-05-16 Thread via cfe-commits

Author: owenca
Date: 2022-05-16T02:43:35-07:00
New Revision: 9dffab9d524a05742a765dea27aedc8a7080a402

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

LOG: [clang-format][NFC] Don't call mightFitOnOneLine() unnecessarily

Clean up UnwrappedLineParser for RemoveBracesLLVM to avoid calling
mightFitOnOneLine() as much as possible.

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

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index fa76da15a53d..9990933fcb20 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -43,12 +43,15 @@ namespace format {
   TYPE(ConflictAlternative)
\
   TYPE(ConflictEnd)
\
   TYPE(ConflictStart)  
\
+  /* l_brace of if/for/while */
\
+  TYPE(ControlStatementLBrace) 
\
   TYPE(CppCastLParen)  
\
   TYPE(CtorInitializerColon)   
\
   TYPE(CtorInitializerComma)   
\
   TYPE(DesignatedInitializerLSquare)   
\
   TYPE(DesignatedInitializerPeriod)
\
   TYPE(DictLiteral)
\
+  TYPE(ElseLBrace) 
\
   TYPE(EnumLBrace) 
\
   TYPE(FatArrow)   
\
   TYPE(ForEachMacro)   
\

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index c5135222af69..bde543131931 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -394,7 +394,7 @@ void UnwrappedLineParser::parseFile() {
   if (Style.Language == FormatStyle::LK_TextProto)
 parseBracedList();
   else
-parseLevel(/*HasOpeningBrace=*/false, /*CanContainBracedList=*/true);
+parseLevel(/*OpeningBrace=*/nullptr, /*CanContainBracedList=*/true);
   // Make sure to format the remaining tokens.
   //
   // LK_TextProto is special since its top-level is parsed as the body of a
@@ -463,13 +463,13 @@ bool 
UnwrappedLineParser::precededByCommentOrPPDirective() const {
 }
 
 /// \brief Parses a level, that is ???.
-/// \param HasOpeningBrace If that level is started by an opening brace.
+/// \param OpeningBrace Opening brace (\p nullptr if absent) of that level
 /// \param CanContainBracedList If the content can contain (at any level) a
 /// braced list.
 /// \param NextLBracesType The type for left brace found in this level.
-/// \returns true if a simple block, or false otherwise. (A simple block has a
-/// single statement.)
-bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
+/// \returns true if a simple block of if/else/for/while, or false otherwise.
+/// (A simple block has a single statement.)
+bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace,
  bool CanContainBracedList,
  IfStmtKind *IfKind,
  TokenType NextLBracesType) {
@@ -492,9 +492,9 @@ bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
 else if (FormatTok->getType() == TT_MacroBlockEnd)
   kind = tok::r_brace;
 
-auto ParseDefault = [this, HasOpeningBrace, IfKind, NextLevelLBracesType,
+auto ParseDefault = [this, OpeningBrace, IfKind, NextLevelLBracesType,
  &HasLabel, &StatementCount] {
-  parseStructuralElement(IfKind, !HasOpeningBrace, NextLevelLBracesType,
+  parseStructuralElement(IfKind, !OpeningBrace, NextLevelLBracesType,
  HasLabel ? nullptr : &HasLabel);
   ++StatementCount;
   assert(StatementCount > 0 && "StatementCount overflow!");
@@ -519,16 +519,17 @@ bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
   tryToParseBracedList())
 continue;
   parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
- /*MunchSemi=*/true, /*UnindentWhitesmithBraces=*/false,
- CanContainBracedList,
- /*NextLBracesType=*/NextLBracesType);
+ /*MunchSemi=*/

[PATCH] D125626: [clang-format][NFC] Don't call mightFitOnOneLine() unnecessarily

2022-05-16 Thread Owen Pan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9dffab9d524a: [clang-format][NFC] Don't call 
mightFitOnOneLine() unnecessarily (authored by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125626

Files:
  clang/lib/Format/FormatToken.h
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h

Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -92,12 +92,12 @@
   void reset();
   void parseFile();
   bool precededByCommentOrPPDirective() const;
-  bool parseLevel(bool HasOpeningBrace, bool CanContainBracedList,
+  bool parseLevel(const FormatToken *OpeningBrace, bool CanContainBracedList,
   IfStmtKind *IfKind = nullptr,
   TokenType NextLBracesType = TT_Unknown);
   bool mightFitOnOneLine(UnwrappedLine &Line) const;
   IfStmtKind parseBlock(bool MustBeDeclaration = false, unsigned AddLevels = 1u,
-bool MunchSemi = true,
+bool MunchSemi = true, bool KeepBraces = true,
 bool UnindentWhitesmithsBraces = false,
 bool CanContainBracedList = true,
 TokenType NextLBracesType = TT_Unknown);
@@ -126,7 +126,7 @@
   bool handleCppAttributes();
   FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false);
   void parseTryCatch();
-  void parseLoopBody(bool TryRemoveBraces, bool WrapRightBrace);
+  void parseLoopBody(bool KeepBraces, bool WrapRightBrace);
   void parseForOrWhileLoop();
   void parseDoWhile();
   void parseLabel(bool LeftAlignLabel = false);
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -394,7 +394,7 @@
   if (Style.Language == FormatStyle::LK_TextProto)
 parseBracedList();
   else
-parseLevel(/*HasOpeningBrace=*/false, /*CanContainBracedList=*/true);
+parseLevel(/*OpeningBrace=*/nullptr, /*CanContainBracedList=*/true);
   // Make sure to format the remaining tokens.
   //
   // LK_TextProto is special since its top-level is parsed as the body of a
@@ -463,13 +463,13 @@
 }
 
 /// \brief Parses a level, that is ???.
-/// \param HasOpeningBrace If that level is started by an opening brace.
+/// \param OpeningBrace Opening brace (\p nullptr if absent) of that level
 /// \param CanContainBracedList If the content can contain (at any level) a
 /// braced list.
 /// \param NextLBracesType The type for left brace found in this level.
-/// \returns true if a simple block, or false otherwise. (A simple block has a
-/// single statement.)
-bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
+/// \returns true if a simple block of if/else/for/while, or false otherwise.
+/// (A simple block has a single statement.)
+bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace,
  bool CanContainBracedList,
  IfStmtKind *IfKind,
  TokenType NextLBracesType) {
@@ -492,9 +492,9 @@
 else if (FormatTok->getType() == TT_MacroBlockEnd)
   kind = tok::r_brace;
 
-auto ParseDefault = [this, HasOpeningBrace, IfKind, NextLevelLBracesType,
+auto ParseDefault = [this, OpeningBrace, IfKind, NextLevelLBracesType,
  &HasLabel, &StatementCount] {
-  parseStructuralElement(IfKind, !HasOpeningBrace, NextLevelLBracesType,
+  parseStructuralElement(IfKind, !OpeningBrace, NextLevelLBracesType,
  HasLabel ? nullptr : &HasLabel);
   ++StatementCount;
   assert(StatementCount > 0 && "StatementCount overflow!");
@@ -519,16 +519,17 @@
   tryToParseBracedList())
 continue;
   parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
- /*MunchSemi=*/true, /*UnindentWhitesmithBraces=*/false,
- CanContainBracedList,
- /*NextLBracesType=*/NextLBracesType);
+ /*MunchSemi=*/true, /*KeepBraces=*/true,
+ /*UnindentWhitesmithsBraces=*/false, CanContainBracedList,
+ NextLBracesType);
   ++StatementCount;
   assert(StatementCount > 0 && "StatementCount overflow!");
   addUnwrappedLine();
   break;
 case tok::r_brace:
-  if (HasOpeningBrace) {
-if (!Style.RemoveBracesLLVM)
+  if (OpeningBrace) {
+if (!Style.RemoveBracesLLVM ||
+!OpeningBrace->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace))
   return false;
 if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel ||
 IsPrecededByCommentOrPP

[PATCH] D125675: Optimise findRefs for XRefs and docHighlights

2022-05-16 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 created this revision.
Herald added subscribers: kadircet, arphaman.
Herald added a project: All.
usaxena95 requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Reduces time spent in findRef by 66%.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125675

Files:
  clang-tools-extra/clangd/XRefs.cpp

Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -18,6 +18,7 @@
 #include "index/Index.h"
 #include "index/Merge.h"
 #include "index/Relation.h"
+#include "index/SymbolID.h"
 #include "index/SymbolLocation.h"
 #include "support/Logger.h"
 #include "clang/AST/ASTContext.h"
@@ -47,6 +48,7 @@
 #include "clang/Index/USRGeneration.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
@@ -54,6 +56,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/Error.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -887,8 +890,12 @@
   };
 
   ReferenceFinder(const ParsedAST &AST,
-  const llvm::DenseSet &TargetIDs, bool PerToken)
-  : PerToken(PerToken), AST(AST), TargetIDs(TargetIDs) {}
+  const llvm::DenseSet &TD, bool PerToken)
+  : PerToken(PerToken), AST(AST) {
+for (const Decl *D : TD) {
+  TargetDecls.insert(D->getCanonicalDecl());
+}
+  }
 
   std::vector take() && {
 llvm::sort(References, [](const Reference &L, const Reference &R) {
@@ -913,12 +920,11 @@
llvm::ArrayRef Relations,
SourceLocation Loc,
index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
+if (!TargetDecls.contains(D->getCanonicalDecl()))
+  return true;
 const SourceManager &SM = AST.getSourceManager();
 if (!isInsideMainFile(Loc, SM))
   return true;
-SymbolID ID = getSymbolID(D);
-if (!TargetIDs.contains(ID))
-  return true;
 const auto &TB = AST.getTokens();
 
 llvm::SmallVector Locs;
@@ -942,7 +948,7 @@
 for (SourceLocation L : Locs) {
   L = SM.getFileLoc(L);
   if (const auto *Tok = TB.spelledTokenAt(L))
-References.push_back({*Tok, Roles, ID});
+References.push_back({*Tok, Roles, getSymbolID(D)});
 }
 return true;
   }
@@ -951,12 +957,13 @@
   bool PerToken; // If true, report 3 references for split ObjC selector names.
   std::vector References;
   const ParsedAST &AST;
-  const llvm::DenseSet &TargetIDs;
+  llvm::DenseSet TargetDecls;
 };
 
 std::vector
-findRefs(const llvm::DenseSet &IDs, ParsedAST &AST, bool PerToken) {
-  ReferenceFinder RefFinder(AST, IDs, PerToken);
+findRefs(const llvm::DenseSet &TargetDecls, ParsedAST &AST,
+ bool PerToken) {
+  ReferenceFinder RefFinder(AST, TargetDecls, PerToken);
   index::IndexingOptions IndexOpts;
   IndexOpts.SystemSymbolFilter =
   index::IndexingOptions::SystemSymbolFilterKind::All;
@@ -1242,16 +1249,19 @@
 if (const SelectionTree::Node *N = ST.commonAncestor()) {
   DeclRelationSet Relations =
   DeclRelation::TemplatePattern | DeclRelation::Alias;
-  auto Decls =
-  targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver());
-  if (!Decls.empty()) {
+  llvm::DenseSet TargetDecls;
+  for (const NamedDecl *D :
+   targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver())) {
+TargetDecls.insert(D);
+  }
+  if (!TargetDecls.empty()) {
 // FIXME: we may get multiple DocumentHighlights with the same location
 // and different kinds, deduplicate them.
 llvm::DenseSet Targets;
-for (const NamedDecl *ND : Decls)
-  if (auto ID = getSymbolID(ND))
+for (const Decl *D : TargetDecls)
+  if (auto ID = getSymbolID(D))
 Targets.insert(ID);
-for (const auto &Ref : findRefs(Targets, AST, /*PerToken=*/true))
+for (const auto &Ref : findRefs(TargetDecls, AST, /*PerToken=*/true))
   Result.push_back(toHighlight(Ref, SM));
 return true;
   }
@@ -1377,12 +1387,12 @@
 DeclRelation::TemplatePattern | DeclRelation::Alias;
 std::vector Decls =
 getDeclAtPosition(AST, *CurLoc, Relations);
-llvm::DenseSet TargetsInMainFile;
+llvm::DenseSet TargetDeclsInMainFile;
 for (const NamedDecl *D : Decls) {
   auto ID = getSymbolID(D);
   if (!ID)
 continue;
-  TargetsInMainFile.insert(ID);
+  TargetDeclsInMainFile.insert(D);
   // Not all symbols can be referenced from outside (e.g. function-locals).
   // TODO: we could skip TU-scoped symbols here (e.g. static functions) if
   // we know this fi

[PATCH] D125673: [clangd] Add command-line flag to set background indexing thread priority.

2022-05-16 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks, LGTM. i agree that having this as a config to let users prioritise some 
sources over others could be useful, but it's too intrusive and unclear how 
useful that would be in practice (i don't think people would care to write a 
separate config for those)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125673

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


[PATCH] D125243: [OpenCL] Make -cl-ext a driver option

2022-05-16 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/docs/UsersManual.rst:3145-3146
+
+Note that some targets e.g. SPIR/SPIR-V enable all extensions/features in 
clang by
+default.
+

svenvh wrote:
> Was this meant to go after the command example?
true, will fix this in the final commit! Thanks!


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

https://reviews.llvm.org/D125243

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


[PATCH] D125677: [pseudo] Remove the explicit Accept actions.

2022-05-16 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added a project: All.
hokein requested review of this revision.
Herald added a subscriber: alextsao1999.
Herald added a project: clang-tools-extra.

As pointed out in the previous review section, having a dedicated accept
action doesn't seem to be necessary. This patch implements the the same behavior
without accept acction, which will save some code complexity.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125677

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/LRTable.h
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/lib/LRTable.cpp
  clang-tools-extra/pseudo/lib/LRTableBuild.cpp
  clang-tools-extra/pseudo/test/lr-build-basic.test
  clang-tools-extra/pseudo/test/lr-build-conflicts.test
  clang-tools-extra/pseudo/unittests/GLRTest.cpp
  clang-tools-extra/pseudo/unittests/LRTableTest.cpp

Index: clang-tools-extra/pseudo/unittests/LRTableTest.cpp
===
--- clang-tools-extra/pseudo/unittests/LRTableTest.cpp
+++ clang-tools-extra/pseudo/unittests/LRTableTest.cpp
@@ -33,7 +33,7 @@
   std::vector Entries = {
   {/* State */ 0, tokenSymbol(tok::semi), Action::shift(0)},
   {/* State */ 0, tokenSymbol(tok::semi), Action::reduce(0)},
-  {/* State */ 1, tokenSymbol(tok::eof), Action::accept(2)},
+  {/* State */ 1, tokenSymbol(tok::eof), Action::reduce(2)},
   {/* State */ 2, tokenSymbol(tok::semi), Action::reduce(1)}};
   GrammarTable GT;
   LRTable T = LRTable::buildForTests(GT, Entries);
@@ -41,7 +41,7 @@
   EXPECT_THAT(T.find(0, tokenSymbol(tok::semi)),
   UnorderedElementsAre(Action::shift(0), Action::reduce(0)));
   EXPECT_THAT(T.find(1, tokenSymbol(tok::eof)),
-  UnorderedElementsAre(Action::accept(2)));
+  UnorderedElementsAre(Action::reduce(2)));
   EXPECT_THAT(T.find(1, tokenSymbol(tok::semi)), IsEmpty());
   EXPECT_THAT(T.find(2, tokenSymbol(tok::semi)),
   UnorderedElementsAre(Action::reduce(1)));
Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -393,6 +393,29 @@
 "[  0, end) └─IDENTIFIER := tok[0]\n");
 }
 
+TEST_F(GLRTest, NoExplicitAccept) {
+  build(R"bnf(
+_ := test
+
+test := IDENTIFIER test
+test := IDENTIFIER
+  )bnf");
+  clang::LangOptions LOptions;
+  // Given the following input, and the grammar above, we perform two reductions
+  // of the nonterminal `test` when the next token is `eof`, verify that the
+  // parser stops at the right state.
+  const TokenStream &Tokens = cook(lex("id id", LOptions), LOptions);
+  auto LRTable = LRTable::buildSLR(*G);
+
+  const ForestNode &Parsed =
+  glrParse(Tokens, {*G, LRTable, Arena, GSStack}, id("test"));
+  EXPECT_EQ(Parsed.dumpRecursive(*G),
+"[  0, end) test := IDENTIFIER test\n"
+"[  0,   1) ├─IDENTIFIER := tok[0]\n"
+"[  1, end) └─test := IDENTIFIER\n"
+"[  1, end)   └─IDENTIFIER := tok[1]\n");
+}
+
 } // namespace
 } // namespace pseudo
 } // namespace clang
Index: clang-tools-extra/pseudo/test/lr-build-conflicts.test
===
--- clang-tools-extra/pseudo/test/lr-build-conflicts.test
+++ clang-tools-extra/pseudo/test/lr-build-conflicts.test
@@ -33,7 +33,7 @@
 # TABLE-NEXT: 'IDENTIFIER': shift state 2
 # TABLE-NEXT: 'expr': go to state 1
 # TABLE-NEXT: State 1
-# TABLE-NEXT: 'EOF': accept
+# TABLE-NEXT: 'EOF': reduce by rule 2 '_ := expr'
 # TABLE-NEXT: '-': shift state 3
 # TABLE-NEXT: State 2
 # TABLE-NEXT: 'EOF': reduce by rule 1 'expr := IDENTIFIER'
Index: clang-tools-extra/pseudo/test/lr-build-basic.test
===
--- clang-tools-extra/pseudo/test/lr-build-basic.test
+++ clang-tools-extra/pseudo/test/lr-build-basic.test
@@ -22,7 +22,7 @@
 # TABLE-NEXT: 'expr': go to state 1
 # TABLE-NEXT: 'id': go to state 2
 # TABLE-NEXT: State 1
-# TABLE-NEXT: 'EOF': accept
+# TABLE-NEXT: 'EOF': reduce by rule 2 '_ := expr'
 # TABLE-NEXT: State 2
 # TABLE-NEXT: 'EOF': reduce by rule 1 'expr := id'
 # TABLE-NEXT: State 3
Index: clang-tools-extra/pseudo/lib/LRTableBuild.cpp
===
--- clang-tools-extra/pseudo/lib/LRTableBuild.cpp
+++ clang-tools-extra/pseudo/lib/LRTableBuild.cpp
@@ -124,11 +124,6 @@
   auto FollowSets = followSets(G);
   for (StateID SID = 0; SID < Graph.states().size(); ++SID) {
 for (const Item &I : Graph.states()[SID].Items) {
-  // If we've just parsed the start symbol, we can accept the input.
-  if (G.lookupRule(I.rule()).Target == G.underscore() && !I.hasNext()) {
-Build.insert({SID, 

[PATCH] D125675: Optimise findRefs for XRefs and docHighlights

2022-05-16 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a reviewer: kadircet.
kadircet added a comment.

66% win sounds great, it would be nice to have some detailed numbers (but this 
is clearly a huge win, so no need to reperform the experiments if numbers are 
gone)




Comment at: clang-tools-extra/clangd/XRefs.cpp:895
+  : PerToken(PerToken), AST(AST) {
+for (const Decl *D : TD) {
+  TargetDecls.insert(D->getCanonicalDecl());

nit: no need for braces

you can directly build the set with canonicaldecls and consume it here



Comment at: clang-tools-extra/clangd/XRefs.cpp:951
   if (const auto *Tok = TB.spelledTokenAt(L))
-References.push_back({*Tok, Roles, ID});
+References.push_back({*Tok, Roles, getSymbolID(D)});
 }

we're still calling getsymbolid here lots of times, for probably the same 
symbol.

as discussed, what about building a lookup table on construction from 
canonicaldecl to symbolid and use that lookup table instead of calling 
getsymbolid over and over here?



Comment at: clang-tools-extra/clangd/XRefs.cpp:1255
+   targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver())) {
+TargetDecls.insert(D);
+  }

i mean directly inserting canonicaldecls here.



Comment at: clang-tools-extra/clangd/XRefs.cpp:1260
 // and different kinds, deduplicate them.
 llvm::DenseSet Targets;
+for (const Decl *D : TargetDecls)

no need for this and the following loop anymore.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125675

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


[PATCH] D125026: [clang-tidy][NFC] Reimplement SimplifyBooleanExpr with RecursiveASTVisitors

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

Since latest update speed up gone from 0.87s to 0.04s for SemaCodeComplete.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125026

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


[PATCH] D125401: [OpenCL] Do not guard vload/store_half builtins

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

LGTM! Thanks


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

https://reviews.llvm.org/D125401

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


[PATCH] D125208: [OpenCL] Fix __remove_address_space documentation code example

2022-05-16 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia accepted this revision.
Anastasia 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/D125208/new/

https://reviews.llvm.org/D125208

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


[PATCH] D125678: [clang][extract-api] Don't emit symbols prefixed with an underscore

2022-05-16 Thread Daniel Grumberg via Phabricator via cfe-commits
dang created this revision.
dang added reviewers: zixuw, ributzka, QuietMisdreavus.
Herald added a project: All.
dang requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

These symbols are understood to not be used for client API consumption
by convention so they should not appear in the generated symbol graph.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125678

Files:
  clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
  clang/test/ExtractAPI/underscored.c

Index: clang/test/ExtractAPI/underscored.c
===
--- /dev/null
+++ clang/test/ExtractAPI/underscored.c
@@ -0,0 +1,396 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%{/t:regex_replacement}@g" \
+// RUN: %t/reference.output.json.in >> %t/reference.output.json
+// RUN: %clang_cc1 -extract-api -triple arm64-apple-macosx \
+// RUN:   -x c-header %t/input.h -o %t/output.json -verify
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+//--- input.h
+// expected-no-diagnostics
+
+// Global record
+int _HiddenGlobal;
+int exposed_global;
+
+// Record type
+struct _HiddenRecord {
+  int a;
+};
+
+struct ExposedRecord {
+  int a;
+};
+
+// Typedef
+typedef struct {} _HiddenTypedef;
+typedef int ExposedTypedef;
+typedef _HiddenTypedef ExposedTypedefToHidden;
+
+// Macros
+#define _HIDDEN_MACRO 5
+#define EXPOSED_MACRO 5
+
+// Symbols that start with '_' should not appear in the reference output
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationships": [
+{
+  "kind": "memberOf",
+  "source": "c:@S@ExposedRecord@FI@a",
+  "target": "c:@S@ExposedRecord"
+}
+  ],
+  "symbols": [
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:I",
+  "spelling": "int"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "exposed_global"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "c",
+"precise": "c:@exposed_global"
+  },
+  "kind": {
+"displayName": "Global Variable",
+"identifier": "c.var"
+  },
+  "location": {
+"position": {
+  "character": 5,
+  "line": 5
+},
+"uri": "file://INPUT_DIR/input.h"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "exposed_global"
+  }
+],
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "exposed_global"
+  }
+],
+"title": "exposed_global"
+  },
+  "pathComponents": [
+"exposed_global"
+  ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "struct"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "ExposedRecord"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "c",
+"precise": "c:@S@ExposedRecord"
+  },
+  "kind": {
+"displayName": "Structure",
+"identifier": "c.struct"
+  },
+  "location": {
+"position": {
+  "character": 8,
+  "line": 12
+},
+"uri": "file://INPUT_DIR/input.h"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "ExposedRecord"
+  }
+],
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "ExposedRecord"
+  }
+],
+"title": "ExposedRecord"
+  },
+  "pathComponents": [
+"ExposedRecord"
+  ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:I",
+  "spelling": "int"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "a"

[PATCH] D125679: [Clang] Added options for integrated backend only used for SPIR-V for now

2022-05-16 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia created this revision.
Anastasia added reviewers: mpaszkowski, iliya-diyachkov, svenvh, linjamaki.
Herald added subscribers: ThomasRaoux, ebevhan.
Herald added a project: All.
Anastasia requested review of this revision.
Herald added a subscriber: MaskRay.

Following the new flow for external object code emission provide flags to 
switch between integrated and external backend similar to the integrated 
assembler options.

SPIR-V target is the only user of this functionality at this point.

This patch also updated SPIR-V documentation to clarify that integrated object 
code emission for SPIR-V is an experimental feature.


https://reviews.llvm.org/D125679

Files:
  clang/docs/UsersManual.rst
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/SPIRV.h
  clang/test/Driver/clang_f_opts.c
  clang/test/Driver/spirv-toolchain.cl

Index: clang/test/Driver/spirv-toolchain.cl
===
--- clang/test/Driver/spirv-toolchain.cl
+++ clang/test/Driver/spirv-toolchain.cl
@@ -69,3 +69,11 @@
 // SPLINK-SAME: "-o" [[BC:".*bc"]]
 // SPLINK: {{llvm-spirv.*"}} [[BC]] "-o" [[SPV2:".*o"]]
 // SPLINK: {{spirv-link.*"}} [[SPV1]] [[SPV2]] "-o" "a.out"
+
+//-
+// Check external vs internal object emission.
+// RUN: %clang -### --target=spirv64 -fno-integrated-objemitter %s 2>&1 | FileCheck --check-prefix=XTOR %s
+// RUN: %clang -### --target=spirv64 -fintegrated-objemitter %s 2>&1 | FileCheck --check-prefix=BACKEND %s
+
+// XTOR: {{llvm-spirv.*"}}
+// BACKEND-NOT: {{llvm-spirv.*"}}
Index: clang/test/Driver/clang_f_opts.c
===
--- clang/test/Driver/clang_f_opts.c
+++ clang/test/Driver/clang_f_opts.c
@@ -605,3 +605,8 @@
 // CHECK_JMC_WARN_NOT_ELF: -fjmc works only for ELF; option ignored
 // CHECK_NOJMC-NOT: -fjmc
 // CHECK_JMC: -fjmc
+
+// RUN: %clang -### -fintegrated-objemitter -target x86_64 %s 2>&1 | FileCheck -check-prefix=CHECK-INT-OBJEMITTER %s
+// CHECK-INT-OBJEMITTER-NOT: unsupported option '-fintegrated-objemitter' for target
+// RUN: %clang -### -fno-integrated-objemitter -target x86_64 %s 2>&1 | FileCheck -check-prefix=CHECK-NOINT-OBJEMITTER %s
+// CHECK-NOINT-OBJEMITTER: unsupported option '-fno-integrated-objemitter' for target
Index: clang/lib/Driver/ToolChains/SPIRV.h
===
--- clang/lib/Driver/ToolChains/SPIRV.h
+++ clang/lib/Driver/ToolChains/SPIRV.h
@@ -64,8 +64,9 @@
   : ToolChain(D, Triple, Args) {}
 
   bool useIntegratedAs() const override { return true; }
-  bool useIntegratedBackend() const override { return false; }
 
+  bool IsIntegratedBackendDefault() const override { return false; }
+  bool IsNonIntegratedBackendSupported() const override { return true; }
   bool IsMathErrnoDefault() const override { return false; }
   bool isCrossCompiling() const override { return true; }
   bool isPICDefault() const override { return false; }
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -106,6 +106,34 @@
   IsIntegratedAssemblerDefault());
 }
 
+bool ToolChain::useIntegratedBackend() const {
+  assert(
+  ((IsIntegratedBackendDefault() && IsIntegratedBackendSupported()) ||
+   (!IsIntegratedBackendDefault() || IsNonIntegratedBackendSupported())) &&
+  "(Non-)integrated backend set incorrectly!");
+
+  bool IBackend = Args.hasFlag(options::OPT_fintegrated_objemitter,
+   options::OPT_fno_integrated_objemitter,
+   IsIntegratedBackendDefault());
+
+  // Diagnose when integrated-objemitter options are not supported by this
+  // toolchain.
+  unsigned DiagID;
+  if ((IBackend && !IsIntegratedBackendSupported()) ||
+  (!IBackend && !IsNonIntegratedBackendSupported()))
+DiagID = clang::diag::err_drv_unsupported_opt_for_target;
+  else
+DiagID = clang::diag::warn_drv_unsupported_opt_for_target;
+  Arg *A = Args.getLastArg(options::OPT_fno_integrated_objemitter);
+  if (A && !IsNonIntegratedBackendSupported())
+D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
+  A = Args.getLastArg(options::OPT_fintegrated_objemitter);
+  if (A && !IsIntegratedBackendSupported())
+D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
+
+  return IBackend;
+}
+
 bool ToolChain::useRelaxRelocations() const {
   return ENABLE_X86_RELAX_RELOCATIONS;
 }
Index: clang/include/clang/Driver/ToolChain.h
===
--- clang/include/clang/Driver/ToolChain.h
+++ clang/include/clang/Driver/ToolChain.h
@@ -385,11 +385,23 @@
   /// by default.
   virtual bool IsIntegratedAssemblerDef

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

2022-05-16 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia updated this revision to Diff 429678.
Anastasia added a comment.

Fixed typo in docs


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

https://reviews.llvm.org/D124776

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

Index: llvm/unittests/ADT/TripleTest.cpp
===
--- llvm/unittests/ADT/TripleTest.cpp
+++ llvm/unittests/ADT/TripleTest.cpp
@@ -243,11 +243,85 @@
 
   T = Triple("spirv32-unknown-unknown");
   EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv32v1.0-unknown-unknown");
+  EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v10, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv32v1.1-unknown-unknown");
+  EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v11, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv32v1.2-unknown-unknown");
+  EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v12, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv32v1.3-unknown-unknown");
+  EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v13, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv32v1.4-unknown-unknown");
+  EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v14, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv32v1.5-unknown-unknown");
+  EXPECT_EQ(Triple::spirv32, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v15, T.getSubArch());
   EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
   EXPECT_EQ(Triple::UnknownOS, T.getOS());
 
   T = Triple("spirv64-unknown-unknown");
   EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv64v1.0-unknown-unknown");
+  EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v10, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv64v1.1-unknown-unknown");
+  EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v11, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv64v1.2-unknown-unknown");
+  EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v12, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv64v1.3-unknown-unknown");
+  EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v13, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv64v1.4-unknown-unknown");
+  EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v14, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::UnknownOS, T.getOS());
+
+  T = Triple("spirv64v1.5-unknown-unknown");
+  EXPECT_EQ(Triple::spirv64, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v15, T.getSubArch());
   EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
   EXPECT_EQ(Triple::UnknownOS, T.getOS());
 
Index: llvm/lib/Support/Triple.cpp
===
--- llvm/lib/Support/Triple.cpp
+++ llvm/lib/Support/Triple.cpp
@@ -495,8 +495,10 @@
 .Case("hsail64", Triple::hsail64)
 .Case("spir", Triple::spir)
 .Case("spir64", Triple::spir64)
-.Case("spirv32", Triple::spirv32)
-.Case("spirv64", Triple::spirv64)
+.Cases("spirv32", "spirv32v1.0", "spirv32v1.1", "spirv32v1.2",
+   "spirv32v1.3", "spirv32v1.4", "spirv32v1.5", Triple::spirv32)
+.Cases("spirv64", "spirv64v1.0", "spirv64v1.1", "spirv64v1.2",
+   "spirv64v1.3", "spirv64v1.4", "spirv64v1.5", Triple::spirv64)
 .StartsWith("kalimba", Triple::kalimba)
 .Case("lanai", Triple::lanai)
 .Case("renderscript32", Triple::renderscript32)
@@ -654,6 +656,16 @@
   if (SubArchName == "arm64e")
 return Triple::AArch64SubArch_arm64e;
 
+  if (SubArchName.startswith("spirv"))
+return StringSwitch(SubArchName)
+.EndsWith("v1.0", Triple::SPIRVSubArch_v10)
+.EndsWi

[PATCH] D110685: [HIPSPV][4/4] Add option to use llc to emit SPIR-V

2022-05-16 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

Actually after some more thinking I have decided to go for a generic flag and I 
have created the review for it: https://reviews.llvm.org/D125679. Perhaps you 
can built your functionality on top of it when you get to it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110685

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


[PATCH] D125604: [FileCheck] Catch missspelled directives.

2022-05-16 Thread Thomas Preud'homme via Phabricator via cfe-commits
thopre added inline comments.



Comment at: llvm/lib/FileCheck/FileCheck.cpp:1774-1781
+static std::pair
+FindCheckType(const FileCheckRequest &Req, StringRef Buffer, StringRef Prefix) 
{
+  bool Misspelled = false;
+  auto Res = FindCheckType(Req, Buffer, Prefix, Misspelled);
+  if (Res.first != Check::CheckNone && Misspelled)
+return {Check::CheckMisspelled, Res.second};
+  return Res;

Instead of introducing a new wrapper, why don't you change all the return to 
call a constructor method (e.g. `make_check_type()`) that does what this 
wrapper do? Then there would not be any FindCheckType that take a Misspelled 
parameter.

I'm also not sure about Misspelled being a check kind. It feels conceptually 
wrong but on the other hand I guess it makes the implementation simpler.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125604

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


[PATCH] D124500: [clang-tidy] Support expressions of literals in modernize-macro-to-enum

2022-05-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp:204
+  return true;
+}
+

LegalizeAdulthood wrote:
> LegalizeAdulthood wrote:
> > aaron.ballman wrote:
> > > LegalizeAdulthood wrote:
> > > > LegalizeAdulthood wrote:
> > > > > aaron.ballman wrote:
> > > > > > LegalizeAdulthood wrote:
> > > > > > > aaron.ballman wrote:
> > > > > > > > Comma operator?
> > > > > > > Remember that the use case here is identifying expressions that 
> > > > > > > are initializers for an enum.  If you were doing a code review 
> > > > > > > and you saw this:
> > > > > > > ```
> > > > > > > enum {
> > > > > > > FOO = (2, 3)
> > > > > > > };
> > > > > > > ```
> > > > > > > Would you be OK with that?  I wouldn't.  Clang even warns about 
> > > > > > > it: https://godbolt.org/z/Y641cb8Y9
> > > > > > > 
> > > > > > > Therefore I deliberately left comma operator out of the grammar.
> > > > > > This is another case where I think you're predicting that users 
> > > > > > won't be using the full expressivity of the language and we'll get 
> > > > > > bug reports later. Again, in insolation, I tend to agree that I 
> > > > > > wouldn't be happy seeing that code. However, users write some very 
> > > > > > creative code and there's no technical reason why we can't or 
> > > > > > shouldn't handle comma operators.
> > > > > "Don't let the perfect be the enemy of the good."
> > > > > 
> > > > > My inclination is to simply explicitly state that comma operator is 
> > > > > not recognized in the documentation.  It's already implicit by it's 
> > > > > absence from the list of recognized operators.
> > > > > 
> > > > > Again, the worst that happens is that your macro isn't converted.
> > > > > 
> > > > > I'm open to being convinced that it's important, but you haven't 
> > > > > convinced me yet `:)`
> > > > It wasn't much extra work/code to add comma operator support so I've 
> > > > done that.
> > > > "Don't let the perfect be the enemy of the good."
> > > 
> > > This is a production compiler toolchain. Correctness is important and 
> > > that sometimes means caring more about perfection than you otherwise 
> > > would like to.
> > > 
> > > > I'm open to being convinced that it's important, but you haven't 
> > > > convinced me yet :)
> > > 
> > > It's less about importance and more about maintainability coupled with 
> > > correctness. With your approach, we get something that will have a long 
> > > tail of bugs. If you used Clang's parser, you don't get the same issue -- 
> > > maintenance largely comes along for free, and the bugs are far less 
> > > likely.
> > > 
> > > About the only reason I like your current approach over using clang's 
> > > parsing is that it quite likely performs much better than doing an actual 
> > > token parsing of the expression. But as you pointed out, about the worst 
> > > thing for a check can do is take correct code and make it incorrect -- 
> > > doing that right requires some amount of semantic evaluation of the 
> > > expressions (which you're not doing). For example:
> > > ```
> > > #define FINE 1LL << 30LL;
> > > #define BAD 1LL << 31LL;
> > > #define ALSO_BAD 1LL << 32L;
> > > ```
> > > We'll convert this into an enumeration and break `-pedantic-errors` 
> > > builds in C. If we had a `ConstantExpr` object, we could see what it's 
> > > value is and note that it's greater than what fits into an `int` and 
> > > decide to do something smarter.
> > > 
> > > So I continue to see the current approach as being somewhat reasonable 
> > > (especially for experimentation), but incorrect in the long run. Not 
> > > sufficiently incorrect for me to block this patch on, but incorrect 
> > > enough that the first time this check becomes a maintenance burden, I'll 
> > > be asking more strongly to do this the correct way.
> > > > "Don't let the perfect be the enemy of the good."
> > > 
> > > This is a production compiler toolchain. Correctness is important and 
> > > that sometimes means caring more about perfection than you otherwise 
> > > would like to.
> > 
> > That's fair.
> > 
> > > For example:
> > > ```
> > > #define FINE 1LL << 30LL;
> > > #define BAD 1LL << 31LL;
> > > #define ALSO_BAD 1LL << 32L;
> > > ```
> > 
> > Oh this brings up the pesky "semicolons disappear from the AST" issue.  I 
> > wonder what happens when we're just processing tokens, though.  I will add 
> > a test to see.  This could be a case where my approach results in more 
> > correctness than `clangParse`!
> > 
> > > Not sufficiently incorrect for me to block this patch on, but incorrect 
> > > enough that the first time this check becomes a maintenance burden, I'll 
> > > be asking more strongly to do this the correct way.
> > 
> > I agree.
> So I was research the C standard for what it says are acceptable initializer 
> values for an enum and it //disallows// the comma operator:
> 
> https://en.cppreference.com/w/c/la

[PATCH] D125622: [clang-tidy] Reject invalid enum initializers in C files

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

Note, I'm in C standards committee meetings all week this week, so I expect I 
won't be doing many reviews this week and I'll be catching up as best I can 
starting next week.




Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:324
 {
-  IntegralLiteralExpressionMatcher Matcher(MacroTokens);
-  return Matcher.match();
+  IntegralLiteralExpressionMatcher Matcher(MacroTokens, LangOpts.C99 == 0);
+  bool Matched = Matcher.match();

Huh? Comma wasn't allowed in C89 either... In fact, there's no language mode 
which allows top-level commas in either C or C++ -- the issue with the comma 
operator is a parsing one. You can't tell the difference between the comma 
being part of the initializer expression or the comma being the separator 
between enumerators.



Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:326
+  bool Matched = Matcher.match();
+  if (LangOpts.C99 &&
+  (Matcher.largestLiteralSize() != LiteralSize::Int &&

And C89?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.c:1
+// RUN: %check_clang_tidy %s modernize-macro-to-enum %t
+

It'd be useful to run this test in C++ mode as well to demonstrate the 
behavioral differences.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.c:3-7
+// C requires enum values to fit into an int.
+#define TOO_BIG1 1L
+#define TOO_BIG2 1UL
+#define TOO_BIG3 1LL
+#define TOO_BIG4 1ULL

How do we want to handle the fact that Clang has an extension to allow this? 
Perhaps we want a config option for pedantic vs non-pedantic fixes?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.c:9
+
+// C forbids comma operator in initializing expressions.
+#define BAD_OP 1, 2

It's also forbidden in C++.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.c:10
+// C forbids comma operator in initializing expressions.
+#define BAD_OP 1, 2
+

Can you add a test:
```
#define GOOD_OP (1, 2)
```
to make sure it still gets converted to an enum?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125622

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


[PATCH] D124435: [X86] Always extend the integer parameters in callee

2022-05-16 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

I find the option names you have a bit confusing. I'd like to suggest calling 
them, instead:

caller: Extend a small integer parameter in the caller; callee will assume it 
has already been extended.
callee : Pass a small integer parameter directly in caller, extend in callee 
when converting to full-width.
both: Extend a small integer parameter in the caller; callee ALSO extends when 
converting to full-width.
default: Use the default rule for the target.

I think that gets more to the point of what's going on here, even though it's 
not exactly the case that "callee" always extends.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124435

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


[clang] acc80ea - [AST] Cleanup on getting the underlying decl of using-shdow decl.

2022-05-16 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-05-16T13:58:08+02:00
New Revision: acc80ea71bac51458df9d75552651e7c161db64b

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

LOG: [AST] Cleanup on getting the underlying decl of using-shdow decl.

This should be a NFC cleanup. It removes a unnecessary loop to get the 
underlying
decl, and add an assertion.

The underlying decl of a using-shadow decl is always the original declaration
has been brought into the scope, clang never builds a nested using-shadow
decl (see Sema::BuildUsingShadowDecl).

Reviewed By: sammccall

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

Added: 


Modified: 
clang/lib/AST/Decl.cpp
clang/lib/AST/DeclCXX.cpp

Removed: 




diff  --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 911479bee5ff9..1c5c64d1b3650 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -1851,7 +1851,7 @@ bool NamedDecl::hasLinkage() const {
 
 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
   NamedDecl *ND = this;
-  while (auto *UD = dyn_cast(ND))
+  if (auto *UD = dyn_cast(ND))
 ND = UD->getTargetDecl();
 
   if (auto *AD = dyn_cast(ND))

diff  --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index cb6a355f7294a..020c7da52041d 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -2968,8 +2968,10 @@ UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, 
DeclContext *DC,
  BaseUsingDecl *Introducer, NamedDecl *Target)
 : NamedDecl(K, DC, Loc, Name), redeclarable_base(C),
   UsingOrNextShadow(Introducer) {
-  if (Target)
+  if (Target) {
+assert(!isa(Target));
 setTargetDecl(Target);
+  }
   setImplicit();
 }
 



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


[PATCH] D123422: [AST] Cleanup on getting the underlying decl of using-shdow decl.

2022-05-16 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGacc80ea71bac: [AST] Cleanup on getting the underlying decl 
of using-shdow decl. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123422

Files:
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclCXX.cpp


Index: clang/lib/AST/DeclCXX.cpp
===
--- clang/lib/AST/DeclCXX.cpp
+++ clang/lib/AST/DeclCXX.cpp
@@ -2968,8 +2968,10 @@
  BaseUsingDecl *Introducer, NamedDecl *Target)
 : NamedDecl(K, DC, Loc, Name), redeclarable_base(C),
   UsingOrNextShadow(Introducer) {
-  if (Target)
+  if (Target) {
+assert(!isa(Target));
 setTargetDecl(Target);
+  }
   setImplicit();
 }
 
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -1851,7 +1851,7 @@
 
 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
   NamedDecl *ND = this;
-  while (auto *UD = dyn_cast(ND))
+  if (auto *UD = dyn_cast(ND))
 ND = UD->getTargetDecl();
 
   if (auto *AD = dyn_cast(ND))


Index: clang/lib/AST/DeclCXX.cpp
===
--- clang/lib/AST/DeclCXX.cpp
+++ clang/lib/AST/DeclCXX.cpp
@@ -2968,8 +2968,10 @@
  BaseUsingDecl *Introducer, NamedDecl *Target)
 : NamedDecl(K, DC, Loc, Name), redeclarable_base(C),
   UsingOrNextShadow(Introducer) {
-  if (Target)
+  if (Target) {
+assert(!isa(Target));
 setTargetDecl(Target);
+  }
   setImplicit();
 }
 
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -1851,7 +1851,7 @@
 
 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
   NamedDecl *ND = this;
-  while (auto *UD = dyn_cast(ND))
+  if (auto *UD = dyn_cast(ND))
 ND = UD->getTargetDecl();
 
   if (auto *AD = dyn_cast(ND))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125682: Add documentHighlight in clangd check for performance measurements.

2022-05-16 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 created this revision.
usaxena95 added a reviewer: kadircet.
Herald added a subscriber: arphaman.
Herald added a project: All.
usaxena95 requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125682

Files:
  clang-tools-extra/clangd/tool/Check.cpp


Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -253,6 +253,9 @@
   auto Hover = getHover(*AST, Pos, Style, &Index);
   vlog("hover: {0}", Hover.hasValue());
 
+  unsigned DocHighlights = findDocumentHighlights(*AST, Pos).size();
+  vlog("documentHighlight: {0}", DocHighlights);
+
   if (EnableCodeCompletion) {
 Position EndPos = offsetToPosition(Inputs.Contents, End);
 auto CC = codeComplete(File, EndPos, Preamble.get(), Inputs, CCOpts);


Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -253,6 +253,9 @@
   auto Hover = getHover(*AST, Pos, Style, &Index);
   vlog("hover: {0}", Hover.hasValue());
 
+  unsigned DocHighlights = findDocumentHighlights(*AST, Pos).size();
+  vlog("documentHighlight: {0}", DocHighlights);
+
   if (EnableCodeCompletion) {
 Position EndPos = offsetToPosition(Inputs.Contents, End);
 auto CC = codeComplete(File, EndPos, Preamble.get(), Inputs, CCOpts);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125535: [clang][NFC] Cleanup some coroutine tests

2022-05-16 Thread Nathan Sidwell via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG80bebbc7cb77: [clang][NFC] Cleanup some coroutine tests 
(authored by urnathan).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125535

Files:
  clang/test/CodeGenCoroutines/coro-ret-void.cpp
  clang/test/CoverageMapping/coroutine.cpp


Index: clang/test/CoverageMapping/coroutine.cpp
===
--- clang/test/CoverageMapping/coroutine.cpp
+++ clang/test/CoverageMapping/coroutine.cpp
@@ -30,6 +30,7 @@
 int get_return_object();
 suspend_always initial_suspend();
 suspend_always final_suspend() noexcept;
+void unhandled_exception() noexcept;
 void return_value(int);
   };
 };
Index: clang/test/CodeGenCoroutines/coro-ret-void.cpp
===
--- clang/test/CodeGenCoroutines/coro-ret-void.cpp
+++ clang/test/CodeGenCoroutines/coro-ret-void.cpp
@@ -8,6 +8,7 @@
 std::suspend_never initial_suspend();
 std::suspend_never final_suspend() noexcept;
 void return_void();
+void unhandled_exception() noexcept;
   };
 };
 
@@ -39,6 +40,7 @@
 std::suspend_never initial_suspend();
 std::suspend_never final_suspend() noexcept;
 void return_value(int);
+void unhandled_exception() noexcept;
   };
 };
 


Index: clang/test/CoverageMapping/coroutine.cpp
===
--- clang/test/CoverageMapping/coroutine.cpp
+++ clang/test/CoverageMapping/coroutine.cpp
@@ -30,6 +30,7 @@
 int get_return_object();
 suspend_always initial_suspend();
 suspend_always final_suspend() noexcept;
+void unhandled_exception() noexcept;
 void return_value(int);
   };
 };
Index: clang/test/CodeGenCoroutines/coro-ret-void.cpp
===
--- clang/test/CodeGenCoroutines/coro-ret-void.cpp
+++ clang/test/CodeGenCoroutines/coro-ret-void.cpp
@@ -8,6 +8,7 @@
 std::suspend_never initial_suspend();
 std::suspend_never final_suspend() noexcept;
 void return_void();
+void unhandled_exception() noexcept;
   };
 };
 
@@ -39,6 +40,7 @@
 std::suspend_never initial_suspend();
 std::suspend_never final_suspend() noexcept;
 void return_value(int);
+void unhandled_exception() noexcept;
   };
 };
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 80bebbc - [clang][NFC] Cleanup some coroutine tests

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

Author: Nathan Sidwell
Date: 2022-05-16T05:15:12-07:00
New Revision: 80bebbc7cb77979ef9d229450b7ea84e3e9c6a5a

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

LOG: [clang][NFC] Cleanup some coroutine tests

I noticed these two tests emit a warning about a missing
unhandled_exception.  That's irrelevant to what is being tested, but
is unnecessary noise.

Reviewed By: dblaikie

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

Added: 


Modified: 
clang/test/CodeGenCoroutines/coro-ret-void.cpp
clang/test/CoverageMapping/coroutine.cpp

Removed: 




diff  --git a/clang/test/CodeGenCoroutines/coro-ret-void.cpp 
b/clang/test/CodeGenCoroutines/coro-ret-void.cpp
index 7bc1bcd958b7a..ae139afabc4d4 100644
--- a/clang/test/CodeGenCoroutines/coro-ret-void.cpp
+++ b/clang/test/CodeGenCoroutines/coro-ret-void.cpp
@@ -8,6 +8,7 @@ struct coro1 {
 std::suspend_never initial_suspend();
 std::suspend_never final_suspend() noexcept;
 void return_void();
+void unhandled_exception() noexcept;
   };
 };
 
@@ -39,6 +40,7 @@ struct coro2 {
 std::suspend_never initial_suspend();
 std::suspend_never final_suspend() noexcept;
 void return_value(int);
+void unhandled_exception() noexcept;
   };
 };
 

diff  --git a/clang/test/CoverageMapping/coroutine.cpp 
b/clang/test/CoverageMapping/coroutine.cpp
index c9de301f81757..da38acc442be2 100644
--- a/clang/test/CoverageMapping/coroutine.cpp
+++ b/clang/test/CoverageMapping/coroutine.cpp
@@ -30,6 +30,7 @@ struct std::coroutine_traits {
 int get_return_object();
 suspend_always initial_suspend();
 suspend_always final_suspend() noexcept;
+void unhandled_exception() noexcept;
 void return_value(int);
   };
 };



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


[PATCH] D125429: Comment parsing: Allow inline commands to have 0 or more than 1 argument

2022-05-16 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a comment.

In D125429#3512642 , @aaronpuchert 
wrote:

> Proposed this in D125580 .

Landed this two days ago and no one complained about it so far, so let's hope 
that solved it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125429

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


[PATCH] D125026: [clang-tidy][NFC] Reimplement SimplifyBooleanExpr with RecursiveASTVisitors

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

LGTM, thank you for this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125026

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


[PATCH] D125026: [clang-tidy][NFC] Reimplement SimplifyBooleanExpr with RecursiveASTVisitors

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

So those times were a little unfair as now we don't use ParentMapContext, 
however the cost of building that is included in the running time for the check.
In a use case where you have other enabled checks with do make use of that, the 
cost for building would be moved to other checks.
In order to level the playing field slightly, I've build the ParentMapContext 
ahead of time in both implementations for a fairer comparison in typical use 
cases.
This yields 0.20s for the original impl and 0.04s for this implementation.
Not quite as large a gap but still a 5x improvement.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125026

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


[PATCH] D125555: [clang] Add __has_target_feature

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

It's not clear to me why existing facilities shouldn't be extended to cover 
this case rather than coming up with another feature testing macro. There's 
already plenty of confusion for users to decide between `__has_feature` and 
`__has_extension`, and now we're talking about adding a third choice to the mix.




Comment at: clang/docs/LanguageExtensions.rst:260
 
+``__has_target_feature``
+

The first question that comes to mind for me is: why is `__has_feature` not 
sufficient?



Comment at: clang/docs/LanguageExtensions.rst:275
+  // On amdgcn target
+  #if __has_target_feature("s-memtime-inst")
+x = __builtin_amdgcn_s_memtime();

yaxunl wrote:
> tra wrote:
> > Do you have a better example? This particular case could've been handled by 
> > existing `__has_builtin()`.
> > 
> > While I could see usefulness of checking features (e.g. for CUDA/NVPTX it 
> > could be used to chose inline assembly supported only by newer PTX 
> > versions, but even then that choice could be made using existing methods, 
> > even if they are not always direct (e.g. by using CUDA_VERSION as a proxy 
> > for "new enough PTX version").
> > 
> `__has_builtin` returns 1 as long as the builtin is known to clang, even if 
> the builtin is not supported by the target CPU. This is because the required 
> target feature for a builtin is in ASTContext, whereas `__has_builtin` is 
> evaluated in preprocessor, where the information is not known.
> `__has_builtin` returns 1 as long as the builtin is known to clang, even if 
> the builtin is not supported by the target CPU. This is because the required 
> target feature for a builtin is in ASTContext, whereas `__has_builtin` is 
> evaluated in preprocessor, where the information is not known.

Why is that not a deficiency with `__has_builtin` that we should fix?


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

https://reviews.llvm.org/D12

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


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

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

Glad this is working! It looks exciting...

My high level comments are:

- the core "what are the ultimate param vars for this call" function is large 
and reusable enough that we should give this a public interface in AST.h
- the implementation does a few "extra" things and it's not clear they're worth 
their complexity cost
- the RecursiveASTVisitor is a bit of a "god object" at the moment, and should 
probably be split up

(Sorry if the comments below are duplicative)




Comment at: clang-tools-extra/clangd/InlayHints.cpp:189
 
+bool isExpandedParameter(const ParmVarDecl *Param) {
+  auto PlainType = Param->getType().getNonReferenceType();

nit: isPackExpandedParameter
(usually "expanded" means macro expansion)



Comment at: clang-tools-extra/clangd/InlayHints.cpp:197
+
+class ForwardingParameterVisitor
+: public RecursiveASTVisitor {

I think this visitor has too many responsibilities:
 - it controls the lifetime of caches for reuse of partial results. (FWIW, I'm 
skeptical there's any serious benefit of this on real code, and would prefer to 
avoid paying any complexity costs for it)
 - it begins a traversal over function bodies, hooking interesting nodes to 
find forwarding calls and analyzing them
 - it owns the queues that are used for recursive resolution. (Again, it's 
unclear if these are providing value, but it's hard to separate them out from 
the design).
 - (via inheritance) it implements the mechanics of traversal itself

Could you try to reduce the scope of the visitor down to its very minimum: the 
inherited implementation of traversal + recording of forwarding calls?

e.g.
```
// Traverses a function body, recording locations where a particular
// parameter pack was forwarded to another call.
class FindForwardingCalls : public RecursiveASTVisitor {
  FindForwardingCalls(ParmVarDecl Pack);

  struct ForwardingCall {
FunctionDecl *Callee;
unsigned PackOffset; // e.g. 0 for make_unique, 1 for map::try_emplace
  };

  vector> ForwardingCalls;
};
```

Then the other pieces can be decoupled and structured in ways that make the 
most sense individually.



Comment at: clang-tools-extra/clangd/InlayHints.cpp:201
+  void
+  resolveForwardedParameters(const FunctionDecl *Callee,
+ llvm::SmallVector &Params) {

this is only called once, and the Params is always Callee->params().

Can this be a function instead that takes only Callee and returns the params?

If possible, I'd declare this function in `AST.h` and hide the 
RecursiveASTVisitor in `AST.cpp`.



Comment at: clang-tools-extra/clangd/InlayHints.cpp:208
+// If the parameter is part of an expanded pack and not yet resolved
+if (/*isExpandedParameter(Param) && */
+ForwardedParams.find(Param) == ForwardedParams.end()) {

nridge wrote:
> nridge wrote:
> > upsj wrote:
> > > This needs to be fixed, see `ParameterHints.VariadicPlain` vs. 
> > > `ParameterHints.VariadicForwarded` if uncommented - I'd need some input 
> > > from somebody with more knowledge about the AST
> > It looks like `isExpandedParameter()` relies on the 
> > `SubstTemplateTypeParmType` type sugar being present in the ParmVarDecl's 
> > type, but in some cases, the ParmVarDecl's type points to the canonical 
> > type directly.
> > 
> > I'm not sure what sort of guarantees the AST intends to make about the 
> > presence of type sugar. Based on past experience with Eclipse CDT, it's 
> > very easy to lose type sugar and maintaining it in all the right places 
> > takes some effort.
> Upon further investigation, it looks like the ParmVarDecl is retaining the 
> type sugar fine, it's the `getNonReferenceType()` call in 
> `isExpandedParameter()` that loses it.
> 
> What happens with perfect forwarding when the argument is an lvalue is a bit 
> subtle. In this testcase:
> 
> ```
> template 
> void bar(Args&&... args) { return foo(std::forward(args)...); }
> void baz() {
>   int b;
>   bar($param[[b]]);
> }
> ```
> 
> the template argument that `bar()` is instantiated with is `Args = [int &]`. 
> Substituting into `Args&&`, that then becomes `int& &&` which collapses into 
> `int&`, leaving the instantiated parameter type an lvalue reference type.
> 
> Clang does in fact model this accurately, which means the type structure is:
> 
> ```
> BuiltinType
>   ReferenceType
> SubstTemplateTypeParmType
>   ReferenceType
> ```
> 
> The outer reference type is the `&&` that's outside the `Args`, the 
> `SubstTemplateTypeParmType` reflects the substitution `Args = int&`, and the 
> inner `ReferenceType` is the `int&`.
> 
> The problem is, `getNonReferenceType()` unpacks _all_ the reference types, 
> skipping past the `SubstTemplateTypeParmType` and giving you the 
> `BuiltinType`.
Ah, great catch.

I think it's fine to assume that ParmVarDe

[PATCH] D125683: [runtimes] Replace LIBCXX_ENABLE_STATIC_ABI_LIBRARY & friends by a new LIBCXX_CXX_ABI choice

2022-05-16 Thread Louis Dionne via Phabricator via cfe-commits
ldionne created this revision.
ldionne added reviewers: phosek, mstorsjo.
Herald added subscribers: abrachet, mgorny.
Herald added a project: All.
ldionne requested review of this revision.
Herald added projects: clang, Sanitizers, libc++, libc++abi, LLVM.
Herald added subscribers: llvm-commits, libcxx-commits, Sanitizers, cfe-commits.
Herald added a reviewer: libc++.
Herald added a reviewer: libc++abi.

Instead of having complicated options like LIBCXX_ENABLE_STATIC_ABI_LIBRARY
and LIBCXX_STATICALLY_LINK_ABI_IN_STATIC_LIBRARY, introduce the new
libcxxabi-objects choice of ABI library to allow merging the ABI library
objects into libc++.

Note that the same refactoring can be applied to how libc++abi merges
libunwind's objects, however that can be done as a separate step.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125683

Files:
  clang/cmake/caches/Android.cmake
  clang/cmake/caches/Fuchsia-stage2.cmake
  clang/cmake/caches/Fuchsia.cmake
  compiler-rt/cmake/Modules/AddCompilerRT.cmake
  libcxx/CMakeLists.txt
  libcxx/cmake/Modules/HandleLibCXXABI.cmake
  libcxx/cmake/caches/MinGW.cmake
  libcxx/docs/BuildingLibcxx.rst
  libcxx/docs/ReleaseNotes.rst
  libcxx/src/CMakeLists.txt
  libcxx/test/CMakeLists.txt
  libcxx/test/configs/legacy.cfg.in
  libcxxabi/CMakeLists.txt
  llvm/docs/HowToBuildWindowsItaniumPrograms.rst

Index: llvm/docs/HowToBuildWindowsItaniumPrograms.rst
===
--- llvm/docs/HowToBuildWindowsItaniumPrograms.rst
+++ llvm/docs/HowToBuildWindowsItaniumPrograms.rst
@@ -124,7 +124,6 @@
 * ``-DLIBCXXABI_ENABLE_SHARED=OFF``
 * ``-DLIBCXXABI_ENABLE_STATIC=ON``
 * ``-DLIBCXX_ENABLE_SHARED=ON'``
-* ``-DLIBCXX_ENABLE_STATIC_ABI_LIBRARY=ON``
 
 To break the symbol dependency between libc++abi and libc++ we
 build libc++abi as a static library and then statically link it
@@ -157,7 +156,6 @@
 
 Windows Itanium does not offer a POSIX-like layer over WIN32.
 
-* ``-DLIBCXX_ENABLE_STATIC_ABI_LIBRARY=ON``
 * ``-DLIBCXX_CXX_ABI=libcxxabi``
 * ``-DLIBCXX_CXX_ABI_INCLUDE_PATHS=/include``
 * ``-DLIBCXX_CXX_ABI_LIBRARY_PATH=/lib``
Index: libcxxabi/CMakeLists.txt
===
--- libcxxabi/CMakeLists.txt
+++ libcxxabi/CMakeLists.txt
@@ -251,7 +251,7 @@
 if (WIN32 AND LIBCXXABI_ENABLE_STATIC AND NOT LIBCXXABI_ENABLE_SHARED)
   # If LIBCXX_ENABLE_SHARED isn't set (by the user on the cmake command
   # line or via a cache file), use its expected default value (enabled).
-  if ((LIBCXX_ENABLE_SHARED OR NOT DEFINED LIBCXX_ENABLE_SHARED) AND LIBCXX_ENABLE_STATIC_ABI_LIBRARY)
+  if ((LIBCXX_ENABLE_SHARED OR NOT DEFINED LIBCXX_ENABLE_SHARED) AND LIBCXX_CXX_ABI STREQUAL libcxxabi-objects)
 # Building libcxxabi statically, but intending for it to be statically
 # linked into a shared libcxx; keep dllexport enabled within libcxxabi,
 # as the symbols will need to be exported from libcxx.
Index: libcxx/test/configs/legacy.cfg.in
===
--- libcxx/test/configs/legacy.cfg.in
+++ libcxx/test/configs/legacy.cfg.in
@@ -14,7 +14,7 @@
 config.cxx_library_root = "@LIBCXX_LIBRARY_DIR@"
 config.abi_library_root = "@LIBCXX_CXX_ABI_LIBRARY_PATH@"
 config.enable_shared= @LIBCXX_LINK_TESTS_WITH_SHARED_LIBCXX@
-config.cxx_abi  = "@LIBCXX_CXXABI_FOR_TESTS@"
+config.cxx_abi  = "@LIBCXX_CXX_ABI@"
 config.configuration_variant= "@LIBCXX_LIT_VARIANT@"
 config.host_triple  = "@LLVM_HOST_TRIPLE@"
 config.sysroot  = "@CMAKE_SYSROOT@"
Index: libcxx/test/CMakeLists.txt
===
--- libcxx/test/CMakeLists.txt
+++ libcxx/test/CMakeLists.txt
@@ -14,14 +14,6 @@
 set(LIBCXX_TEST_COMPILER_FLAGS "" CACHE STRING
 "Additonal linker flags to pass when compiling the tests")
 
-# The tests shouldn't link to any ABI library when it has been linked into
-# libc++ statically or via a linker script.
-if (LIBCXX_ENABLE_STATIC_ABI_LIBRARY OR LIBCXX_ENABLE_ABI_LINKER_SCRIPT)
-  set(LIBCXX_CXXABI_FOR_TESTS "none")
-else()
-  set(LIBCXX_CXXABI_FOR_TESTS "${LIBCXX_CXX_ABI}")
-endif()
-
 # The tests shouldn't link to libunwind if we have a linker script which
 # already does so.
 if (LIBCXX_ENABLE_ABI_LINKER_SCRIPT)
Index: libcxx/src/CMakeLists.txt
===
--- libcxx/src/CMakeLists.txt
+++ libcxx/src/CMakeLists.txt
@@ -204,7 +204,7 @@
 if (LIBCXX_ENABLE_SHARED)
   add_library(cxx_shared SHARED ${exclude_from_all} ${LIBCXX_SOURCES} ${LIBCXX_HEADERS})
   target_include_directories(cxx_shared PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
-  target_link_libraries(cxx_shared PUBLIC cxx-headers
+  target_link_libraries(cxx_shared PUBLIC cxx-headers libcxx-abi-shared
PRIVATE ${LIBCXX_LIBRARIES})
   set_target_properties(cxx_shared
   

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

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

Few initial comments...




Comment at: clang-tools-extra/pseudo/gen/Main.cpp:8
+//===--===//
+
+#include "clang-pseudo/Grammar.h"

missing description



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/cxx/cxx.h:35
+// It provides a simple uniform way to access a particular nonterminal.
+enum Symbol : SymbolID {
+#define NONTERMINAL(X, Y) X = Y,

enum class? I suspect having to cast these explicitly is worth it if using them 
is rare.

Otherwise we'll end up with rules in the same namespace as symbols, later.



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/cxx/cxx.h:37
+#define NONTERMINAL(X, Y) X = Y,
+#include "CxxSymbols.inc"
+#undef NONTERMINAL

we've got {cxx, Cxx} in filenames.
We should be consistent, and per LLVM style I think `CXX` is correct?



Comment at: clang-tools-extra/pseudo/lib/CMakeLists.txt:3
 
-add_clang_library(clangPseudo
+# Needed by LLVM's CMake checks because this file defines multiple targets.
+set(LLVM_OPTIONAL_SOURCES

We do have a layering relationship here, and a requirement to keep the 
"grammar" dependencies small - should we move it into a subdirectory?



Comment at: clang-tools-extra/pseudo/lib/CMakeLists.txt:45
+include(${CMAKE_CURRENT_SOURCE_DIR}/../gen/cxx_gen.cmake)
+add_clang_library(clangPseudoCxx
+  cxx/cxx.cpp

why is this not in cxx/CMakeLists.txt?



Comment at: clang-tools-extra/pseudo/lib/cxx/cxx.cpp:1
+//===--- cxx.cpp - Define public intefaces for C++ grammar 
===//
+//

nit: interfaces


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125667

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


[PATCH] D125684: [clangd] Support UnresolvedUsingTypeLoc AST node in FindTarget.

2022-05-16 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: kadircet.
Herald added subscribers: usaxena95, arphaman.
Herald added a project: All.
hokein requested review of this revision.
Herald added subscribers: MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

to make features like hover, go-to-def work when the cursor is on the
UnresolvedUsingTypeLoc.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125684

Files:
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp


Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -268,6 +268,17 @@
   EXPECT_DECLS("DeducedTemplateSpecializationTypeLoc",
{"using ns::S", Rel::Alias}, {"template  class S"},
{"class S", Rel::TemplatePattern});
+
+  Code = R"cpp(
+template
+class Foo { public: class foo {}; };
+template  class A : public Foo {
+  using typename Foo::foo;
+  [[foo]] abc;
+};
+  )cpp";
+  EXPECT_DECLS("UnresolvedUsingTypeLoc",
+   {"using typename Foo::foo", Rel::Alias});
 }
 
 TEST_F(TargetDeclTest, BaseSpecifier) {
Index: clang-tools-extra/clangd/FindTarget.cpp
===
--- clang-tools-extra/clangd/FindTarget.cpp
+++ clang-tools-extra/clangd/FindTarget.cpp
@@ -127,11 +127,6 @@
 //  template using pvec = vector; pvec x;
 //There's no Decl `pvec`, we must choose `pvec` or `vector`
 //and both are lossy. We must know upfront what the caller ultimately 
wants.
-//
-// FIXME: improve common dependent scope using name lookup in primary 
templates.
-// We currently handle several dependent constructs, but some others remain to
-// be handled:
-//  - UnresolvedUsingTypenameDecl
 struct TargetFinder {
   using RelSet = DeclRelationSet;
   using Rel = DeclRelation;
@@ -207,6 +202,10 @@
 }
   }
   Flags |= Rel::Alias; // continue with the alias
+} else if (isa(D)) {
+  // FIXME: improve common dependent scope using name lookup in primary
+  // templates.
+  Flags |= Rel::Alias;
 } else if (const UsingShadowDecl *USD = dyn_cast(D)) {
   // Include the Introducing decl, but don't traverse it. This may end up
   // including *all* shadows, which we don't want.
@@ -382,6 +381,9 @@
 // TypeLoc never has a deduced type. https://llvm.org/PR42914
 Outer.add(DT->getDeducedType(), Flags);
   }
+  void VisitUnresolvedUsingType(const UnresolvedUsingType * UUT) {
+Outer.add(UUT->getDecl(), Flags);
+  }
   void VisitDeducedTemplateSpecializationType(
   const DeducedTemplateSpecializationType *DTST) {
 if (const auto *USD = DTST->getTemplateName().getAsUsingShadowDecl())


Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -268,6 +268,17 @@
   EXPECT_DECLS("DeducedTemplateSpecializationTypeLoc",
{"using ns::S", Rel::Alias}, {"template  class S"},
{"class S", Rel::TemplatePattern});
+
+  Code = R"cpp(
+template
+class Foo { public: class foo {}; };
+template  class A : public Foo {
+  using typename Foo::foo;
+  [[foo]] abc;
+};
+  )cpp";
+  EXPECT_DECLS("UnresolvedUsingTypeLoc",
+   {"using typename Foo::foo", Rel::Alias});
 }
 
 TEST_F(TargetDeclTest, BaseSpecifier) {
Index: clang-tools-extra/clangd/FindTarget.cpp
===
--- clang-tools-extra/clangd/FindTarget.cpp
+++ clang-tools-extra/clangd/FindTarget.cpp
@@ -127,11 +127,6 @@
 //  template using pvec = vector; pvec x;
 //There's no Decl `pvec`, we must choose `pvec` or `vector`
 //and both are lossy. We must know upfront what the caller ultimately wants.
-//
-// FIXME: improve common dependent scope using name lookup in primary templates.
-// We currently handle several dependent constructs, but some others remain to
-// be handled:
-//  - UnresolvedUsingTypenameDecl
 struct TargetFinder {
   using RelSet = DeclRelationSet;
   using Rel = DeclRelation;
@@ -207,6 +202,10 @@
 }
   }
   Flags |= Rel::Alias; // continue with the alias
+} else if (isa(D)) {
+  // FIXME: improve common dependent scope using name lookup in primary
+  // templates.
+  Flags |= Rel::Alias;
 } else if (const UsingShadowDecl *USD = dyn_cast(D)) {
   // Include the Introducing decl, but don't traverse it. This may end up
   // including *all* shadows, which we don't want.
@@ -382,6 +381,9 @@
 // TypeLoc never has a deduced type. https://llvm.org/PR42914

[PATCH] D125683: [runtimes] Replace LIBCXX_ENABLE_STATIC_ABI_LIBRARY & friends by a new LIBCXX_CXX_ABI choice

2022-05-16 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

It looks like this patch still lacks compatibility handling for all external 
users that are setting this option, which need to be able to set the option in 
this way at least until after the 15.0.0 release.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125683

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


[PATCH] D125675: Optimise findRefs for XRefs and docHighlights

2022-05-16 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 429696.
usaxena95 marked 4 inline comments as done.
usaxena95 added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125675

Files:
  clang-tools-extra/clangd/XRefs.cpp

Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -18,6 +18,7 @@
 #include "index/Index.h"
 #include "index/Merge.h"
 #include "index/Relation.h"
+#include "index/SymbolID.h"
 #include "index/SymbolLocation.h"
 #include "support/Logger.h"
 #include "clang/AST/ASTContext.h"
@@ -47,6 +48,7 @@
 #include "clang/Index/USRGeneration.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
@@ -397,8 +399,8 @@
 }
   }
   // Special case: void foo() ^override: jump to the overridden method.
-if (NodeKind.isSame(ASTNodeKind::getFromNodeKind()) ||
-NodeKind.isSame(ASTNodeKind::getFromNodeKind())) {
+  if (NodeKind.isSame(ASTNodeKind::getFromNodeKind()) ||
+  NodeKind.isSame(ASTNodeKind::getFromNodeKind())) {
 // We may be overridding multiple methods - offer them all.
 for (const NamedDecl *ND : CMD->overridden_methods())
   AddResultDecl(ND);
@@ -887,8 +889,13 @@
   };
 
   ReferenceFinder(const ParsedAST &AST,
-  const llvm::DenseSet &TargetIDs, bool PerToken)
-  : PerToken(PerToken), AST(AST), TargetIDs(TargetIDs) {}
+  const llvm::DenseSet &Target, bool PerToken)
+  : PerToken(PerToken), AST(AST) {
+for (const Decl *D : Target) {
+  const Decl *CD = D->getCanonicalDecl();
+  TargetDeclAndID[CD] = getSymbolID(CD);
+}
+  }
 
   std::vector take() && {
 llvm::sort(References, [](const Reference &L, const Reference &R) {
@@ -913,12 +920,12 @@
llvm::ArrayRef Relations,
SourceLocation Loc,
index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
+auto DeclID = TargetDeclAndID.find(D->getCanonicalDecl());
+if (DeclID == TargetDeclAndID.end())
+  return true;
 const SourceManager &SM = AST.getSourceManager();
 if (!isInsideMainFile(Loc, SM))
   return true;
-SymbolID ID = getSymbolID(D);
-if (!TargetIDs.contains(ID))
-  return true;
 const auto &TB = AST.getTokens();
 
 llvm::SmallVector Locs;
@@ -942,7 +949,7 @@
 for (SourceLocation L : Locs) {
   L = SM.getFileLoc(L);
   if (const auto *Tok = TB.spelledTokenAt(L))
-References.push_back({*Tok, Roles, ID});
+References.push_back({*Tok, Roles, DeclID->getSecond()});
 }
 return true;
   }
@@ -951,12 +958,13 @@
   bool PerToken; // If true, report 3 references for split ObjC selector names.
   std::vector References;
   const ParsedAST &AST;
-  const llvm::DenseSet &TargetIDs;
+  llvm::DenseMap TargetDeclAndID;
 };
 
 std::vector
-findRefs(const llvm::DenseSet &IDs, ParsedAST &AST, bool PerToken) {
-  ReferenceFinder RefFinder(AST, IDs, PerToken);
+findRefs(const llvm::DenseSet &TargetDecls, ParsedAST &AST,
+ bool PerToken) {
+  ReferenceFinder RefFinder(AST, TargetDecls, PerToken);
   index::IndexingOptions IndexOpts;
   IndexOpts.SystemSymbolFilter =
   index::IndexingOptions::SystemSymbolFilterKind::All;
@@ -1242,16 +1250,15 @@
 if (const SelectionTree::Node *N = ST.commonAncestor()) {
   DeclRelationSet Relations =
   DeclRelation::TemplatePattern | DeclRelation::Alias;
-  auto Decls =
-  targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver());
-  if (!Decls.empty()) {
+  llvm::DenseSet TargetDecls;
+  for (const NamedDecl *D :
+   targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver())) {
+TargetDecls.insert(D);
+  }
+  if (!TargetDecls.empty()) {
 // FIXME: we may get multiple DocumentHighlights with the same location
 // and different kinds, deduplicate them.
-llvm::DenseSet Targets;
-for (const NamedDecl *ND : Decls)
-  if (auto ID = getSymbolID(ND))
-Targets.insert(ID);
-for (const auto &Ref : findRefs(Targets, AST, /*PerToken=*/true))
+for (const auto &Ref : findRefs(TargetDecls, AST, /*PerToken=*/true))
   Result.push_back(toHighlight(Ref, SM));
 return true;
   }
@@ -1377,12 +1384,12 @@
 DeclRelation::TemplatePattern | DeclRelation::Alias;
 std::vector Decls =
 getDeclAtPosition(AST, *CurLoc, Relations);
-llvm::DenseSet TargetsInMainFile;
+llvm::DenseSet TargetInMainFile;
 for (const NamedDecl *D : Decls) {
   auto ID = getSymbolID(D);
   if (!ID)
 continue;
-  Targe

[PATCH] D125675: Optimise findRefs for XRefs and docHighlights

2022-05-16 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 added inline comments.



Comment at: clang-tools-extra/clangd/XRefs.cpp:951
   if (const auto *Tok = TB.spelledTokenAt(L))
-References.push_back({*Tok, Roles, ID});
+References.push_back({*Tok, Roles, getSymbolID(D)});
 }

kadircet wrote:
> we're still calling getsymbolid here lots of times, for probably the same 
> symbol.
> 
> as discussed, what about building a lookup table on construction from 
> canonicaldecl to symbolid and use that lookup table instead of calling 
> getsymbolid over and over here?
I don't mind adding a lookup table for this but this is not huge, only O(#ref) 
as compared to previous O(size of TU). 





Comment at: clang-tools-extra/clangd/XRefs.cpp:1255
+   targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver())) {
+TargetDecls.insert(D);
+  }

kadircet wrote:
> i mean directly inserting canonicaldecls here.
This would make it messy to duplicate this on each end of the call. 
+ This has potential of introducing bugs in future findRef calls if we don't 
pass the canonical decls. Or we would have to assert that we only get canonical 
decls.
I think this is an implementation detail of findRefs and should not be visible 
outside its API for simplicity.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125675

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


[PATCH] D125675: Optimise findRefs for XRefs and docHighlights

2022-05-16 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 429697.
usaxena95 added a comment.

Format.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125675

Files:
  clang-tools-extra/clangd/XRefs.cpp

Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -18,6 +18,7 @@
 #include "index/Index.h"
 #include "index/Merge.h"
 #include "index/Relation.h"
+#include "index/SymbolID.h"
 #include "index/SymbolLocation.h"
 #include "support/Logger.h"
 #include "clang/AST/ASTContext.h"
@@ -47,6 +48,7 @@
 #include "clang/Index/USRGeneration.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
@@ -397,8 +399,8 @@
 }
   }
   // Special case: void foo() ^override: jump to the overridden method.
-if (NodeKind.isSame(ASTNodeKind::getFromNodeKind()) ||
-NodeKind.isSame(ASTNodeKind::getFromNodeKind())) {
+  if (NodeKind.isSame(ASTNodeKind::getFromNodeKind()) ||
+  NodeKind.isSame(ASTNodeKind::getFromNodeKind())) {
 // We may be overridding multiple methods - offer them all.
 for (const NamedDecl *ND : CMD->overridden_methods())
   AddResultDecl(ND);
@@ -887,8 +889,13 @@
   };
 
   ReferenceFinder(const ParsedAST &AST,
-  const llvm::DenseSet &TargetIDs, bool PerToken)
-  : PerToken(PerToken), AST(AST), TargetIDs(TargetIDs) {}
+  const llvm::DenseSet &Target, bool PerToken)
+  : PerToken(PerToken), AST(AST) {
+for (const Decl *D : Target) {
+  const Decl *CD = D->getCanonicalDecl();
+  TargetDeclAndID[CD] = getSymbolID(CD);
+}
+  }
 
   std::vector take() && {
 llvm::sort(References, [](const Reference &L, const Reference &R) {
@@ -913,12 +920,12 @@
llvm::ArrayRef Relations,
SourceLocation Loc,
index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
+auto DeclID = TargetDeclAndID.find(D->getCanonicalDecl());
+if (DeclID == TargetDeclAndID.end())
+  return true;
 const SourceManager &SM = AST.getSourceManager();
 if (!isInsideMainFile(Loc, SM))
   return true;
-SymbolID ID = getSymbolID(D);
-if (!TargetIDs.contains(ID))
-  return true;
 const auto &TB = AST.getTokens();
 
 llvm::SmallVector Locs;
@@ -942,7 +949,7 @@
 for (SourceLocation L : Locs) {
   L = SM.getFileLoc(L);
   if (const auto *Tok = TB.spelledTokenAt(L))
-References.push_back({*Tok, Roles, ID});
+References.push_back({*Tok, Roles, DeclID->getSecond()});
 }
 return true;
   }
@@ -951,12 +958,13 @@
   bool PerToken; // If true, report 3 references for split ObjC selector names.
   std::vector References;
   const ParsedAST &AST;
-  const llvm::DenseSet &TargetIDs;
+  llvm::DenseMap TargetDeclAndID;
 };
 
 std::vector
-findRefs(const llvm::DenseSet &IDs, ParsedAST &AST, bool PerToken) {
-  ReferenceFinder RefFinder(AST, IDs, PerToken);
+findRefs(const llvm::DenseSet &TargetDecls, ParsedAST &AST,
+ bool PerToken) {
+  ReferenceFinder RefFinder(AST, TargetDecls, PerToken);
   index::IndexingOptions IndexOpts;
   IndexOpts.SystemSymbolFilter =
   index::IndexingOptions::SystemSymbolFilterKind::All;
@@ -1242,16 +1250,15 @@
 if (const SelectionTree::Node *N = ST.commonAncestor()) {
   DeclRelationSet Relations =
   DeclRelation::TemplatePattern | DeclRelation::Alias;
-  auto Decls =
-  targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver());
-  if (!Decls.empty()) {
+  llvm::DenseSet TargetDecls;
+  for (const NamedDecl *D :
+   targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver())) {
+TargetDecls.insert(D);
+  }
+  if (!TargetDecls.empty()) {
 // FIXME: we may get multiple DocumentHighlights with the same location
 // and different kinds, deduplicate them.
-llvm::DenseSet Targets;
-for (const NamedDecl *ND : Decls)
-  if (auto ID = getSymbolID(ND))
-Targets.insert(ID);
-for (const auto &Ref : findRefs(Targets, AST, /*PerToken=*/true))
+for (const auto &Ref : findRefs(TargetDecls, AST, /*PerToken=*/true))
   Result.push_back(toHighlight(Ref, SM));
 return true;
   }
@@ -1377,12 +1384,12 @@
 DeclRelation::TemplatePattern | DeclRelation::Alias;
 std::vector Decls =
 getDeclAtPosition(AST, *CurLoc, Relations);
-llvm::DenseSet TargetsInMainFile;
+llvm::DenseSet TargetsInMainFile;
 for (const NamedDecl *D : Decls) {
   auto ID = getSymbolID(D);
   if (!ID)
 continue;
-  TargetsInMainFile.insert(ID);
+  TargetsInMainFile.ins

[PATCH] D124446: [clang-tidy] Add the misc-discarded-return-value check

2022-05-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tools-extra/clang-tidy/misc/DiscardedReturnValueCheck.cpp:28
+
+  std::uint8_t R = static_cast(ConsumedCalls * 100) / TotalCalls;
+  assert(R <= 100 && "Invalid percentage, maybe bogus compacted data?");





Comment at: 
clang-tools-extra/clang-tidy/misc/DiscardedReturnValueCheck.cpp:83-86
+void DiscardedReturnValueCheck::onStartOfTranslationUnit() {
+  ConsumedCalls.clear();
+  CallMap.clear();
+}

Is this code necessary?



Comment at: clang-tools-extra/clang-tidy/misc/DiscardedReturnValueCheck.cpp:181
+
+  static const auto Decltype = decltypeType(hasUnderlyingExpr(Call));
+  static const auto TemplateArg =

So, I'm not super keen on this approach of having to try to identify every 
single place in which an expression is considered to be "used" -- this is going 
to be fragile because we'll miss places and it's going to be a maintenance 
burden because new places will be added as the languages evolve.

For example, if we're handling `decltype` as a use, why not `noexcept`? Or 
conditional `explicit`? What about a `co_return` statement?

I'm not certain what we can do to improve this, but I think it's worth trying 
to explore options to see if we can generalize what constitutes a use so that 
we can write a few custom matchers to do the heavy lifting instead of trying to 
play whack-a-mole.



Comment at: clang-tools-extra/clang-tidy/misc/DiscardedReturnValueCheck.h:21-22
+
+/// Flags function calls which return value is discarded if most of the
+/// other calls of the function consume the return value.
+///

It'd be good to comment that this only considers the statistical uses in *one* 
translation unit, not across the entire project.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/misc-discarded-return-value.rst:6-7
+
+Flags function calls which return value is discarded if most of the other calls
+to the function consume the return value.
+

You should also make it clear in the docs that this only considers the 
statistics of a single translation unit.

(I suspect you'll get far more clean results if the check was run over a whole 
program instead of just a single TU, but I'm not certain if we've made that 
situation sufficiently simple in clang-tidy yet to be worth trying to support.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124446

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


[PATCH] D125026: [clang-tidy][NFC] Reimplement SimplifyBooleanExpr with RecursiveASTVisitors

2022-05-16 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6f8726191960: [clang-tidy][NFC] Reimplement 
SimplifyBooleanExpr with RecursiveASTVisitors (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125026

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
  clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp
@@ -2,8 +2,6 @@
 #include "ClangTidyTest.h"
 #include "readability/BracesAroundStatementsCheck.h"
 #include "readability/NamespaceCommentCheck.h"
-#include "readability/SimplifyBooleanExprMatchers.h"
-#include "clang/ASTMatchers/ASTMatchers.h"
 #include "gtest/gtest.h"
 
 namespace clang {
@@ -14,91 +12,6 @@
 using readability::NamespaceCommentCheck;
 using namespace ast_matchers;
 
-TEST_P(ASTMatchersTest, HasCaseSubstatement) {
-  EXPECT_TRUE(matches(
-  "void f() { switch (1) { case 1: return; break; default: break; } }",
-  traverse(TK_AsIs, caseStmt(hasSubstatement(returnStmt());
-}
-
-TEST_P(ASTMatchersTest, HasDefaultSubstatement) {
-  EXPECT_TRUE(matches(
-  "void f() { switch (1) { case 1: return; break; default: break; } }",
-  traverse(TK_AsIs, defaultStmt(hasSubstatement(breakStmt());
-}
-
-TEST_P(ASTMatchersTest, HasLabelSubstatement) {
-  EXPECT_TRUE(
-  matches("void f() { while (1) { bar: break; foo: return; } }",
-  traverse(TK_AsIs, labelStmt(hasSubstatement(breakStmt());
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceSimple) {
-  const char *Text = "int f() { int x = 5; if (x < 0) return 1; return 0; }";
-  EXPECT_TRUE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
-  EXPECT_FALSE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), labelStmt();
-  EXPECT_FALSE(matches(
-  Text, compoundStmt(hasSubstatementSequence(returnStmt(), ifStmt();
-  EXPECT_FALSE(matches(
-  Text, compoundStmt(hasSubstatementSequence(switchStmt(), labelStmt();
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceAlmost) {
-  const char *Text = R"code(
-int f() {
-  int x = 5;
-  if (x < 10)
-;
-  if (x < 0)
-return 1;
-  return 0;
-}
-)code";
-  EXPECT_TRUE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
-  EXPECT_TRUE(
-  matches(Text, compoundStmt(hasSubstatementSequence(ifStmt(), ifStmt();
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceComplex) {
-  const char *Text = R"code(
-int f() {
-  int x = 5;
-  if (x < 10)
-x -= 10;
-  if (x < 0)
-return 1;
-  return 0;
-}
-)code";
-  EXPECT_TRUE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
-  EXPECT_FALSE(
-  matches(Text, compoundStmt(hasSubstatementSequence(ifStmt(), expr();
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceExpression) {
-  const char *Text = R"code(
-int f() {
-  return ({ int x = 5;
-  int result;
-  if (x < 10)
-x -= 10;
-  if (x < 0)
-result = 1;
-  else
-result = 0;
-  result;
-});
-  }
-)code";
-  EXPECT_TRUE(
-  matches(Text, stmtExpr(hasSubstatementSequence(ifStmt(), expr();
-  EXPECT_FALSE(
-  matches(Text, stmtExpr(hasSubstatementSequence(ifStmt(), returnStmt();
-}
-
 // Copied from ASTMatchersTests
 static std::vector allTestClangConfigs() {
   std::vector all_configs;
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
+++ /dev/null
@@ -1,68 +0,0 @@
-//===-- SimplifyBooleanExprMatchers.h - clang-tidy ===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-
-#include "clang/ASTMatchers/ASTMatchersInternal.h"
-#include "clang/ASTMatchers/ASTMatchersMacros.h"
-
-namespace clang {
-namespace ast_matchers {
-
-/// Matches the substatement associated with a case, default or label statement.
-///
-/// Given
-/// \code
-///   switch (1) { case 1: break; case 2: return; break; default: return; break;
-///   }
-///   foo: return;
-///   bar: break;
-/// \endcode
-///
-/// caseStmt(hasSubstatement(returnStmt()))

[clang-tools-extra] 6f87261 - [clang-tidy][NFC] Reimplement SimplifyBooleanExpr with RecursiveASTVisitors

2022-05-16 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-05-16T14:42:44+01:00
New Revision: 6f8726191960f068d1068f84dfb9077d85c64fb9

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

LOG: [clang-tidy][NFC] Reimplement SimplifyBooleanExpr with RecursiveASTVisitors

Reimplement the matching logic using Visitors instead of matchers.

Benchmarks from running the check over SemaCodeComplete.cpp
Before 0.20s, After 0.04s

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp

Removed: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h



diff  --git 
a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
index 61ba4b857636c..2300b4260c600 100644
--- a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -7,7 +7,6 @@
 
//===--===//
 
 #include "SimplifyBooleanExprCheck.h"
-#include "SimplifyBooleanExprMatchers.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Lex/Lexer.h"
 
@@ -22,46 +21,18 @@ namespace readability {
 
 namespace {
 
-StringRef getText(const MatchFinder::MatchResult &Result, SourceRange Range) {
+StringRef getText(const ASTContext &Context, SourceRange Range) {
   return Lexer::getSourceText(CharSourceRange::getTokenRange(Range),
-  *Result.SourceManager,
-  Result.Context->getLangOpts());
+  Context.getSourceManager(),
+  Context.getLangOpts());
 }
 
-template 
-StringRef getText(const MatchFinder::MatchResult &Result, T &Node) {
-  return getText(Result, Node.getSourceRange());
+template  StringRef getText(const ASTContext &Context, T &Node) {
+  return getText(Context, Node.getSourceRange());
 }
 
 } // namespace
 
-static constexpr char ConditionThenStmtId[] = "if-bool-yields-then";
-static constexpr char ConditionElseStmtId[] = "if-bool-yields-else";
-static constexpr char TernaryId[] = "ternary-bool-yields-condition";
-static constexpr char TernaryNegatedId[] = "ternary-bool-yields-not-condition";
-static constexpr char IfReturnsBoolId[] = "if-return";
-static constexpr char IfReturnsNotBoolId[] = "if-not-return";
-static constexpr char ThenLiteralId[] = "then-literal";
-static constexpr char IfAssignVariableId[] = "if-assign-lvalue";
-static constexpr char IfAssignLocId[] = "if-assign-loc";
-static constexpr char IfAssignBoolId[] = "if-assign";
-static constexpr char IfAssignNotBoolId[] = "if-assign-not";
-static constexpr char IfAssignVarId[] = "if-assign-var";
-static constexpr char CompoundReturnId[] = "compound-return";
-static constexpr char CompoundIfId[] = "compound-if";
-static constexpr char CompoundBoolId[] = "compound-bool";
-static constexpr char CompoundNotBoolId[] = "compound-bool-not";
-static constexpr char CaseId[] = "case";
-static constexpr char CaseCompoundBoolId[] = "case-compound-bool";
-static constexpr char CaseCompoundNotBoolId[] = "case-compound-bool-not";
-static constexpr char DefaultId[] = "default";
-static constexpr char DefaultCompoundBoolId[] = "default-compound-bool";
-static constexpr char DefaultCompoundNotBoolId[] = "default-compound-bool-not";
-static constexpr char LabelId[] = "label";
-static constexpr char LabelCompoundBoolId[] = "label-compound-bool";
-static constexpr char LabelCompoundNotBoolId[] = "label-compound-bool-not";
-static constexpr char IfStmtId[] = "if";
-
 static constexpr char SimplifyOperatorDiagnostic[] =
 "redundant boolean literal supplied to boolean operator";
 static constexpr char SimplifyConditionDiagnostic[] =
@@ -69,33 +40,6 @@ static constexpr char SimplifyConditionDiagnostic[] =
 static constexpr char SimplifyConditionalReturnDiagnostic[] =
 "redundant boolean literal in conditional return statement";
 
-static const Expr *getBoolLiteral(const MatchFinder::MatchResult &Result,
-  StringRef Id) {
-  if (const Expr *Literal = Result.Nodes.getNodeAs(Id))
-return Literal->getBeginLoc().isMacroID() ? nullptr : Literal;
-  if (const auto *Negated = Result.Nodes.getNodeAs(Id)) {
-if (Negated->getOpcode() == UO_LNot &&
-isa(Negated->getSubExpr()))
-  return Negated->getBeginLoc().isMacroID() ? nullptr : Negated;
-  }
-  return nullptr;
-}
-
-static internal::BindableMatcher literalOrNegatedBool(bool Value) {
-  ret

[PATCH] D124446: [clang-tidy] Add the misc-discarded-return-value check

2022-05-16 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/misc/DiscardedReturnValueCheck.cpp:83-86
+void DiscardedReturnValueCheck::onStartOfTranslationUnit() {
+  ConsumedCalls.clear();
+  CallMap.clear();
+}

aaron.ballman wrote:
> Is this code necessary?
Yes, if you have checks that store TU-specific data, and you run `clang-tidy 
a.cpp b.cpp` then if you do not clear the data structures, dangling pointers 
into already destroyed ASTs will remain.



Comment at: clang-tools-extra/clang-tidy/misc/DiscardedReturnValueCheck.cpp:181
+
+  static const auto Decltype = decltypeType(hasUnderlyingExpr(Call));
+  static const auto TemplateArg =

aaron.ballman wrote:
> So, I'm not super keen on this approach of having to try to identify every 
> single place in which an expression is considered to be "used" -- this is 
> going to be fragile because we'll miss places and it's going to be a 
> maintenance burden because new places will be added as the languages evolve.
> 
> For example, if we're handling `decltype` as a use, why not `noexcept`? Or 
> conditional `explicit`? What about a `co_return` statement?
> 
> I'm not certain what we can do to improve this, but I think it's worth trying 
> to explore options to see if we can generalize what constitutes a use so that 
> we can write a few custom matchers to do the heavy lifting instead of trying 
> to play whack-a-mole.
I've been having other thoughts about this `decltype` here... Actually, neither 
`decltype` nor `noexcept` should be handled as a //"use"// at all, while 
`co_return` should be the same as a `return` -- however, I think it was due to 
lack of projects where such could be meaningfully measured as a missed case was 
why implementing that failed.

For `decltype`, `typedef`, and `noexcept` (and perhaps several others), the 
good solution would be having a third route: calls that //should not be 
counted//. Neither as a "consumed call", nor as a "bare call". Ignored, from 
both calculations. Maybe even for template arguments below.



Comment at: clang-tools-extra/clang-tidy/misc/DiscardedReturnValueCheck.cpp:181
+
+  static const auto Decltype = decltypeType(hasUnderlyingExpr(Call));
+  static const auto TemplateArg =

whisperity wrote:
> aaron.ballman wrote:
> > So, I'm not super keen on this approach of having to try to identify every 
> > single place in which an expression is considered to be "used" -- this is 
> > going to be fragile because we'll miss places and it's going to be a 
> > maintenance burden because new places will be added as the languages evolve.
> > 
> > For example, if we're handling `decltype` as a use, why not `noexcept`? Or 
> > conditional `explicit`? What about a `co_return` statement?
> > 
> > I'm not certain what we can do to improve this, but I think it's worth 
> > trying to explore options to see if we can generalize what constitutes a 
> > use so that we can write a few custom matchers to do the heavy lifting 
> > instead of trying to play whack-a-mole.
> I've been having other thoughts about this `decltype` here... Actually, 
> neither `decltype` nor `noexcept` should be handled as a //"use"// at all, 
> while `co_return` should be the same as a `return` -- however, I think it was 
> due to lack of projects where such could be meaningfully measured as a missed 
> case was why implementing that failed.
> 
> For `decltype`, `typedef`, and `noexcept` (and perhaps several others), the 
> good solution would be having a third route: calls that //should not be 
> counted//. Neither as a "consumed call", nor as a "bare call". Ignored, from 
> both calculations. Maybe even for template arguments below.
As for better matching... Unfortunately, types in the AST are so varied and 
`hasDescendant` is too generic to express something like `stmt(anyOf(ifStmt(), 
forStmt(), switchStmt()), hasDescendant(Call))` to express in a single 
expression matching uses... The conditions are not always direct children of 
the outer node, while `hasDescendant` will match not just the condition but the 
entire tree... resulting in things like //both// functions in

```lang=cpp
if (foo())
  bar()
```

matching.

Well... generalisation... I can throw in a formal fluke:

> A **use** is a //context// for a specific `CallExpr C` in which we can 
> reasonably assume that the value produced by evaluating `C` is loaded by 
> another expression.

Now what I found is `-Wunused-result`, aka `SemaDiagnostics::warn_unused_expr`, 
which is triggered in the function `ExprResult Sema::ActOnFinishFullExpr(Expr* 
FE, SourceLocation CC, bool DiscardedValue, bool IsConstexpr);`. Now this 
function itself does //some// heuristics inside (with a **lot** of `FIXME`s as 
of rGdab5e10ea5dbc2e6314e0e7ce54a9c51fbcb44bd), but notably, `DiscardedValue` 
is a parameter. According to a quick search, this function (and its overloads) 
have **82** callsites withi

[PATCH] D125675: Optimise findRefs for XRefs and docHighlights

2022-05-16 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks for noticing this, LGTM!




Comment at: clang-tools-extra/clangd/XRefs.cpp:961
   const ParsedAST &AST;
-  const llvm::DenseSet &TargetIDs;
+  llvm::DenseMap TargetDeclAndID;
 };

s/TargetDeclAndID/TargetDeclToID



Comment at: clang-tools-extra/clangd/XRefs.cpp:965
 std::vector
-findRefs(const llvm::DenseSet &IDs, ParsedAST &AST, bool PerToken) {
-  ReferenceFinder RefFinder(AST, IDs, PerToken);
+findRefs(const llvm::DenseSet &TargetDecls, ParsedAST &AST,
+ bool PerToken) {

i'd actually update the interface here to just take an `ArrayRef` as 
targets, as we're currently building those extra dense sets just to iterate 
over them. both `allTargetDecls` and `getDeclAtPosition` (which uses 
`allTargetDecls` underneath) are guaranteed to not return duplicates. So we can 
pass their result directly here. Up to you though.



Comment at: clang-tools-extra/clangd/XRefs.cpp:1919
   // If there's a specific type alias, point at that rather than unwrapping.
-  if (const auto* TDT = T->getAs())
+  if (const auto *TDT = T->getAs())
 return QualType(TDT, 0);

can you revert this change?



Comment at: clang-tools-extra/clangd/XRefs.cpp:951
   if (const auto *Tok = TB.spelledTokenAt(L))
-References.push_back({*Tok, Roles, ID});
+References.push_back({*Tok, Roles, getSymbolID(D)});
 }

usaxena95 wrote:
> kadircet wrote:
> > we're still calling getsymbolid here lots of times, for probably the same 
> > symbol.
> > 
> > as discussed, what about building a lookup table on construction from 
> > canonicaldecl to symbolid and use that lookup table instead of calling 
> > getsymbolid over and over here?
> I don't mind adding a lookup table for this but this is not huge, only 
> O(#ref) as compared to previous O(size of TU). 
> 
> 
thanks. previous one was also size of main file, not the whole TU (if you see 
indications of the latter in a different application let's take a look at that 
separately).

but there are big enough files in which you can have thousands of references to 
stringref and what not. so i think this actually matters.



Comment at: clang-tools-extra/clangd/XRefs.cpp:1255
+   targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver())) {
+TargetDecls.insert(D);
+  }

usaxena95 wrote:
> kadircet wrote:
> > i mean directly inserting canonicaldecls here.
> This would make it messy to duplicate this on each end of the call. 
> + This has potential of introducing bugs in future findRef calls if we don't 
> pass the canonical decls. Or we would have to assert that we only get 
> canonical decls.
> I think this is an implementation detail of findRefs and should not be 
> visible outside its API for simplicity.
SG, it's an implementation detail of this file already so not a big deal. But 
moreover we're building a separate lookup table already now, so obsolete.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125675

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


[PATCH] D124701: [clang] Honor __attribute__((no_builtin("foo"))) on functions

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

- Update documentation


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124701

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/no-builtin-2.c

Index: clang/test/CodeGen/no-builtin-2.c
===
--- /dev/null
+++ clang/test/CodeGen/no-builtin-2.c
@@ -0,0 +1,63 @@
+// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck %s
+
+typedef typeof(sizeof(0)) size_t;
+
+void bar(char *s);
+void *memset(void *s, int c, size_t n);
+void *memcpy(void *d, const void *s, size_t n);
+void *memmove(void *d, const void *s, size_t n);
+
+// CHECK: define{{.*}} void @foo1({{.*}}) #[[NO_NOBUILTIN:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   call void @llvm.memset
+// CHECK:   call void @llvm.memcpy
+// CHECK:   call void @llvm.memmove
+void foo1(char *s, char *d, size_t n) {
+  bar(s);
+  memset(s, 0, n);
+  memcpy(d, s, n);
+  memmove(d, s, n);
+}
+
+// CHECK: define{{.*}} void @foo2({{.*}}) #[[NOBUILTIN_MEMSET:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call {{.*}} @memset
+// CHECK:   call void @llvm.memcpy
+// CHECK:   call void @llvm.memmove
+void foo2(char *s, char *d, size_t n) __attribute__((no_builtin("memset"))) {
+  bar(s);
+  memset(s, 1, n);
+  memcpy(d, s, n);
+  memmove(d, s, n);
+}
+
+// CHECK: define{{.*}} void @foo3({{.*}}) #[[NOBUILTIN_MEMSET_MEMCPY:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call {{.*}} @memset
+// CHECK:   {{.*}}call {{.*}} @memcpy
+// CHECK:   call void @llvm.memmove
+void foo3(char *s, char *d, size_t n) __attribute__((no_builtin("memset", "memcpy"))) {
+  bar(s);
+  memset(s, 2, n);
+  memcpy(d, s, n);
+  memmove(d, s, n);
+}
+
+// CHECK: define{{.*}} void @foo4({{.*}}) #[[NOBUILTINS:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call {{.*}} @memset
+// CHECK:   {{.*}}call {{.*}} @memcpy
+// CHECK:   {{.*}}call {{.*}} @memmove
+void foo4(char *s, char *d, size_t n) __attribute__((no_builtin("*"))) {
+  bar(s);
+  memset(s, 2, n);
+  memcpy(d, s, n);
+  memmove(s, d, n);
+}
+
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtins"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET_MEMCPY]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTINS]] = {{{.*}}"no-builtins"{{.*}}}
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -1142,7 +1142,8 @@
   if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc))
 return;
 
-  if (Builtin::Context::isBuiltinFunc(BuiltinName))
+  bool ParsedAttrIsWildCard = BuiltinName == kWildcard;
+  if (Builtin::Context::isBuiltinFunc(BuiltinName) || ParsedAttrIsWildCard)
 AddBuiltinName(BuiltinName);
   else
 S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -5034,7 +5034,16 @@
   const FunctionDecl *FD = cast(GD.getDecl());
 
   if (auto builtinID = FD->getBuiltinID()) {
+std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
+std::string NoBuiltins = "no-builtins";
 std::string FDInlineName = (FD->getName() + ".inline").str();
+
+bool IsPredefinedLibFunction =
+CGF.getContext().BuiltinInfo.isPredefinedLibFunction(builtinID);
+bool HasAttributeNoBuiltin =
+CGF.CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
+CGF.CurFn->getAttributes().hasFnAttr(NoBuiltins);
+
 // When directing calling an inline builtin, call it through it's mangled
 // name to make it clear it's not the actual builtin.
 if (CGF.CurFn->getName() != FDInlineName &&
@@ -5054,8 +5063,11 @@
 
 // Replaceable builtins provide their own implementation of a builtin. If we
 // are in an inline builtin implementation, avoid trivial infinite
-// recursion.
-else
+// recursion. Honor __attribute__((no_builtin("foo"))) or
+// __attribute((no_builtin("*"))) on the current function unless foo is
+// not a predefined library function which means we must generate the
+// builtin no matter what.
+else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
   return CGCallee::forBuiltin(builtinID, FD);
   }
 
Index: clang/include/clang/Basic/AttrDo

[clang] b147717 - [MSVC] Add support for pragma alloc_text

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

Author: Stephen Long
Date: 2022-05-16T07:00:17-07:00
New Revision: b147717bb36c915bedfb33c07259cac4f09502a1

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

LOG: [MSVC] Add support for pragma alloc_text

`#pragma alloc_text` is a MSVC pragma that names the code section where 
functions should be placed. It only
applies to functions with C linkage.

https://docs.microsoft.com/en-us/cpp/preprocessor/alloc-text?view=msvc-170

Reviewed By: aaron.ballman

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

Added: 
clang/test/CodeGen/msvc_pragma_alloc_text.cpp
clang/test/Sema/pragma-ms-alloc-text.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParsePragma.cpp
clang/lib/Sema/SemaAttr.cpp
clang/lib/Sema/SemaDecl.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a43880c2fd74..59c42384c4ed7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -281,6 +281,9 @@ New Pragmas in Clang
 - Added support for MSVC's ``#pragma function``, which tells the compiler to
   generate calls to functions listed in the pragma instead of using the
   builtins.
+- Added support for MSVC's ``#pragma alloc_text``. The pragma names the code
+  section functions are placed in. The pragma only applies to functions with
+  C linkage.
 
 - ...
 

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index dfca233033a9f..6dcf2eafbf210 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -990,6 +990,8 @@ def err_super_in_lambda_unsupported : Error<
 
 def err_pragma_expected_file_scope : Error<
   "'#pragma %0' can only appear at file scope">;
+def err_pragma_alloc_text_c_linkage: Error<
+  "'#pragma alloc_text' is applicable only to functions with C linkage">;
 
 def warn_pragma_unused_undeclared_var : Warning<
   "undeclared variable %0 used as an argument for '#pragma unused'">,

diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index 4e4fcb53474ec..e44ef6bb8f19d 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -199,6 +199,7 @@ class Parser : public CodeCompletionHandler {
   std::unique_ptr MSFunction;
   std::unique_ptr MSOptimize;
   std::unique_ptr MSFenvAccess;
+  std::unique_ptr MSAllocText;
   std::unique_ptr CUDAForceHostDeviceHandler;
   std::unique_ptr OptimizeHandler;
   std::unique_ptr LoopHintHandler;
@@ -725,6 +726,8 @@ class Parser : public CodeCompletionHandler {
  SourceLocation PragmaLocation);
   bool HandlePragmaMSFunction(StringRef PragmaName,
   SourceLocation PragmaLocation);
+  bool HandlePragmaMSAllocText(StringRef PragmaName,
+   SourceLocation PragmaLocation);
 
   /// Handle the annotation token produced for
   /// #pragma align...

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 13d403bf8db94..e9bd7569984c9 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -724,6 +724,9 @@ class Sema final {
   StringLiteral *CurInitSeg;
   SourceLocation CurInitSegLoc;
 
+  /// Sections used with #pragma alloc_text.
+  llvm::StringMap> FunctionToSectionMap;
+
   /// VisContext - Manages the stack for \#pragma GCC visibility.
   void *VisContext; // Really a "PragmaVisStack*"
 
@@ -10200,6 +10203,12 @@ class Sema final {
   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
 StringLiteral *SegmentName);
 
+  /// Called on well-formed \#pragma alloc_text().
+  void ActOnPragmaMSAllocText(
+  SourceLocation PragmaLocation, StringRef Section,
+  const SmallVector>
+  &Functions);
+
   /// Called on #pragma clang __debug dump II
   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
 
@@ -10341,6 +10350,11 @@ class Sema final {
   /// with attribute optnone.
   void AddRangeBasedOptnone(FunctionDecl *FD);
 
+  /// Only called on function definitions; if there is a `#pragma alloc_text`
+  /// that decides which code section the function should be in, add
+  /// attribute section to the function.
+  void AddSectionMSAllocText(FunctionDecl *FD);
+
   /// Adds the 'optnone' attribute to the function declaration if there
   /// are no conflicts; Loc represents the location causing the 'optnone'
   /// attribute to be added (usually because of a pragma).

diff  --git a/clang/lib/Parse/ParsePragma.cpp b/clang/lib/Parse/ParsePragma.cpp
index cf637fc0d80b7.

[PATCH] D125011: [MSVC] Add support for pragma alloc_text

2022-05-16 Thread Stephen Long via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb147717bb36c: [MSVC] Add support for pragma alloc_text 
(authored by steplong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125011

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/CodeGen/msvc_pragma_alloc_text.cpp
  clang/test/Sema/pragma-ms-alloc-text.cpp

Index: clang/test/Sema/pragma-ms-alloc-text.cpp
===
--- /dev/null
+++ clang/test/Sema/pragma-ms-alloc-text.cpp
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s
+
+#pragma alloc_text()// expected-warning {{expected a string literal for the section name in '#pragma alloc_text'}}
+#pragma alloc_text(a// expected-warning {{expected ',' in '#pragma alloc_text'}}
+#pragma alloc_text(a, a // expected-warning {{missing ')' after '#pragma alloc_text'}}
+#pragma alloc_text(a, a)// expected-error {{use of undeclared a}}
+#pragma alloc_text(L"a", a) // expected-warning {{expected a string literal for the section name}}
+
+void foo();
+#pragma alloc_text(a, foo) // expected-error {{'#pragma alloc_text' is applicable only to functions with C linkage}}
+
+extern "C" void foo1();
+#pragma alloc_text(a, foo1)  // no-warning
+#pragma alloc_text(a, foo1) asdf // expected-warning {{extra tokens at end of '#pragma alloc_text'}}
+#pragma alloc_text(a, foo1   // expected-warning {{missing ')' after '#pragma alloc_text'}}
+
+namespace N {
+#pragma alloc_text(b, foo1) // no-warning
+}
+
+extern "C" {
+void foo2();
+#pragma alloc_text(a, foo2) // no-warning
+}
+
+void foo3() {
+#pragma alloc_text(a, foo1) // expected-error {{'#pragma alloc_text' can only appear at file scope}}
+}
+
+extern "C" void foo4();
+#pragma alloc_text(c, foo4) // no-warning
+void foo4() {}
+
+void foo5();// expected-note {{previous declaration is here}}
+#pragma alloc_text(c, foo5) // expected-error {{'#pragma alloc_text' is applicable only to functions with C linkage}}
+extern "C" void foo5() {}   // expected-error {{declaration of 'foo5' has a different language linkage}}
Index: clang/test/CodeGen/msvc_pragma_alloc_text.cpp
===
--- /dev/null
+++ clang/test/CodeGen/msvc_pragma_alloc_text.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -fms-extensions -S -emit-llvm -o - %s | FileCheck %s
+
+extern "C" {
+
+void foo();
+void foo1();
+void foo2();
+void foo3();
+
+#pragma alloc_text("abc", foo, foo1)
+#pragma alloc_text("def", foo2)
+#pragma alloc_text("def", foo3)
+
+// CHECK-LABEL: define{{.*}} void @foo() {{.*}} section "abc"
+void foo() {}
+
+// CHECK-LABEL: define{{.*}} void @foo1() {{.*}} section "abc"
+void foo1() {}
+
+// CHECK-LABEL: define{{.*}} void @foo2() {{.*}} section "def"
+void foo2() {}
+
+// CHECK-LABEL: define{{.*}} void @foo3() {{.*}} section "def"
+void foo3() {}
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -10219,6 +10219,7 @@
   if (D.isFunctionDefinition()) {
 AddRangeBasedOptnone(NewFD);
 AddImplicitMSFunctionNoBuiltinAttr(NewFD);
+AddSectionMSAllocText(NewFD);
   }
 
   // If this is the first declaration of an extern C variable, update
Index: clang/lib/Sema/SemaAttr.cpp
===
--- clang/lib/Sema/SemaAttr.cpp
+++ clang/lib/Sema/SemaAttr.cpp
@@ -741,6 +741,37 @@
   CurInitSegLoc = PragmaLocation;
 }
 
+void Sema::ActOnPragmaMSAllocText(
+SourceLocation PragmaLocation, StringRef Section,
+const SmallVector>
+&Functions) {
+  if (!CurContext->getRedeclContext()->isFileContext()) {
+Diag(PragmaLocation, diag::err_pragma_expected_file_scope) << "alloc_text";
+return;
+  }
+
+  for (auto &Function : Functions) {
+IdentifierInfo *II;
+SourceLocation Loc;
+std::tie(II, Loc) = Function;
+
+DeclarationName DN(II);
+NamedDecl *ND = LookupSingleName(TUScope, DN, Loc, LookupOrdinaryName);
+if (!ND) {
+  Diag(Loc, diag::err_undeclared_use) << II->getName();
+  return;
+}
+
+DeclContext *DC = ND->getDeclContext();
+if (!DC->isExternCContext()) {
+  Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
+  return;
+}
+
+FunctionToSectionMap[II->getName()] = std::make_tuple(Section, Loc);
+  }
+}
+
 void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
  SourceLocation PragmaLoc) {
 
@@ -1082,6 +1113,22 @@
 AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
 }
 
+void Sema::Add

[PATCH] D125272: [clang] Add -fcheck-new support

2022-05-16 Thread Pedro Falcato via Phabricator via cfe-commits
heatd added a comment.

In D125272#3504113 , @heatd wrote:

> Adjusted the driver code to use addOptInFlag, adjusted the test, fixed the 
> comment.

Ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125272

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


[PATCH] D124806: [clang-tidy] add support for Demorgan conversions to readability-simplify-bool-expr

2022-05-16 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 429715.
njames93 added a comment.

Rebased.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124806

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-demorgan.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-demorgan.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-demorgan.cpp
@@ -0,0 +1,67 @@
+// RUN: %check_clang_tidy %s readability-simplify-boolean-expr %t
+
+void foo(bool A1, bool A2, bool A3, bool A4) {
+  bool X;
+  X = !(!A1 || A2);
+  X = !(A1 || !A2);
+  X = !(!A1 || !A2);
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (A1 && !A2);
+  // CHECK-FIXES-NEXT: X = (!A1 && A2);
+  // CHECK-FIXES-NEXT: X = (A1 && A2);
+
+  X = !(!A1 && A2);
+  X = !(A1 && !A2);
+  X = !(!A1 && !A2);
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (A1 || !A2);
+  // CHECK-FIXES-NEXT: X = (!A1 || A2);
+  // CHECK-FIXES-NEXT: X = (A1 || A2);
+
+  X = !(!A1 && !A2 && !A3);
+  X = !(!A1 && (!A2 && !A3));
+  X = !(!A1 && (A2 && A3));
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (A1 || A2 || A3);
+  // CHECK-FIXES-NEXT: X = (A1 || A2 || A3);
+  // CHECK-FIXES-NEXT: X = (A1 || !A2 || !A3);
+
+  X = !(A1 && A2 == A3);
+  X = !(!A1 && A2 > A3);
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (!A1 || A2 != A3);
+  // CHECK-FIXES-NEXT: X = (A1 || A2 <= A3);
+
+  // Ensure the check doesn't try to combine fixes for the inner and outer demorgan simplification.
+  X = !(!A1 && !(!A2 && !A3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-2]]:16: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (A1 || (!A2 && !A3));
+
+  // Testing to see how it handles parens
+  X = !(A1 && !A2 && !A3);
+  X = !(A1 && !A2 || !A3);
+  X = !(!A1 || A2 && !A3);
+  X = !((A1 || !A2) && !A3);
+  X = !((A1 || !A2) || !A3);
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (!A1 || A2 || A3);
+  // CHECK-FIXES-NEXT: X = ((!A1 || A2) && A3);
+  // CHECK-FIXES-NEXT: X = (A1 && (!A2 || A3));
+  // CHECK-FIXES-NEXT: X = ((!A1 && A2) || A3);
+  // CHECK-FIXES-NEXT: X = (!A1 && A2 && A3);
+  X = !((A1 || A2) && (!A3 || A4));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = ((!A1 && !A2) || (A3 && !A4));
+}
Index: clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
@@ -4,7 +4,8 @@
 =
 
 Looks for boolean expressions involving boolean constants and simplifies
-them to use the appropriate boolean expression directly.
+them to use the appropriate boolean expression 

[PATCH] D125555: [clang] Add __has_target_feature

2022-05-16 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 2 inline comments as done.
yaxunl added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:260
 
+``__has_target_feature``
+

aaron.ballman wrote:
> The first question that comes to mind for me is: why is `__has_feature` not 
> sufficient?
`__has_target_feature` accepts predefined target features for the specified 
target triple and CPU. The names of target features are determined by the 
target. They may overlap with clang features and cause ambiguity. Another issue 
is that they usually contain '-', which makes them not valid identifiers of 
C/C++, therefore the builtin macro has to accept a string literal argument 
instead of identifier argument like `__has_feature`. 



Comment at: clang/docs/LanguageExtensions.rst:275
+  // On amdgcn target
+  #if __has_target_feature("s-memtime-inst")
+x = __builtin_amdgcn_s_memtime();

aaron.ballman wrote:
> yaxunl wrote:
> > tra wrote:
> > > Do you have a better example? This particular case could've been handled 
> > > by existing `__has_builtin()`.
> > > 
> > > While I could see usefulness of checking features (e.g. for CUDA/NVPTX it 
> > > could be used to chose inline assembly supported only by newer PTX 
> > > versions, but even then that choice could be made using existing methods, 
> > > even if they are not always direct (e.g. by using CUDA_VERSION as a proxy 
> > > for "new enough PTX version").
> > > 
> > `__has_builtin` returns 1 as long as the builtin is known to clang, even if 
> > the builtin is not supported by the target CPU. This is because the 
> > required target feature for a builtin is in ASTContext, whereas 
> > `__has_builtin` is evaluated in preprocessor, where the information is not 
> > known.
> > `__has_builtin` returns 1 as long as the builtin is known to clang, even if 
> > the builtin is not supported by the target CPU. This is because the 
> > required target feature for a builtin is in ASTContext, whereas 
> > `__has_builtin` is evaluated in preprocessor, where the information is not 
> > known.
> 
> Why is that not a deficiency with `__has_builtin` that we should fix?
It is arguable whether this is a bug for `__has_builtin`. I tend to treat it as 
a bug and think it should be fixed. However, fixing it may cause regressions 
since there may be existing code expecting `__has_builtin` not depending on 
availability of required target feature. This will limit the usability of a fix 
for this issue.

Even if we agree that this is a bug for `__has_builtin` which should be fixed, 
this does conflict with adding `__has_target_feature`, as 
`__has_target_feature` has more uses than determining whether a target builtin 
is available, e.g. choosing different algorithms based on availability of 
certain target feature, or using certain inline assembly code.


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

https://reviews.llvm.org/D12

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


[PATCH] D125555: [clang] Add __has_target_feature

2022-05-16 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked an inline comment as done.
yaxunl added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:275
+  // On amdgcn target
+  #if __has_target_feature("s-memtime-inst")
+x = __builtin_amdgcn_s_memtime();

yaxunl wrote:
> aaron.ballman wrote:
> > yaxunl wrote:
> > > tra wrote:
> > > > Do you have a better example? This particular case could've been 
> > > > handled by existing `__has_builtin()`.
> > > > 
> > > > While I could see usefulness of checking features (e.g. for CUDA/NVPTX 
> > > > it could be used to chose inline assembly supported only by newer PTX 
> > > > versions, but even then that choice could be made using existing 
> > > > methods, even if they are not always direct (e.g. by using CUDA_VERSION 
> > > > as a proxy for "new enough PTX version").
> > > > 
> > > `__has_builtin` returns 1 as long as the builtin is known to clang, even 
> > > if the builtin is not supported by the target CPU. This is because the 
> > > required target feature for a builtin is in ASTContext, whereas 
> > > `__has_builtin` is evaluated in preprocessor, where the information is 
> > > not known.
> > > `__has_builtin` returns 1 as long as the builtin is known to clang, even 
> > > if the builtin is not supported by the target CPU. This is because the 
> > > required target feature for a builtin is in ASTContext, whereas 
> > > `__has_builtin` is evaluated in preprocessor, where the information is 
> > > not known.
> > 
> > Why is that not a deficiency with `__has_builtin` that we should fix?
> It is arguable whether this is a bug for `__has_builtin`. I tend to treat it 
> as a bug and think it should be fixed. However, fixing it may cause 
> regressions since there may be existing code expecting `__has_builtin` not 
> depending on availability of required target feature. This will limit the 
> usability of a fix for this issue.
> 
> Even if we agree that this is a bug for `__has_builtin` which should be 
> fixed, this does conflict with adding `__has_target_feature`, as 
> `__has_target_feature` has more uses than determining whether a target 
> builtin is available, e.g. choosing different algorithms based on 
> availability of certain target feature, or using certain inline assembly code.
> It is arguable whether this is a bug for `__has_builtin`. I tend to treat it 
> as a bug and think it should be fixed. However, fixing it may cause 
> regressions since there may be existing code expecting `__has_builtin` not 
> depending on availability of required target feature. This will limit the 
> usability of a fix for this issue.
> 
> Even if we agree that this is a bug for `__has_builtin` which should be 
> fixed, this does conflict with adding `__has_target_feature`, as 
> `__has_target_feature` has more uses than determining whether a target 
> builtin is available, e.g. choosing different algorithms based on 
> availability of certain target feature, or using certain inline assembly code.

sorry typo. this does not conflict


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

https://reviews.llvm.org/D12

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


[PATCH] D123676: [clang-format] Fix WhitespaceSensitiveMacros not being honoured when macro closing parenthesis is followed by a newline.

2022-05-16 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added a comment.

It looks like this regressed the following example by adding an unwanted level 
of indentation to the `#elif B` branch:

  % ./clang-format --version
  clang-format version 15.0.0 (https://github.com/llvm/llvm-project.git 
50cd52d9357224cce66a9e00c9a0417c658a5655)
  % cat test.cc 
  #define MACRO_BEGIN
  
  MACRO_BEGIN
  
  namespace internal {
  
  #if A
  int f() { return 0; }
  #elif B
  int f() { return 1; }
  #endif
  
  }  // namespace internal
  % ./clang-format test.cc
  #define MACRO_BEGIN
  
  MACRO_BEGIN
  
  namespace internal {
  
  #if A
  int f() { return 0; }
  #elif B
int f() { return 1; }
  #endif
  
  } // namespace internal
  % 

@curdeius could you please take a look?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123676

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


[PATCH] D91157: [AArch64] Out-of-line atomics (-moutline-atomics) implementation.

2022-05-16 Thread Sebastian Pop via Phabricator via cfe-commits
sebpop added a comment.
Herald added a subscriber: MaskRay.
Herald added a project: All.

Hi Pavel,

We need to handle one more case for __sync_* builtins, please see testcase and 
patches applied to GCC:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105162


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91157

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


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

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

Mark this and D125691  as WIP since I'm still 
testing the approach on various combinations of debug info and optimization 
options (O0, O3 , thinlto, 
split-dwarf, split-dwarf-inlining, gline-tables-only, etc.).
Except of the testing purpose itself I'm also trying to catch the issue 
reported by David here https://reviews.llvm.org/D113741#3437182 for previous 
implementation (while I hope this approach wouldn't trigger the issue, it'd be 
good to catch and fix it anyway).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125693

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


[PATCH] D125694: [clang][DebugInfo] Allow function-local statics to be scoped within a lexical block (4/5)

2022-05-16 Thread Kristina Bessonova via Phabricator via cfe-commits
krisb created this revision.
krisb added reviewers: dblaikie, aprantl, probinson.
Herald added a project: All.
krisb requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is a part from D113743  split to make it 
easier to test and review.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125694

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenCXX/debug-info-static-locals.cpp


Index: clang/test/CodeGenCXX/debug-info-static-locals.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/debug-info-static-locals.cpp
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -triple x86_64-none-linux-gnu -emit-llvm 
-debug-info-kind=limited %s -o - | FileCheck %s
+
+// Test that static local variables emitted in correct scopes.
+
+void test() {
+  static int bar = 2;
+  {
+static int bar = 1;
+{
+  static int bar = 0;
+}
+  }
+}
+
+// CHECK: [[FS_GVE:![0-9]+]] = !DIGlobalVariableExpression(var: 
[[FS_GV:![0-9]+]]
+// CHECK: [[FS_GV]] = distinct !DIGlobalVariable(name: "bar", scope: 
[[FSCOPE:![0-9]+]]
+// CHECK: [[FSCOPE]] = distinct !DISubprogram(name: "test"
+// CHECK-SAME:localDecls: [[FS_DECLS:![0-9]+]]
+// CHECK: [[FS_DECLS]] = !{[[FS_GVE]]}
+// CHECK: [[LB1_GVE:![0-9]+]] = !DIGlobalVariableExpression(var: 
[[LB1_GV:![0-9]+]]
+// CHECK: [[LB1_GV]] = distinct !DIGlobalVariable(name: "bar", scope: 
[[LB1SCOPE:![0-9]+]]
+// CHECK: [[LB1SCOPE]] = distinct !DILexicalBlock(scope: [[FSCOPE]]
+// CHECK-SAME:localDecls: 
[[LB1_DECLS:![0-9]+]]
+// CHECK: [[LB1_DECLS]] = !{[[LB1_GVE]]}
+// CHECK: [[LB2_GVE:![0-9]+]] = !DIGlobalVariableExpression(var: 
[[LB2_GV:![0-9]+]]
+// CHECK: [[LB2_GV]] = distinct !DIGlobalVariable(name: "bar", scope: 
[[LB2SCOPE:![0-9]+]]
+// CHECK: [[LB2SCOPE]] = distinct !DILexicalBlock(scope: [[LB1SCOPE]]
+// CHECK-SAME:localDecls: 
[[LB2_DECLS:![0-9]+]]
+// CHECK: [[LB2_DECLS]] = !{[[LB2_GVE]]}
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3746,6 +3746,14 @@
 TemplateParameters = nullptr;
   }
 
+  // Get context for static locals (that are technically globals) the same way
+  // we do for "local" locals -- by using current lexical block.
+  if (VD->isStaticLocal()) {
+assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack 
empty!");
+VDContext = LexicalBlockStack.back();
+return;
+  }
+
   // Since we emit declarations (DW_AT_members) for static members, place the
   // definition of those static members in the namespace they were declared in
   // in the source code (the lexical decl context).


Index: clang/test/CodeGenCXX/debug-info-static-locals.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/debug-info-static-locals.cpp
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -triple x86_64-none-linux-gnu -emit-llvm -debug-info-kind=limited %s -o - | FileCheck %s
+
+// Test that static local variables emitted in correct scopes.
+
+void test() {
+  static int bar = 2;
+  {
+static int bar = 1;
+{
+  static int bar = 0;
+}
+  }
+}
+
+// CHECK: [[FS_GVE:![0-9]+]] = !DIGlobalVariableExpression(var: [[FS_GV:![0-9]+]]
+// CHECK: [[FS_GV]] = distinct !DIGlobalVariable(name: "bar", scope: [[FSCOPE:![0-9]+]]
+// CHECK: [[FSCOPE]] = distinct !DISubprogram(name: "test"
+// CHECK-SAME:localDecls: [[FS_DECLS:![0-9]+]]
+// CHECK: [[FS_DECLS]] = !{[[FS_GVE]]}
+// CHECK: [[LB1_GVE:![0-9]+]] = !DIGlobalVariableExpression(var: [[LB1_GV:![0-9]+]]
+// CHECK: [[LB1_GV]] = distinct !DIGlobalVariable(name: "bar", scope: [[LB1SCOPE:![0-9]+]]
+// CHECK: [[LB1SCOPE]] = distinct !DILexicalBlock(scope: [[FSCOPE]]
+// CHECK-SAME:localDecls: [[LB1_DECLS:![0-9]+]]
+// CHECK: [[LB1_DECLS]] = !{[[LB1_GVE]]}
+// CHECK: [[LB2_GVE:![0-9]+]] = !DIGlobalVariableExpression(var: [[LB2_GV:![0-9]+]]
+// CHECK: [[LB2_GV]] = distinct !DIGlobalVariable(name: "bar", scope: [[LB2SCOPE:![0-9]+]]
+// CHECK: [[LB2SCOPE]] = distinct !DILexicalBlock(scope: [[LB1SCOPE]]
+// CHECK-SAME:localDecls: [[LB2_DECLS:![0-9]+]]
+// CHECK: [[LB2_DECLS]] = !{[[LB2_GVE]]}
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3746,6 +3746,14 @@
 TemplateParameters = nullptr;
   }
 
+  // Get context for static locals (that are technically globals) the same way
+  // we do for "local" locals -- by using current lexical block.
+  if (VD->isStaticLocal()) {
+assert(!LexicalBlockStack.empty() && "Region stack m

  1   2   >