[PATCH] D119599: [clang-format] Add option to align compound assignments like `+=`

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

You either get commit access 
https://llvm.org/docs/DeveloperPolicy.html#obtaining-commit-access or ask 
someone of us to push it for you. In the latter case we need a name and mail 
for the commit. I recommend the former, especially if you want to contribute 
more, it's not that hard, just ask. :)

Then you can push to the main branch on Github.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119599

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


[PATCH] D121549: Define ABI breaking class members correctly

2022-03-13 Thread Daniil Kovalev via Phabricator via cfe-commits
kovdan01 created this revision.
kovdan01 added reviewers: dexonsmith, craig.topper.
Herald added subscribers: sdasgup3, wenzhicui, wrengr, Chia-hungDuan, dcaballe, 
cota, teijeong, rdzhabarov, tatianashp, ThomasRaoux, msifontes, ecnelises, 
jurahul, Kayjukh, grosul1, Joonsoo, liufengdb, aartbik, mgester, arpith-jacob, 
antiagainst, shauheen, mravishankar, rriddle, mehdi_amini, javed.absar, 
hiraditya, qcolombet, MatzeB.
Herald added a reviewer: antiagainst.
Herald added a project: All.
kovdan01 requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, stephenneuendorffer, 
nicolasvasilache.
Herald added projects: clang, MLIR, LLVM.

Non-static class members declared under #ifndef NDEBUG should be declared
under #if LLVM_ENABLE_ABI_BREAKING_CHECKS to make headers library-friendly and
allow cross-linking.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121549

Files:
  clang/lib/Sema/TypeLocBuilder.cpp
  clang/lib/Sema/TypeLocBuilder.h
  llvm/include/llvm/CodeGen/GlobalISel/GISelWorkList.h
  llvm/include/llvm/CodeGen/MachineScheduler.h
  llvm/include/llvm/CodeGen/PBQP/ReductionRules.h
  llvm/include/llvm/CodeGen/RegAllocPBQP.h
  llvm/include/llvm/CodeGen/SelectionDAG.h
  llvm/lib/CodeGen/MachineScheduler.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
  llvm/lib/Target/SystemZ/SystemZHazardRecognizer.h
  mlir/lib/Target/SPIRV/Deserialization/Deserializer.h

Index: mlir/lib/Target/SPIRV/Deserialization/Deserializer.h
===
--- mlir/lib/Target/SPIRV/Deserialization/Deserializer.h
+++ mlir/lib/Target/SPIRV/Deserialization/Deserializer.h
@@ -598,6 +598,7 @@
   /// A list of all structs which have unresolved member types.
   SmallVector deferredStructTypesInfos;
 
+  // TODO: place logger undef #if LLVM_ENABLE_ABI_BREAKING_CHECKS
 #ifndef NDEBUG
   /// A logger used to emit information during the deserialzation process.
   llvm::ScopedPrinter logger;
Index: llvm/lib/Target/SystemZ/SystemZHazardRecognizer.h
===
--- llvm/lib/Target/SystemZ/SystemZHazardRecognizer.h
+++ llvm/lib/Target/SystemZ/SystemZHazardRecognizer.h
@@ -141,6 +141,7 @@
   /// a negative value means it would be good to schedule SU next.
   int resourcesCost(SUnit *SU);
 
+  // TODO: place CurGroupDbg undef #if LLVM_ENABLE_ABI_BREAKING_CHECKS
 #ifndef NDEBUG
   // Debug dumping.
   std::string CurGroupDbg; // current group as text
Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
+++ llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
@@ -181,11 +181,11 @@
 /// clearGraphAttrs - Clear all previously defined node graph attributes.
 /// Intended to be used from a debugging tool (eg. gdb).
 void SelectionDAG::clearGraphAttrs() {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   NodeGraphAttrs.clear();
 #else
-  errs() << "SelectionDAG::clearGraphAttrs is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::setGraphAttrs is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
 #endif
 }
 
@@ -193,11 +193,11 @@
 /// setGraphAttrs - Set graph attributes for a node. (eg. "color=red".)
 ///
 void SelectionDAG::setGraphAttrs(const SDNode *N, const char *Attrs) {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   NodeGraphAttrs[N] = Attrs;
 #else
-  errs() << "SelectionDAG::setGraphAttrs is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::setGraphAttrs is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
 #endif
 }
 
@@ -205,7 +205,7 @@
 /// getGraphAttrs - Get graph attributes for a node. (eg. "color=red".)
 /// Used from getNodeAttributes.
 std::string SelectionDAG::getGraphAttrs(const SDNode *N) const {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   std::map::const_iterator I =
 NodeGraphAttrs.find(N);
 
@@ -214,8 +214,8 @@
   else
 return "";
 #else
-  errs() << "SelectionDAG::getGraphAttrs is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::getGraphAttrs is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
   return std::string();
 #endif
 }
@@ -223,11 +223,11 @@
 /// setGraphColor - Convenience for setting node color attribute.
 ///
 void SelectionDAG::setGraphColor(const SDNode *N, const char *Color) {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   NodeGraphAttrs[N] = std::string("color=") + Color;
 #else
-  errs() << "SelectionDAG::setGraphColor is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() <<

[PATCH] D121549: Define ABI breaking class members correctly

2022-03-13 Thread Daniil Kovalev via Phabricator via cfe-commits
kovdan01 updated this revision to Diff 414929.
kovdan01 added a comment.

Fix typo


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

https://reviews.llvm.org/D121549

Files:
  clang/lib/Sema/TypeLocBuilder.cpp
  clang/lib/Sema/TypeLocBuilder.h
  llvm/include/llvm/CodeGen/GlobalISel/GISelWorkList.h
  llvm/include/llvm/CodeGen/MachineScheduler.h
  llvm/include/llvm/CodeGen/PBQP/ReductionRules.h
  llvm/include/llvm/CodeGen/RegAllocPBQP.h
  llvm/include/llvm/CodeGen/SelectionDAG.h
  llvm/lib/CodeGen/MachineScheduler.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
  llvm/lib/Target/SystemZ/SystemZHazardRecognizer.h
  mlir/lib/Target/SPIRV/Deserialization/Deserializer.h

Index: mlir/lib/Target/SPIRV/Deserialization/Deserializer.h
===
--- mlir/lib/Target/SPIRV/Deserialization/Deserializer.h
+++ mlir/lib/Target/SPIRV/Deserialization/Deserializer.h
@@ -598,6 +598,7 @@
   /// A list of all structs which have unresolved member types.
   SmallVector deferredStructTypesInfos;
 
+  // TODO: place logger under #if LLVM_ENABLE_ABI_BREAKING_CHECKS
 #ifndef NDEBUG
   /// A logger used to emit information during the deserialzation process.
   llvm::ScopedPrinter logger;
Index: llvm/lib/Target/SystemZ/SystemZHazardRecognizer.h
===
--- llvm/lib/Target/SystemZ/SystemZHazardRecognizer.h
+++ llvm/lib/Target/SystemZ/SystemZHazardRecognizer.h
@@ -141,6 +141,7 @@
   /// a negative value means it would be good to schedule SU next.
   int resourcesCost(SUnit *SU);
 
+  // TODO: place CurGroupDbg under #if LLVM_ENABLE_ABI_BREAKING_CHECKS
 #ifndef NDEBUG
   // Debug dumping.
   std::string CurGroupDbg; // current group as text
Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
+++ llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
@@ -181,11 +181,11 @@
 /// clearGraphAttrs - Clear all previously defined node graph attributes.
 /// Intended to be used from a debugging tool (eg. gdb).
 void SelectionDAG::clearGraphAttrs() {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   NodeGraphAttrs.clear();
 #else
-  errs() << "SelectionDAG::clearGraphAttrs is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::clearGraphAttrs is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
 #endif
 }
 
@@ -193,11 +193,11 @@
 /// setGraphAttrs - Set graph attributes for a node. (eg. "color=red".)
 ///
 void SelectionDAG::setGraphAttrs(const SDNode *N, const char *Attrs) {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   NodeGraphAttrs[N] = Attrs;
 #else
-  errs() << "SelectionDAG::setGraphAttrs is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::setGraphAttrs is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
 #endif
 }
 
@@ -205,7 +205,7 @@
 /// getGraphAttrs - Get graph attributes for a node. (eg. "color=red".)
 /// Used from getNodeAttributes.
 std::string SelectionDAG::getGraphAttrs(const SDNode *N) const {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   std::map::const_iterator I =
 NodeGraphAttrs.find(N);
 
@@ -214,8 +214,8 @@
   else
 return "";
 #else
-  errs() << "SelectionDAG::getGraphAttrs is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::getGraphAttrs is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
   return std::string();
 #endif
 }
@@ -223,11 +223,11 @@
 /// setGraphColor - Convenience for setting node color attribute.
 ///
 void SelectionDAG::setGraphColor(const SDNode *N, const char *Color) {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   NodeGraphAttrs[N] = std::string("color=") + Color;
 #else
-  errs() << "SelectionDAG::setGraphColor is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::setGraphColor is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
 #endif
 }
 
Index: llvm/lib/CodeGen/MachineScheduler.cpp
===
--- llvm/lib/CodeGen/MachineScheduler.cpp
+++ llvm/lib/CodeGen/MachineScheduler.cpp
@@ -752,7 +752,7 @@
 }
 
 bool ScheduleDAGMI::checkSchedLimit() {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
 CurrentTop = CurrentBottom;
 return false;
@@ -2006,7 +2006,7 @@
   ReservedCycles.clear();
   ReservedCyclesIndex.clear();
   ResourceGroupSubUnitMasks.clear();
-#ifndef NDEBUG
+#i

[PATCH] D121550: [clang-format] Fix crash on invalid requires expression

2022-03-13 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks created this revision.
HazardyKnusperkeks added reviewers: owenpan, curdeius, MyDeveloperDay.
HazardyKnusperkeks added a project: clang-format.
Herald added a project: All.
HazardyKnusperkeks requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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

As driveby rename `Left` to `OpeningParen`, this gives a better overview what 
it is, and we have  a loop in the function, where `Left` is not adjusted.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121550

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp

Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -331,6 +331,14 @@
   EXPECT_TOKEN(Tokens[13], tok::l_brace, TT_RequiresExpressionLBrace);
   EXPECT_TOKEN(Tokens[29], tok::kw_requires,
TT_RequiresClauseInARequiresExpression);
+
+  // Invalid Code, but we don't want to crash. See http://llvm.org/PR54350.
+  Tokens = annotate("bool r10 = requires (struct new_struct { int x; } s) { "
+"requires true; };");
+  ASSERT_EQ(Tokens.size(), 21u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::kw_requires, TT_RequiresExpression);
+  EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_RequiresExpressionLParen);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_RequiresExpressionLBrace);
 }
 
 TEST_F(TokenAnnotatorTest, RequiresDoesNotChangeParsingOfTheRest) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -23891,9 +23891,9 @@
   verifyFormat(
   "template  concept C = decltype([]() -> std::true_type {\n"
   "return {};\n"
-  "  }())::value\n"
-  "  && requires(T t) { t.bar(); } &&\n"
-  "  sizeof(T) <= 8;",
+  "  }())::value &&\n"
+  "  requires(T t) { t.bar(); } && "
+  "sizeof(T) <= 8;",
   Style);
 
   verifyFormat("template  concept Semiregular =\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -211,32 +211,34 @@
   bool parseParens(bool LookForDecls = false) {
 if (!CurrentToken)
   return false;
-FormatToken *Left = CurrentToken->Previous;
-assert(Left && "Unknown previous token");
-FormatToken *PrevNonComment = Left->getPreviousNonComment();
-Left->ParentBracket = Contexts.back().ContextKind;
+assert(CurrentToken->Previous && "Unknown previous token");
+FormatToken &OpeningParen = *CurrentToken->Previous;
+assert(OpeningParen.is(tok::l_paren));
+FormatToken *PrevNonComment = OpeningParen.getPreviousNonComment();
+OpeningParen.ParentBracket = Contexts.back().ContextKind;
 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
 
 // FIXME: This is a bit of a hack. Do better.
 Contexts.back().ColonIsForRangeExpr =
 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
 
-if (Left->Previous && Left->Previous->is(TT_UntouchableMacroFunc)) {
-  Left->Finalized = true;
+if (OpeningParen.Previous &&
+OpeningParen.Previous->is(TT_UntouchableMacroFunc)) {
+  OpeningParen.Finalized = true;
   return parseUntouchableParens();
 }
 
 bool StartsObjCMethodExpr = false;
-if (FormatToken *MaybeSel = Left->Previous) {
+if (FormatToken *MaybeSel = OpeningParen.Previous) {
   // @selector( starts a selector.
   if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
   MaybeSel->Previous->is(tok::at))
 StartsObjCMethodExpr = true;
 }
 
-if (Left->is(TT_OverloadedOperatorLParen)) {
+if (OpeningParen.is(TT_OverloadedOperatorLParen)) {
   // Find the previous kw_operator token.
-  FormatToken *Prev = Left;
+  FormatToken *Prev = &OpeningParen;
   while (!Prev->is(tok::kw_operator)) {
 Prev = Prev->Previous;
 assert(Prev && "Expect a kw_operator prior to the OperatorLParen!");
@@ -255,54 +257,58 @@
   // type X = (...);
   // export type X = (...);
   Contexts.back().IsExpression = false;
-} else if (Left->Previous &&
-   (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_while,
-tok::l_paren, tok::comma) ||
-Left->Previous->isIf() ||
-Left->Previous->is(TT_BinaryOperator))) {
+} else if (Opening

[PATCH] D121550: [clang-format] Fix crash on invalid requires expression

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



Comment at: clang/lib/Format/TokenAnnotator.cpp:424-425
 
-  if (CurrentToken->is(tok::l_brace))
-Left->setType(TT_Unknown); // Not TT_ObjCBlockLParen
+  if (CurrentToken->is(tok::l_brace) && 
OpeningParen.is(TT_ObjCBlockLParen))
+OpeningParen.setType(TT_Unknown);
   if (CurrentToken->is(tok::comma) && CurrentToken->Next &&

This is the actual fix. It reset to many types, although the comment said what 
it should reset.



Comment at: clang/unittests/Format/FormatTest.cpp:23894-23896
+  "  }())::value &&\n"
+  "  requires(T t) { t.bar(); } && "
+  "sizeof(T) <= 8;",

I know we don't like changing tests, but I think there was a bug before which 
were never hit in our tests but here.

Before
```
 M=0 C=1 T=Unknown S=1 F=0 B=0 BK=0 P=130 Name=decltype L=42 PPK=2 
FakeLParens=5/ FakeRParens=0 II=0xf136c40 Text='decltype'
 M=0 C=0 T=Unknown S=0 F=0 B=1 BK=0 P=23 Name=l_paren L=43 PPK=2 FakeLParens= 
FakeRParens=0 II=0x0 Text='('
 M=0 C=1 T=LambdaLSquare S=0 F=0 B=0 BK=0 P=140 Name=l_square L=44 PPK=2 
FakeLParens=1/ FakeRParens=0 II=0x0 Text='['
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=79 Name=r_square L=45 PPK=2 FakeLParens= 
FakeRParens=0 II=0x0 Text=']'
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=l_paren L=46 PPK=2 FakeLParens= 
FakeRParens=0 II=0x0 Text='('
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=160 Name=r_paren L=47 PPK=2 FakeLParens= 
FakeRParens=0 II=0x0 Text=')'
 M=0 C=1 T=LambdaArrow S=1 F=0 B=0 BK=0 P=150 Name=arrow L=50 PPK=2 
FakeLParens= FakeRParens=0 II=0x0 Text='->'
 M=0 C=0 T=Unknown S=1 F=0 B=0 BK=0 P=43 Name=identifier L=54 PPK=2 
FakeLParens= FakeRParens=0 II=0xf130c60 Text='std'
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=coloncolon L=56 PPK=2 
FakeLParens= FakeRParens=0 II=0x0 Text='::'
 M=0 C=1 T=Unknown S=0 F=0 B=0 BK=0 P=540 Name=identifier L=65 PPK=2 
FakeLParens= FakeRParens=0 II=0xf130c88 Text='true_type'
 M=0 C=0 T=LambdaLBrace S=1 F=0 B=0 BK=1 P=43 Name=l_brace L=67 PPK=2 
FakeLParens= FakeRParens=0 II=0x0 Text='{'
 M=0 C=1 T=Unknown S=1 F=0 B=0 BK=0 P=61 Name=r_brace L=80 PPK=2 FakeLParens= 
FakeRParens=0 II=0x0 Text='}'
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=l_paren L=81 PPK=2 FakeLParens= 
FakeRParens=0 II=0x0 Text='('
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=160 Name=r_paren L=82 PPK=2 FakeLParens= 
FakeRParens=1 II=0x0 Text=')'
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=r_paren L=83 PPK=2 FakeLParens= 
FakeRParens=0 II=0x0 Text=')'
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=23 Name=coloncolon L=85 PPK=2 
FakeLParens= FakeRParens=0 II=0x0 Text='::'
 M=0 C=1 T=TrailingAnnotation S=0 F=0 B=0 BK=0 P=520 Name=identifier L=90 PPK=2 
FakeLParens= FakeRParens=0 II=0xf130ca8 Text='value'
 M=0 C=1 T=BinaryOperator S=1 F=0 B=0 BK=0 P=25 Name=ampamp L=93 PPK=2 
FakeLParens= FakeRParens=0 II=0x0 Text='&&'
```
after
```
 M=0 C=1 T=Unknown S=1 F=0 B=0 BK=0 P=130 Name=decltype L=42 PPK=2 
FakeLParens=5/ FakeRParens=0 II=0xee66c40 Text='decltype'
 M=0 C=0 T=TypeDeclarationParen S=0 F=0 B=1 BK=0 P=23 Name=l_paren L=43 PPK=2 
FakeLParens= FakeRParens=0 II=0x0 Text='('
 M=0 C=0 T=LambdaLSquare S=0 F=0 B=0 BK=0 P=140 Name=l_square L=44 PPK=2 
FakeLParens=1/ FakeRParens=0 II=0x0 Text='['
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=79 Name=r_square L=45 PPK=2 FakeLParens= 
FakeRParens=0 II=0x0 Text=']'
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=l_paren L=46 PPK=2 FakeLParens= 
FakeRParens=0 II=0x0 Text='('
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=160 Name=r_paren L=47 PPK=2 FakeLParens= 
FakeRParens=0 II=0x0 Text=')'
 M=0 C=1 T=LambdaArrow S=1 F=0 B=0 BK=0 P=150 Name=arrow L=50 PPK=2 
FakeLParens= FakeRParens=0 II=0x0 Text='->'
 M=0 C=0 T=Unknown S=1 F=0 B=0 BK=0 P=43 Name=identifier L=54 PPK=2 
FakeLParens= FakeRParens=0 II=0xee60c60 Text='std'
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=coloncolon L=56 PPK=2 
FakeLParens= FakeRParens=0 II=0x0 Text='::'
 M=0 C=1 T=Unknown S=0 F=0 B=0 BK=0 P=540 Name=identifier L=65 PPK=2 
FakeLParens= FakeRParens=0 II=0xee60c88 Text='true_type'
 M=0 C=0 T=LambdaLBrace S=1 F=0 B=0 BK=1 P=43 Name=l_brace L=67 PPK=2 
FakeLParens= FakeRParens=0 II=0x0 Text='{'
 M=0 C=1 T=Unknown S=1 F=0 B=0 BK=0 P=61 Name=r_brace L=80 PPK=2 FakeLParens= 
FakeRParens=0 II=0x0 Text='}'
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=l_paren L=81 PPK=2 FakeLParens= 
FakeRParens=0 II=0x0 Text='('
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=160 Name=r_paren L=82 PPK=2 FakeLParens= 
FakeRParens=1 II=0x0 Text=')'
 M=0 C=0 T=TypeDeclarationParen S=0 F=0 B=0 BK=0 P=43 Name=r_paren L=83 PPK=2 
FakeLParens= FakeRParens=0 II=0x0 Text=')'
 M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=23 Name=coloncolon L=85 PPK=2 
FakeLParens= FakeRParens=0 II=0x0 Text='::'
 M=0 C=1 T=Unknown S=0 F=0 B=0 BK=0 P=520 Name=identifier L=90 PPK=2 
FakeLParens= FakeRParens=0 II=0xee60ca8 Text='value'
 M=0 C=0 T=BinaryOperator S=1 

[PATCH] D120610: [DebugInfo] Include DW_TAG_skeleton_unit when looking for parent UnitDie

2022-03-13 Thread Alexander Yermolovich via Phabricator via cfe-commits
ayermolo added a comment.

@wenlei Thanks for digging in to this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120610

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


[PATCH] D112019: [clang-format] [PR51412] AlignConsecutiveMacros fights with Visual Studio and resource.h

2022-03-13 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 414938.
MyDeveloperDay marked 2 inline comments as done.
MyDeveloperDay added a comment.
Herald added a project: All.

Address review comments and update for current trunk (up the first supported 
version in the documentation)


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

https://reviews.llvm.org/D112019

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  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
@@ -16112,6 +16112,31 @@
Style));
 }
 
+TEST_F(FormatTest, AlignConsecutiveMacrosMinWidth) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
+  verifyFormat("#define a3\n"
+   "#define  4\n"
+   "#define ccc  (5)",
+   Style);
+  Style.AlignConsecutiveMacrosMinWidth = 30;
+  verifyFormat("#define a 3\n"
+   "#define   4\n"
+   "#define ccc   (5)",
+   Style);
+
+  verifyFormat("#define a 3\n"
+   "#define vveylonglonglongmacro 4\n"
+   "#define ccc   (5)",
+   Style);
+
+  Style.AlignConsecutiveMacrosIgnoreMax = true;
+  verifyFormat("#define a 3\n"
+   "#define vveylonglonglongmacro 4\n"
+   "#define ccc   (5)",
+   Style);
+}
+
 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
   FormatStyle Alignment = getLLVMStyle();
   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
@@ -19575,6 +19600,7 @@
 TEST_F(FormatTest, ParsesConfigurationBools) {
   FormatStyle Style = {};
   Style.Language = FormatStyle::LK_Cpp;
+  CHECK_PARSE_BOOL(AlignConsecutiveMacrosIgnoreMax);
   CHECK_PARSE_BOOL(AlignTrailingComments);
   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
@@ -19710,6 +19736,9 @@
   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
   AlignConsecutiveAssignments,
   FormatStyle::ACS_AcrossEmptyLinesAndComments);
+  CHECK_PARSE("AlignConsecutiveMacrosMinWidth: 32",
+  AlignConsecutiveMacrosMinWidth, 32u);
+
   // For backwards compability, false / true should still parse
   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
   FormatStyle::ACS_None);
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -600,11 +600,15 @@
 //
 // We need to adjust the StartOfTokenColumn of each Change that is on a line
 // containing any matching token to be aligned and located after such token.
-static void AlignMacroSequence(
-unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn,
-unsigned &MaxColumn, bool &FoundMatchOnLine,
-std::function AlignMacrosMatches,
-SmallVector &Changes) {
+static void
+AlignMacroSequence(unsigned &StartOfSequence, unsigned &EndOfSequence,
+   unsigned &MinColumn, unsigned &MaxColumn,
+   bool &FoundMatchOnLine,
+   std::function
+   AlignMacrosMatches,
+   SmallVector &Changes,
+   const FormatStyle &Style) {
   if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) {
 
 FoundMatchOnLine = false;
@@ -619,7 +623,7 @@
   // If this is the first matching token to be aligned, remember by how many
   // spaces it has to be shifted, so the rest of the changes on the line are
   // shifted by the same amount
-  if (!FoundMatchOnLine && AlignMacrosMatches(Changes[I])) {
+  if (!FoundMatchOnLine && AlignMacrosMatches(Changes[I], Style)) {
 FoundMatchOnLine = true;
 Shift = MinColumn - Changes[I].StartOfTokenColumn;
 Changes[I].Spaces += Shift;
@@ -632,7 +636,7 @@
 }
   }
 
-  MinColumn = 0;
+  MinColumn = Style.AlignConsecutiveMacrosMinWidth;
   MaxColumn = UINT_MAX;
   StartOfSequence = 0;
   EndOfSequence = 0;
@@ -642,7 +646,7 @@
   if (Style.AlignConsecutiveMacros == FormatStyle::ACS_None)
 return;
 
-  auto AlignMacrosMatches = [](const Change &C) {
+  auto AlignMacrosMatches = [](const Change &C, const FormatStyle &Style) {
 const FormatToken *Current = C.Tok;
 unsigned SpacesRequiredBefore = 1;
 
@@ -664,6 +668,10 @@
 if (!Current->Previous || !Current->Previous->is(tok::pp_define))
   r

[clang-tools-extra] 200e7a8 - [clang-tidy][docs][NFC] Refer to the CERT rule in bugprone-shared-ptr-array-mismatch docs

2022-03-13 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-03-13T17:51:00+01:00
New Revision: 200e7a84701257afe80fd0b168fef78cf29aa523

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

LOG: [clang-tidy][docs][NFC] Refer to the CERT rule in 
bugprone-shared-ptr-array-mismatch docs

Document the connection between this checker and the corresponding CERT
rule.

Reviewed By: aaron.ballman

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

Added: 


Modified: 

clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst

Removed: 




diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst
index d15c28272d697..0833195edbb79 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst
@@ -29,3 +29,8 @@ Example:
 std::shared_ptr x(new Foo[10]); // no replacement in this case
 // ^ warning: shared pointer to non-array is 
initialized with array [bugprone-shared-ptr-array-mismatch]
   };
+
+This check partially covers the CERT C++ Coding Standard rule
+`MEM51-CPP. Properly deallocate dynamically allocated resources
+`_
+However, only the ``std::shared_ptr`` case is detected by this check.



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


[clang-tools-extra] d321f09 - [clang-tidy][docs][NFC] Update URL and docs of PostfixOperatorCheck

2022-03-13 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-03-13T17:51:00+01:00
New Revision: d321f0992684b0dad255fe2d9bb14523a685c5c4

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

LOG: [clang-tidy][docs][NFC] Update URL and docs of PostfixOperatorCheck

The docs URL was dangling, and the docs suggested that it has no fixits,
but it actually had.

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/cert/PostfixOperatorCheck.h
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/cert/PostfixOperatorCheck.h 
b/clang-tools-extra/clang-tidy/cert/PostfixOperatorCheck.h
index 08d892d8165b7..3ccf03be1b579 100644
--- a/clang-tools-extra/clang-tidy/cert/PostfixOperatorCheck.h
+++ b/clang-tools-extra/clang-tidy/cert/PostfixOperatorCheck.h
@@ -19,7 +19,7 @@ namespace cert {
 /// object.
 ///
 /// For the user-facing documentation see:
-/// http://clang.llvm.org/extra/clang-tidy/checks/cert-postfix-operator.html
+/// https://clang.llvm.org/extra/clang-tidy/checks/cert-dcl21-cpp.html
 class PostfixOperatorCheck : public ClangTidyCheck {
 public:
   PostfixOperatorCheck(StringRef Name, ClangTidyContext *Context)

diff  --git a/clang-tools-extra/docs/clang-tidy/checks/list.rst 
b/clang-tools-extra/docs/clang-tidy/checks/list.rst
index f2b361e2aecbc..ebdcd7ae1041e 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -113,7 +113,7 @@ Clang-Tidy Checks
`bugprone-unused-return-value `_,
`bugprone-use-after-move `_,
`bugprone-virtual-near-miss `_, "Yes"
-   `cert-dcl21-cpp `_,
+   `cert-dcl21-cpp `_, "Yes"
`cert-dcl50-cpp `_,
`cert-dcl58-cpp `_,
`cert-env33-c `_,



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


[clang-tools-extra] 665879b - [clang-tidy][docs] Fix wrong url in DontModifyStdNamespaceCheck

2022-03-13 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-03-13T17:51:00+01:00
New Revision: 665879b9e7d1bc1b3a329b152d27225d7c975ca3

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

LOG: [clang-tidy][docs] Fix wrong url in DontModifyStdNamespaceCheck

It was probably a copy-paste mistake.
The check was added as `cert-dcl58-cpp`, so the doc should point there.

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.h 
b/clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.h
index 3cc03e875353e..4b3b8fb603b9f 100644
--- a/clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.h
+++ b/clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.h
@@ -19,7 +19,7 @@ namespace cert {
 /// This check warns for such modifications.
 ///
 /// For the user-facing documentation see:
-/// http://clang.llvm.org/extra/clang-tidy/checks/cert-msc53-cpp.html
+/// https://clang.llvm.org/extra/clang-tidy/checks/cert-dcl58-cpp.html
 class DontModifyStdNamespaceCheck : public ClangTidyCheck {
 public:
   DontModifyStdNamespaceCheck(StringRef Name, ClangTidyContext *Context)



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


[PATCH] D121214: [clang-tidy][docs][NFC] Refer to the CERT rule in bugprone-shared-ptr-array-mismatch docs

2022-03-13 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG200e7a847012: [clang-tidy][docs][NFC] Refer to the CERT rule 
in bugprone-shared-ptr-array… (authored by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121214

Files:
  
clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst


Index: 
clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst
===
--- 
clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst
+++ 
clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst
@@ -29,3 +29,8 @@
 std::shared_ptr x(new Foo[10]); // no replacement in this case
 // ^ warning: shared pointer to non-array is 
initialized with array [bugprone-shared-ptr-array-mismatch]
   };
+
+This check partially covers the CERT C++ Coding Standard rule
+`MEM51-CPP. Properly deallocate dynamically allocated resources
+`_
+However, only the ``std::shared_ptr`` case is detected by this check.


Index: clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone-shared-ptr-array-mismatch.rst
@@ -29,3 +29,8 @@
 std::shared_ptr x(new Foo[10]); // no replacement in this case
 // ^ warning: shared pointer to non-array is initialized with array [bugprone-shared-ptr-array-mismatch]
   };
+
+This check partially covers the CERT C++ Coding Standard rule
+`MEM51-CPP. Properly deallocate dynamically allocated resources
+`_
+However, only the ``std::shared_ptr`` case is detected by this check.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121372: [clang-tidy][docs][NFC] Update URL and docs of PostfixOperatorCheck

2022-03-13 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd321f0992684: [clang-tidy][docs][NFC] Update URL and docs of 
PostfixOperatorCheck (authored by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121372

Files:
  clang-tools-extra/clang-tidy/cert/PostfixOperatorCheck.h
  clang-tools-extra/docs/clang-tidy/checks/list.rst


Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -113,7 +113,7 @@
`bugprone-unused-return-value `_,
`bugprone-use-after-move `_,
`bugprone-virtual-near-miss `_, "Yes"
-   `cert-dcl21-cpp `_,
+   `cert-dcl21-cpp `_, "Yes"
`cert-dcl50-cpp `_,
`cert-dcl58-cpp `_,
`cert-env33-c `_,
Index: clang-tools-extra/clang-tidy/cert/PostfixOperatorCheck.h
===
--- clang-tools-extra/clang-tidy/cert/PostfixOperatorCheck.h
+++ clang-tools-extra/clang-tidy/cert/PostfixOperatorCheck.h
@@ -19,7 +19,7 @@
 /// object.
 ///
 /// For the user-facing documentation see:
-/// http://clang.llvm.org/extra/clang-tidy/checks/cert-postfix-operator.html
+/// https://clang.llvm.org/extra/clang-tidy/checks/cert-dcl21-cpp.html
 class PostfixOperatorCheck : public ClangTidyCheck {
 public:
   PostfixOperatorCheck(StringRef Name, ClangTidyContext *Context)


Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -113,7 +113,7 @@
`bugprone-unused-return-value `_,
`bugprone-use-after-move `_,
`bugprone-virtual-near-miss `_, "Yes"
-   `cert-dcl21-cpp `_,
+   `cert-dcl21-cpp `_, "Yes"
`cert-dcl50-cpp `_,
`cert-dcl58-cpp `_,
`cert-env33-c `_,
Index: clang-tools-extra/clang-tidy/cert/PostfixOperatorCheck.h
===
--- clang-tools-extra/clang-tidy/cert/PostfixOperatorCheck.h
+++ clang-tools-extra/clang-tidy/cert/PostfixOperatorCheck.h
@@ -19,7 +19,7 @@
 /// object.
 ///
 /// For the user-facing documentation see:
-/// http://clang.llvm.org/extra/clang-tidy/checks/cert-postfix-operator.html
+/// https://clang.llvm.org/extra/clang-tidy/checks/cert-dcl21-cpp.html
 class PostfixOperatorCheck : public ClangTidyCheck {
 public:
   PostfixOperatorCheck(StringRef Name, ClangTidyContext *Context)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121373: [clang-tidy][docs] Fix wrong url in DontModifyStdNamespaceCheck

2022-03-13 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG665879b9e7d1: [clang-tidy][docs] Fix wrong url in 
DontModifyStdNamespaceCheck (authored by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121373

Files:
  clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.h


Index: clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.h
===
--- clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.h
+++ clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.h
@@ -19,7 +19,7 @@
 /// This check warns for such modifications.
 ///
 /// For the user-facing documentation see:
-/// http://clang.llvm.org/extra/clang-tidy/checks/cert-msc53-cpp.html
+/// https://clang.llvm.org/extra/clang-tidy/checks/cert-dcl58-cpp.html
 class DontModifyStdNamespaceCheck : public ClangTidyCheck {
 public:
   DontModifyStdNamespaceCheck(StringRef Name, ClangTidyContext *Context)


Index: clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.h
===
--- clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.h
+++ clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.h
@@ -19,7 +19,7 @@
 /// This check warns for such modifications.
 ///
 /// For the user-facing documentation see:
-/// http://clang.llvm.org/extra/clang-tidy/checks/cert-msc53-cpp.html
+/// https://clang.llvm.org/extra/clang-tidy/checks/cert-dcl58-cpp.html
 class DontModifyStdNamespaceCheck : public ClangTidyCheck {
 public:
   DontModifyStdNamespaceCheck(StringRef Name, ClangTidyContext *Context)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121550: [clang-format] Fix crash on invalid requires expression

2022-03-13 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Format/TokenAnnotator.cpp:215
+assert(CurrentToken->Previous && "Unknown previous token");
+FormatToken &OpeningParen = *CurrentToken->Previous;
+assert(OpeningParen.is(tok::l_paren));

Maybe you can commit the rename as a NFC commit and rebase the patch to remove 
the noise?



Comment at: clang/unittests/Format/FormatTest.cpp:23894-23896
+  "  }())::value &&\n"
+  "  requires(T t) { t.bar(); } && "
+  "sizeof(T) <= 8;",

HazardyKnusperkeks wrote:
> I know we don't like changing tests, but I think there was a bug before which 
> were never hit in our tests but here.
> 
> Before
> ```
>  M=0 C=1 T=Unknown S=1 F=0 B=0 BK=0 P=130 Name=decltype L=42 PPK=2 
> FakeLParens=5/ FakeRParens=0 II=0xf136c40 Text='decltype'
>  M=0 C=0 T=Unknown S=0 F=0 B=1 BK=0 P=23 Name=l_paren L=43 PPK=2 FakeLParens= 
> FakeRParens=0 II=0x0 Text='('
>  M=0 C=1 T=LambdaLSquare S=0 F=0 B=0 BK=0 P=140 Name=l_square L=44 PPK=2 
> FakeLParens=1/ FakeRParens=0 II=0x0 Text='['
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=79 Name=r_square L=45 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text=']'
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=l_paren L=46 PPK=2 FakeLParens= 
> FakeRParens=0 II=0x0 Text='('
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=160 Name=r_paren L=47 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text=')'
>  M=0 C=1 T=LambdaArrow S=1 F=0 B=0 BK=0 P=150 Name=arrow L=50 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text='->'
>  M=0 C=0 T=Unknown S=1 F=0 B=0 BK=0 P=43 Name=identifier L=54 PPK=2 
> FakeLParens= FakeRParens=0 II=0xf130c60 Text='std'
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=coloncolon L=56 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text='::'
>  M=0 C=1 T=Unknown S=0 F=0 B=0 BK=0 P=540 Name=identifier L=65 PPK=2 
> FakeLParens= FakeRParens=0 II=0xf130c88 Text='true_type'
>  M=0 C=0 T=LambdaLBrace S=1 F=0 B=0 BK=1 P=43 Name=l_brace L=67 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text='{'
>  M=0 C=1 T=Unknown S=1 F=0 B=0 BK=0 P=61 Name=r_brace L=80 PPK=2 FakeLParens= 
> FakeRParens=0 II=0x0 Text='}'
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=l_paren L=81 PPK=2 FakeLParens= 
> FakeRParens=0 II=0x0 Text='('
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=160 Name=r_paren L=82 PPK=2 
> FakeLParens= FakeRParens=1 II=0x0 Text=')'
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=r_paren L=83 PPK=2 FakeLParens= 
> FakeRParens=0 II=0x0 Text=')'
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=23 Name=coloncolon L=85 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text='::'
>  M=0 C=1 T=TrailingAnnotation S=0 F=0 B=0 BK=0 P=520 Name=identifier L=90 
> PPK=2 FakeLParens= FakeRParens=0 II=0xf130ca8 Text='value'
>  M=0 C=1 T=BinaryOperator S=1 F=0 B=0 BK=0 P=25 Name=ampamp L=93 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text='&&'
> ```
> after
> ```
>  M=0 C=1 T=Unknown S=1 F=0 B=0 BK=0 P=130 Name=decltype L=42 PPK=2 
> FakeLParens=5/ FakeRParens=0 II=0xee66c40 Text='decltype'
>  M=0 C=0 T=TypeDeclarationParen S=0 F=0 B=1 BK=0 P=23 Name=l_paren L=43 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text='('
>  M=0 C=0 T=LambdaLSquare S=0 F=0 B=0 BK=0 P=140 Name=l_square L=44 PPK=2 
> FakeLParens=1/ FakeRParens=0 II=0x0 Text='['
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=79 Name=r_square L=45 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text=']'
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=l_paren L=46 PPK=2 FakeLParens= 
> FakeRParens=0 II=0x0 Text='('
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=160 Name=r_paren L=47 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text=')'
>  M=0 C=1 T=LambdaArrow S=1 F=0 B=0 BK=0 P=150 Name=arrow L=50 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text='->'
>  M=0 C=0 T=Unknown S=1 F=0 B=0 BK=0 P=43 Name=identifier L=54 PPK=2 
> FakeLParens= FakeRParens=0 II=0xee60c60 Text='std'
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=coloncolon L=56 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text='::'
>  M=0 C=1 T=Unknown S=0 F=0 B=0 BK=0 P=540 Name=identifier L=65 PPK=2 
> FakeLParens= FakeRParens=0 II=0xee60c88 Text='true_type'
>  M=0 C=0 T=LambdaLBrace S=1 F=0 B=0 BK=1 P=43 Name=l_brace L=67 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text='{'
>  M=0 C=1 T=Unknown S=1 F=0 B=0 BK=0 P=61 Name=r_brace L=80 PPK=2 FakeLParens= 
> FakeRParens=0 II=0x0 Text='}'
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=43 Name=l_paren L=81 PPK=2 FakeLParens= 
> FakeRParens=0 II=0x0 Text='('
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=160 Name=r_paren L=82 PPK=2 
> FakeLParens= FakeRParens=1 II=0x0 Text=')'
>  M=0 C=0 T=TypeDeclarationParen S=0 F=0 B=0 BK=0 P=43 Name=r_paren L=83 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text=')'
>  M=0 C=0 T=Unknown S=0 F=0 B=0 BK=0 P=23 Name=coloncolon L=85 PPK=2 
> FakeLParens= FakeRParens=0 II=0x0 Text='::'
>  M=0 C=1 T=Unknown S=0 F=0 B=0 BK=0 P=520 

[PATCH] D112019: [clang-format] [PR51412] AlignConsecutiveMacros fights with Visual Studio and resource.h

2022-03-13 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.

LGTM.


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

https://reviews.llvm.org/D112019

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


[PATCH] D121549: Define ABI breaking class members correctly

2022-03-13 Thread Mehdi AMINI via Phabricator via cfe-commits
mehdi_amini added inline comments.



Comment at: mlir/lib/Target/SPIRV/Deserialization/Deserializer.h:601
 
+  // TODO: place logger under #if LLVM_ENABLE_ABI_BREAKING_CHECKS
 #ifndef NDEBUG

This is a private header (you're in the `lib` directory and not in the 
`include` directory)

Same for the SystemZ one above I believe.


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

https://reviews.llvm.org/D121549

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


[PATCH] D112019: [clang-format] [PR51412] AlignConsecutiveMacros fights with Visual Studio and resource.h

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

Why limit to macros, could it be a member of AlignConsecutiveStyle and apply to 
the other stuff as well?




Comment at: clang/include/clang/Format/Format.h:256
+  /// \endcode
+  /// \version 14
+  unsigned AlignConsecutiveMacrosMinWidth;

Version 15



Comment at: clang/lib/Format/Format.cpp:1154
+  LLVMStyle.AlignConsecutiveMacrosMinWidth = 0;
+  LLVMStyle.AlignConsecutiveMacrosIgnoreMax = false;
   LLVMStyle.AllowAllArgumentsOnNextLine = true;

I before M


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

https://reviews.llvm.org/D112019

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


[PATCH] D112019: [clang-format] [PR51412] AlignConsecutiveMacros fights with Visual Studio and resource.h

2022-03-13 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 414950.
MyDeveloperDay marked 2 inline comments as done.

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

https://reviews.llvm.org/D112019

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  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
@@ -16112,6 +16112,31 @@
Style));
 }
 
+TEST_F(FormatTest, AlignConsecutiveMacrosMinWidth) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
+  verifyFormat("#define a3\n"
+   "#define  4\n"
+   "#define ccc  (5)",
+   Style);
+  Style.AlignConsecutiveMacrosMinWidth = 30;
+  verifyFormat("#define a 3\n"
+   "#define   4\n"
+   "#define ccc   (5)",
+   Style);
+
+  verifyFormat("#define a 3\n"
+   "#define vveylonglonglongmacro 4\n"
+   "#define ccc   (5)",
+   Style);
+
+  Style.AlignConsecutiveMacrosIgnoreMax = true;
+  verifyFormat("#define a 3\n"
+   "#define vveylonglonglongmacro 4\n"
+   "#define ccc   (5)",
+   Style);
+}
+
 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
   FormatStyle Alignment = getLLVMStyle();
   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
@@ -19575,6 +19600,7 @@
 TEST_F(FormatTest, ParsesConfigurationBools) {
   FormatStyle Style = {};
   Style.Language = FormatStyle::LK_Cpp;
+  CHECK_PARSE_BOOL(AlignConsecutiveMacrosIgnoreMax);
   CHECK_PARSE_BOOL(AlignTrailingComments);
   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
@@ -19710,6 +19736,9 @@
   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
   AlignConsecutiveAssignments,
   FormatStyle::ACS_AcrossEmptyLinesAndComments);
+  CHECK_PARSE("AlignConsecutiveMacrosMinWidth: 32",
+  AlignConsecutiveMacrosMinWidth, 32u);
+
   // For backwards compability, false / true should still parse
   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
   FormatStyle::ACS_None);
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -600,11 +600,15 @@
 //
 // We need to adjust the StartOfTokenColumn of each Change that is on a line
 // containing any matching token to be aligned and located after such token.
-static void AlignMacroSequence(
-unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn,
-unsigned &MaxColumn, bool &FoundMatchOnLine,
-std::function AlignMacrosMatches,
-SmallVector &Changes) {
+static void
+AlignMacroSequence(unsigned &StartOfSequence, unsigned &EndOfSequence,
+   unsigned &MinColumn, unsigned &MaxColumn,
+   bool &FoundMatchOnLine,
+   std::function
+   AlignMacrosMatches,
+   SmallVector &Changes,
+   const FormatStyle &Style) {
   if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) {
 
 FoundMatchOnLine = false;
@@ -619,7 +623,7 @@
   // If this is the first matching token to be aligned, remember by how many
   // spaces it has to be shifted, so the rest of the changes on the line are
   // shifted by the same amount
-  if (!FoundMatchOnLine && AlignMacrosMatches(Changes[I])) {
+  if (!FoundMatchOnLine && AlignMacrosMatches(Changes[I], Style)) {
 FoundMatchOnLine = true;
 Shift = MinColumn - Changes[I].StartOfTokenColumn;
 Changes[I].Spaces += Shift;
@@ -632,7 +636,7 @@
 }
   }
 
-  MinColumn = 0;
+  MinColumn = Style.AlignConsecutiveMacrosMinWidth;
   MaxColumn = UINT_MAX;
   StartOfSequence = 0;
   EndOfSequence = 0;
@@ -642,7 +646,7 @@
   if (Style.AlignConsecutiveMacros == FormatStyle::ACS_None)
 return;
 
-  auto AlignMacrosMatches = [](const Change &C) {
+  auto AlignMacrosMatches = [](const Change &C, const FormatStyle &Style) {
 const FormatToken *Current = C.Tok;
 unsigned SpacesRequiredBefore = 1;
 
@@ -664,6 +668,10 @@
 if (!Current->Previous || !Current->Previous->is(tok::pp_define))
   return false;
 
+if (Style.AlignConsecutiveMacrosIgnoreMax &&
+C.StartOfTokenColumn > Style.AlignConsecutiveMacrosMinWidth)
+  return false;
+
 // For a

[PATCH] D112019: [clang-format] [PR51412] AlignConsecutiveMacros fights with Visual Studio and resource.h

2022-03-13 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

In D112019#3378024 , 
@HazardyKnusperkeks wrote:

> Why limit to macros, could it be a member of AlignConsecutiveStyle and apply 
> to the other stuff as well?

I personally don't have a use case other than the resource.h case that I raise 
above, do you think this would be useful to be elsewhere in the other 
AlignConsecutive cases?

Of course, this code alters AlignMacroSequence() and not AlignTokens() what if 
we unified the options (so they were part of the struct? but kept the 
functionality change in separate reviews? for now the options would have no 
effect on other Consecutive options?


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

https://reviews.llvm.org/D112019

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


[PATCH] D121556: [randstruct] Add randomize structure layout support

2022-03-13 Thread Bill Wendling via Phabricator via cfe-commits
void created this revision.
Herald added subscribers: dang, jdoerfert, mgorny.
Herald added a reviewer: aaron.ballman.
Herald added a project: All.
void requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The Randstruct feature is a compile-time hardening technique that
randomizes the field layout for designated structures of a code base.
Admittedly, this is mostly useful for closed-source releases of code,
since the randomization seed would need to be available for public and
open source applications.

Why implement it? This patch set enhances Clang’s feature parity with
that of GCC which already has the Randstruct feature. It's used by the
Linux kernel in certain structures to help thwart attacks that depend on
structure layouts in memory.

This patch set is a from-scratch reimplementation of the Randstruct
feature that was originally ported to GCC. The patches for the GCC
implementation can be found here:

  https://www.openwall.com/lists/kernel-hardening/2017/04/06/14

Link: https://lists.llvm.org/pipermail/cfe-dev/2019-March/061607.html
Co-authored-by: Cole Nixon 
Co-authored-by: Connor Kuehl 
Co-authored-by: James Foster 
Co-authored-by: Jeff Takahashi 
Co-authored-by: Jordan Cantrell 
Co-authored-by: Nikk Forbus 
Co-authored-by: Tim Pugh 
Co-authored-by: Bill Wendling 
Signed-off-by: Bill Wendling 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121556

Files:
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/AST/Randstruct.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Driver/Options.td
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/AST/Randstruct.cpp
  clang/lib/AST/RecordLayoutBuilder.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Sema/AnalysisBasedWarnings.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/unittests/AST/CMakeLists.txt
  clang/unittests/AST/RandstructTest.cpp

Index: clang/unittests/AST/RandstructTest.cpp
===
--- /dev/null
+++ clang/unittests/AST/RandstructTest.cpp
@@ -0,0 +1,409 @@
+//===- unittest/AST/RandstructTest.cpp ===//
+//
+// 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 contains tests for Clang's structure field layout randomization.
+//
+//===--===//
+
+/*
+ * Build this test suite by running `make ASTTests` in the build folder.
+ *
+ * Run this test suite by running the following in the build folder:
+ * ` ./tools/clang/unittests/AST/ASTTests
+ * --gtest_filter=StructureLayoutRandomization*`
+ */
+
+#include "clang/AST/Randstruct.h"
+#include "gtest/gtest.h"
+
+#include "DeclMatcher.h"
+#include "clang/AST/RecordLayout.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Testing/CommandLineArgs.h"
+#include "clang/Tooling/Tooling.h"
+
+#include 
+
+using namespace clang;
+using namespace clang::ast_matchers;
+using namespace clang::randstruct;
+
+using field_names = std::vector;
+
+namespace {
+
+std::unique_ptr makeAST(const std::string &SourceCode) {
+  std::vector Args = getCommandLineArgsForTesting(Lang_C99);
+  Args.push_back("-frandstruct-seed=1234567890abcdef");
+  return tooling::buildASTFromCodeWithArgs(SourceCode, Args, "input.cc");
+}
+
+RecordDecl *getRecordDeclFromAST(const ASTContext &C, const std::string &Name) {
+  return FirstDeclMatcher().match(C.getTranslationUnitDecl(),
+  recordDecl(hasName(Name)));
+}
+
+std::vector getFieldNamesFromRecord(const RecordDecl *RD) {
+  std::vector Fields;
+
+  Fields.reserve(8);
+  for (auto *Field : RD->fields())
+Fields.push_back(Field->getNameAsString());
+
+  return Fields;
+}
+
+bool isSubsequence(const field_names &Seq, const field_names &Subseq) {
+  unsigned SeqLen = Seq.size();
+  unsigned SubLen = Subseq.size();
+
+  bool IsSubseq = false;
+  for (unsigned I = 0; I < SeqLen; ++I)
+if (Seq[I] == Subseq[0]) {
+  IsSubseq = true;
+  for (unsigned J = 0; J + I < SeqLen && J < SubLen; ++J) {
+if (Seq[J + I] != Subseq[J]) {
+  IsSubseq = false;
+  break;
+}
+  }
+}
+
+  return IsSubseq;
+}
+
+} // end anonymous namespace
+
+namespace clang {
+namespace ast

[PATCH] D121556: [randstruct] Add randomize structure layout support

2022-03-13 Thread Bill Wendling via Phabricator via cfe-commits
void added reviewers: jfb, connorkuehl, rsmith, timpugh.
void added subscribers: connorkuehl, Dan, xbolva00, shawnl, dexonsmith, daloni, 
hintonda, riccibruno, vlad.tsyrklevich, ebevhan, kees, pcc, nickdesaulniers.
void added a comment.

This is a soft reworking of @connorkuehl's work in 
https://reviews.llvm.org/D59254. Please take a look!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121556

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


[clang] 596fa2d - [clang-format] Handle attributes before case label.

2022-03-13 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-13T21:53:40+01:00
New Revision: 596fa2d90044841c33b9a0e6b17406c2a45077a2

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

LOG: [clang-format] Handle attributes before case label.

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

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 3a245b8b5fa0d..47e794c7b1ca6 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -480,6 +480,10 @@ bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
   unsigned StatementCount = 0;
   bool SwitchLabelEncountered = false;
   do {
+if (FormatTok->getType() == TT_AttributeMacro) {
+  nextToken();
+  continue;
+}
 tok::TokenKind kind = FormatTok->Tok.getKind();
 if (FormatTok->getType() == TT_MacroBlockBegin)
   kind = tok::l_brace;
@@ -569,6 +573,8 @@ bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
 parseCSharpAttribute();
 break;
   }
+  if (handleCppAttributes())
+break;
   LLVM_FALLTHROUGH;
 default:
   ParseDefault();
@@ -1390,9 +1396,11 @@ void 
UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind,
 // e.g. "default void f() {}" in a Java interface.
 break;
   case tok::kw_case:
-if (Style.isJavaScript() && Line->MustBeDeclaration)
+if (Style.isJavaScript() && Line->MustBeDeclaration) {
   // 'case: string' field declaration.
+  nextToken();
   break;
+}
 parseCaseLabel();
 return;
   case tok::kw_try:
@@ -1813,6 +1821,12 @@ void 
UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind,
 case tok::kw_new:
   parseNew();
   break;
+case tok::kw_case:
+  if (Style.isJavaScript() && Line->MustBeDeclaration)
+// 'case: string' field declaration.
+break;
+  parseCaseLabel();
+  break;
 default:
   nextToken();
   break;
@@ -2376,17 +2390,24 @@ static void markOptionalBraces(FormatToken *LeftBrace) {
   RightBrace->Optional = true;
 }
 
+void UnwrappedLineParser::handleAttributes() {
+  // Handle AttributeMacro, e.g. `if (x) UNLIKELY`.
+  if (FormatTok->is(TT_AttributeMacro))
+nextToken();
+  handleCppAttributes();
+}
+
+bool UnwrappedLineParser::handleCppAttributes() {
+  // Handle [[likely]] / [[unlikely]] attributes.
+  if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute()) {
+parseSquare();
+return true;
+  }
+  return false;
+}
+
 FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
   bool KeepBraces) {
-  auto HandleAttributes = [this]() {
-// Handle AttributeMacro, e.g. `if (x) UNLIKELY`.
-if (FormatTok->is(TT_AttributeMacro))
-  nextToken();
-// Handle [[likely]] / [[unlikely]] attributes.
-if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute())
-  parseSquare();
-  };
-
   assert(FormatTok->is(tok::kw_if) && "'if' expected");
   nextToken();
   if (FormatTok->is(tok::exclaim))
@@ -2399,7 +2420,7 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
 if (FormatTok->is(tok::l_paren))
   parseParens();
   }
-  HandleAttributes();
+  handleAttributes();
 
   bool NeedsUnwrappedLine = false;
   keepAncestorBraces();
@@ -2436,7 +2457,7 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
   Kind = IfStmtKind::IfElse;
 }
 nextToken();
-HandleAttributes();
+handleAttributes();
 if (FormatTok->is(tok::l_brace)) {
   ElseLeftBrace = FormatTok;
   CompoundStatementIndenter Indenter(this, Style, Line->Level);

diff  --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index 5cc01398a5457..798bae24ad075 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -121,6 +121,8 @@ class UnwrappedLineParser {
   void parseSquare(bool LambdaIntroducer = false);
   void keepAncestorBraces();
   void parseUnbracedBody(bool CheckEOF = false);
+  void handleAttributes();
+  bool handleCppAttributes();
   FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false);
   void parseTryCatch();
   void parseForOrWhileLoop();

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 37a42382e8f85..430a195f60255 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unit

[PATCH] D121450: [clang-format] Handle attributes before case label.

2022-03-13 Thread Marek Kurdej via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
curdeius marked 2 inline comments as done.
Closed by commit rG596fa2d90044: [clang-format] Handle attributes before case 
label. (authored by curdeius).

Changed prior to commit:
  https://reviews.llvm.org/D121450?vs=414610&id=414952#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121450

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -2602,6 +2602,52 @@
"}",
getLLVMStyleWithColumns(34));
 
+  verifyFormat("switch (a) {\n"
+   "[[likely]] case 1:\n"
+   "  return;\n"
+   "}");
+  verifyFormat("switch (a) {\n"
+   "[[likely]] [[other::likely]] case 1:\n"
+   "  return;\n"
+   "}");
+  verifyFormat("switch (x) {\n"
+   "case 1:\n"
+   "  return;\n"
+   "[[likely]] case 2:\n"
+   "  return;\n"
+   "}");
+  verifyFormat("switch (a) {\n"
+   "case 1:\n"
+   "[[likely]] case 2:\n"
+   "  return;\n"
+   "}");
+  FormatStyle Attributes = getLLVMStyle();
+  Attributes.AttributeMacros.push_back("LIKELY");
+  Attributes.AttributeMacros.push_back("OTHER_LIKELY");
+  verifyFormat("switch (a) {\n"
+   "LIKELY case b:\n"
+   "  return;\n"
+   "}",
+   Attributes);
+  verifyFormat("switch (a) {\n"
+   "LIKELY OTHER_LIKELY() case b:\n"
+   "  return;\n"
+   "}",
+   Attributes);
+  verifyFormat("switch (a) {\n"
+   "case 1:\n"
+   "  return;\n"
+   "LIKELY case 2:\n"
+   "  return;\n"
+   "}",
+   Attributes);
+  verifyFormat("switch (a) {\n"
+   "case 1:\n"
+   "LIKELY case 2:\n"
+   "  return;\n"
+   "}",
+   Attributes);
+
   FormatStyle Style = getLLVMStyle();
   Style.IndentCaseLabels = true;
   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -121,6 +121,8 @@
   void parseSquare(bool LambdaIntroducer = false);
   void keepAncestorBraces();
   void parseUnbracedBody(bool CheckEOF = false);
+  void handleAttributes();
+  bool handleCppAttributes();
   FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false);
   void parseTryCatch();
   void parseForOrWhileLoop();
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -480,6 +480,10 @@
   unsigned StatementCount = 0;
   bool SwitchLabelEncountered = false;
   do {
+if (FormatTok->getType() == TT_AttributeMacro) {
+  nextToken();
+  continue;
+}
 tok::TokenKind kind = FormatTok->Tok.getKind();
 if (FormatTok->getType() == TT_MacroBlockBegin)
   kind = tok::l_brace;
@@ -569,6 +573,8 @@
 parseCSharpAttribute();
 break;
   }
+  if (handleCppAttributes())
+break;
   LLVM_FALLTHROUGH;
 default:
   ParseDefault();
@@ -1390,9 +1396,11 @@
 // e.g. "default void f() {}" in a Java interface.
 break;
   case tok::kw_case:
-if (Style.isJavaScript() && Line->MustBeDeclaration)
+if (Style.isJavaScript() && Line->MustBeDeclaration) {
   // 'case: string' field declaration.
+  nextToken();
   break;
+}
 parseCaseLabel();
 return;
   case tok::kw_try:
@@ -1813,6 +1821,12 @@
 case tok::kw_new:
   parseNew();
   break;
+case tok::kw_case:
+  if (Style.isJavaScript() && Line->MustBeDeclaration)
+// 'case: string' field declaration.
+break;
+  parseCaseLabel();
+  break;
 default:
   nextToken();
   break;
@@ -2376,17 +2390,24 @@
   RightBrace->Optional = true;
 }
 
+void UnwrappedLineParser::handleAttributes() {
+  // Handle AttributeMacro, e.g. `if (x) UNLIKELY`.
+  if (FormatTok->is(TT_AttributeMacro))
+nextToken();
+  handleCppAttributes();
+}
+
+bool UnwrappedLineParser::handleCppAttributes() {
+  // Handle [[likely]] / [[unlikely]] attributes.
+  if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute()) {
+parseSquare();
+return true;
+  }
+  return false;
+}
+
 FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
 

[clang] 36d13d3 - [clang-format] Add space to comments starting with '#'.

2022-03-13 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-13T21:56:22+01:00
New Revision: 36d13d3f8adb3d1a6bae71370afa23d11a94dc78

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

LOG: [clang-format] Add space to comments starting with '#'.

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

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Added: 


Modified: 
clang/lib/Format/BreakableToken.cpp
clang/unittests/Format/FormatTestComments.cpp

Removed: 




diff  --git a/clang/lib/Format/BreakableToken.cpp 
b/clang/lib/Format/BreakableToken.cpp
index 967ddeb82383a..ae084e9e14544 100644
--- a/clang/lib/Format/BreakableToken.cpp
+++ b/clang/lib/Format/BreakableToken.cpp
@@ -779,11 +779,14 @@ BreakableLineCommentSection::BreakableLineCommentSection(
 const char FirstCommentChar = Lines[i][IndentPrefix.size()];
 const unsigned FirstCharByteSize =
 encoding::getCodePointNumBytes(FirstCommentChar, Encoding);
-return encoding::columnWidth(
-   Lines[i].substr(IndentPrefix.size(), FirstCharByteSize),
-   Encoding) == 1 &&
-   (FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) ||
-isHorizontalWhitespace(FirstCommentChar));
+if (encoding::columnWidth(
+Lines[i].substr(IndentPrefix.size(), FirstCharByteSize),
+Encoding) != 1)
+  return false;
+if (FirstCommentChar == '#')
+  return false;
+return FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) ||
+   isHorizontalWhitespace(FirstCommentChar);
   };
 
   // On the first line of the comment section we calculate how many spaces

diff  --git a/clang/unittests/Format/FormatTestComments.cpp 
b/clang/unittests/Format/FormatTestComments.cpp
index f83ffb393ac2f..27cc6013611c2 100644
--- a/clang/unittests/Format/FormatTestComments.cpp
+++ b/clang/unittests/Format/FormatTestComments.cpp
@@ -91,6 +91,9 @@ TEST_F(FormatTestComments, UnderstandsSingleLineComments) {
"// line 2\n"
"void f() {}\n");
 
+  EXPECT_EQ("// comment\n", format("//comment\n"));
+  EXPECT_EQ("// #comment\n", format("//#comment\n"));
+
   EXPECT_EQ("// comment\n"
 "// clang-format on\n",
 format("//comment\n"
@@ -3302,6 +3305,7 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 format(NoTextInComment, Style));
 
   Style.SpacesInLineCommentPrefix.Minimum = 0;
+  EXPECT_EQ("//#comment", format("//#comment", Style));
   EXPECT_EQ("//\n"
 "\n"
 "void foo() { //\n"
@@ -3310,6 +3314,7 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 format(NoTextInComment, Style));
 
   Style.SpacesInLineCommentPrefix.Minimum = 5;
+  EXPECT_EQ("// #comment", format("//#comment", Style));
   EXPECT_EQ("//\n"
 "\n"
 "void foo() { //\n"
@@ -3463,6 +3468,7 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 format(Code, Style));
 
   Style.SpacesInLineCommentPrefix = {0, 0};
+  EXPECT_EQ("//#comment", format("//   #comment", Style));
   EXPECT_EQ("//Free comment without space\n"
 "\n"
 "//Free comment with 3 spaces\n"



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


[PATCH] D121451: [clang-format] Add space to comments starting with '#'.

2022-03-13 Thread Marek Kurdej via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG36d13d3f8adb: [clang-format] Add space to comments starting 
with '#'. (authored by curdeius).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121451

Files:
  clang/lib/Format/BreakableToken.cpp
  clang/unittests/Format/FormatTestComments.cpp


Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -91,6 +91,9 @@
"// line 2\n"
"void f() {}\n");
 
+  EXPECT_EQ("// comment\n", format("//comment\n"));
+  EXPECT_EQ("// #comment\n", format("//#comment\n"));
+
   EXPECT_EQ("// comment\n"
 "// clang-format on\n",
 format("//comment\n"
@@ -3302,6 +3305,7 @@
 format(NoTextInComment, Style));
 
   Style.SpacesInLineCommentPrefix.Minimum = 0;
+  EXPECT_EQ("//#comment", format("//#comment", Style));
   EXPECT_EQ("//\n"
 "\n"
 "void foo() { //\n"
@@ -3310,6 +3314,7 @@
 format(NoTextInComment, Style));
 
   Style.SpacesInLineCommentPrefix.Minimum = 5;
+  EXPECT_EQ("// #comment", format("//#comment", Style));
   EXPECT_EQ("//\n"
 "\n"
 "void foo() { //\n"
@@ -3463,6 +3468,7 @@
 format(Code, Style));
 
   Style.SpacesInLineCommentPrefix = {0, 0};
+  EXPECT_EQ("//#comment", format("//   #comment", Style));
   EXPECT_EQ("//Free comment without space\n"
 "\n"
 "//Free comment with 3 spaces\n"
Index: clang/lib/Format/BreakableToken.cpp
===
--- clang/lib/Format/BreakableToken.cpp
+++ clang/lib/Format/BreakableToken.cpp
@@ -779,11 +779,14 @@
 const char FirstCommentChar = Lines[i][IndentPrefix.size()];
 const unsigned FirstCharByteSize =
 encoding::getCodePointNumBytes(FirstCommentChar, Encoding);
-return encoding::columnWidth(
-   Lines[i].substr(IndentPrefix.size(), FirstCharByteSize),
-   Encoding) == 1 &&
-   (FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) ||
-isHorizontalWhitespace(FirstCommentChar));
+if (encoding::columnWidth(
+Lines[i].substr(IndentPrefix.size(), FirstCharByteSize),
+Encoding) != 1)
+  return false;
+if (FirstCommentChar == '#')
+  return false;
+return FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) ||
+   isHorizontalWhitespace(FirstCommentChar);
   };
 
   // On the first line of the comment section we calculate how many spaces


Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -91,6 +91,9 @@
"// line 2\n"
"void f() {}\n");
 
+  EXPECT_EQ("// comment\n", format("//comment\n"));
+  EXPECT_EQ("// #comment\n", format("//#comment\n"));
+
   EXPECT_EQ("// comment\n"
 "// clang-format on\n",
 format("//comment\n"
@@ -3302,6 +3305,7 @@
 format(NoTextInComment, Style));
 
   Style.SpacesInLineCommentPrefix.Minimum = 0;
+  EXPECT_EQ("//#comment", format("//#comment", Style));
   EXPECT_EQ("//\n"
 "\n"
 "void foo() { //\n"
@@ -3310,6 +3314,7 @@
 format(NoTextInComment, Style));
 
   Style.SpacesInLineCommentPrefix.Minimum = 5;
+  EXPECT_EQ("// #comment", format("//#comment", Style));
   EXPECT_EQ("//\n"
 "\n"
 "void foo() { //\n"
@@ -3463,6 +3468,7 @@
 format(Code, Style));
 
   Style.SpacesInLineCommentPrefix = {0, 0};
+  EXPECT_EQ("//#comment", format("//   #comment", Style));
   EXPECT_EQ("//Free comment without space\n"
 "\n"
 "//Free comment with 3 spaces\n"
Index: clang/lib/Format/BreakableToken.cpp
===
--- clang/lib/Format/BreakableToken.cpp
+++ clang/lib/Format/BreakableToken.cpp
@@ -779,11 +779,14 @@
 const char FirstCommentChar = Lines[i][IndentPrefix.size()];
 const unsigned FirstCharByteSize =
 encoding::getCodePointNumBytes(FirstCommentChar, Encoding);
-return encoding::columnWidth(
-   Lines[i].substr(IndentPrefix.size(), FirstCharByteSize),
-   Encoding) == 1 &&
-   (FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) ||
-isHorizontalWhitespace(FirstCommentChar));
+if (encoding::columnWidth(
+Lines[i].substr(IndentPrefix.size(), FirstCharByteSize),
+Encoding) != 1)
+  r

[clang] a140b71 - [clang-format] Correctly format variable templates.

2022-03-13 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-13T22:00:17+01:00
New Revision: a140b7104fdae0d9eff5b18efbc784754e0ca274

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

LOG: [clang-format] Correctly format variable templates.

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

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1c662c9a909c9..77ef54e0e2d59 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1510,8 +1510,30 @@ class AnnotatingParser {
   if (Current.getPrecedence() != prec::Assignment)
 return false;
 
-  if (Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return))
+  if (Line.First->isOneOf(tok::kw_using, tok::kw_return))
 return false;
+  if (Line.First->is(tok::kw_template)) {
+// `template` keyword can start a variable template.
+const FormatToken *Tok = Line.First->getNextNonComment();
+assert(Tok); // Current token is on the same line.
+if (Tok->isNot(TT_TemplateOpener)) {
+  // Explicit template instantiations do not have `<>`.
+  return false;
+}
+
+Tok = Tok->MatchingParen;
+if (!Tok)
+  return false;
+Tok = Tok->getNextNonComment();
+if (!Tok)
+  return false;
+
+if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_concept,
+ tok::kw_struct, tok::kw_using))
+  return false;
+
+return true;
+  }
 
   // Type aliases use `type X = ...;` in TypeScript and can be exported
   // using `export type ...`.

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 430a195f60255..45e8c0b79cfb2 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25525,6 +25525,12 @@ TEST_F(FormatTest, 
AlignArrayOfStructuresRightAlignmentNonSquare) {
Style);
 }
 
+TEST_F(FormatTest, FormatsVariableTemplates) {
+  verifyFormat("inline bool var = is_integral_v && is_signed_v;");
+  verifyFormat("template  "
+   "inline bool var = is_integral_v && is_signed_v;");
+}
+
 } // namespace
 } // namespace format
 } // namespace clang

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 17801e4bb9839..7e753bc5a34d5 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -117,6 +117,31 @@ TEST_F(TokenAnnotatorTest, UnderstandsEnums) {
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_EnumLBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsDefaultedAndDeletedFunctions) {
+  auto Tokens = annotate("auto operator<=>(const T &) const & = default;");
+  EXPECT_EQ(Tokens.size(), 14u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::amp, TT_PointerOrReference);
+
+  Tokens = annotate("template  void F(T) && = delete;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[10], tok::ampamp, TT_PointerOrReference);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsVariables) {
+  auto Tokens =
+  annotate("inline bool var = is_integral_v && is_signed_v;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::ampamp, TT_BinaryOperator);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsVariableTemplates) {
+  auto Tokens =
+  annotate("template  "
+   "inline bool var = is_integral_v && is_signed_v;");
+  EXPECT_EQ(Tokens.size(), 20u) << Tokens;
+  EXPECT_TOKEN(Tokens[13], tok::ampamp, TT_BinaryOperator);
+}
+
 TEST_F(TokenAnnotatorTest, UnderstandsLBracesInMacroDefinition) {
   auto Tokens = annotate("#define BEGIN NS {");
   EXPECT_EQ(Tokens.size(), 6u) << Tokens;



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


[PATCH] D121456: [clang-format] Correctly format variable templates.

2022-03-13 Thread Marek Kurdej via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa140b7104fda: [clang-format] Correctly format variable 
templates. (authored by curdeius).

Changed prior to commit:
  https://reviews.llvm.org/D121456?vs=414634&id=414954#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121456

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -117,6 +117,31 @@
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_EnumLBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsDefaultedAndDeletedFunctions) {
+  auto Tokens = annotate("auto operator<=>(const T &) const & = default;");
+  EXPECT_EQ(Tokens.size(), 14u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::amp, TT_PointerOrReference);
+
+  Tokens = annotate("template  void F(T) && = delete;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[10], tok::ampamp, TT_PointerOrReference);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsVariables) {
+  auto Tokens =
+  annotate("inline bool var = is_integral_v && is_signed_v;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::ampamp, TT_BinaryOperator);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsVariableTemplates) {
+  auto Tokens =
+  annotate("template  "
+   "inline bool var = is_integral_v && is_signed_v;");
+  EXPECT_EQ(Tokens.size(), 20u) << Tokens;
+  EXPECT_TOKEN(Tokens[13], tok::ampamp, TT_BinaryOperator);
+}
+
 TEST_F(TokenAnnotatorTest, UnderstandsLBracesInMacroDefinition) {
   auto Tokens = annotate("#define BEGIN NS {");
   EXPECT_EQ(Tokens.size(), 6u) << Tokens;
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -25525,6 +25525,12 @@
Style);
 }
 
+TEST_F(FormatTest, FormatsVariableTemplates) {
+  verifyFormat("inline bool var = is_integral_v && is_signed_v;");
+  verifyFormat("template  "
+   "inline bool var = is_integral_v && is_signed_v;");
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -1510,8 +1510,30 @@
   if (Current.getPrecedence() != prec::Assignment)
 return false;
 
-  if (Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return))
+  if (Line.First->isOneOf(tok::kw_using, tok::kw_return))
 return false;
+  if (Line.First->is(tok::kw_template)) {
+// `template` keyword can start a variable template.
+const FormatToken *Tok = Line.First->getNextNonComment();
+assert(Tok); // Current token is on the same line.
+if (Tok->isNot(TT_TemplateOpener)) {
+  // Explicit template instantiations do not have `<>`.
+  return false;
+}
+
+Tok = Tok->MatchingParen;
+if (!Tok)
+  return false;
+Tok = Tok->getNextNonComment();
+if (!Tok)
+  return false;
+
+if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_concept,
+ tok::kw_struct, tok::kw_using))
+  return false;
+
+return true;
+  }
 
   // Type aliases use `type X = ...;` in TypeScript and can be exported
   // using `export type ...`.


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -117,6 +117,31 @@
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_EnumLBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsDefaultedAndDeletedFunctions) {
+  auto Tokens = annotate("auto operator<=>(const T &) const & = default;");
+  EXPECT_EQ(Tokens.size(), 14u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::amp, TT_PointerOrReference);
+
+  Tokens = annotate("template  void F(T) && = delete;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[10], tok::ampamp, TT_PointerOrReference);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsVariables) {
+  auto Tokens =
+  annotate("inline bool var = is_integral_v && is_signed_v;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::ampamp, TT_BinaryOperator);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsVariableTemplates) {
+  auto Tokens =
+  annotate("template  "
+   "inline bool var = is_integral_v && is_signed_v;");
+  EXPECT_EQ(Tokens.size(), 20u) << 

[PATCH] D121557: [clang-format][NFC] Rename Left to OpeningParen...

2022-03-13 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks created this revision.
HazardyKnusperkeks added reviewers: owenpan, MyDeveloperDay, curdeius.
HazardyKnusperkeks added a project: clang-format.
Herald added a project: All.
HazardyKnusperkeks requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

in TokenAnnotator::parseParens(). Left is misleading since we have a loop and 
Left is not adjusted.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121557

Files:
  clang/lib/Format/TokenAnnotator.cpp

Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -211,32 +211,34 @@
   bool parseParens(bool LookForDecls = false) {
 if (!CurrentToken)
   return false;
-FormatToken *Left = CurrentToken->Previous;
-assert(Left && "Unknown previous token");
-FormatToken *PrevNonComment = Left->getPreviousNonComment();
-Left->ParentBracket = Contexts.back().ContextKind;
+assert(CurrentToken->Previous && "Unknown previous token");
+FormatToken &OpeningParen = *CurrentToken->Previous;
+assert(OpeningParen.is(tok::l_paren));
+FormatToken *PrevNonComment = OpeningParen.getPreviousNonComment();
+OpeningParen.ParentBracket = Contexts.back().ContextKind;
 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
 
 // FIXME: This is a bit of a hack. Do better.
 Contexts.back().ColonIsForRangeExpr =
 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
 
-if (Left->Previous && Left->Previous->is(TT_UntouchableMacroFunc)) {
-  Left->Finalized = true;
+if (OpeningParen.Previous &&
+OpeningParen.Previous->is(TT_UntouchableMacroFunc)) {
+  OpeningParen.Finalized = true;
   return parseUntouchableParens();
 }
 
 bool StartsObjCMethodExpr = false;
-if (FormatToken *MaybeSel = Left->Previous) {
+if (FormatToken *MaybeSel = OpeningParen.Previous) {
   // @selector( starts a selector.
   if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
   MaybeSel->Previous->is(tok::at))
 StartsObjCMethodExpr = true;
 }
 
-if (Left->is(TT_OverloadedOperatorLParen)) {
+if (OpeningParen.is(TT_OverloadedOperatorLParen)) {
   // Find the previous kw_operator token.
-  FormatToken *Prev = Left;
+  FormatToken *Prev = &OpeningParen;
   while (!Prev->is(tok::kw_operator)) {
 Prev = Prev->Previous;
 assert(Prev && "Expect a kw_operator prior to the OperatorLParen!");
@@ -255,54 +257,58 @@
   // type X = (...);
   // export type X = (...);
   Contexts.back().IsExpression = false;
-} else if (Left->Previous &&
-   (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_while,
-tok::l_paren, tok::comma) ||
-Left->Previous->isIf() ||
-Left->Previous->is(TT_BinaryOperator))) {
+} else if (OpeningParen.Previous &&
+   (OpeningParen.Previous->isOneOf(tok::kw_static_assert,
+   tok::kw_while, tok::l_paren,
+   tok::comma) ||
+OpeningParen.Previous->isIf() ||
+OpeningParen.Previous->is(TT_BinaryOperator))) {
   // static_assert, if and while usually contain expressions.
   Contexts.back().IsExpression = true;
-} else if (Style.isJavaScript() && Left->Previous &&
-   (Left->Previous->is(Keywords.kw_function) ||
-(Left->Previous->endsSequence(tok::identifier,
-  Keywords.kw_function {
+} else if (Style.isJavaScript() && OpeningParen.Previous &&
+   (OpeningParen.Previous->is(Keywords.kw_function) ||
+(OpeningParen.Previous->endsSequence(tok::identifier,
+ Keywords.kw_function {
   // function(...) or function f(...)
   Contexts.back().IsExpression = false;
-} else if (Style.isJavaScript() && Left->Previous &&
-   Left->Previous->is(TT_JsTypeColon)) {
+} else if (Style.isJavaScript() && OpeningParen.Previous &&
+   OpeningParen.Previous->is(TT_JsTypeColon)) {
   // let x: (SomeType);
   Contexts.back().IsExpression = false;
-} else if (isLambdaParameterList(Left)) {
+} else if (isLambdaParameterList(&OpeningParen)) {
   // This is a parameter list of a lambda expression.
   Contexts.back().IsExpression = false;
 } else if (Line.InPPDirective &&
-   (!Left->Previous || !Left->Previous->is(tok::identifier))) {
+   (!OpeningParen.Previous ||
+!OpeningParen.Previous->is(tok::identifier))) {
   Contexts.back().IsExpression = true;
 } else if (Contexts[Contexts.size() - 2].CaretFound) {

[PATCH] D121550: [clang-format] Fix crash on invalid requires expression

2022-03-13 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks updated this revision to Diff 414956.
HazardyKnusperkeks marked 2 inline comments as done.
HazardyKnusperkeks added a comment.

Split rename and bug fix


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

https://reviews.llvm.org/D121550

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -331,6 +331,14 @@
   EXPECT_TOKEN(Tokens[13], tok::l_brace, TT_RequiresExpressionLBrace);
   EXPECT_TOKEN(Tokens[29], tok::kw_requires,
TT_RequiresClauseInARequiresExpression);
+
+  // Invalid Code, but we don't want to crash. See http://llvm.org/PR54350.
+  Tokens = annotate("bool r10 = requires (struct new_struct { int x; } s) { "
+"requires true; };");
+  ASSERT_EQ(Tokens.size(), 21u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::kw_requires, TT_RequiresExpression);
+  EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_RequiresExpressionLParen);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_RequiresExpressionLBrace);
 }
 
 TEST_F(TokenAnnotatorTest, RequiresDoesNotChangeParsingOfTheRest) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -23891,9 +23891,9 @@
   verifyFormat(
   "template  concept C = decltype([]() -> std::true_type {\n"
   "return {};\n"
-  "  }())::value\n"
-  "  && requires(T t) { t.bar(); } &&\n"
-  "  sizeof(T) <= 8;",
+  "  }())::value &&\n"
+  "  requires(T t) { t.bar(); } && "
+  "sizeof(T) <= 8;",
   Style);
 
   verifyFormat("template  concept Semiregular =\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -421,8 +421,8 @@
   if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
 return false;
 
-  if (CurrentToken->is(tok::l_brace))
-OpeningParen.setType(TT_Unknown); // Not TT_ObjCBlockLParen
+  if (CurrentToken->is(tok::l_brace) && 
OpeningParen.is(TT_ObjCBlockLParen))
+OpeningParen.setType(TT_Unknown);
   if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
   !CurrentToken->Next->HasUnescapedNewline &&
   !CurrentToken->Next->isTrailingComment())


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -331,6 +331,14 @@
   EXPECT_TOKEN(Tokens[13], tok::l_brace, TT_RequiresExpressionLBrace);
   EXPECT_TOKEN(Tokens[29], tok::kw_requires,
TT_RequiresClauseInARequiresExpression);
+
+  // Invalid Code, but we don't want to crash. See http://llvm.org/PR54350.
+  Tokens = annotate("bool r10 = requires (struct new_struct { int x; } s) { "
+"requires true; };");
+  ASSERT_EQ(Tokens.size(), 21u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::kw_requires, TT_RequiresExpression);
+  EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_RequiresExpressionLParen);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_RequiresExpressionLBrace);
 }
 
 TEST_F(TokenAnnotatorTest, RequiresDoesNotChangeParsingOfTheRest) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -23891,9 +23891,9 @@
   verifyFormat(
   "template  concept C = decltype([]() -> std::true_type {\n"
   "return {};\n"
-  "  }())::value\n"
-  "  && requires(T t) { t.bar(); } &&\n"
-  "  sizeof(T) <= 8;",
+  "  }())::value &&\n"
+  "  requires(T t) { t.bar(); } && "
+  "sizeof(T) <= 8;",
   Style);
 
   verifyFormat("template  concept Semiregular =\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -421,8 +421,8 @@
   if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
 return false;
 
-  if (CurrentToken->is(tok::l_brace))
-OpeningParen.setType(TT_Unknown); // Not TT_ObjCBlockLPa

[PATCH] D121550: [clang-format] Fix crash on invalid requires expression

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



Comment at: clang/lib/Format/TokenAnnotator.cpp:215
+assert(CurrentToken->Previous && "Unknown previous token");
+FormatToken &OpeningParen = *CurrentToken->Previous;
+assert(OpeningParen.is(tok::l_paren));

curdeius wrote:
> Maybe you can commit the rename as a NFC commit and rebase the patch to 
> remove the noise?
Done in D121557



Comment at: clang/unittests/Format/TokenAnnotatorTest.cpp:335
+
+  // Invalid Code, but we don't want to crash. See http://llvm.org/PR54350.
+  Tokens = annotate("bool r10 = requires (struct new_struct { int x; } s) { "

curdeius wrote:
> I'd prefer a valid C++ code (if it's not too complicated) if possible but 
> that's acceptable.
I thought I'd stick to the bug report. The only thing that comes to my mind 
does compile on gcc, but clang gives a specific error (which I support, without 
having looked into the standard). https://gcc.godbolt.org/z/WvT9861b6


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

https://reviews.llvm.org/D121550

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


[PATCH] D121557: [clang-format][NFC] Rename Left to OpeningParen...

2022-03-13 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121557

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


[PATCH] D121558: [clang-format][NFC] Left renamed to OpeningBrace...

2022-03-13 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks created this revision.
HazardyKnusperkeks added reviewers: owenpan, MyDeveloperDay, curdeius.
HazardyKnusperkeks added a project: clang-format.
Herald added a project: All.
HazardyKnusperkeks requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

in TokenAnnotator::parseBrace. Left is misleading, because we have a loop and 
Left does not move.

Also return early.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121558

Files:
  clang/lib/Format/TokenAnnotator.cpp

Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -774,63 +774,66 @@
   }
 
   bool parseBrace() {
-if (CurrentToken) {
-  FormatToken *Left = CurrentToken->Previous;
-  Left->ParentBracket = Contexts.back().ContextKind;
+if (!CurrentToken)
+  return true;
 
-  if (Contexts.back().CaretFound)
-Left->setType(TT_ObjCBlockLBrace);
-  Contexts.back().CaretFound = false;
+assert(CurrentToken->Previous);
+FormatToken &OpeningBrace = *CurrentToken->Previous;
+assert(OpeningBrace.is(tok::l_brace));
+OpeningBrace.ParentBracket = Contexts.back().ContextKind;
 
-  ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
-  Contexts.back().ColonIsDictLiteral = true;
-  if (Left->is(BK_BracedInit))
-Contexts.back().IsExpression = true;
-  if (Style.isJavaScript() && Left->Previous &&
-  Left->Previous->is(TT_JsTypeColon))
-Contexts.back().IsExpression = false;
+if (Contexts.back().CaretFound)
+  OpeningBrace.setType(TT_ObjCBlockLBrace);
+Contexts.back().CaretFound = false;
 
-  unsigned CommaCount = 0;
-  while (CurrentToken) {
-if (CurrentToken->is(tok::r_brace)) {
-  assert(Left->Optional == CurrentToken->Optional);
-  Left->MatchingParen = CurrentToken;
-  CurrentToken->MatchingParen = Left;
-  if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
-if (Left->ParentBracket == tok::l_brace &&
-couldBeInStructArrayInitializer() && CommaCount > 0)
-  Contexts.back().InStructArrayInitializer = true;
-  }
-  next();
-  return true;
-}
-if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
-  return false;
-updateParameterCount(Left, CurrentToken);
-if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
-  FormatToken *Previous = CurrentToken->getPreviousNonComment();
-  if (Previous->is(TT_JsTypeOptionalQuestion))
-Previous = Previous->getPreviousNonComment();
-  if ((CurrentToken->is(tok::colon) &&
-   (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
-  Style.Language == FormatStyle::LK_Proto ||
-  Style.Language == FormatStyle::LK_TextProto) {
-Left->setType(TT_DictLiteral);
-if (Previous->Tok.getIdentifierInfo() ||
-Previous->is(tok::string_literal))
-  Previous->setType(TT_SelectorName);
-  }
-  if (CurrentToken->is(tok::colon) || Style.isJavaScript())
-Left->setType(TT_DictLiteral);
+ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
+Contexts.back().ColonIsDictLiteral = true;
+if (OpeningBrace.is(BK_BracedInit))
+  Contexts.back().IsExpression = true;
+if (Style.isJavaScript() && OpeningBrace.Previous &&
+OpeningBrace.Previous->is(TT_JsTypeColon))
+  Contexts.back().IsExpression = false;
+
+unsigned CommaCount = 0;
+while (CurrentToken) {
+  if (CurrentToken->is(tok::r_brace)) {
+assert(OpeningBrace.Optional == CurrentToken->Optional);
+OpeningBrace.MatchingParen = CurrentToken;
+CurrentToken->MatchingParen = &OpeningBrace;
+if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
+  if (OpeningBrace.ParentBracket == tok::l_brace &&
+  couldBeInStructArrayInitializer() && CommaCount > 0)
+Contexts.back().InStructArrayInitializer = true;
 }
-if (CurrentToken->is(tok::comma)) {
-  if (Style.isJavaScript())
-Left->overwriteFixedType(TT_DictLiteral);
-  ++CommaCount;
+next();
+return true;
+  }
+  if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
+return false;
+  updateParameterCount(&OpeningBrace, CurrentToken);
+  if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
+FormatToken *Previous = CurrentToken->getPreviousNonComment();
+if (Previous->is(TT_JsTypeOptionalQuestion))
+  Previous = Previous->getPreviousNonComment();
+if ((CurrentToken->is(tok::colon) &&
+ (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
+   

[PATCH] D121559: [clang-format] Fix crash on asm block with label

2022-03-13 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks created this revision.
HazardyKnusperkeks added reviewers: owenpan, MyDeveloperDay, curdeius.
HazardyKnusperkeks added a project: clang-format.
Herald added a project: All.
HazardyKnusperkeks requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121559

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -577,6 +577,15 @@
   << I;
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsAsm) {
+  auto Tokens = annotate("__asm{\n"
+ "a:\n"
+ "};");
+  ASSERT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::kw_asm, TT_Unknown);
+  EXPECT_TOKEN(Tokens[1], tok::l_brace, TT_InlineASMBrace);
+  EXPECT_TOKEN(Tokens[4], tok::r_brace, TT_InlineASMBrace);
+}
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -824,8 +824,10 @@
   Previous->is(tok::string_literal))
 Previous->setType(TT_SelectorName);
 }
-if (CurrentToken->is(tok::colon) || Style.isJavaScript())
+if (CurrentToken->is(tok::colon) && OpeningBrace.is(TT_Unknown))
   OpeningBrace.setType(TT_DictLiteral);
+if (Style.isJavaScript())
+  OpeningBrace.overwriteFixedType(TT_DictLiteral);
   }
   if (CurrentToken->is(tok::comma)) {
 if (Style.isJavaScript())


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -577,6 +577,15 @@
   << I;
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsAsm) {
+  auto Tokens = annotate("__asm{\n"
+ "a:\n"
+ "};");
+  ASSERT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::kw_asm, TT_Unknown);
+  EXPECT_TOKEN(Tokens[1], tok::l_brace, TT_InlineASMBrace);
+  EXPECT_TOKEN(Tokens[4], tok::r_brace, TT_InlineASMBrace);
+}
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -824,8 +824,10 @@
   Previous->is(tok::string_literal))
 Previous->setType(TT_SelectorName);
 }
-if (CurrentToken->is(tok::colon) || Style.isJavaScript())
+if (CurrentToken->is(tok::colon) && OpeningBrace.is(TT_Unknown))
   OpeningBrace.setType(TT_DictLiteral);
+if (Style.isJavaScript())
+  OpeningBrace.overwriteFixedType(TT_DictLiteral);
   }
   if (CurrentToken->is(tok::comma)) {
 if (Style.isJavaScript())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 0570af1 - [clang-format] Fix incorrect assertion on macro definitions with keyword class.

2022-03-13 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-13T22:17:48+01:00
New Revision: 0570af17585d98be0c12f6760118eb94071d9c26

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

LOG: [clang-format] Fix incorrect assertion on macro definitions with keyword 
class.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 5b5439901b2f7..1393a2a321183 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -484,7 +484,8 @@ class LineJoiner {
   } else {
 // Try to merge a block with left brace unwrapped that wasn't yet
 // covered.
-assert(!TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
+assert(TheLine->InPPDirective ||
+   !TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
 tok::kw_struct));
 ShouldMerge = !Style.BraceWrapping.AfterFunction ||
   (NextLine.First->is(tok::r_brace) &&

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 45e8c0b79cfb2..baa3993805bcb 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1877,6 +1877,13 @@ TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("#define __except(x)");
   verifyFormat("#define __try(x)");
 
+  // https://llvm.org/PR54348.
+  verifyFormat(
+  "#define A"
+  "  "
+  "\\\n"
+  "  class & {}");
+
   FormatStyle Style = getLLVMStyle();
   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
   Style.BraceWrapping.AfterFunction = true;



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


[PATCH] D121550: [clang-format] Fix crash on invalid requires expression

2022-03-13 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

LGTM. And thanks for splitting the patch.




Comment at: clang/unittests/Format/TokenAnnotatorTest.cpp:335
+
+  // Invalid Code, but we don't want to crash. See http://llvm.org/PR54350.
+  Tokens = annotate("bool r10 = requires (struct new_struct { int x; } s) { "

HazardyKnusperkeks wrote:
> curdeius wrote:
> > I'd prefer a valid C++ code (if it's not too complicated) if possible but 
> > that's acceptable.
> I thought I'd stick to the bug report. The only thing that comes to my mind 
> does compile on gcc, but clang gives a specific error (which I support, 
> without having looked into the standard). https://gcc.godbolt.org/z/WvT9861b6
Ok, now I see that it's actual test code. It's perfectly fine the.


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

https://reviews.llvm.org/D121550

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


[PATCH] D121558: [clang-format][NFC] Left renamed to OpeningBrace...

2022-03-13 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121558

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


[PATCH] D112019: [clang-format] [PR51412] AlignConsecutiveMacros fights with Visual Studio and resource.h

2022-03-13 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks accepted this revision.
HazardyKnusperkeks added a comment.

In D112019#3378031 , @MyDeveloperDay 
wrote:

> In D112019#3378024 , 
> @HazardyKnusperkeks wrote:
>
>> Why limit to macros, could it be a member of AlignConsecutiveStyle and apply 
>> to the other stuff as well?
>
> I personally don't have a use case other than the resource.h case that I 
> raise above, do you think this would be useful to be elsewhere in the other 
> AlignConsecutive cases?
>
> Of course, this code alters AlignMacroSequence() and not AlignTokens() what 
> if we unified the options (so they were part of the struct? but kept the 
> functionality change in separate reviews? for now the options would have no 
> effect on other Consecutive options?

I don't know if there will be a use case. The more I think about it, it maybe 
harder to apply it to the other options.
I withdraw my comment. :)


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

https://reviews.llvm.org/D112019

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


[PATCH] D121512: [Support] Change zlib::compress to return void

2022-03-13 Thread Joerg Sonnenberger via Phabricator via cfe-commits
joerg added a comment.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121512

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


[PATCH] D121560: [clang][Opt] Add NoArgUnusedWith to not warn for unused redundant options

2022-03-13 Thread Alex Brachet via Phabricator via cfe-commits
abrachet created this revision.
abrachet added reviewers: MaskRay, thakis.
Herald added subscribers: ormris, dang, usaxena95, kadircet, rupprecht, 
arphaman, steven_wu, hiraditya, arichardson, sbc100, emaste.
Herald added a reviewer: JDevlieghere.
Herald added a reviewer: alexander-shaposhnikov.
Herald added a reviewer: rupprecht.
Herald added a reviewer: jhenderson.
Herald added projects: lld-macho, All.
Herald added a reviewer: lld-macho.
abrachet requested review of this revision.
Herald added subscribers: cfe-commits, llvm-commits, aheejin.
Herald added projects: LLVM, clang-tools-extra.

`NoArgUnusedWith` can be used for options which together are redundant or not 
meaningful. This patch adds an example for `-static-libcxx` and `-nostdlib`. 
The former isn't meaningful with the latter. Projects might elect to build with 
a flag like `static-libcxx` globally and use `nostdlib` for specific TU's, in 
this case they would get unused args warnings.


https://reviews.llvm.org/D121560

Files:
  clang-tools-extra/clangd/CompileCommands.cpp
  clang/include/clang/Driver/Options.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/DriverOptions.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Driver/claim-unused.c
  lld/COFF/Driver.h
  lld/COFF/DriverUtils.cpp
  lld/ELF/Driver.h
  lld/ELF/DriverUtils.cpp
  lld/MachO/Driver.h
  lld/MachO/DriverUtils.cpp
  lld/MinGW/Driver.cpp
  lld/wasm/Driver.cpp
  lldb/tools/driver/Driver.cpp
  lldb/tools/lldb-server/lldb-gdbserver.cpp
  lldb/tools/lldb-vscode/lldb-vscode.cpp
  llvm/include/llvm/Option/OptParser.td
  llvm/include/llvm/Option/OptTable.h
  llvm/include/llvm/Option/Option.h
  llvm/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp
  llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp
  llvm/tools/dsymutil/dsymutil.cpp
  llvm/tools/llvm-cvtres/llvm-cvtres.cpp
  llvm/tools/llvm-cxxfilt/llvm-cxxfilt.cpp
  llvm/tools/llvm-lipo/llvm-lipo.cpp
  llvm/tools/llvm-ml/llvm-ml.cpp
  llvm/tools/llvm-mt/llvm-mt.cpp
  llvm/tools/llvm-nm/llvm-nm.cpp
  llvm/tools/llvm-objcopy/ObjcopyOptions.cpp
  llvm/tools/llvm-objdump/ObjdumpOptID.h
  llvm/tools/llvm-objdump/llvm-objdump.cpp
  llvm/tools/llvm-rc/llvm-rc.cpp
  llvm/tools/llvm-readobj/llvm-readobj.cpp
  llvm/tools/llvm-size/llvm-size.cpp
  llvm/tools/llvm-strings/llvm-strings.cpp
  llvm/tools/llvm-symbolizer/llvm-symbolizer.cpp
  llvm/tools/llvm-tli-checker/llvm-tli-checker.cpp
  llvm/unittests/Option/OptionMarshallingTest.cpp
  llvm/unittests/Option/OptionParsingTest.cpp
  llvm/utils/TableGen/OptParserEmitter.cpp

Index: llvm/utils/TableGen/OptParserEmitter.cpp
===
--- llvm/utils/TableGen/OptParserEmitter.cpp
+++ llvm/utils/TableGen/OptParserEmitter.cpp
@@ -258,6 +258,16 @@
   OS << "#endif // PREFIX\n\n";
 
   OS << "/\n";
+
+  OS << R"(
+#ifndef OPT_PREFIX
+#define OPT_PREFIX
+#endif
+
+#define CAT_(A, B) A ## B
+#define CAT(A, B) CAT_(A, B)
+#define GET_OPT(OPT) CAT(OPT_PREFIX, OPT)
+  )";
   OS << "// Groups\n\n";
   OS << "#ifdef OPTION\n";
   for (const Record &R : llvm::make_pointee_range(Groups)) {
@@ -298,6 +308,9 @@
 OS << ", nullptr";
 
 // The option Values (unused for groups).
+OS << ", nullptr";
+
+// NoArgUnusedWith (unused for groups).
 OS << ", nullptr)\n";
   }
   OS << "\n";
@@ -388,6 +401,20 @@
   write_cstring(OS, R.getValueAsString("Values"));
 else
   OS << "nullptr";
+
+// List of flags who's presence should cause this flag to not warn if used.
+OS << ", ";
+std::vector List = R.getValueAsListOfDefs("NoArgUnusedWith");
+if (!List.size()) {
+  OS << "nullptr";
+  return;
+}
+OS << "((const unsigned *)&(unsigned []){";
+// First element is the length of the array.
+OS << List.size();
+for (Record *R : List)
+  OS << ", GET_OPT(" << R->getName() << ")";
+OS << "})";
   };
 
   auto IsMarshallingOption = [](const Record &R) {
@@ -405,6 +432,11 @@
   OptsWithMarshalling.push_back(&R);
   }
   OS << "#endif // OPTION\n";
+  OS << R"(#undef GET_OPT
+#undef CAT
+#undef CAT_
+#undef OPT_PREFIX
+)";
 
   auto CmpMarshallingOpts = [](const Record *const *A, const Record *const *B) {
 unsigned AID = (*A)->getID();
Index: llvm/unittests/Option/OptionParsingTest.cpp
===
--- llvm/unittests/Option/OptionParsingTest.cpp
+++ llvm/unittests/Option/OptionParsingTest.cpp
@@ -18,7 +18,7 @@
 enum ID {
   OPT_INVALID = 0, // This is not an option ID.
 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
-   HELPTEXT, METAVAR, VALUES)  \
+   HELPTEXT, METAVAR, VALUES, UNUSEDWITH)  \
   OPT_##ID,
 #include "Opts.inc"
   LastOption
@@ -37,9 +37,9 @@
 
 static const OptTable::Info InfoTable[] = {
 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARG

[PATCH] D121560: [clang][Opt] Add NoArgUnusedWith to not warn for unused redundant options

2022-03-13 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

> This patch adds an example for -static-libcxx and -nostdlib.

We have -static-libstdc++ but not -static-libc++. (D53238 
 attempts to add `-static` and name it 
`-static=c++stdlib`)

> NoArgUnusedWith can be used for options which together are redundant or not 
> meaningful.

I agree that `-Wunused-command-line-argument` sometimes gets in the way and 
removing the warnings is sometimes inconvenient.

You can currently avoid the warning with: `--start-no-unused-arguments 
-static-libstdc++ --end-no-unused-arguments`.

For `NoArgUnusedWith`, intuitively I am unsure whether it is sufficient for 
many options. For example, you probably want to remove the diagnostic with 
`-nostdlib++` and `-nodefaultlibs` as well.
There are just so many similar options.




Comment at: clang/lib/Driver/Driver.cpp:4426
 
+  std::function ConsideredUsed =
+  [&ConsideredUsed](llvm::opt::DerivedArgList &Args, Arg *A) {

Unless you want to capture it somewhere.


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

https://reviews.llvm.org/D121560

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


[PATCH] D121560: [clang][Opt] Add NoArgUnusedWith to not warn for unused redundant options

2022-03-13 Thread Alex Brachet via Phabricator via cfe-commits
abrachet updated this revision to Diff 414965.
abrachet edited the summary of this revision.
abrachet added a comment.

Update example to have multiple options in NoArgUnusedWith


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

https://reviews.llvm.org/D121560

Files:
  clang-tools-extra/clangd/CompileCommands.cpp
  clang/include/clang/Driver/Options.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/DriverOptions.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Driver/claim-unused.c
  lld/COFF/Driver.h
  lld/COFF/DriverUtils.cpp
  lld/ELF/Driver.h
  lld/ELF/DriverUtils.cpp
  lld/MachO/Driver.h
  lld/MachO/DriverUtils.cpp
  lld/MinGW/Driver.cpp
  lld/wasm/Driver.cpp
  lldb/tools/driver/Driver.cpp
  lldb/tools/lldb-server/lldb-gdbserver.cpp
  lldb/tools/lldb-vscode/lldb-vscode.cpp
  llvm/include/llvm/Option/OptParser.td
  llvm/include/llvm/Option/OptTable.h
  llvm/include/llvm/Option/Option.h
  llvm/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp
  llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp
  llvm/tools/dsymutil/dsymutil.cpp
  llvm/tools/llvm-cvtres/llvm-cvtres.cpp
  llvm/tools/llvm-cxxfilt/llvm-cxxfilt.cpp
  llvm/tools/llvm-lipo/llvm-lipo.cpp
  llvm/tools/llvm-ml/llvm-ml.cpp
  llvm/tools/llvm-mt/llvm-mt.cpp
  llvm/tools/llvm-nm/llvm-nm.cpp
  llvm/tools/llvm-objcopy/ObjcopyOptions.cpp
  llvm/tools/llvm-objdump/ObjdumpOptID.h
  llvm/tools/llvm-objdump/llvm-objdump.cpp
  llvm/tools/llvm-rc/llvm-rc.cpp
  llvm/tools/llvm-readobj/llvm-readobj.cpp
  llvm/tools/llvm-size/llvm-size.cpp
  llvm/tools/llvm-strings/llvm-strings.cpp
  llvm/tools/llvm-symbolizer/llvm-symbolizer.cpp
  llvm/tools/llvm-tli-checker/llvm-tli-checker.cpp
  llvm/unittests/Option/OptionMarshallingTest.cpp
  llvm/unittests/Option/OptionParsingTest.cpp
  llvm/utils/TableGen/OptParserEmitter.cpp

Index: llvm/utils/TableGen/OptParserEmitter.cpp
===
--- llvm/utils/TableGen/OptParserEmitter.cpp
+++ llvm/utils/TableGen/OptParserEmitter.cpp
@@ -258,6 +258,16 @@
   OS << "#endif // PREFIX\n\n";
 
   OS << "/\n";
+
+  OS << R"(
+#ifndef OPT_PREFIX
+#define OPT_PREFIX
+#endif
+
+#define CAT_(A, B) A ## B
+#define CAT(A, B) CAT_(A, B)
+#define GET_OPT(OPT) CAT(OPT_PREFIX, OPT)
+  )";
   OS << "// Groups\n\n";
   OS << "#ifdef OPTION\n";
   for (const Record &R : llvm::make_pointee_range(Groups)) {
@@ -298,6 +308,9 @@
 OS << ", nullptr";
 
 // The option Values (unused for groups).
+OS << ", nullptr";
+
+// NoArgUnusedWith (unused for groups).
 OS << ", nullptr)\n";
   }
   OS << "\n";
@@ -388,6 +401,20 @@
   write_cstring(OS, R.getValueAsString("Values"));
 else
   OS << "nullptr";
+
+// List of flags who's presence should cause this flag to not warn if used.
+OS << ", ";
+std::vector List = R.getValueAsListOfDefs("NoArgUnusedWith");
+if (!List.size()) {
+  OS << "nullptr";
+  return;
+}
+OS << "((const unsigned *)&(unsigned []){";
+// First element is the length of the array.
+OS << List.size();
+for (Record *R : List)
+  OS << ", GET_OPT(" << R->getName() << ")";
+OS << "})";
   };
 
   auto IsMarshallingOption = [](const Record &R) {
@@ -405,6 +432,11 @@
   OptsWithMarshalling.push_back(&R);
   }
   OS << "#endif // OPTION\n";
+  OS << R"(#undef GET_OPT
+#undef CAT
+#undef CAT_
+#undef OPT_PREFIX
+)";
 
   auto CmpMarshallingOpts = [](const Record *const *A, const Record *const *B) {
 unsigned AID = (*A)->getID();
Index: llvm/unittests/Option/OptionParsingTest.cpp
===
--- llvm/unittests/Option/OptionParsingTest.cpp
+++ llvm/unittests/Option/OptionParsingTest.cpp
@@ -18,7 +18,7 @@
 enum ID {
   OPT_INVALID = 0, // This is not an option ID.
 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
-   HELPTEXT, METAVAR, VALUES)  \
+   HELPTEXT, METAVAR, VALUES, UNUSEDWITH)  \
   OPT_##ID,
 #include "Opts.inc"
   LastOption
@@ -37,9 +37,9 @@
 
 static const OptTable::Info InfoTable[] = {
 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
-   HELPTEXT, METAVAR, VALUES)  \
+   HELPTEXT, METAVAR, VALUES, UNUSEDWITH)  \
   {PREFIX, NAME,  HELPTEXT,METAVAR, OPT_##ID,  Option::KIND##Class,\
-   PARAM,  FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS, VALUES},
+   PARAM,  FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS, VALUES, UNUSEDWITH},
 #include "Opts.inc"
 #undef OPTION
 };
Index: llvm/unittests/Option/OptionMarshallingTest.cpp
===
--- llvm/unittests/Option/OptionMarshallingTest.cpp
+++ llvm/unittests/Option/OptionMarshallingTest.cpp
@@ -18,9 +18,9 @@
 static const OptionWithM

[PATCH] D121560: [clang][Opt] Add NoArgUnusedWith to not warn for unused redundant options

2022-03-13 Thread Alex Brachet via Phabricator via cfe-commits
abrachet marked an inline comment as done.
abrachet added a comment.

In D121560#3378181 , @MaskRay wrote:

>> This patch adds an example for -static-libcxx and -nostdlib.
>
> We have -static-libstdc++ but not -static-libc++. (D53238 
>  attempts to add `-static` and name it 
> `-static=c++stdlib`)

Thank you, updated the description

>> NoArgUnusedWith can be used for options which together are redundant or not 
>> meaningful.
>
> I agree that `-Wunused-command-line-argument` sometimes gets in the way and 
> removing the warnings is sometimes inconvenient.
>
> You can currently avoid the warning with: `--start-no-unused-arguments 
> -static-libstdc++ --end-no-unused-arguments`.

Yeah, we are currently using this in some places, but if you just globally set 
`-static-libstdc++` as `--start-no-unused-arguments -static-libstdc++ 
--end-no-unused-arguments`, then you lose out when it should actually warn. 
Likewise right now we set `-Wno-unused-command-line-argument` in a few places 
where this is an issue

> For `NoArgUnusedWith`, intuitively I am unsure it is the desired interface. 
> For `-static-libstdc++`, you probably want to remove the diagnostic with 
> `-nostdlib++` and `-nodefaultlibs` as well. There are just so many similar 
> options.

Added to the example both of these flags to show `NoArgUnusedWith` can support 
multiple flags. There's a lot more redundant flags, and I'll get to some in 
follow up patches




Comment at: clang/lib/Driver/Driver.cpp:4426
 
+  std::function ConsideredUsed =
+  [&ConsideredUsed](llvm::opt::DerivedArgList &Args, Arg *A) {

MaskRay wrote:
> Unless you want to capture it somewhere.
Indeed, `ConsideredUsed` is used in the llvm::any_of call


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

https://reviews.llvm.org/D121560

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


[PATCH] D111400: [Clang] Implement P2242R3

2022-03-13 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3-2b.cpp:16
+}
+
+constexpr int f(int x) {

Add a `NonLiteral` case and a case with a labelled statement and no `goto`?



Comment at: clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3-2b.cpp:37-38
+int x = f(0);
+constexpr int y = f(0); //expected-error {{must be initialized by a constant 
expression}} \
+// expected-note {{in call to 'f(0)'}}
+

I'm mildly confused over why the error case for the constexpr evaluation 
appears in this file (which is about the structure of the body) and not in 
`constant-expression-cxx2b.cpp` (which is about constant expression evaluation).



Comment at: clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp:194-201
+  static constexpr int n = 123;
+#ifndef CXX2b
+  // expected-error@-2 {{definition of a static variable in a constexpr 
function is a C++2b extension}}
+#endif
+#if !defined(CXX14)
+  // expected-error@-5 {{variable declaration in a constexpr function is a 
C++14 extension}}
+#endif

The return statement needs to happen before the declaration of the static 
variable.



Comment at: clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp:353
+#ifndef CXX14
+  // expected-error@-5 {{C++14}}
+#endif

The abbreviated message snippet might be easy to understand if someone was 
looking at the diff from this patch, but it would likely be less so if they 
were just looking at the code later.



Comment at: clang/test/SemaCXX/constant-expression-cxx2b.cpp:3-7
+constexpr int f(int n) {  // expected-error {{constexpr function never 
produces a constant expression}}
+  static const int m = n; //  expected-note {{declared here}}  \
+  //  expected-warning {{definition of a static 
variable in a constexpr function is incompatible with C++ standards before 
C++2b}}
+  return m;   //  expected-note {{initializer of 'm' is not a 
constant expression}}
+}

Same comment as the `thread_local` case below. Also, the expected error is 
missing even if the function is called in a context requiring constant 
evaluation.



Comment at: clang/test/SemaCXX/constant-expression-cxx2b.cpp:8-12
+constexpr int g(int n) {//  expected-error {{constexpr function never 
produces a constant expression}}
+  thread_local const int m = n; //  expected-note {{declared here}} \
+//  expected-warning {{definition of a 
thread_local variable in a constexpr function is incompatible with C++ 
standards before C++2b}}
+  return m; //  expected-note {{initializer of 'm' is not 
a constant expression}}
+}

The implementation generates an error because the `return` is `m` and not 
something like `&m - &m`.

The wording has:

  - a control flow that passes through a declaration of a variable with static 
or thread storage duration

as one of the things that cannot be evaluated for a constant expression.

The patch does not generate an error on the `&m - &m` version of the test.



Comment at: clang/test/SemaCXX/cxx1z-constexpr-lambdas.cpp:118-122
-auto NCL = [](int i) { static int j; return j; }; //expected-note{{declared 
here}}
-constexpr int (*fp5)(int) = NCL;
-constexpr int I =  //expected-error{{must be initialized by a constant 
expression}}
-  fp5(5); //expected-note{{non-constexpr function}} 
-

Patch does not change the behaviour of this test anymore (and this file does 
not have a C++2b `RUN` line). Should keep the test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111400

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


[PATCH] D121559: [clang-format] Fix crash on asm block with label

2022-03-13 Thread Owen Pan via Phabricator via cfe-commits
owenpan accepted this revision.
owenpan added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:829
   OpeningBrace.setType(TT_DictLiteral);
+if (Style.isJavaScript())
+  OpeningBrace.overwriteFixedType(TT_DictLiteral);





Comment at: clang/unittests/Format/TokenAnnotatorTest.cpp:588
+  EXPECT_TOKEN(Tokens[4], tok::r_brace, TT_InlineASMBrace);
+}
 } // namespace




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121559

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


[PATCH] D109977: LLVM Driver Multicall tool

2022-03-13 Thread Petr Hosek via Phabricator via cfe-commits
phosek added a comment.

Another potential future improvement is error reporting for subcommands:

  $ ./bin/llvm clang   
  llvm: error: no input files
  $ ./bin/clang
  clang-15: error: no input files

Ideally, the multicall tool would produce the same error message.




Comment at: llvm/cmake/modules/AddLLVM.cmake:897
+set_property(GLOBAL APPEND PROPERTY LLVM_DRIVER_TOOLS ${name})
+target_link_libraries(${obj_name} PUBLIC ${LLVM_PTHREAD_LIB})
+llvm_config(${obj_name} ${USE_SHARED} ${LLVM_LINK_COMPONENTS} )

The error that @MaskRay reported is because we use `PUBLIC` with 
`target_link_libraries()` here, but we use plain form of 
`target_link_libraries()` later in  `explicit_llvm_config` that is invoked 
`llvm_config` (see 
https://github.com/llvm/llvm-project/blob/1643f01232b41b93e5f3a21d89b111efab0e378a/llvm/cmake/modules/LLVM-Config.cmake#L110).
 Omitting `PUBLIC` here appears to be sufficient to avoid the error.



Comment at: llvm/tools/CMakeLists.txt:59
+# scrape up tools from other projects into itself.
+add_subdirectory(llvm-driver)

Should this be guarded by `LLVM_TOOL_LLVM_DRIVER_BUILD` to behave as the commit 
message says? Currently the `llvm-driver` appears to be built regardless of 
`LLVM_TOOL_LLVM_DRIVER_BUILD`.



Comment at: llvm/tools/llvm-driver/llvm-driver.cpp:43
+  if (LaunchedTool == "llvm") {
+LaunchedTool = Argv[1];
+ConsumeFirstArg = true;

When the tool is invoked without any arguments (that is, simply as 
`./bin/llvm`) this will lead to out-of-bounds array access. We should handle 
this case explicitly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109977

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


[PATCH] D121175: [clang] Add -Wstart-no-unknown-warning-option/-Wend-no-unknown-warning-option.

2022-03-13 Thread Petr Hosek via Phabricator via cfe-commits
phosek added a comment.

In D121175#3372056 , @condy wrote:

> IMHO, it's the duty of build systems. CMake provides 
> `check_cxx_compiler_flag` to report unknown options.

That's only true for build systems that perform configure time checks like 
CMake, but not for build systems like GN or Bazel.

This is motivated by our use case. We use GN and build with `-Werror`. We 
continuously test against tip-of-tree Clang to catch and report issues early. 
That becomes a problem when new warnings are introduced that trigger errors in 
our codebase. Since these can take anywhere from few days to a few weeks to 
address, we prefer suppressing the warning first while we do the cleanup.

We cannot use `-Wno-newly-introduced-warning` because our platform Clang 
doesn't yet recognize that warning, so instead we have to use 
`-Wno-unknown-warning-option`, but that may let other invalid warning options 
into our codebase (for example, misspelled warning options).

With this change, we can use `-Wstart-no-unknown-warning-option 
-Wno-newly-introduced-warning -Wend-no-unknown-warning-option` to only suppress 
the newly introduced warning.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121175

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


[PATCH] D121095: [C++20][Modules][HU 1/5] Introduce header units as a module type.

2022-03-13 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu accepted this revision.
ChuanqiXu added a comment.
This revision is now accepted and ready to land.

LGTM with suggested changes.




Comment at: clang/include/clang/Sema/Sema.h:2978-2980
+  /// The parser has begun a translation unit to be compiled as a C++20
+  /// Header Unit.
+  void ActOnStartOfHeaderUnit();

iains wrote:
> ChuanqiXu wrote:
> > From the implementation, I think it should be called only in 
> > `ActOnStartOfTranslationUnit`. So it would be better to move this function 
> > to private section to avoid accident calls. We should add such constraint 
> > as assumption or at least comment to tell it should be called by 
> > `ActOnStartOfTranslationUnit`.
> > 
> > ---
> > 
> > The name `ActOnStartOf*` implies there should be a corresponding 
> > `ActOnEndOf*`  methods. But there isn't one. So I would suggest to give 
> > another name to avoid ambiguity.
> > From the implementation, I think it should be called only in 
> > `ActOnStartOfTranslationUnit`. So it would be better to move this function 
> > to private section to avoid accident calls. We should add such constraint 
> > as assumption or at least comment to tell it should be called by 
> > `ActOnStartOfTranslationUnit`.
> 
> OK, I've made this private and updated the comment to note that this is a 
> helper for ActOnStartOfTranslationUnit
> 
> > ---
> > 
> > The name `ActOnStartOf*` implies there should be a corresponding 
> > `ActOnEndOf*`  methods. But there isn't one. So I would suggest to give 
> > another name to avoid ambiguity.
> 
> Is this a rule?
> 
> I think that the name `ActOnStartOfHeaderUnit()` says exactly what we are 
> doing, of course, at some time we might need an `ActOnEndOfHeaderUnit()` - 
> but we should not add an empty function for that reason.
> 
> (this is not a sticking point; if consensus is that the name is confusing, I 
> will change it).
> 
I don't find the rule that there must be a pair for `ActOnStartOf*` and 
`ActOnEndOf*`. I just find almost all other methods does so. For the 
consistency problem, I would still suggest to change the name to something else.



Comment at: clang/lib/AST/Decl.cpp:1573-1574
   InternalLinkage = isInAnonymousNamespace();
-return InternalLinkage ? M->Parent : nullptr;
+return InternalLinkage ? M->Kind == Module::ModuleHeaderUnit ? M : 
M->Parent
+   : nullptr;
   }

iains wrote:
> ChuanqiXu wrote:
> > How about
> > ```
> > return InternalLinkage ? M->getTopLevelModule() : nullptr; 
> > ```
> that would alter the behaviour of the existing code.
> 
> getTopLevelModule() will return the ultimate parent:
> ```
>   const Module *Result = this;
>   while (Result->Parent)
> Result = Result->Parent;
> ```
> where the existing code only returns the immediate parent (perhaps that is 
> unintended, but it should be fixed separately if so).
> 
I am sure that in C++20 modules, there would be 2 levels of hierarchy at most. 
I am OK to fix it later (Hope we don't forget it.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121095

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


[PATCH] D121096: [C++20][Modules][HU 2/5] Support searching Header Units in user or system search paths.

2022-03-13 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu accepted this revision.
ChuanqiXu added a comment.
This revision is now accepted and ready to land.

LGTM except we should remove the dead error emitting.




Comment at: clang/lib/Frontend/CompilerInvocation.cpp:2796-2797
+// not intended to be a module map or header unit.
+IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap &&
+   HUK == InputKind::HeaderUnit_None;
 

iains wrote:
> ChuanqiXu wrote:
> > Oh, now I find `Header` and `HeaderUnit` might be a little bit confusing. 
> > It looks like `Header` should include `HeaderUnit` at the first sight. It 
> > is not true. But I don't have only suggestions...
> We have an amount of existing handling specific to "generic headers".
>  (header unit = none, header = true)
> 
> The intention is that HeaderUnitKind is used to disambiguate the cases we are 
> dealing with C+=20 header units.
> 
> I am not sure it would be worth the code churn to replace all uses of header 
> with a HUK.
OK, this is a historical problem. It makes no sense require us to fix it in 
this patch.



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:2855-2857
+  assert((DashX.getHeaderUnit() == InputKind::HeaderUnit_None ||
+  Inputs.size() == 1) &&
+ "Expected only one input file for header unit");

iains wrote:
> ChuanqiXu wrote:
> > So the compiler would crash if there is multiple inputs for header unit? I 
> > feel it is not most friendly. How about emitting an error here?
> well the driver is supposed to catch these problems (in the case of C++20 
> modules mode it will generate several compile jobs, one per header).
> 
> I added an error for this tho.
Oh, so if the compiler wouldn't crash in that case, I think the original 
assertion is acceptable. And the current error is dead code, which is bad. 
Let's take the original assertion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121096

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


[PATCH] D100692: clang-tidy: discover binaries in build dir

2022-03-13 Thread Keith Smiley via Phabricator via cfe-commits
keith updated this revision to Diff 414975.
keith added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D100692

Files:
  clang-tools-extra/clang-tidy/tool/run-clang-tidy.py

Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- run-clang-tidy.py - Parallel clang-tidy runner *- python -*--===#
 #
@@ -41,6 +41,7 @@
 import json
 import multiprocessing
 import os
+import queue
 import re
 import shutil
 import subprocess
@@ -54,13 +55,6 @@
 except ImportError:
   yaml = None
 
-is_py2 = sys.version[0] == '2'
-
-if is_py2:
-import Queue as queue
-else:
-import queue as queue
-
 
 def strtobool(val):
   """Convert a string representation of truth to a bool following LLVM's CLI argument parsing."""
@@ -158,20 +152,29 @@
 open(mergefile, 'w').close()
 
 
-def check_clang_apply_replacements_binary(args):
-  """Checks if invoking supplied clang-apply-replacements binary works."""
-  try:
-subprocess.check_call([args.clang_apply_replacements_binary, '--version'])
-  except:
-print('Unable to run clang-apply-replacements. Is clang-apply-replacements '
-  'binary correctly specified?', file=sys.stderr)
-traceback.print_exc()
-sys.exit(1)
+def find_binary(arg, name, build_path):
+  """Get the path for a binary or exit"""
+  if arg:
+if shutil.which(arg):
+  return arg
+else:
+  raise SystemExit(
+"error: passed binary '{}' was not found or is not executable"
+.format(arg))
 
+  built_path = os.path.join(build_path, "bin", name)
+  binary = shutil.which(name) or shutil.which(built_path)
+  if binary:
+return binary
+  else:
+raise SystemExit(
+  "error: failed to find {} in $PATH or at {}"
+  .format(name, built_path))
 
-def apply_fixes(args, tmpdir):
+
+def apply_fixes(args, clang_apply_replacements_binary, tmpdir):
   """Calls clang-apply-fixes on a given directory."""
-  invocation = [args.clang_apply_replacements_binary]
+  invocation = [clang_apply_replacements_binary]
   if args.format:
 invocation.append('-format')
   if args.style:
@@ -180,11 +183,12 @@
   subprocess.call(invocation)
 
 
-def run_tidy(args, tmpdir, build_path, queue, lock, failed_files):
+def run_tidy(args, clang_tidy_binary, tmpdir, build_path, queue, lock,
+ failed_files):
   """Takes filenames out of queue and runs clang-tidy on them."""
   while True:
 name = queue.get()
-invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
+invocation = get_tidy_invocation(name, clang_tidy_binary, args.checks,
  tmpdir, build_path, args.header_filter,
  args.allow_enabling_alpha_checkers,
  args.extra_arg, args.extra_arg_before,
@@ -210,15 +214,13 @@
   parser = argparse.ArgumentParser(description='Runs clang-tidy over all files '
'in a compilation database. Requires '
'clang-tidy and clang-apply-replacements in '
-   '$PATH.')
+   '$PATH or in your build directory.')
   parser.add_argument('-allow-enabling-alpha-checkers',
   action='store_true', help='allow alpha checkers from '
 'clang-analyzer.')
   parser.add_argument('-clang-tidy-binary', metavar='PATH',
-  default='clang-tidy',
   help='path to clang-tidy binary')
   parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
-  default='clang-apply-replacements',
   help='path to clang-apply-replacements binary')
   parser.add_argument('-checks', default=None,
   help='checks filter, when not specified, use clang-tidy '
@@ -278,8 +280,18 @@
 # Find our database
 build_path = find_compilation_database(db_path)
 
+  clang_tidy_binary = find_binary(args.clang_tidy_binary, "clang-tidy",
+  build_path)
+
+  tmpdir = None
+  if args.fix or (yaml and args.export_fixes):
+clang_apply_replacements_binary = find_binary(
+  args.clang_apply_replacements_binary, "clang-apply-replacements",
+  build_path)
+tmpdir = tempfile.mkdtemp()
+
   try:
-invocation = get_tidy_invocation("", args.clang_tidy_binary, args.checks,
+invocation = get_tidy_invocation("", clang_tidy_binary, args.checks,
  None, build_path, args.header_filter,
  args.allow_enabling_alpha_checkers,
   

[PATCH] D121445: [Clang][CSKY] Add the CSKY target and compiler driver

2022-03-13 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu added inline comments.



Comment at: clang/lib/Basic/Targets/CSKY.cpp:43
+  Builder.defineMacro("__CSKYABI__", ABI == "abiv2" ? "2" : "1");
+  Builder.defineMacro("__cskyabi__", ABI == "abiv2" ? "2" : "1");
+

DavidSpickett wrote:
> Any need to handle when ABI is not avbiv2 or abiv1 or will it always be one 
> of the two?
Yes. It always be one of the two.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121445

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


[PATCH] D111579: [clang] Fix DIFile directory root on Windows

2022-03-13 Thread Keith Smiley via Phabricator via cfe-commits
keith updated this revision to Diff 414976.
keith added a comment.
Herald added a project: All.

Remove variables from test expectations

This didn't work out because of the double vs single slash of the expansions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111579

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-prefix-map.c


Index: clang/test/CodeGen/debug-prefix-map.c
===
--- clang/test/CodeGen/debug-prefix-map.c
+++ clang/test/CodeGen/debug-prefix-map.c
@@ -1,10 +1,10 @@
-// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=/UNLIKELY_PATH/empty %s -emit-llvm -o - | FileCheck %s 
-check-prefix CHECK-NO-MAIN-FILE-NAME
-// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=/UNLIKELY_PATH=empty %s -emit-llvm -o - | FileCheck %s 
-check-prefix CHECK-EVIL
-// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=/UNLIKELY_PATH/empty %s -emit-llvm -o - -main-file-name 
debug-prefix-map.c | FileCheck %s
-// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=/UNLIKELY_PATH/empty %s -emit-llvm -o - 
-fdebug-compilation-dir %p | FileCheck %s -check-prefix CHECK-COMPILATION-DIR
-// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=/UNLIKELY_PATH/empty %s -emit-llvm -o - -isysroot %p 
-debugger-tuning=lldb | FileCheck %s -check-prefix CHECK-SYSROOT
-// RUN: %clang -g -fdebug-prefix-map=%p=/UNLIKELY_PATH/empty -S -c %s 
-emit-llvm -o - | FileCheck %s
-// RUN: %clang -g -ffile-prefix-map=%p=/UNLIKELY_PATH/empty -S -c %s 
-emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH%{fssep}empty %s -emit-llvm -o - 
| FileCheck %s -check-prefix CHECK-NO-MAIN-FILE-NAME
+// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH=empty %s -emit-llvm -o - | 
FileCheck %s -check-prefix CHECK-EVIL
+// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH%{fssep}empty %s -emit-llvm -o - 
-main-file-name debug-prefix-map.c | FileCheck %s
+// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH%{fssep}empty %s -emit-llvm -o - 
-fdebug-compilation-dir %p | FileCheck %s -check-prefix CHECK-COMPILATION-DIR
+// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH%{fssep}empty %s -emit-llvm -o - 
-isysroot %p -debugger-tuning=lldb | FileCheck %s -check-prefix CHECK-SYSROOT
+// RUN: %clang -g -fdebug-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH%{fssep}empty 
-S -c %s -emit-llvm -o - | FileCheck %s
+// RUN: %clang -g -ffile-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH%{fssep}empty 
-S -c %s -emit-llvm -o - | FileCheck %s
 
 #include "Inputs/stdio.h"
 
@@ -19,26 +19,24 @@
   vprintf("string", argp);
 }
 
-// CHECK-NO-MAIN-FILE-NAME: !DIFile(filename: 
"/UNLIKELY_PATH/empty{{/|}}"
-// CHECK-NO-MAIN-FILE-NAME: !DIFile(filename: 
"/UNLIKELY_PATH/empty{{/|}}{{.*}}",
-// On POSIX systems "Dir" should actually be empty, but on Windows we
-// can't recognize "/UNLIKELY_PATH" as being an absolute path.
-// CHECK-NO-MAIN-FILE-NAME-SAME:directory: "{{()|(.*:.*)}}")
-// CHECK-NO-MAIN-FILE-NAME: !DIFile(filename: 
"/UNLIKELY_PATH/empty{{/|}}Inputs/stdio.h",
-// CHECK-NO-MAIN-FILE-NAME-SAME:directory: "{{()|(.*:.*)}}")
+// CHECK-NO-MAIN-FILE-NAME: !DIFile(filename: 
"{{/|\w:}}UNLIKELY_PATH{{/|}}empty{{/|}}",
+// CHECK-NO-MAIN-FILE-NAME: !DIFile(filename: 
"{{/|\w:}}UNLIKELY_PATH{{/|}}empty{{/|}}{{.*}}",
+// CHECK-NO-MAIN-FILE-NAME-SAME:directory: "")
+// CHECK-NO-MAIN-FILE-NAME: !DIFile(filename: 
"{{/|\w:}}UNLIKELY_PATH{{/|}}empty{{/|}}Inputs{{/|}}stdio.h",
+// CHECK-NO-MAIN-FILE-NAME-SAME:directory: "")
 // CHECK-NO-MAIN-FILE-NAME-NOT: !DIFile(filename:
 
-// CHECK-EVIL: !DIFile(filename: "/UNLIKELY_PATH=empty{{/|}}{{.*}}"
-// CHECK-EVIL: !DIFile(filename: 
"/UNLIKELY_PATH=empty{{/|}}{{.*}}Inputs/stdio.h",
-// CHECK-EVIL-SAME:directory: "{{()|(.*:.*)}}")
+// CHECK-EVIL: !DIFile(filename: 
"{{/|\w:}}UNLIKELY_PATH=empty{{/|}}{{.*}}"
+// CHECK-EVIL: !DIFile(filename: 
"{{/|\w:}}UNLIKELY_PATH=empty{{/|}}{{.*}}Inputs{{/|}}stdio.h",
+// CHECK-EVIL-SAME:directory: "")
 // CHECK-EVIL-NOT: !DIFile(filename:
 
-// CHECK: !DIFile(filename: "/UNLIKELY_PATH/empty{{/|}}{{.*}}"
-// CHECK: !DIFile(filename: 
"/UNLIKELY_PATH/empty{{/|}}{{.*}}Inputs/stdio.h",
-// CHECK-SAME:directory: "{{()|(.*:.*)}}")
+// CHECK: !DIFile(filename: 
"{{/|\w:}}UNLIKELY_PATH{{/|}}empty{{/|}}{{.*}}",
+// CHECK: !DIFile(filename: 
"{{/|\w:}}UNLIKELY_PATH{{/|}}empty{{/|}}{{.*}}Inputs{{/|}}stdio.h",
+// CHECK-SAME:directory: ""
 // CHECK-NOT: !DIFile(filename:
 
-// CHECK-COMPILATION

[PATCH] D111457: [test] Add lit helper for windows paths

2022-03-13 Thread Keith Smiley via Phabricator via cfe-commits
keith added a comment.
Herald added a project: All.

@compnerd can you re-review here? I think I covered your feedback, let me know!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111457

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


[PATCH] D121345: [RISCV] Add +experimental-zvfh extension to cover half types in vectors.

2022-03-13 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng added inline comments.



Comment at: llvm/lib/Support/RISCVISAInfo.cpp:727
 
+  if (Exts.count("zvfh") && !Exts.count("zfh") && !Exts.count("zhinx"))
+return createStringError(

Zvfh require `Zfhmin` rather than `Zfh`

Spec: `The Zvfh extension additionally requires the Zfhmin extension.`
https://github.com/riscv/riscv-v-spec/pull/780/files#diff-ea57dd7a8daf0aa62f553688c1970c8e6608945d25597f8661c5ea6670fb509cR5182



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121345

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


[PATCH] D121097: [C++20][Modules][HU 3/5] Emit module macros for header units.

2022-03-13 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

Maybe it's worth to add a test from: http://eel.is/c++draft/cpp.import#8




Comment at: clang/include/clang/Serialization/ASTWriter.h:127-128
 
+  /// The module is a header unit.
+  bool IsHeaderUnit = false;
+

I think the member is redundant. I thought we could use 
`WritingModule->isHeaderUnit()` to replace it.



Comment at: clang/lib/Serialization/ASTWriter.cpp:2287-2288
 /// preprocessor.
-void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
+void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule,
+  Module *Mod) {
   uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();

We could replace the use of `Mod` with WritingModule too. (If I don't misread 
the code)



Comment at: clang/lib/Serialization/ASTWriter.cpp:2358-2378
+bool EmittedModuleMacros = false;
+if (IsHeaderUnit) {
+  // This is for the main TU when it is a C++20 header unit.
+  // We preserve the final state of defined macros, and we do not emit ones
+  // that are undefined.
+  if (!MD || shouldIgnoreMacro(MD, IsModule, PP) ||
+  MD->getKind() == MacroDirective::MD_Undefine)

Is it possible to merge the implementation with the following for PCH? It looks 
like there are some redundancies.



Comment at: clang/lib/Serialization/ASTWriter.cpp:2360-2362
+  // This is for the main TU when it is a C++20 header unit.
+  // We preserve the final state of defined macros, and we do not emit ones
+  // that are undefined.

How about to add comments to show the **different logic** of emitting macros 
for header unit and PCH? I guess other readers might be confusing too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121097

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


[PATCH] D121445: [Clang][CSKY] Add the CSKY target and compiler driver

2022-03-13 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu added inline comments.



Comment at: clang/test/Driver/csky-arch.c:26
+
+// RUN: %clang -target csky-unknown-elf -march=csky -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=CSKY %s

rengolin wrote:
> I don't think this is doing what you expect it to do.
> 
> Depending on the output, you can still match all CHECK lines and not have the 
> output you want.
> 
> To avoid issues, we usually separate tests that must pass (positive tests) 
> like the lines above 24, from tests that must fail (negative tests) like the 
> lines below.
You mean separate into two files or two parts in one file?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121445

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


[PATCH] D121098: [C++20][Modules][HU 4/5] Handle pre-processed header units.

2022-03-13 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

It lacks tests. This is not NFC, right?

---

I am a little bit confused for the intuition. Couldn't we just import the 
pre-processed header? What's the problem? Could you elaborate on this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121098

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


[PATCH] D121177: [modules] Merge equivalent extensions and diagnose ivar redeclarations for extensions loaded from different modules.

2022-03-13 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu accepted this revision.
ChuanqiXu added a comment.
This revision is now accepted and ready to land.

OK, if it is prohibited. It looks good to me. Please wait for a few days before 
landing in case there are other comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121177

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


[PATCH] D121559: [clang-format] Fix crash on asm block with label

2022-03-13 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

This patch also fixed 4 out of 6 of the same assertion failures on the .c files 
under `clang/test`. The remaining two are:

1. Analysis/inline-plist.c (#54367 
)
2. Sema/attr-external-source-symbol.c (54368 
)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121559

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


[clang] 93b5505 - [clang-format] Extract doc for entire configuration structs

2022-03-13 Thread via cfe-commits

Author: sstwcw
Date: 2022-03-14T04:41:40Z
New Revision: 93b5505b456f75ff33be20402b0317cbb2131a66

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

LOG: [clang-format] Extract doc for entire configuration structs

Previously the comments for configuration structs as a whole like
`BraceWrappingFlags` did not go into the doc.

Reviewed By: curdeius

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/tools/dump_format_style.py

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 9b5d9ee7ef298..c1af14466dd0e 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -1212,6 +1212,14 @@ the configuration (without a prefix: ``Auto``).
 
   Nested configuration flags:
 
+  Precise control over the wrapping of braces.
+
+  .. code-block:: c++
+
+# Should be declared this way:
+BreakBeforeBraces: Custom
+BraceWrapping:
+AfterClass: true
 
   * ``bool AfterCaseLabel`` Wrap case labels.
 
@@ -3992,6 +4000,15 @@ the configuration (without a prefix: ``Auto``).
 
   Nested configuration flags:
 
+  Precise control over the spacing before parentheses.
+
+  .. code-block:: c++
+
+# Should be declared this way:
+SpaceBeforeParens: Custom
+SpaceBeforeParensOptions:
+  AfterControlStatements: true
+  AfterFunctionDefinitionName: true
 
   * ``bool AfterControlStatements`` If ``true``, put space betwee control 
statement keywords
 (for/if/while...) and opening parentheses.
@@ -4221,6 +4238,7 @@ the configuration (without a prefix: ``Auto``).
 
   Nested configuration flags:
 
+  Control of spaces within a single line comment
 
   * ``unsigned Minimum`` The minimum number of spaces at the start of the 
comment.
 

diff  --git a/clang/docs/tools/dump_format_style.py 
b/clang/docs/tools/dump_format_style.py
index d04920987ec67..fb074435e753e 100755
--- a/clang/docs/tools/dump_format_style.py
+++ b/clang/docs/tools/dump_format_style.py
@@ -118,7 +118,7 @@ def __init__(self, name, comment):
 self.values = []
 
   def __str__(self):
-return '\n'.join(map(str, self.values))
+return self.comment + '\n' + '\n'.join(map(str, self.values))
 
 class NestedField(object):
   def __init__(self, name, comment):



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


[clang] c24b3db - [clang-format] Add option to align compound assignments like `+=`

2022-03-13 Thread via cfe-commits

Author: sstwcw
Date: 2022-03-14T04:41:40Z
New Revision: c24b3db45c7d0f08b423308723cd2e678a0cb7f1

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

LOG: [clang-format] Add option to align compound assignments like `+=`

Reviewed By: curdeius, HazardyKnusperkeks, MyDeveloperDay

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/FormatTestJS.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index c1af14466dd0e..a9e35fdceb810 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -281,70 +281,120 @@ the configuration (without a prefix: ``Auto``).
 int somelongname = 2;
 double c = 3;
 
-  Possible values:
+  Nested configuration flags:
+
+  Alignment options.
+
+  They can also be read as a whole for compatibility. The choices are:
+  - None
+  - Consecutive
+  - AcrossEmptyLines
+  - AcrossComments
+  - AcrossEmptyLinesAndComments
+
+  For example, to align across empty lines and not across comments, either
+  of these work.
+
+  .. code-block:: c++
+
+AlignConsecutiveMacros: AcrossEmptyLines
 
-  * ``ACS_None`` (in configuration: ``None``)
- Do not align assignments on consecutive lines.
+AlignConsecutiveMacros:
+  Enabled: true
+  AcrossEmptyLines: true
+  AcrossComments: false
 
-  * ``ACS_Consecutive`` (in configuration: ``Consecutive``)
- Align assignments on consecutive lines. This will result in
- formattings like:
+  * ``bool Enabled`` Whether aligning is enabled.
 
- .. code-block:: c++
+.. code-block:: c++
+
+  #define SHORT_NAME   42
+  #define LONGER_NAME  0x007f
+  #define EVEN_LONGER_NAME (2)
+  #define foo(x)   (x * x)
+  #define bar(y, z)(y + z)
 
-   int a= 1;
-   int somelongname = 2;
-   double c = 3;
+  int a= 1;
+  int somelongname = 2;
+  double c = 3;
 
-   int d = 3;
-   /* A comment. */
-   double e = 4;
+  int  : 1;
+  int b: 12;
+  int ccc  : 8;
 
-  * ``ACS_AcrossEmptyLines`` (in configuration: ``AcrossEmptyLines``)
- Same as ACS_Consecutive, but also spans over empty lines, e.g.
+  int  = 12;
+  float   b = 23;
+  std::string ccc;
 
- .. code-block:: c++
+  * ``bool AcrossEmptyLines`` Whether to align across empty lines.
 
-   int a= 1;
-   int somelongname = 2;
-   double c = 3;
+.. code-block:: c++
 
-   int d= 3;
-   /* A comment. */
-   double e = 4;
+  true:
+  int a= 1;
+  int somelongname = 2;
+  double c = 3;
 
-  * ``ACS_AcrossComments`` (in configuration: ``AcrossComments``)
- Same as ACS_Consecutive, but also spans over lines only containing
- comments, e.g.
+  int d= 3;
 
- .. code-block:: c++
+  false:
+  int a= 1;
+  int somelongname = 2;
+  double c = 3;
 
-   int a= 1;
-   int somelongname = 2;
-   double c = 3;
+  int d = 3;
 
-   int d= 3;
-   /* A comment. */
-   double e = 4;
+  * ``bool AcrossComments`` Whether to align across comments.
 
-  * ``ACS_AcrossEmptyLinesAndComments``
-(in configuration: ``AcrossEmptyLinesAndComments``)
+.. code-block:: c++
 
- Same as ACS_Consecutive, but also spans over lines only containing
- comments and empty lines, e.g.
+  true:
+  int d= 3;
+  /* A comment. */
+  double e = 4;
 
- .. code-block:: c++
+  false:
+  int d = 3;
+  /* A comment. */
+  double e = 4;
+
+  * ``bool AlignCompound`` Only for ``AlignConsecutiveAssignments``.  Whether 
compound
+assignments like ``+=`` are aligned along with ``=``.
+
+.. code-block:: c++
+
+  true:
+  a   &= 2;
+  bbb  = 2;
+
+  false:
+  a &= 2;
+  bbb = 2;
+
+  * ``bool PadOperators`` Only for ``AlignConsecutiveAssignments``.  Whether 
short
+assignment operators are left-padded to the same length as long
+ones in order to put all assignment operators to the right of
+the left hand side.
+
+.. code-block:: c++
+
+  true:
+  a   >>= 2;
+  bbb   = 2;
+
+  a = 2;
+  bbb >>= 2;
+
+  false:
+  a >>= 2;
+  bbb = 2;
 
-   int a= 1;
-   int somelongname = 2;
-   double c = 3;
+  a = 2;
+  bbb >>=

[PATCH] D120361: [clang-format] Extract doc for entire configuration structs

2022-03-13 Thread sstwcw 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 rG93b5505b456f: [clang-format] Extract doc for entire 
configuration structs (authored by sstwcw).
Herald added a project: All.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120361

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/tools/dump_format_style.py


Index: clang/docs/tools/dump_format_style.py
===
--- clang/docs/tools/dump_format_style.py
+++ clang/docs/tools/dump_format_style.py
@@ -118,7 +118,7 @@
 self.values = []
 
   def __str__(self):
-return '\n'.join(map(str, self.values))
+return self.comment + '\n' + '\n'.join(map(str, self.values))
 
 class NestedField(object):
   def __init__(self, name, comment):
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -1212,6 +1212,14 @@
 
   Nested configuration flags:
 
+  Precise control over the wrapping of braces.
+
+  .. code-block:: c++
+
+# Should be declared this way:
+BreakBeforeBraces: Custom
+BraceWrapping:
+AfterClass: true
 
   * ``bool AfterCaseLabel`` Wrap case labels.
 
@@ -3992,6 +4000,15 @@
 
   Nested configuration flags:
 
+  Precise control over the spacing before parentheses.
+
+  .. code-block:: c++
+
+# Should be declared this way:
+SpaceBeforeParens: Custom
+SpaceBeforeParensOptions:
+  AfterControlStatements: true
+  AfterFunctionDefinitionName: true
 
   * ``bool AfterControlStatements`` If ``true``, put space betwee control 
statement keywords
 (for/if/while...) and opening parentheses.
@@ -4221,6 +4238,7 @@
 
   Nested configuration flags:
 
+  Control of spaces within a single line comment
 
   * ``unsigned Minimum`` The minimum number of spaces at the start of the 
comment.
 


Index: clang/docs/tools/dump_format_style.py
===
--- clang/docs/tools/dump_format_style.py
+++ clang/docs/tools/dump_format_style.py
@@ -118,7 +118,7 @@
 self.values = []
 
   def __str__(self):
-return '\n'.join(map(str, self.values))
+return self.comment + '\n' + '\n'.join(map(str, self.values))
 
 class NestedField(object):
   def __init__(self, name, comment):
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -1212,6 +1212,14 @@
 
   Nested configuration flags:
 
+  Precise control over the wrapping of braces.
+
+  .. code-block:: c++
+
+# Should be declared this way:
+BreakBeforeBraces: Custom
+BraceWrapping:
+AfterClass: true
 
   * ``bool AfterCaseLabel`` Wrap case labels.
 
@@ -3992,6 +4000,15 @@
 
   Nested configuration flags:
 
+  Precise control over the spacing before parentheses.
+
+  .. code-block:: c++
+
+# Should be declared this way:
+SpaceBeforeParens: Custom
+SpaceBeforeParensOptions:
+  AfterControlStatements: true
+  AfterFunctionDefinitionName: true
 
   * ``bool AfterControlStatements`` If ``true``, put space betwee control statement keywords
 (for/if/while...) and opening parentheses.
@@ -4221,6 +4238,7 @@
 
   Nested configuration flags:
 
+  Control of spaces within a single line comment
 
   * ``unsigned Minimum`` The minimum number of spaces at the start of the comment.
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119599: [clang-format] Add option to align compound assignments like `+=`

2022-03-13 Thread sstwcw 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 rGc24b3db45c7d: [clang-format] Add option to align compound 
assignments like `+=` (authored by sstwcw).

Changed prior to commit:
  https://reviews.llvm.org/D119599?vs=414347&id=414986#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119599

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/FormatTestJS.cpp

Index: clang/unittests/Format/FormatTestJS.cpp
===
--- clang/unittests/Format/FormatTestJS.cpp
+++ clang/unittests/Format/FormatTestJS.cpp
@@ -2699,7 +2699,7 @@
 
 TEST_F(FormatTestJS, AlignConsecutiveDeclarations) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
-  Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
+  Style.AlignConsecutiveDeclarations.Enabled = true;
   verifyFormat("letletVariable = 5;\n"
"double constVariable = 10;",
Style);
@@ -2736,7 +2736,7 @@
 TEST_F(FormatTestJS, AlignConsecutiveAssignments) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
 
-  Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
+  Style.AlignConsecutiveAssignments.Enabled = true;
   verifyFormat("let letVariable  = 5;\n"
"double constVariable = 10;",
Style);
@@ -2772,8 +2772,8 @@
 
 TEST_F(FormatTestJS, AlignConsecutiveAssignmentsAndDeclarations) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
-  Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
-  Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
+  Style.AlignConsecutiveDeclarations.Enabled = true;
+  Style.AlignConsecutiveAssignments.Enabled = true;
   verifyFormat("letletVariable   = 5;\n"
"double constVariable = 10;",
Style);
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -2083,7 +2083,7 @@
   " res2 = [](int &a) { return 0; };",
   Style);
 
-  Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
+  Style.AlignConsecutiveDeclarations.Enabled = true;
   verifyFormat("Const unsigned int *c;\n"
"const unsigned int *d;\n"
"Const unsigned int &e;\n"
@@ -2124,7 +2124,7 @@
   "res2 = [](int& a) { return 0; };",
   Style);
 
-  Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
+  Style.AlignConsecutiveDeclarations.Enabled = true;
   verifyFormat("Const unsigned int* c;\n"
"const unsigned int* d;\n"
"Const unsigned int& e;\n"
@@ -2145,7 +2145,7 @@
   verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style);
   verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style);
 
-  Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
+  Style.AlignConsecutiveDeclarations.Enabled = true;
   verifyFormat("Const unsigned int *c;\n"
"const unsigned int *d;\n"
"Const unsigned int& e;\n"
@@ -2181,7 +2181,7 @@
   " res2 = [](int & a) { return 0; };",
   Style);
 
-  Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
+  Style.AlignConsecutiveDeclarations.Enabled = true;
   verifyFormat("Const unsigned int*  c;\n"
"const unsigned int*  d;\n"
"Const unsigned int & e;\n"
@@ -14515,8 +14515,8 @@
"*/\n"
"}",
Tab));
-  Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
-  Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
+  Tab.AlignConsecutiveAssignments.Enabled = true;
+  Tab.AlignConsecutiveDeclarations.Enabled = true;
   Tab.TabWidth = 4;
   Tab.IndentWidth = 4;
   verifyFormat("class Assign {\n"
@@ -14754,8 +14754,8 @@
"*/\n"
"}",
Tab));
-  Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
-  Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
+  Tab.AlignConsecutiveAssignments.Enabled = true;
+  Tab.AlignConsecutiveDeclarations.Enabled = true;
   Tab.TabWidth = 4;
   Tab.IndentWidth = 4;
   verifyFormat("class Assign {\n"
@@ -15925,9 +15925,8 @@
 
 TEST_F(FormatTest, AlignConsecutiveMacros) {
   FormatStyle Style = getLLVMStyle();
-  Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
-  Style.AlignConsecutiveDeclarations =

[PATCH] D111579: [clang] Fix DIFile directory root on Windows

2022-03-13 Thread Keith Smiley via Phabricator via cfe-commits
keith updated this revision to Diff 415004.
keith added a comment.

Replace \w with .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111579

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-prefix-map.c


Index: clang/test/CodeGen/debug-prefix-map.c
===
--- clang/test/CodeGen/debug-prefix-map.c
+++ clang/test/CodeGen/debug-prefix-map.c
@@ -1,10 +1,10 @@
-// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=/UNLIKELY_PATH/empty %s -emit-llvm -o - | FileCheck %s 
-check-prefix CHECK-NO-MAIN-FILE-NAME
-// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=/UNLIKELY_PATH=empty %s -emit-llvm -o - | FileCheck %s 
-check-prefix CHECK-EVIL
-// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=/UNLIKELY_PATH/empty %s -emit-llvm -o - -main-file-name 
debug-prefix-map.c | FileCheck %s
-// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=/UNLIKELY_PATH/empty %s -emit-llvm -o - 
-fdebug-compilation-dir %p | FileCheck %s -check-prefix CHECK-COMPILATION-DIR
-// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=/UNLIKELY_PATH/empty %s -emit-llvm -o - -isysroot %p 
-debugger-tuning=lldb | FileCheck %s -check-prefix CHECK-SYSROOT
-// RUN: %clang -g -fdebug-prefix-map=%p=/UNLIKELY_PATH/empty -S -c %s 
-emit-llvm -o - | FileCheck %s
-// RUN: %clang -g -ffile-prefix-map=%p=/UNLIKELY_PATH/empty -S -c %s 
-emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH%{fssep}empty %s -emit-llvm -o - 
| FileCheck %s -check-prefix CHECK-NO-MAIN-FILE-NAME
+// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH=empty %s -emit-llvm -o - | 
FileCheck %s -check-prefix CHECK-EVIL
+// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH%{fssep}empty %s -emit-llvm -o - 
-main-file-name debug-prefix-map.c | FileCheck %s
+// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH%{fssep}empty %s -emit-llvm -o - 
-fdebug-compilation-dir %p | FileCheck %s -check-prefix CHECK-COMPILATION-DIR
+// RUN: %clang_cc1 -debug-info-kind=standalone 
-fdebug-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH%{fssep}empty %s -emit-llvm -o - 
-isysroot %p -debugger-tuning=lldb | FileCheck %s -check-prefix CHECK-SYSROOT
+// RUN: %clang -g -fdebug-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH%{fssep}empty 
-S -c %s -emit-llvm -o - | FileCheck %s
+// RUN: %clang -g -ffile-prefix-map=%p=%{fssrcroot}UNLIKELY_PATH%{fssep}empty 
-S -c %s -emit-llvm -o - | FileCheck %s
 
 #include "Inputs/stdio.h"
 
@@ -19,26 +19,24 @@
   vprintf("string", argp);
 }
 
-// CHECK-NO-MAIN-FILE-NAME: !DIFile(filename: 
"/UNLIKELY_PATH/empty{{/|}}"
-// CHECK-NO-MAIN-FILE-NAME: !DIFile(filename: 
"/UNLIKELY_PATH/empty{{/|}}{{.*}}",
-// On POSIX systems "Dir" should actually be empty, but on Windows we
-// can't recognize "/UNLIKELY_PATH" as being an absolute path.
-// CHECK-NO-MAIN-FILE-NAME-SAME:directory: "{{()|(.*:.*)}}")
-// CHECK-NO-MAIN-FILE-NAME: !DIFile(filename: 
"/UNLIKELY_PATH/empty{{/|}}Inputs/stdio.h",
-// CHECK-NO-MAIN-FILE-NAME-SAME:directory: "{{()|(.*:.*)}}")
+// CHECK-NO-MAIN-FILE-NAME: !DIFile(filename: 
"{{/|.:}}UNLIKELY_PATH{{/|}}empty{{/|}}",
+// CHECK-NO-MAIN-FILE-NAME: !DIFile(filename: 
"{{/|.:}}UNLIKELY_PATH{{/|}}empty{{/|}}{{.*}}",
+// CHECK-NO-MAIN-FILE-NAME-SAME:directory: "")
+// CHECK-NO-MAIN-FILE-NAME: !DIFile(filename: 
"{{/|.:}}UNLIKELY_PATH{{/|}}empty{{/|}}Inputs{{/|}}stdio.h",
+// CHECK-NO-MAIN-FILE-NAME-SAME:directory: "")
 // CHECK-NO-MAIN-FILE-NAME-NOT: !DIFile(filename:
 
-// CHECK-EVIL: !DIFile(filename: "/UNLIKELY_PATH=empty{{/|}}{{.*}}"
-// CHECK-EVIL: !DIFile(filename: 
"/UNLIKELY_PATH=empty{{/|}}{{.*}}Inputs/stdio.h",
-// CHECK-EVIL-SAME:directory: "{{()|(.*:.*)}}")
+// CHECK-EVIL: !DIFile(filename: 
"{{/|.:}}UNLIKELY_PATH=empty{{/|}}{{.*}}"
+// CHECK-EVIL: !DIFile(filename: 
"{{/|.:}}UNLIKELY_PATH=empty{{/|}}{{.*}}Inputs{{/|}}stdio.h",
+// CHECK-EVIL-SAME:directory: "")
 // CHECK-EVIL-NOT: !DIFile(filename:
 
-// CHECK: !DIFile(filename: "/UNLIKELY_PATH/empty{{/|}}{{.*}}"
-// CHECK: !DIFile(filename: 
"/UNLIKELY_PATH/empty{{/|}}{{.*}}Inputs/stdio.h",
-// CHECK-SAME:directory: "{{()|(.*:.*)}}")
+// CHECK: !DIFile(filename: 
"{{/|.:}}UNLIKELY_PATH{{/|}}empty{{/|}}{{.*}}",
+// CHECK: !DIFile(filename: 
"{{/|.:}}UNLIKELY_PATH{{/|}}empty{{/|}}{{.*}}Inputs{{/|}}stdio.h",
+// CHECK-SAME:directory: ""
 // CHECK-NOT: !DIFile(filename:
 
-// CHECK-COMPILATION-DIR: !DIFile(filename: "{{.*}}", directory: 
"/UNLIKELY_PATH/empty")
-// CHECK-COMPILATION-DIR: !DIFile(filename: "{{.*}}Inputs/stdio.h

[PATCH] D121445: [Clang][CSKY] Add the CSKY target and compiler driver

2022-03-13 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu updated this revision to Diff 415006.
zixuan-wu added a comment.
Herald added subscribers: llvm-commits, hiraditya.
Herald added a project: LLVM.

Address comments.


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

https://reviews.llvm.org/D121445

Files:
  clang/lib/Basic/CMakeLists.txt
  clang/lib/Basic/Targets.cpp
  clang/lib/Basic/Targets/CSKY.cpp
  clang/lib/Basic/Targets/CSKY.h
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Arch/CSKY.cpp
  clang/lib/Driver/ToolChains/Arch/CSKY.h
  clang/lib/Driver/ToolChains/CSKYToolChain.cpp
  clang/lib/Driver/ToolChains/CSKYToolChain.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/test/Driver/Inputs/multilib_csky_linux_sdk/csky-linux-gnuabiv2/bin/ld
  
clang/test/Driver/Inputs/multilib_csky_linux_sdk/csky-linux-gnuabiv2/libc/ck860v/lib/.keep
  
clang/test/Driver/Inputs/multilib_csky_linux_sdk/csky-linux-gnuabiv2/libc/ck860v/usr/lib/crt1.o
  
clang/test/Driver/Inputs/multilib_csky_linux_sdk/csky-linux-gnuabiv2/libc/lib/.keep
  
clang/test/Driver/Inputs/multilib_csky_linux_sdk/csky-linux-gnuabiv2/libc/usr/lib/crt1.o
  
clang/test/Driver/Inputs/multilib_csky_linux_sdk/lib/gcc/csky-linux-gnuabiv2/6.3.0/ck860v/crtbegin.o
  
clang/test/Driver/Inputs/multilib_csky_linux_sdk/lib/gcc/csky-linux-gnuabiv2/6.3.0/ck860v/crtend.o
  
clang/test/Driver/Inputs/multilib_csky_linux_sdk/lib/gcc/csky-linux-gnuabiv2/6.3.0/ck860v/crti.o
  
clang/test/Driver/Inputs/multilib_csky_linux_sdk/lib/gcc/csky-linux-gnuabiv2/6.3.0/ck860v/crtn.o
  
clang/test/Driver/Inputs/multilib_csky_linux_sdk/lib/gcc/csky-linux-gnuabiv2/6.3.0/crtbegin.o
  
clang/test/Driver/Inputs/multilib_csky_linux_sdk/lib/gcc/csky-linux-gnuabiv2/6.3.0/crtend.o
  
clang/test/Driver/Inputs/multilib_csky_linux_sdk/lib/gcc/csky-linux-gnuabiv2/6.3.0/crti.o
  
clang/test/Driver/Inputs/multilib_csky_linux_sdk/lib/gcc/csky-linux-gnuabiv2/6.3.0/crtn.o
  clang/test/Driver/csky-arch-error.c
  clang/test/Driver/csky-arch.c
  clang/test/Driver/csky-cpus.c
  clang/test/Driver/csky-toolchain.c
  clang/test/Preprocessor/csky-target-features.c
  clang/test/Preprocessor/init-csky.c
  llvm/lib/Target/CSKY/CSKY.h

Index: llvm/lib/Target/CSKY/CSKY.h
===
--- llvm/lib/Target/CSKY/CSKY.h
+++ llvm/lib/Target/CSKY/CSKY.h
@@ -19,6 +19,7 @@
 namespace llvm {
 class CSKYTargetMachine;
 class FunctionPass;
+class PassRegistry;
 
 FunctionPass *createCSKYISelDag(CSKYTargetMachine &TM);
 FunctionPass *createCSKYConstantIslandPass();
Index: clang/test/Preprocessor/init-csky.c
===
--- /dev/null
+++ clang/test/Preprocessor/init-csky.c
@@ -0,0 +1,212 @@
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 -triple=csky < /dev/null \
+// RUN:   | FileCheck -match-full-lines -check-prefix=CSKY %s
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 -triple=csky-unknown-linux < /dev/null \
+// RUN:   | FileCheck -match-full-lines -check-prefixes=CSKY,CSKY-LINUX %s
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 -triple=csky \
+// RUN: -fforce-enable-int128 < /dev/null | FileCheck -match-full-lines \
+// RUN: -check-prefixes=CSKY,CSKY-INT128 %s
+// CSKY: #define _ILP32 1
+// CSKY: #define __ATOMIC_ACQUIRE 2
+// CSKY: #define __ATOMIC_ACQ_REL 4
+// CSKY: #define __ATOMIC_CONSUME 1
+// CSKY: #define __ATOMIC_RELAXED 0
+// CSKY: #define __ATOMIC_RELEASE 3
+// CSKY: #define __ATOMIC_SEQ_CST 5
+// CSKY: #define __BIGGEST_ALIGNMENT__ 4
+// CSKY: #define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
+// CSKY: #define __CHAR16_TYPE__ unsigned short
+// CSKY: #define __CHAR32_TYPE__ unsigned int
+// CSKY: #define __CHAR_BIT__ 8
+// CSKY: #define __DBL_DECIMAL_DIG__ 17
+// CSKY: #define __DBL_DENORM_MIN__ 4.9406564584124654e-324
+// CSKY: #define __DBL_DIG__ 15
+// CSKY: #define __DBL_EPSILON__ 2.2204460492503131e-16
+// CSKY: #define __DBL_HAS_DENORM__ 1
+// CSKY: #define __DBL_HAS_INFINITY__ 1
+// CSKY: #define __DBL_HAS_QUIET_NAN__ 1
+// CSKY: #define __DBL_MANT_DIG__ 53
+// CSKY: #define __DBL_MAX_10_EXP__ 308
+// CSKY: #define __DBL_MAX_EXP__ 1024
+// CSKY: #define __DBL_MAX__ 1.7976931348623157e+308
+// CSKY: #define __DBL_MIN_10_EXP__ (-307)
+// CSKY: #define __DBL_MIN_EXP__ (-1021)
+// CSKY: #define __DBL_MIN__ 2.2250738585072014e-308
+// CSKY: #define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
+// CSKY: #define __ELF__ 1
+// CSKY: #define __FINITE_MATH_ONLY__ 0
+// CSKY: #define __FLT_DECIMAL_DIG__ 9
+// CSKY: #define __FLT_DENORM_MIN__ 1.40129846e-45F
+// CSKY: #define __FLT_DIG__ 6
+// CSKY: #define __FLT_EPSILON__ 1.19209290e-7F
+// CSKY: #define __FLT_HAS_DENORM__ 1
+// CSKY: #define __FLT_HAS_INFINITY__ 1
+// CSKY: #define __FLT_HAS_QUIET_NAN__ 1
+// CSKY: #define __FLT_MANT_DIG__ 24
+// CSKY: #define __FLT_MAX_10_EX

[clang] 9e0fc67 - [clang][dataflow] Model the behavior of various optional members

2022-03-13 Thread Stanislav Gatev via cfe-commits

Author: Stanislav Gatev
Date: 2022-03-14T06:50:14Z
New Revision: 9e0fc67683781fe4bd9bc4085084faec1126b41b

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

LOG: [clang][dataflow] Model the behavior of various optional members

Model `make_optional`, optional's default constructor, `emplace`,
`reset`, and `operator bool` members.

Reviewed-by: xazax.hun

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

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Removed: 




diff  --git 
a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp 
b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
index bb6aa5ff74e2c..0963e8e452448 100644
--- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -11,6 +11,8 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 #include 
+#include 
+#include 
 
 namespace clang {
 namespace dataflow {
@@ -41,6 +43,21 @@ static auto isOptionalOperatorCallWithName(llvm::StringRef 
OperatorName) {
  callee(cxxMethodDecl(ofClass(optionalClass();
 }
 
+static auto isMakeOptionalCall() {
+  return callExpr(
+  callee(functionDecl(hasAnyName(
+  "std::make_optional", "base::make_optional", 
"absl::make_optional"))),
+  hasOptionalType());
+}
+
+/// Creates a symbolic value for an `optional` value using `HasValueVal` as the
+/// symbolic value of its "has_value" property.
+StructValue &createOptionalValue(Environment &Env, BoolValue &HasValueVal) {
+  auto OptionalVal = std::make_unique();
+  OptionalVal->setProperty("has_value", HasValueVal);
+  return Env.takeOwnership(std::move(OptionalVal));
+}
+
 /// Returns the symbolic value that represents the "has_value" property of the
 /// optional value `Val`. Returns null if `Val` is null.
 static BoolValue *getHasValue(Value *Val) {
@@ -75,6 +92,13 @@ static void transferUnwrapCall(const Expr *UnwrapExpr, const 
Expr *ObjectExpr,
   State.Lattice.getSourceLocations().insert(ObjectExpr->getBeginLoc());
 }
 
+void transferMakeOptionalCall(const CallExpr *E, LatticeTransferState &State) {
+  auto &Loc = State.Env.createStorageLocation(*E);
+  State.Env.setStorageLocation(*E, Loc);
+  State.Env.setValue(
+  Loc, createOptionalValue(State.Env, 
State.Env.getBoolLiteralValue(true)));
+}
+
 static void transferOptionalHasValueCall(const CXXMemberCallExpr *CallExpr,
  LatticeTransferState &State) {
   if (auto *OptionalVal = cast_or_null(
@@ -89,6 +113,26 @@ static void transferOptionalHasValueCall(const 
CXXMemberCallExpr *CallExpr,
   }
 }
 
+void transferEmplaceCall(const CXXMemberCallExpr *E,
+ LatticeTransferState &State) {
+  if (auto *OptionalLoc = State.Env.getStorageLocation(
+  *E->getImplicitObjectArgument(), SkipPast::ReferenceThenPointer)) {
+State.Env.setValue(
+*OptionalLoc,
+createOptionalValue(State.Env, State.Env.getBoolLiteralValue(true)));
+  }
+}
+
+void transferResetCall(const CXXMemberCallExpr *E,
+   LatticeTransferState &State) {
+  if (auto *OptionalLoc = State.Env.getStorageLocation(
+  *E->getImplicitObjectArgument(), SkipPast::ReferenceThenPointer)) {
+State.Env.setValue(
+*OptionalLoc,
+createOptionalValue(State.Env, State.Env.getBoolLiteralValue(false)));
+  }
+}
+
 static auto buildTransferMatchSwitch() {
   return MatchSwitchBuilder()
   // Attach a symbolic "has_value" state to optional values that we see for
@@ -96,6 +140,9 @@ static auto buildTransferMatchSwitch() {
   .CaseOf(expr(anyOf(declRefExpr(), memberExpr()), hasOptionalType()),
   initializeOptionalReference)
 
+  // make_optional
+  .CaseOf(isMakeOptionalCall(), transferMakeOptionalCall)
+
   // optional::value
   .CaseOf(
   isOptionalMemberCallWithName("value"),
@@ -115,6 +162,16 @@ static auto buildTransferMatchSwitch() {
   .CaseOf(isOptionalMemberCallWithName("has_value"),
   transferOptionalHasValueCall)
 
+  // optional::operator bool
+  .CaseOf(isOptionalMemberCallWithName("operator bool"),
+  transferOptionalHasValueCall)
+
+  // optional::emplace
+  .CaseOf(isOptionalMemberCallWithName("emplace"), transferEmplaceCall)
+
+  // optional::reset
+  .CaseOf(isOptionalMemberCallWithName("reset"), transferResetCall)
+
   .Build();
 }
 

diff  --git 
a/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp 
b/clang/unittests/Analysis

[PATCH] D121378: [clang][dataflow] Model the behavior of various optional members

2022-03-13 Thread Stanislav Gatev via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
sgatev marked an inline comment as done.
Closed by commit rG9e0fc6768378: [clang][dataflow] Model the behavior of 
various optional members (authored by sgatev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121378

Files:
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -29,9 +29,23 @@
 using ::testing::Pair;
 using ::testing::UnorderedElementsAre;
 
+// FIXME: Move header definitions in separate file(s).
 static constexpr char StdTypeTraitsHeader[] = R"(
+#ifndef TYPE_TRAITS_H
+#define TYPE_TRAITS_H
+
 namespace std {
 
+typedef decltype(sizeof(char)) size_t;
+
+template 
+struct integral_constant {
+  static constexpr T value = V;
+};
+
+using true_type = integral_constant;
+using false_type = integral_constant;
+
 template< class T > struct remove_reference  {typedef T type;};
 template< class T > struct remove_reference  {typedef T type;};
 template< class T > struct remove_reference {typedef T type;};
@@ -39,21 +53,135 @@
 template 
   using remove_reference_t = typename remove_reference::type;
 
+template 
+struct remove_extent {
+  typedef T type;
+};
+
+template 
+struct remove_extent {
+  typedef T type;
+};
+
+template 
+struct remove_extent {
+  typedef T type;
+};
+
+template 
+struct is_array : false_type {};
+
+template 
+struct is_array : true_type {};
+
+template 
+struct is_array : true_type {};
+
+template 
+struct is_function : false_type {};
+
+template 
+struct is_function : true_type {};
+
+namespace detail {
+
+template 
+struct type_identity {
+  using type = T;
+};  // or use type_identity (since C++20)
+
+template 
+auto try_add_pointer(int) -> type_identity::type*>;
+template 
+auto try_add_pointer(...) -> type_identity;
+
+}  // namespace detail
+
+template 
+struct add_pointer : decltype(detail::try_add_pointer(0)) {};
+
+template 
+struct conditional {
+  typedef T type;
+};
+
+template 
+struct conditional {
+  typedef F type;
+};
+
+template 
+struct remove_cv {
+  typedef T type;
+};
+template 
+struct remove_cv {
+  typedef T type;
+};
+template 
+struct remove_cv {
+  typedef T type;
+};
+template 
+struct remove_cv {
+  typedef T type;
+};
+
+template 
+struct decay {
+ private:
+  typedef typename remove_reference::type U;
+
+ public:
+  typedef typename conditional<
+  is_array::value, typename remove_extent::type*,
+  typename conditional::value, typename add_pointer::type,
+   typename remove_cv::type>::type>::type type;
+};
+
 } // namespace std
+
+#endif // TYPE_TRAITS_H
 )";
 
 static constexpr char StdUtilityHeader[] = R"(
+#ifndef UTILITY_H
+#define UTILITY_H
+
 #include "std_type_traits.h"
 
 namespace std {
 
 template 
-constexpr std::remove_reference_t&& move(T&& x);
+constexpr remove_reference_t&& move(T&& x);
+
+} // namespace std
+
+#endif // UTILITY_H
+)";
+
+static constexpr char StdInitializerListHeader[] = R"(
+#ifndef INITIALIZER_LIST_H
+#define INITIALIZER_LIST_H
+
+namespace std {
+
+template 
+class initializer_list {
+ public:
+  initializer_list() noexcept;
+};
 
 } // namespace std
+
+#endif // INITIALIZER_LIST_H
 )";
 
 static constexpr char StdOptionalHeader[] = R"(
+#include "std_initializer_list.h"
+#include "std_type_traits.h"
+#include "std_utility.h"
+
 namespace std {
 
 template 
@@ -74,13 +202,41 @@
   const T&& value() const&&;
   T&& value() &&;
 
+  template 
+  constexpr T value_or(U&& v) const&;
+  template 
+  T value_or(U&& v) &&;
+
+  template 
+  T& emplace(Args&&... args);
+
+  template 
+  T& emplace(std::initializer_list ilist, Args&&... args);
+
+  void reset() noexcept;
+
+  constexpr explicit operator bool() const noexcept;
   constexpr bool has_value() const noexcept;
 };
 
+template 
+constexpr optional::type> make_optional(T&& v);
+
+template 
+constexpr optional make_optional(Args&&... args);
+
+template 
+constexpr optional make_optional(std::initializer_list il,
+Args&&... args);
+
 } // namespace std
 )";
 
 static constexpr char AbslOptionalHeader[] = R"(
+#include "std_initializer_list.h"
+#include "std_type_traits.h"
+#include "std_utility.h"
+
 namespace absl {
 
 template 
@@ -101,13 +257,41 @@
   const T&& value() const&&;
   T&& value() &&;
 
+  template 
+  constexpr T value_or(U&& v) const&;
+  template 
+  T value_or(U&& v) &&;
+
+  template 
+  T& emplace(Args&&... args);
+
+  template 
+  T& emplace(std::i