[PATCH] D115604: [Support] Expand `` as the base directory in configuration files.

2021-12-29 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added inline comments.



Comment at: llvm/lib/Support/CommandLine.cpp:1099
+else
+  llvm::sys::path::append(ResponseFile, LHS);
+ResponseFile.append(BasePath);

What happens if `` is used without trailing path? Such line:
```
--sysroot= -abc
```
 would be processed correctly?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115604

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


[PATCH] D116395: [Clang] Emit warning for -x option without effects

2021-12-29 Thread Qiu Chaofan via Phabricator via cfe-commits
qiucf created this revision.
qiucf added reviewers: rsmith, hans, thakis, awarzynski, brad, phosek.
qiucf requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Things might be confusing for people not familiar with how this option works. 
Add this warning like GCC.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116395

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/redundant-args.c


Index: clang/test/Driver/redundant-args.c
===
--- clang/test/Driver/redundant-args.c
+++ clang/test/Driver/redundant-args.c
@@ -1,2 +1,4 @@
-// RUN: %clang -target x86_64-apple-darwin10 \
-// RUN:   -Werror -x c -x c -fsyntax-only %s
+// RUN: %clang -target x86_64-apple-darwin10 -Werror -x c -x c -fsyntax-only %s
+// RUN: %clang -target x86_64-apple-darwin10 %s -### -x c 2>&1 | FileCheck %s
+
+// CHECK: warning: '-x c' after last input file has no effect
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2269,6 +2269,7 @@
 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
   }
 
+  size_t InputsBeforeOptX = 0;
   for (Arg *A : Args) {
 if (A->getOption().getKind() == Option::InputClass) {
   const char *Value = A->getValue();
@@ -2387,6 +2388,7 @@
   InputTypeArg = A;
   InputType = types::lookupTypeForTypeSpecifier(A->getValue());
   A->claim();
+  InputsBeforeOptX = Inputs.size();
 
   // Follow gcc behavior and treat as linker input for invalid -x
   // options. Its not clear why we shouldn't just revert to unknown; but
@@ -2411,6 +2413,8 @@
 Arg *A = MakeInputArg(Args, Opts, "-");
 Inputs.push_back(std::make_pair(types::TY_C, A));
   }
+  if (Inputs.size() == InputsBeforeOptX && InputTypeArg != nullptr)
+Diag(diag::warn_drv_ignored_option_x) << InputTypeArg->getValue(0);
 }
 
 namespace {
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -568,6 +568,9 @@
   "'%0' does not support '-%1'; flag ignored">,
   InGroup;
 
+def warn_drv_ignored_option_x : Warning<
+  "'-x %0' after last input file has no effect">, InGroup;
+
 def warn_drv_darwin_sdk_invalid_settings : Warning<
   "SDK settings were ignored as 'SDKSettings.json' could not be parsed">,
   InGroup>;


Index: clang/test/Driver/redundant-args.c
===
--- clang/test/Driver/redundant-args.c
+++ clang/test/Driver/redundant-args.c
@@ -1,2 +1,4 @@
-// RUN: %clang -target x86_64-apple-darwin10 \
-// RUN:   -Werror -x c -x c -fsyntax-only %s
+// RUN: %clang -target x86_64-apple-darwin10 -Werror -x c -x c -fsyntax-only %s
+// RUN: %clang -target x86_64-apple-darwin10 %s -### -x c 2>&1 | FileCheck %s
+
+// CHECK: warning: '-x c' after last input file has no effect
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2269,6 +2269,7 @@
 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
   }
 
+  size_t InputsBeforeOptX = 0;
   for (Arg *A : Args) {
 if (A->getOption().getKind() == Option::InputClass) {
   const char *Value = A->getValue();
@@ -2387,6 +2388,7 @@
   InputTypeArg = A;
   InputType = types::lookupTypeForTypeSpecifier(A->getValue());
   A->claim();
+  InputsBeforeOptX = Inputs.size();
 
   // Follow gcc behavior and treat as linker input for invalid -x
   // options. Its not clear why we shouldn't just revert to unknown; but
@@ -2411,6 +2413,8 @@
 Arg *A = MakeInputArg(Args, Opts, "-");
 Inputs.push_back(std::make_pair(types::TY_C, A));
   }
+  if (Inputs.size() == InputsBeforeOptX && InputTypeArg != nullptr)
+Diag(diag::warn_drv_ignored_option_x) << InputTypeArg->getValue(0);
 }
 
 namespace {
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -568,6 +568,9 @@
   "'%0' does not support '-%1'; flag ignored">,
   InGroup;
 
+def warn_drv_ignored_option_x : Warning<
+  "'-x %0' after last input file has no effect">, InGroup;
+
 def warn_drv_darwin_sdk_invalid_settings : Warning<
   "SDK settings were ignored as 'SDKSettings.json' could not be parsed">,
   InGroup>;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2021-12-29 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:23224
+
+  EXPECT_EQ("if (a)\n"
+"  if (b)\n"

owenpan wrote:
> MyDeveloperDay wrote:
> > any reason these can't be verifyFormats?
> Did you mean to add the expected part as a separate case? I don't think it 
> would add any value if there are no braces to remove in the first place?
> Did you mean to add the expected part as a separate case? I don't think it 
> would add any value if there are no braces to remove in the first place?

Nvm. I think you wanted something like `verifyFormat(PostformatCode, 
PreformatCode, Style)`? Yes, I could do that, but I would have to relax the 
restriction to calling `BracesRemover()` in Format.cpp, i.e. checking `isCpp()` 
instead.


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

https://reviews.llvm.org/D116316

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


[PATCH] D116003: [NFC] Specify targets for clang stack-protector-guard.c

2021-12-29 Thread Qiu Chaofan 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 rG4039d17355b7: [NFC] Specify targets for clang 
stack-protector-guard.c (authored by qiucf).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116003

Files:
  clang/test/CodeGen/stack-protector-guard.c


Index: clang/test/CodeGen/stack-protector-guard.c
===
--- clang/test/CodeGen/stack-protector-guard.c
+++ clang/test/CodeGen/stack-protector-guard.c
@@ -1,16 +1,25 @@
-// RUN: %clang_cc1 -mstack-protector-guard=sysreg \
-// RUN:-mstack-protector-guard-reg=sp_el0 \
-// RUN:-mstack-protector-guard-offset=1024 \
-// RUN:-emit-llvm %s -o - | FileCheck %s
-// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck --check-prefix=CHECK-NONE %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple x86_64-linux-gnu \
+// RUN:   -mstack-protector-guard-offset=1024 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple 
powerpc64le-linux-gnu \
+// RUN:   -mstack-protector-guard-offset=1024 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple arm-linux-gnueabi \
+// RUN:   -mstack-protector-guard-offset=1024 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple 
thumbv7-linux-gnueabi \
+// RUN:   -mstack-protector-guard-offset=1024 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple aarch64-linux-gnu \
+// RUN:   -mstack-protector-guard-offset=1024 
-mstack-protector-guard-reg=sp_el0 \
+// RUN:   -emit-llvm %s -o - | FileCheck %s --check-prefix=AARCH64
 void foo(int*);
 void bar(int x) {
   int baz[x];
   foo(baz);
 }
 
-// CHECK: !llvm.module.flags = !{{{.*}}[[ATTR1:![0-9]+]], [[ATTR2:![0-9]+]], 
[[ATTR3:![0-9]+]]}
+// CHECK: !llvm.module.flags = !{{{.*}}[[ATTR1:![0-9]+]], [[ATTR2:![0-9]+]]}
 // CHECK: [[ATTR1]] = !{i32 1, !"stack-protector-guard", !"sysreg"}
-// CHECK: [[ATTR2]] = !{i32 1, !"stack-protector-guard-reg", !"sp_el0"}
-// CHECK: [[ATTR3]] = !{i32 1, !"stack-protector-guard-offset", i32 1024}
-// CHECK-NONE-NOT: !"stack-protector-guard
+// CHECK: [[ATTR2]] = !{i32 1, !"stack-protector-guard-offset", i32 1024}
+
+// AARCH64: !llvm.module.flags = !{{{.*}}[[ATTR1:![0-9]+]], [[ATTR2:![0-9]+]], 
[[ATTR3:![0-9]+]]}
+// AARCH64: [[ATTR1]] = !{i32 1, !"stack-protector-guard", !"sysreg"}
+// AARCH64: [[ATTR2]] = !{i32 1, !"stack-protector-guard-reg", !"sp_el0"}
+// AARCH64: [[ATTR3]] = !{i32 1, !"stack-protector-guard-offset", i32 1024}


Index: clang/test/CodeGen/stack-protector-guard.c
===
--- clang/test/CodeGen/stack-protector-guard.c
+++ clang/test/CodeGen/stack-protector-guard.c
@@ -1,16 +1,25 @@
-// RUN: %clang_cc1 -mstack-protector-guard=sysreg \
-// RUN:-mstack-protector-guard-reg=sp_el0 \
-// RUN:-mstack-protector-guard-offset=1024 \
-// RUN:-emit-llvm %s -o - | FileCheck %s
-// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck --check-prefix=CHECK-NONE %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple x86_64-linux-gnu \
+// RUN:   -mstack-protector-guard-offset=1024 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple powerpc64le-linux-gnu \
+// RUN:   -mstack-protector-guard-offset=1024 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple arm-linux-gnueabi \
+// RUN:   -mstack-protector-guard-offset=1024 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple thumbv7-linux-gnueabi \
+// RUN:   -mstack-protector-guard-offset=1024 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple aarch64-linux-gnu \
+// RUN:   -mstack-protector-guard-offset=1024 -mstack-protector-guard-reg=sp_el0 \
+// RUN:   -emit-llvm %s -o - | FileCheck %s --check-prefix=AARCH64
 void foo(int*);
 void bar(int x) {
   int baz[x];
   foo(baz);
 }
 
-// CHECK: !llvm.module.flags = !{{{.*}}[[ATTR1:![0-9]+]], [[ATTR2:![0-9]+]], [[ATTR3:![0-9]+]]}
+// CHECK: !llvm.module.flags = !{{{.*}}[[ATTR1:![0-9]+]], [[ATTR2:![0-9]+]]}
 // CHECK: [[ATTR1]] = !{i32 1, !"stack-protector-guard", !"sysreg"}
-// CHECK: [[ATTR2]] = !{i32 1, !"stack-protector-guard-reg", !"sp_el0"}
-// CHECK: [[ATTR3]] = !{i32 1, !"stack-protector-guard-offset", i32 1024}
-// CHECK-NONE-NOT: !"stack-protector-guard
+// CHECK: [[ATTR2]] = !{i32 1, !"stack-protector-guard-offset", i32 1024}
+
+// AARCH64: !llvm.module.flags = !{{{.*}}[[ATTR1:![0-9]+]], [[ATTR2:![0-9]+]], [[ATTR3:![0-9]+]]}
+// AARCH64: [[ATTR1]] = !{i32 1, !"stack-protector-guard", !"sysreg"}
+// AARCH64: [[ATTR2]] = !{i32 1, !"stack-protector-guard-reg", !"sp_el0"}
+// 

[clang] 4039d17 - [NFC] Specify targets for clang stack-protector-guard.c

2021-12-29 Thread Qiu Chaofan via cfe-commits

Author: Qiu Chaofan
Date: 2021-12-30T10:13:41+08:00
New Revision: 4039d17355b7dc54d847d05d8685912cf081a113

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

LOG: [NFC] Specify targets for clang stack-protector-guard.c

The run line of stack-protector-guard.c doesn't specify the triple,
which means it depends on the platform running the test. This makes
some failure hidden.

Reviewed By: nickdesaulniers

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

Added: 


Modified: 
clang/test/CodeGen/stack-protector-guard.c

Removed: 




diff  --git a/clang/test/CodeGen/stack-protector-guard.c 
b/clang/test/CodeGen/stack-protector-guard.c
index a5483ba0f1942..5839ab06033a1 100644
--- a/clang/test/CodeGen/stack-protector-guard.c
+++ b/clang/test/CodeGen/stack-protector-guard.c
@@ -1,16 +1,25 @@
-// RUN: %clang_cc1 -mstack-protector-guard=sysreg \
-// RUN:-mstack-protector-guard-reg=sp_el0 \
-// RUN:-mstack-protector-guard-offset=1024 \
-// RUN:-emit-llvm %s -o - | FileCheck %s
-// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck --check-prefix=CHECK-NONE %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple x86_64-linux-gnu \
+// RUN:   -mstack-protector-guard-offset=1024 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple 
powerpc64le-linux-gnu \
+// RUN:   -mstack-protector-guard-offset=1024 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple arm-linux-gnueabi \
+// RUN:   -mstack-protector-guard-offset=1024 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple 
thumbv7-linux-gnueabi \
+// RUN:   -mstack-protector-guard-offset=1024 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -mstack-protector-guard=sysreg -triple aarch64-linux-gnu \
+// RUN:   -mstack-protector-guard-offset=1024 
-mstack-protector-guard-reg=sp_el0 \
+// RUN:   -emit-llvm %s -o - | FileCheck %s --check-prefix=AARCH64
 void foo(int*);
 void bar(int x) {
   int baz[x];
   foo(baz);
 }
 
-// CHECK: !llvm.module.flags = !{{{.*}}[[ATTR1:![0-9]+]], [[ATTR2:![0-9]+]], 
[[ATTR3:![0-9]+]]}
+// CHECK: !llvm.module.flags = !{{{.*}}[[ATTR1:![0-9]+]], [[ATTR2:![0-9]+]]}
 // CHECK: [[ATTR1]] = !{i32 1, !"stack-protector-guard", !"sysreg"}
-// CHECK: [[ATTR2]] = !{i32 1, !"stack-protector-guard-reg", !"sp_el0"}
-// CHECK: [[ATTR3]] = !{i32 1, !"stack-protector-guard-offset", i32 1024}
-// CHECK-NONE-NOT: !"stack-protector-guard
+// CHECK: [[ATTR2]] = !{i32 1, !"stack-protector-guard-offset", i32 1024}
+
+// AARCH64: !llvm.module.flags = !{{{.*}}[[ATTR1:![0-9]+]], [[ATTR2:![0-9]+]], 
[[ATTR3:![0-9]+]]}
+// AARCH64: [[ATTR1]] = !{i32 1, !"stack-protector-guard", !"sysreg"}
+// AARCH64: [[ATTR2]] = !{i32 1, !"stack-protector-guard-reg", !"sp_el0"}
+// AARCH64: [[ATTR3]] = !{i32 1, !"stack-protector-guard-offset", i32 1024}



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


[PATCH] D116387: [CodeCompletion][clangd] Clean __uglified parameter names in completion & hover

2021-12-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kbobyrev.
Herald added subscribers: dexonsmith, usaxena95, kadircet, arphaman.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added projects: clang, clang-tools-extra.

Underscore-uglified identifiers are used in standard library implementations to
guard against collisions with macros, and they hurt readability considerably.
(Consider `push_back(Tp_ &&__value)` vs `push_back(Tp value)`.
When we're describing an interface, the exact names of parameters are not
critical so we can drop these prefixes.

This patch adds a new PrintingPolicy flag that can applies this stripping
when recursively printing pieces of AST.
We set it in code completion/signature help, and in clangd's hover display.
All three features also do a bit of manual poking at names, so fix up those too.

Fixes https://github.com/clangd/clangd/issues/736


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116387

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp
  clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
  clang/include/clang/AST/PrettyPrinter.h
  clang/include/clang/Basic/IdentifierTable.h
  clang/lib/AST/DeclPrinter.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/AST/TemplateName.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/Basic/IdentifierTable.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/deuglify.cpp
  clang/unittests/AST/DeclPrinterTest.cpp
  clang/unittests/AST/StmtPrinterTest.cpp
  clang/unittests/AST/TypePrinterTest.cpp

Index: clang/unittests/AST/TypePrinterTest.cpp
===
--- clang/unittests/AST/TypePrinterTest.cpp
+++ clang/unittests/AST/TypePrinterTest.cpp
@@ -62,4 +62,21 @@
   ASSERT_TRUE(PrintedTypeMatches(
   Code, {}, Matcher, "const N::Type &",
   [](PrintingPolicy ) { Policy.FullyQualifiedName = true; }));
-}
\ No newline at end of file
+}
+
+TEST(TypePrinter, ParamsUglified) {
+  llvm::StringLiteral Code = R"cpp(
+template  class __f>
+const __f<_Tp&> *A = nullptr;
+  )cpp";
+  auto Clean = [](PrintingPolicy ) {
+Policy.CleanUglifiedParameters = true;
+  };
+
+  ASSERT_TRUE(PrintedTypeMatches(Code, {},
+ varDecl(hasType(qualType().bind("id"))),
+ "const __f<_Tp &> *", nullptr));
+  ASSERT_TRUE(PrintedTypeMatches(Code, {},
+ varDecl(hasType(qualType().bind("id"))),
+ "const f *", Clean));
+}
Index: clang/unittests/AST/StmtPrinterTest.cpp
===
--- clang/unittests/AST/StmtPrinterTest.cpp
+++ clang/unittests/AST/StmtPrinterTest.cpp
@@ -263,3 +263,22 @@
 
   [](PrintingPolicy ) { PP.TerseOutput = true; }));
 }
+
+TEST(StmtPrinter, ParamsUglified) {
+  llvm::StringLiteral Code = R"cpp(
+template  class _C>
+auto foo(int __j) {
+  return typename _C<_T>::_F(_I, __j);
+}
+  )cpp";
+  auto Clean = [](PrintingPolicy ) {
+Policy.CleanUglifiedParameters = true;
+  };
+
+  ASSERT_TRUE(PrintedStmtCXXMatches(StdVer::CXX14, Code,
+returnStmt().bind("id"),
+"return typename _C<_T>::_F(_I, __j);\n"));
+  ASSERT_TRUE(
+  PrintedStmtCXXMatches(StdVer::CXX14, Code, returnStmt().bind("id"),
+"return typename C::_F(I, j);\n", Clean));
+}
Index: clang/unittests/AST/DeclPrinterTest.cpp
===
--- clang/unittests/AST/DeclPrinterTest.cpp
+++ clang/unittests/AST/DeclPrinterTest.cpp
@@ -1336,6 +1336,41 @@
   ASSERT_TRUE(PrintedDeclCXX11Matches(Code, "NT2", "int NT2 = 5"));
 }
 
+TEST(DeclPrinter, TestFunctionParamUglified) {
+  llvm::StringLiteral Code = R"cpp(
+class __c;
+void _A(__c *__param);
+  )cpp";
+  auto Clean = [](PrintingPolicy ) {
+Policy.CleanUglifiedParameters = true;
+  };
+
+  ASSERT_TRUE(PrintedDeclCXX17Matches(Code, namedDecl(hasName("_A")).bind("id"),
+  "void _A(__c *__param)"));
+  ASSERT_TRUE(PrintedDeclCXX17Matches(Code, namedDecl(hasName("_A")).bind("id"),
+  "void _A(__c *param)", Clean));
+}
+
+TEST(DeclPrinter, TestTemplateParamUglified) {
+  llvm::StringLiteral Code = R"cpp(
+template  class _Container>
+struct _A{};
+  )cpp";
+  auto Clean = [](PrintingPolicy ) {
+Policy.CleanUglifiedParameters = true;
+  };
+
+  ASSERT_TRUE(PrintedDeclCXX17Matches(
+  Code, classTemplateDecl(hasName("_A")).bind("id"),
+  "template  class _Container> "
+  "struct _A {}"));
+  ASSERT_TRUE(PrintedDeclCXX17Matches(
+  Code, classTemplateDecl(hasName("_A")).bind("id"),
+  "template  class Container> "
+  "struct _A {}",
+  Clean));
+}
+
 

[PATCH] D116386: [clang-tidy] Narrow cppguidelines-macro-usage to actual constants

2021-12-29 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood created this revision.
LegalizeAdulthood added a reviewer: alexfh.
Herald added subscribers: carlosgalvezp, kbarton, xazax.hun, nemanjai.
LegalizeAdulthood requested review of this revision.
Herald added a project: clang-tools-extra.

Previously, any macro that didn't look like a varargs macro
or a function style macro was reported with a warning that
it should be replaced with a constexpr const declaration.
This is only reasonable when the macro body contains constants
and not expansions like ",", "[[noreturn]]", "__declspec(xxx)",
etc.

So instead of always issuing a warning about every macro that
doesn't look like a varargs or function style macro, examine the
tokens in the macro and only warn about the macro if it contains
only comment and constant tokens.

Fixes #39945


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116386

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-macro-usage.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-macro-usage.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-macro-usage.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-macro-usage.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s cppcoreguidelines-macro-usage %t -- -header-filter=.* -system-headers --
+// RUN: %check_clang_tidy %s cppcoreguidelines-macro-usage -std=c++17-or-later %t -- -header-filter=.* -system-headers --
 
 #ifndef INCLUDE_GUARD
 #define INCLUDE_GUARD
@@ -6,6 +6,21 @@
 #define PROBLEMATIC_CONSTANT 0
 // CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro 'PROBLEMATIC_CONSTANT' used to declare a constant; consider using a 'constexpr' constant
 
+#define PROBLEMATIC_CONSTANT_CHAR '0'
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro 'PROBLEMATIC_CONSTANT_CHAR' used to declare a constant; consider using a 'constexpr' constant
+
+#define PROBLEMATIC_CONSTANT_WIDE_CHAR L'0'
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro 'PROBLEMATIC_CONSTANT_WIDE_CHAR' used to declare a constant; consider using a 'constexpr' constant
+
+#define PROBLEMATIC_CONSTANT_UTF8_CHAR u8'0'
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro 'PROBLEMATIC_CONSTANT_UTF8_CHAR' used to declare a constant; consider using a 'constexpr' constant
+
+#define PROBLEMATIC_CONSTANT_UTF16_CHAR u'0'
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro 'PROBLEMATIC_CONSTANT_UTF16_CHAR' used to declare a constant; consider using a 'constexpr' constant
+
+#define PROBLEMATIC_CONSTANT_UTF32_CHAR U'0'
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro 'PROBLEMATIC_CONSTANT_UTF32_CHAR' used to declare a constant; consider using a 'constexpr' constant
+
 #define PROBLEMATIC_FUNCTION(x, y) ((a) > (b) ? (a) : (b))
 // CHECK-MESSAGES: [[@LINE-1]]:9: warning: function-like macro 'PROBLEMATIC_FUNCTION' used; consider a 'constexpr' template function
 
@@ -15,4 +30,17 @@
 #define PROBLEMATIC_VARIADIC2(x, ...) (__VA_ARGS__)
 // CHECK-MESSAGES: [[@LINE-1]]:9: warning: variadic macro 'PROBLEMATIC_VARIADIC2' used; consider using a 'constexpr' variadic template function
 
+// These are all examples of common macros that shouldn't have constexpr suggestions.
+#define COMMA ,
+
+#define NORETURN [[noreturn]]
+
+#define DEPRECATED attribute((deprecated))
+
+#if LIB_EXPORTS
+#define DLLEXPORTS __declspec(dllexport)
+#else
+#define DLLEXPORTS __declspec(dllimport)
+#endif
+
 #endif
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp
@@ -78,22 +78,52 @@
   this, SM, AllowedRegexp, CheckCapsOnly, IgnoreCommandLineMacros));
 }
 
+namespace {
+
+bool isConstantToken(const MacroDirective *MD) {
+  for (const auto  : MD->getMacroInfo()->tokens()) {
+switch (Token.getKind()) {
+case tok::comment:
+case tok::numeric_constant:
+case tok::char_constant:
+case tok::wide_char_constant:
+case tok::utf8_char_constant:
+case tok::utf16_char_constant:
+case tok::utf32_char_constant:
+case tok::string_literal:
+case tok::wide_string_literal:
+case tok::header_name:
+case tok::utf8_string_literal:
+case tok::utf16_string_literal:
+case tok::utf32_string_literal:
+  break;
+default:
+  return false;
+}
+  }
+  return true;
+}
+
+} // namespace
+
 void MacroUsageCheck::warnMacro(const MacroDirective *MD, StringRef MacroName) {
-  StringRef Message =
-  "macro '%0' used to declare a constant; consider using a 'constexpr' "
-  "constant";
+  StringRef Message;
 
+  if (isConstantToken(MD))
+Message = "macro '%0' used to declare a constant; consider using a "
+  "'constexpr' constant";
   /// A variadic macro is 

[PATCH] D116370: [clang][dataflow] Add multi-variable constant propagation example.

2021-12-29 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

In D116370#3213120 , @xazax.hun wrote:

> Does it make sense to have both the single and multi variable tracking tests? 
> Or do we want to have these as some sort of steps in a tutorial?

Right -- the intent in keeping the original one was for an (eventual) tutorial. 
 For that matter, if you think there's changes I should make to the single 
variable version to bring them closer together, I'd be happy to do that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116370

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


[PATCH] D116371: [clang-format] Support inheriting from more than 1 parents in the fallback case

2021-12-29 Thread Zhao Wei Liew via Phabricator via cfe-commits
zwliew updated this revision to Diff 396580.
zwliew added a comment.
Herald added a subscriber: cfe-commits.

Rebased on master for context.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116371

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -21480,8 +21480,8 @@
   ASSERT_TRUE((bool)StyleTd);
   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
 
-  // Test 9.1: overwriting a file style, when parent no file exists with no
-  // fallback style
+  // Test 9.1.1: overwriting a file style, when no parent file exists with no
+  // fallback style.
   ASSERT_TRUE(FS.addFile(
   "/e/sub/.clang-format", 0,
   llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
@@ -21496,6 +21496,25 @@
 return Style;
   }());
 
+  // Test 9.1.2: propagate more than one level with no parent file.
+  ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
+ llvm::MemoryBuffer::getMemBuffer("int i;")));
+  ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
+ llvm::MemoryBuffer::getMemBuffer(
+ "BasedOnStyle: InheritParentConfig\n"
+ "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
+  std::vector NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
+
+  ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
+  Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", );
+  ASSERT_TRUE(static_cast(Style9));
+  ASSERT_EQ(*Style9, [] {
+auto Style = getNoStyle();
+Style.ColumnLimit = 20;
+Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
+return Style;
+  }());
+
   // Test 9.2: with LLVM fallback style
   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", );
   ASSERT_TRUE(static_cast(Style9));
@@ -21519,15 +21538,7 @@
 return Style;
   }());
 
-  // Test 9.4: propagate more than one level
-  ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
- llvm::MemoryBuffer::getMemBuffer("int i;")));
-  ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
- llvm::MemoryBuffer::getMemBuffer(
- "BasedOnStyle: InheritParentConfig\n"
- "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
-  std::vector NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
-
+  // Test 9.4: propagate more than one level with a parent file.
   const auto SubSubStyle = [] {
 auto Style = getGoogleStyle();
 Style.ColumnLimit = 20;
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -3324,6 +3324,16 @@
 
   auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
 
+  auto applyChildFormatTexts = [&](FormatStyle *Style) {
+for (const auto  : llvm::reverse(ChildFormatTextToApply)) {
+  auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
+   dropDiagnosticHandler);
+  // It was already correctly parsed.
+  assert(!EC);
+  static_cast(EC);
+}
+  };
+
   for (StringRef Directory = Path; !Directory.empty();
Directory = llvm::sys::path::parent_path(Directory)) {
 
@@ -3363,14 +3373,7 @@
 return Style;
 
   LLVM_DEBUG(llvm::dbgs() << "Applying child configurations\n");
-
-  for (const auto  : llvm::reverse(ChildFormatTextToApply)) {
-auto Ec = parseConfiguration(*MemBuf, , AllowUnknownOptions,
- dropDiagnosticHandler);
-// It was already correctly parsed.
-assert(!Ec);
-static_cast(Ec);
-  }
+  applyChildFormatTexts();
 
   return Style;
 }
@@ -3396,17 +3399,9 @@
  UnsuitableConfigFiles);
 
   if (!ChildFormatTextToApply.empty()) {
-assert(ChildFormatTextToApply.size() == 1);
-
 LLVM_DEBUG(llvm::dbgs()
-   << "Applying child configuration on fallback style\n");
-
-auto Ec =
-parseConfiguration(*ChildFormatTextToApply.front(), ,
-   AllowUnknownOptions, dropDiagnosticHandler);
-// It was already correctly parsed.
-assert(!Ec);
-static_cast(Ec);
+   << "Applying child configurations on fallback style\n");
+applyChildFormatTexts();
   }
 
   return FallbackStyle;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2021-12-29 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2303
+  assert(IfRightBrace->MatchingParen == IfLeftBrace);
+  IfLeftBrace->MatchingParen = nullptr;
+  IfRightBrace->MatchingParen = nullptr;

HazardyKnusperkeks wrote:
> Why null that?
`MatchingParen` is used to flag braces that may be optional. If it turns out 
that they should not be removed, we must reset it. Otherwise, the test case on 
line 23314 in FormatTest.cpp below would fail.


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

https://reviews.llvm.org/D116316

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


[PATCH] D105169: [Clang/Test]: Rename enable_noundef_analysis to disable-noundef-analysis and turn it off by default

2021-12-29 Thread Hyeongyu Kim via Phabricator via cfe-commits
hyeongyukim added a comment.

Great. I'll check it out.

> I have a reproducer for the first two, as that is all I had time for; if you 
> would like them for the other two, I can get those for you tomorrow.

@nathanchance I think the other two can be reproduced without difficulty. If 
the reproduction fails, I will request it :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105169

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


[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2021-12-29 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/docs/ClangFormatStyleOptions.rst:3398
 
+**RemoveBracesLLVM** (``Boolean``) :versionbadge:`clang-format 14`
+  Remove optional braces of control statements (``if``, ``else``, ``for``,

MyDeveloperDay wrote:
> Can we agree on one set of options that can be used for both insertion and 
> removal even if this patch only does removal 
> Can we agree on one set of options that can be used for both insertion and 
> removal even if this patch only does removal 

One idea is to run insertion for all missing braces and then this option to 
remove the optional ones for LLVM, i.e., an `AutomaticBraces` if you will.



Comment at: clang/docs/ClangFormatStyleOptions.rst:3398
 
+**RemoveBracesLLVM** (``Boolean``) :versionbadge:`clang-format 14`
+  Remove optional braces of control statements (``if``, ``else``, ``for``,

curdeius wrote:
> I don't think it's a good idea to make this option dependent on a particular 
> style. Even if it works for LLVM style only for the moment.
> I don't think it's a good idea to make this option dependent on a particular 
> style. Even if it works for LLVM style only for the moment.

As @MyDeveloperDay said before, eliding braces was (by far?) the most frequent 
review comments, and the community would appreciate something like this. So 
it's likely that this option will get used and experimented, and we will get 
bug reports and other feedback to improve the functionalities. Once we think 
it's ready, we can easily configure/package the functionalities for other 
styles.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2338
+  KeepAncestorBraces();
+  NestedTooDeep.push_back(false);
   if (FormatTok->is(tok::l_brace)) {

HazardyKnusperkeks wrote:
> owenpan wrote:
> > HazardyKnusperkeks wrote:
> > > I think it is worth to create a RAII type for that.
> > Can you explain why an RAII type would be beneficial here?
> You have a lot of push/pop pairs. There is the risk someone (in the future) 
> may misuse it.
I see. I will think about it.



Comment at: clang/unittests/Format/FormatTest.cpp:23224
+
+  EXPECT_EQ("if (a)\n"
+"  if (b)\n"

MyDeveloperDay wrote:
> any reason these can't be verifyFormats?
Did you mean to add the expected part as a separate case? I don't think it 
would add any value if there are no braces to remove in the first place?


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

https://reviews.llvm.org/D116316

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


[PATCH] D105169: [Clang/Test]: Rename enable_noundef_analysis to disable-noundef-analysis and turn it off by default

2021-12-29 Thread Nathan Chancellor via Phabricator via cfe-commits
nathanchance added a comment.

@hyeongyukim I hand reduced a couple of the translation units that I see issues 
in so apologies if they are a little verbose.

The full set of warnings:

  drivers/net/ethernet/renesas/ravb.lto.o: warning: objtool: 
.text.ravb_set_gti: unexpected end of section
  drivers/net/ethernet/wiznet/w5100.lto.o: warning: objtool: 
.text.w5100_tx_skb: unexpected end of section
  drivers/net/ethernet/wiznet/w5100.lto.o: warning: objtool: 
.text.w5100_readbuf: unexpected end of section
  drivers/video/fbdev/intelfb/intelfb.lto.o: warning: objtool: 
.text.intelfbhw_validate_mode: unexpected end of section

which individually can be viewed at the following links:

https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/net/ethernet/renesas/ravb_main.c?h=v5.16-rc7#n2480
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/net/ethernet/wiznet/w5100.c?h=v5.16-rc7#n798
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/net/ethernet/wiznet/w5100.c?h=v5.16-rc7#n513
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/video/fbdev/intelfb/intelfbhw.c?h=v5.16-rc7#n313

I have a reproducer for the first two, as that is all I had time for; if you 
would like them for the other two, I can get those for you tomorrow.

https://github.com/nathanchance/creduce-files/tree/3699d2b725a305c0f02a7672447b30578115ba51/D105169-ravb_main

  $ clang -O2 -flto=thin -fsanitize=integer-divide-by-zero -c -o ravb_main.o 
ravb_main.i
  ravb_main.i:68:5: warning: expression result unused [-Wunused-value]
  __rem;
  ^
  1 warning generated.
  
  $ ld.lld -m elf_x86_64 -r -o ravb.lto.o --whole-archive ravb_main.o
  
  $ ./objtool orc generate --module --no-fp --no-unreachable --uaccess --mcount 
ravb.lto.o
  ravb.lto.o: warning: objtool: .text.ravb_set_gti: unexpected end of section

This one can also be reproduced without LTO:

  $ clang -O2 -fsanitize=integer-divide-by-zero -c -o ravb_main.o ravb_main.i
  
  $ ./objtool orc generate --module --no-fp --no-unreachable --uaccess --mcount 
ravb_main.o
  ravb_main.o: warning: objtool: .text: unexpected end of section

As far as I can tell, that function already has a check to avoid dividing by 
zero.

https://github.com/nathanchance/creduce-files/tree/3699d2b725a305c0f02a7672447b30578115ba51/D105169-w5100

  $ clang -O2 -flto=thin -fsanitize=integer-divide-by-zero -c -o w5100.o w5100.i
  
  $ ld.lld -m elf_x86_64 -r -o w5100.lto.o --whole-archive w5100.o
  
  $ w5100.lto.o: warning: objtool: .text.w5100_tx_skb: unexpected end of section

Without LTO, another warning is emitted, with a similar root cause I believe:

  $ clang -O2 -fsanitize=integer-divide-by-zero -c -o w5100.o w5100.i
  
  $ ./objtool orc generate --module --no-fp --no-unreachable --uaccess --mcount 
w5100.o
  w5100.o: warning: objtool: w5100_tx_skb() falls through to next function 
w5100_probe()

In theory, `w5100_writebuf()` should probably have a check for `s0_tx_buf_size` 
being zero but the input is completely controlled by the kernel, as can be seen 
in `w5100_probe()` (`s0_tx_buf_size` cannot be zero). Most if not all kernel 
maintainers are not going to accept patches adding checks that are superfluous.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105169

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


[PATCH] D116314: [clang-format] Add style to separate definition blocks

2021-12-29 Thread ksyx via Phabricator via cfe-commits
ksyx updated this revision to Diff 396577.
ksyx added a comment.

Apply suggestion from clangfmt


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

https://reviews.llvm.org/D116314

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/CMakeLists.txt
  clang/lib/Format/DefinitionBlockSeparator.cpp
  clang/lib/Format/DefinitionBlockSeparator.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/WhitespaceManager.cpp
  clang/lib/Format/WhitespaceManager.h
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/DefinitionBlockSeparatorTest.cpp

Index: clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
===
--- /dev/null
+++ clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -0,0 +1,316 @@
+//===- DefinitionBlockSeparatorTest.cpp - Formatting unit tests ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "FormatTestUtils.h"
+#include "clang/Format/Format.h"
+
+#include "llvm/Support/Debug.h"
+#include "gtest/gtest.h"
+
+#define DEBUG_TYPE "definition-block-separator-test"
+
+namespace clang {
+namespace format {
+namespace {
+
+class DefinitionBlockSeparatorTest : public ::testing::Test {
+protected:
+  static std::string
+  separateDefinitionBlocks(llvm::StringRef Code,
+   const std::vector ,
+   const FormatStyle  = getLLVMStyle()) {
+LLVM_DEBUG(llvm::errs() << "---\n");
+LLVM_DEBUG(llvm::errs() << Code << "\n\n");
+tooling::Replacements Replaces =
+clang::format::separateDefinitionBlocks(Style, Code, Ranges, "");
+auto Result = applyAllReplacements(Code, Replaces);
+EXPECT_TRUE(static_cast(Result));
+LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
+return *Result;
+  }
+
+  static std::string
+  separateDefinitionBlocks(llvm::StringRef Code,
+   const FormatStyle  = getLLVMStyle()) {
+return separateDefinitionBlocks(
+Code,
+/*Ranges=*/{1, tooling::Range(0, Code.size())}, Style);
+  }
+
+  static void verifyFormat(llvm::StringRef Code,
+   const FormatStyle  = getLLVMStyle(),
+   llvm::StringRef ExpectedCode = "") {
+bool HasOriginalCode = true;
+if (ExpectedCode == "") {
+  ExpectedCode = Code;
+  HasOriginalCode = false;
+}
+
+FormatStyle InverseStyle = Style;
+if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
+  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
+else
+  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+EXPECT_EQ(ExpectedCode.str(), separateDefinitionBlocks(ExpectedCode, Style))
+<< "Expected code is not stable";
+std::string InverseResult = separateDefinitionBlocks(Code, InverseStyle);
+EXPECT_NE(Code.str(), InverseResult)
+<< "Inverse formatting makes no difference";
+std::string CodeToFormat =
+HasOriginalCode ? Code.str() : removeEmptyLines(Code);
+std::string Result = separateDefinitionBlocks(CodeToFormat, Style);
+EXPECT_EQ(ExpectedCode.str(), Result) << "Test failed. Formatted:\n"
+  << Result;
+  }
+
+  static std::string removeEmptyLines(llvm::StringRef Code) {
+std::string Result = "";
+for (auto Char : Code.str()) {
+  if (Result.size()) {
+auto LastChar = Result.back();
+if ((Char == '\n' && LastChar == '\n') ||
+(Char == '\r' && (LastChar == '\r' || LastChar == '\n')))
+  continue;
+  }
+  Result.push_back(Char);
+}
+return Result;
+  }
+};
+
+TEST_F(DefinitionBlockSeparatorTest, Basic) {
+  FormatStyle Style = getLLVMStyle();
+  Style.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  verifyFormat("int foo() {\n"
+   "  int i, j;\n"
+   "}\n"
+   "\n"
+   "int bar() {\n"
+   "  int j, k;\n"
+   "}",
+   Style);
+
+  verifyFormat("struct foo {\n"
+   "  int i, j;\n"
+   "};\n"
+   "\n"
+   "struct bar {\n"
+   "  int j, k;\n"
+   "};",
+   Style);
+
+  verifyFormat("class foo {\n"
+   "  int i, j;\n"
+   "};\n"
+   "\n"
+   "class bar {\n"
+   "  int j, k;\n"
+   "};",
+   Style);
+
+  verifyFormat("namespace foo {\n"
+   "  int i, j;\n"
+   "}\n"
+   "\n"
+   "namespace bar {\n"
+   "  int j, k;\n"
+   "}",
+   

[PATCH] D115604: [Support] Expand `` as the base directory in configuration files.

2021-12-29 Thread Jack Andersen via Phabricator via cfe-commits
jackoalan updated this revision to Diff 396576.
jackoalan added a comment.

Update call parameters in `ExpandResponseFilesDatabase::expand`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115604

Files:
  clang/docs/ReleaseNotes.rst
  clang/docs/UsersManual.rst
  clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
  llvm/include/llvm/Support/CommandLine.h
  llvm/lib/Support/CommandLine.cpp
  llvm/unittests/Support/CommandLineTest.cpp

Index: llvm/unittests/Support/CommandLineTest.cpp
===
--- llvm/unittests/Support/CommandLineTest.cpp
+++ llvm/unittests/Support/CommandLineTest.cpp
@@ -827,7 +827,7 @@
   llvm::BumpPtrAllocator A;
   llvm::StringSaver Saver(A);
   ASSERT_TRUE(llvm::cl::ExpandResponseFiles(
-  Saver, llvm::cl::TokenizeGNUCommandLine, Argv, false, true,
+  Saver, llvm::cl::TokenizeGNUCommandLine, Argv, false, true, false,
   /*CurrentDir=*/StringRef(TestRoot), FS));
   EXPECT_THAT(Argv, testing::Pointwise(
 StringEquality(),
@@ -889,9 +889,9 @@
 #else
   cl::TokenizerCallback Tokenizer = cl::TokenizeGNUCommandLine;
 #endif
-  ASSERT_FALSE(cl::ExpandResponseFiles(Saver, Tokenizer, Argv, false, false,
-   /*CurrentDir=*/llvm::StringRef(TestRoot),
-   FS));
+  ASSERT_FALSE(
+  cl::ExpandResponseFiles(Saver, Tokenizer, Argv, false, false, false,
+  /*CurrentDir=*/llvm::StringRef(TestRoot), FS));
 
   EXPECT_THAT(Argv,
   testing::Pointwise(StringEquality(),
@@ -929,7 +929,7 @@
   BumpPtrAllocator A;
   StringSaver Saver(A);
   ASSERT_FALSE(cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv,
-   false, false,
+   false, false, false,
/*CurrentDir=*/StringRef(TestRoot), FS));
 
   // ASSERT instead of EXPECT to prevent potential out-of-bounds access.
@@ -964,7 +964,7 @@
   BumpPtrAllocator A;
   StringSaver Saver(A);
   ASSERT_TRUE(cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv,
-  false, true,
+  false, true, false,
   /*CurrentDir=*/StringRef(TestRoot), FS));
   EXPECT_THAT(Argv,
   testing::Pointwise(StringEquality(), {"test/test", "-flag"}));
@@ -984,7 +984,7 @@
   BumpPtrAllocator A;
   StringSaver Saver(A);
   ASSERT_TRUE(cl::ExpandResponseFiles(Saver, cl::TokenizeWindowsCommandLine,
-  Argv, true, true,
+  Argv, true, true, false,
   /*CurrentDir=*/StringRef(TestRoot), FS));
   const char *Expected[] = {"clang", "-Xclang", "-Wno-whatever", nullptr,
 "input.cpp"};
@@ -1038,25 +1038,34 @@
   llvm::SmallVector Argv;
 
   TempDir TestDir("unittest", /*Unique*/ true);
+  TempDir TestSubDir(TestDir.path("subdir"), /*Unique*/ false);
 
-  llvm::SmallString<128> TestCfg;
-  llvm::sys::path::append(TestCfg, TestDir.path(), "foo");
-
+  llvm::SmallString<128> TestCfg = TestDir.path("foo");
   TempFile ConfigFile(TestCfg, "",
   "# Comment\n"
   "-option_1\n"
+  "-option_2=/dir1\n"
   "@subconfig\n"
-  "-option_3=abcd\n"
-  "-option_4=\\\n"
+  "-option_7=abcd\n"
+  "-option_8=\\\n"
   "cdef\n");
 
-  llvm::SmallString<128> TestCfg2;
-  llvm::sys::path::append(TestCfg2, TestDir.path(), "subconfig");
+  llvm::SmallString<128> TestCfg2 = TestDir.path("subconfig");
   TempFile ConfigFile2(TestCfg2, "",
-   "-option_2\n"
+   "-option_3\n"
+   "-option_4=/dir2\n"
+   "@subdir/subfoo\n"
"\n"
"   # comment\n");
 
+  llvm::SmallString<128> TestCfg3 = TestSubDir.path("subfoo");
+  TempFile ConfigFile3(TestCfg3, "",
+   "-option_5=/dir3\n"
+   "@/subfoo2\n");
+
+  llvm::SmallString<128> TestCfg4 = TestSubDir.path("subfoo2");
+  TempFile ConfigFile4(TestCfg4, "", "-option_6=qwerty\n");
+
   // Make sure the current directory is not the directory where config files
   // resides. In this case the code that expands response files will not find
   // 'subconfig' unless it resolves nested inclusions relative to the including
@@ -1071,11 +1080,18 @@
   bool Result = llvm::cl::readConfigFile(ConfigFile.path(), Saver, Argv);
 
   EXPECT_TRUE(Result);
-  EXPECT_EQ(Argv.size(), 4U);
+  EXPECT_EQ(Argv.size(), 8U);
   EXPECT_STREQ(Argv[0], "-option_1");
-  EXPECT_STREQ(Argv[1], 

[PATCH] D116314: [clang-format] Add style to separate definition blocks

2021-12-29 Thread ksyx via Phabricator via cfe-commits
ksyx updated this revision to Diff 396575.
ksyx added a comment.

Apply clangfmt's suggestions


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

https://reviews.llvm.org/D116314

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/CMakeLists.txt
  clang/lib/Format/DefinitionBlockSeparator.cpp
  clang/lib/Format/DefinitionBlockSeparator.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/WhitespaceManager.cpp
  clang/lib/Format/WhitespaceManager.h
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/DefinitionBlockSeparatorTest.cpp

Index: clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
===
--- /dev/null
+++ clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -0,0 +1,316 @@
+//===- DefinitionBlockSeparatorTest.cpp - Formatting unit tests ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Format/Format.h"
+#include "FormatTestUtils.h"
+
+#include "llvm/Support/Debug.h"
+#include "gtest/gtest.h"
+
+#define DEBUG_TYPE "definition-block-separator-test"
+
+namespace clang {
+namespace format {
+namespace {
+
+class DefinitionBlockSeparatorTest : public ::testing::Test {
+protected:
+  static std::string
+  separateDefinitionBlocks(llvm::StringRef Code,
+   const std::vector ,
+   const FormatStyle  = getLLVMStyle()) {
+LLVM_DEBUG(llvm::errs() << "---\n");
+LLVM_DEBUG(llvm::errs() << Code << "\n\n");
+tooling::Replacements Replaces =
+clang::format::separateDefinitionBlocks(Style, Code, Ranges, "");
+auto Result = applyAllReplacements(Code, Replaces);
+EXPECT_TRUE(static_cast(Result));
+LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
+return *Result;
+  }
+
+  static std::string
+  separateDefinitionBlocks(llvm::StringRef Code,
+   const FormatStyle  = getLLVMStyle()) {
+return separateDefinitionBlocks(
+Code,
+/*Ranges=*/{1, tooling::Range(0, Code.size())}, Style);
+  }
+
+  static void verifyFormat(llvm::StringRef Code,
+   const FormatStyle  = getLLVMStyle(),
+   llvm::StringRef ExpectedCode = "") {
+bool HasOriginalCode = true;
+if (ExpectedCode == "") {
+  ExpectedCode = Code;
+  HasOriginalCode = false;
+}
+
+FormatStyle InverseStyle = Style;
+if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
+  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
+else
+  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+EXPECT_EQ(ExpectedCode.str(), separateDefinitionBlocks(ExpectedCode, Style))
+<< "Expected code is not stable";
+std::string InverseResult = separateDefinitionBlocks(Code, InverseStyle);
+EXPECT_NE(Code.str(), InverseResult)
+<< "Inverse formatting makes no difference";
+std::string CodeToFormat =
+HasOriginalCode ? Code.str() : removeEmptyLines(Code);
+std::string Result = separateDefinitionBlocks(CodeToFormat, Style);
+EXPECT_EQ(ExpectedCode.str(), Result) << "Test failed. Formatted:\n"
+  << Result;
+  }
+
+  static std::string removeEmptyLines(llvm::StringRef Code) {
+std::string Result = "";
+  for (auto Char : Code.str()) {
+if (Result.size()) {
+  auto LastChar = Result.back();
+  if ((Char == '\n' && LastChar == '\n') ||
+  (Char == '\r' && (LastChar == '\r' || LastChar == '\n')))
+continue;
+}
+Result.push_back(Char);
+  }
+return Result;
+  }
+};
+
+TEST_F(DefinitionBlockSeparatorTest, Basic) {
+  FormatStyle Style = getLLVMStyle();
+  Style.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  verifyFormat("int foo() {\n"
+   "  int i, j;\n"
+   "}\n"
+   "\n"
+   "int bar() {\n"
+   "  int j, k;\n"
+   "}",
+   Style);
+
+  verifyFormat("struct foo {\n"
+   "  int i, j;\n"
+   "};\n"
+   "\n"
+   "struct bar {\n"
+   "  int j, k;\n"
+   "};",
+   Style);
+
+  verifyFormat("class foo {\n"
+   "  int i, j;\n"
+   "};\n"
+   "\n"
+   "class bar {\n"
+   "  int j, k;\n"
+   "};",
+   Style);
+
+  verifyFormat("namespace foo {\n"
+   "  int i, j;\n"
+   "}\n"
+   "\n"
+   "namespace bar {\n"
+   "  int j, k;\n"
+   "}",
+

[PATCH] D116314: [clang-format] Add style to separate definition blocks

2021-12-29 Thread ksyx via Phabricator via cfe-commits
ksyx updated this revision to Diff 396574.
ksyx marked 9 inline comments as done.
ksyx edited the summary of this revision.
ksyx added a comment.

- Improve compatibility to other languages
- Improve unit test by test format stability, inverse result, and generate some 
input from expected output
- Reformat sample code
- Use more concise word for SDS_Leave


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

https://reviews.llvm.org/D116314

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/CMakeLists.txt
  clang/lib/Format/DefinitionBlockSeparator.cpp
  clang/lib/Format/DefinitionBlockSeparator.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/WhitespaceManager.cpp
  clang/lib/Format/WhitespaceManager.h
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/DefinitionBlockSeparatorTest.cpp

Index: clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
===
--- /dev/null
+++ clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -0,0 +1,316 @@
+//===- DefinitionBlockSeparatorTest.cpp - Formatting unit tests ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Format/Format.h"
+#include "FormatTestUtils.h"
+
+#include "llvm/Support/Debug.h"
+#include "gtest/gtest.h"
+
+#define DEBUG_TYPE "definition-block-separator-test"
+
+namespace clang {
+namespace format {
+namespace {
+
+class DefinitionBlockSeparatorTest : public ::testing::Test {
+protected:
+  static std::string
+  separateDefinitionBlocks(llvm::StringRef Code,
+   const std::vector ,
+   const FormatStyle  = getLLVMStyle()) {
+LLVM_DEBUG(llvm::errs() << "---\n");
+LLVM_DEBUG(llvm::errs() << Code << "\n\n");
+tooling::Replacements Replaces =
+clang::format::separateDefinitionBlocks(Style, Code, Ranges, "");
+auto Result = applyAllReplacements(Code, Replaces);
+EXPECT_TRUE(static_cast(Result));
+LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
+return *Result;
+  }
+
+  static std::string
+  separateDefinitionBlocks(llvm::StringRef Code,
+   const FormatStyle  = getLLVMStyle()) {
+return separateDefinitionBlocks(
+Code,
+/*Ranges=*/{1, tooling::Range(0, Code.size())}, Style);
+  }
+
+  static void verifyFormat(llvm::StringRef Code,
+   const FormatStyle  = getLLVMStyle(),
+   llvm::StringRef ExpectedCode = "") {
+bool HasOriginalCode = true;
+if (ExpectedCode == "") {
+  ExpectedCode = Code;
+  HasOriginalCode = false;
+}
+
+FormatStyle InverseStyle = Style;
+if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
+  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
+else
+  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+EXPECT_EQ(ExpectedCode.str(), separateDefinitionBlocks(ExpectedCode, Style))
+<< "Expected code is not stable";
+std::string InverseResult = separateDefinitionBlocks(Code, InverseStyle);
+EXPECT_NE(Code.str(), InverseResult)
+<< "Inverse formatting makes no difference";
+std::string CodeToFormat =
+HasOriginalCode ? Code.str() : removeEmptyLines(Code);
+std::string Result = separateDefinitionBlocks(CodeToFormat, Style);
+EXPECT_EQ(ExpectedCode.str(), Result) << "Test failed. Formatted:\n"
+  << Result;
+  }
+
+  static std::string removeEmptyLines(llvm::StringRef Code) {
+std::string Result = "";
+  for (auto Char : Code.str()) {
+if (Result.size()) {
+  auto LastChar = Result.back();
+  if ((Char == '\n' && LastChar == '\n') ||
+  (Char == '\r' && (LastChar == '\r' || LastChar == '\n')))
+continue;
+}
+Result.push_back(Char);
+  }
+return Result;
+  }
+};
+
+TEST_F(DefinitionBlockSeparatorTest, Basic) {
+  FormatStyle Style = getLLVMStyle();
+  Style.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  verifyFormat("int foo() {\n"
+   "  int i, j;\n"
+   "}\n"
+   "\n"
+   "int bar() {\n"
+   "  int j, k;\n"
+   "}",
+   Style);
+
+  verifyFormat("struct foo {\n"
+   "  int i, j;\n"
+   "};\n"
+   "\n"
+   "struct bar {\n"
+   "  int j, k;\n"
+   "};",
+   Style);
+
+  verifyFormat("class foo {\n"
+   "  int i, j;\n"
+   "};\n"
+   "\n"
+   "class bar {\n"
+   "  

[PATCH] D116370: [clang][dataflow] Add multi-variable constant propagation example.

2021-12-29 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

Does it make sense to have both the single and multi variable tracking tests? 
Or do we want to have these as some sort of steps in a tutorial?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116370

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


[PATCH] D116369: [clang][dataflow] Add parameterized map lattice.

2021-12-29 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/MapLattice.h:92
+  /// entry as it was in the source map.
+  LatticeJoinEffect join(const MapLattice ) {
+LatticeJoinEffect Effect = LatticeJoinEffect::Unchanged;

It looks like apart from the join operation the rest of the methods are simply 
forwarding to DenseMap. I was wondering if it would make more sense to make the 
framework support `join` as a free function (possibly using some custom type 
traits?) to avoid forcing the user to write wrappers like this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116369

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


[PATCH] D116368: [clang][dataflow] Add transfer function for VarDecl statements

2021-12-29 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

Thanks! I have some questions inline.




Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:61
+  ///  `D` must not be assigned a storage location.
+  void setStorageLocation(const VarDecl , StorageLocation ) {
+assert(VarDeclToLoc.find() == VarDeclToLoc.end());

Are other language constructs coming in a follow-up PR? (E.g.: FieldDecl, 
locations on the heap). I'd like to some TODO comments if that is the case. Or 
if they are not supported by design, I'd love to some some comments about that.

Environment is referencing `ValueDecl` as opposed to `VarDecl`. What is the 
reason for this asymmetry?
I think I overall find it confusing that some of the DeclToLoc mapping is here 
some is in the Environment.
Does this has something to do with the fact that certain mappings should be the 
same regardless of which basic blocks we are processing (i.e., invariant 
globally so we do not need to duplicate it)? If that is the case please make it 
clear in the comments. 



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:76
+  std::vector> Locs;
+  std::vector> Vals;
+  llvm::DenseMap VarDeclToLoc;

Just curious: would it make sense to deduplicate these values?



Comment at: clang/include/clang/Analysis/FlowSensitive/Value.h:33
+
+  virtual ~Value() {}
+

` = default;`



Comment at: clang/include/clang/Analysis/FlowSensitive/Value.h:78
+
+  StorageLocation *getLocation() const { return Loc; }
+

I wonder if getLocation is ambiguous. (The pointer's own location vs the 
pointee location.) How about something like `getPointeeLoc`?



Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:32
+template 
+bool denseMapsAreEqual(const llvm::DenseMap ,
+   const llvm::DenseMap ) {

Shouldn't we add `operator==` instead?



Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:46
+template 
+llvm::DenseMap intersectDenseMaps(const llvm::DenseMap ,
+const llvm::DenseMap ) {

I wonder if these algorithms should rather be somewhere in the support library.



Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:88
+for (const FieldDecl *Field : Type->getAsRecordDecl()->fields()) {
+  FieldLocs.insert({Field, (Field->getType())});
+}

Could this end up creating an overly large state? There might be objects with 
quite a lot fields but each function would only access a small subset of those. 
Alternatively, we could attempt to create the representations for fields on 
demand (this is the approach what the clang static analyzer is using). 



Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:117
+
+Value *Environment::initValueInStorageLocation(const StorageLocation ,
+   QualType Type) {

I think this function implementation is better to be moved closer to the called 
`initValueInStorageLocationUnlessSelfReferential` for readability.



Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:144
+  if (Type->isRealFloatingType()) {
+auto  = DACtx->takeOwnership(std::make_unique());
+setValue(Loc, Value);

Are we planning to track float values in the near future? If not, would it make 
sense to defer creating these objects until then?



Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:154
+if (!Visited.contains(PointeeType)) {
+  Visited.insert(PointeeType);
+  initValueInStorageLocationUnlessSelfReferential(PointeeLoc, PointeeType,

Do we want to canonicalize types before inserting into this set?



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:33
+static void transferDeclStmt(const DeclStmt , Environment ) {
+  if (const auto *D = dyn_cast(S.getSingleDecl())) {
+transferVarDecl(*D, Env);

Maybe add a TODO for `int a, b;` and similar codes?



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:41
+
+  if (const auto *DS = dyn_cast()) {
+transferDeclStmt(*DS, Env);

Instead of using a long `if else` and dynamic casts, don't we want to use an 
`StmtVisitor` instead?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116368

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


[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2021-12-29 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2303
+  assert(IfRightBrace->MatchingParen == IfLeftBrace);
+  IfLeftBrace->MatchingParen = nullptr;
+  IfRightBrace->MatchingParen = nullptr;

Why null that?


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

https://reviews.llvm.org/D116316

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


[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2021-12-29 Thread Owen Pan via Phabricator via cfe-commits
owenpan updated this revision to Diff 396573.
owenpan added a comment.

Fixed a bug and added a test case.


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

https://reviews.llvm.org/D116316

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  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
@@ -18682,6 +18682,7 @@
   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
   CHECK_PARSE_BOOL(ReflowComments);
+  CHECK_PARSE_BOOL(RemoveBracesLLVM);
   CHECK_PARSE_BOOL(SortUsingDeclarations);
   CHECK_PARSE_BOOL(SpacesInParentheses);
   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
@@ -23020,6 +23021,307 @@
Style);
 }
 
+TEST_F(FormatTest, RemoveBraces) {
+  FormatStyle Style = getLLVMStyle();
+  Style.RemoveBracesLLVM = true;
+
+  // The following eight test cases are fully-braced versions of the examples at
+  // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
+  // statement-bodies-of-if-else-loop-statements".
+
+  // 1. Omit the braces, since the body is simple and clearly associated with
+  // the if.
+  EXPECT_EQ("if (isa(D))\n"
+"  handleFunctionDecl(D);\n"
+"else if (isa(D))\n"
+"  handleVarDecl(D);",
+format("if (isa(D)) {\n"
+   "  handleFunctionDecl(D);\n"
+   "} else if (isa(D)) {\n"
+   "  handleVarDecl(D);\n"
+   "}",
+   Style));
+
+  // 2. Here we document the condition itself and not the body.
+  verifyFormat("if (isa(D)) {\n"
+   "  // It is necessary that we explain the situation with this\n"
+   "  // surprisingly long comment, so it would be unclear\n"
+   "  // without the braces whether the following statement is in\n"
+   "  // the scope of the `if`.\n"
+   "  // Because the condition is documented, we can't really\n"
+   "  // hoist this comment that applies to the body above the\n"
+   "  // if.\n"
+   "  handleOtherDecl(D);\n"
+   "}",
+   Style);
+
+  // 3. Use braces on the outer `if` to avoid a potential dangling else
+  // situation.
+  EXPECT_EQ("if (isa(D)) {\n"
+"  for (auto *A : D.attrs())\n"
+"if (shouldProcessAttr(A))\n"
+"  handleAttr(A);\n"
+"}",
+format("if (isa(D)) {\n"
+   "  for (auto *A : D.attrs()) {\n"
+   "if (shouldProcessAttr(A)) {\n"
+   "  handleAttr(A);\n"
+   "}\n"
+   "  }\n"
+   "}",
+   Style));
+
+  // 4. Use braces for the `if` block to keep it uniform with the else block.
+  verifyFormat("if (isa(D)) {\n"
+   "  handleFunctionDecl(D);\n"
+   "} else {\n"
+   "  // In this else case, it is necessary that we explain the\n"
+   "  // situation with this surprisingly long comment, so it\n"
+   "  // would be unclear without the braces whether the\n"
+   "  // following statement is in the scope of the `if`.\n"
+   "  handleOtherDecl(D);\n"
+   "}",
+   Style);
+
+  // 5. This should also omit braces.  The `for` loop contains only a single
+  // statement, so it shouldn't have braces.  The `if` also only contains a
+  // single simple statement (the for loop), so it also should omit braces.
+  EXPECT_EQ("if (isa(D))\n"
+"  for (auto *A : D.attrs())\n"
+"handleAttr(A);",
+format("if (isa(D)) {\n"
+   "  for (auto *A : D.attrs()) {\n"
+   "handleAttr(A);\n"
+   "  }\n"
+   "}",
+   Style));
+
+  // 6. Use braces for the outer `if` since the nested `for` is braced.
+  verifyFormat("if (isa(D)) {\n"
+   "  for (auto *A : D.attrs()) {\n"
+   "// In this for loop body, it is necessary that we explain\n"
+   "// the situation with this surprisingly long comment,\n"
+   "// forcing braces on the `for` block.\n"
+   "handleAttr(A);\n"
+   "  }\n"
+   "}",
+   Style);
+
+  // 7. Use braces on the outer block because there are more than two levels of
+  // nesting.
+  EXPECT_EQ("if (isa(D)) {\n"
+"  for (auto *A : D.attrs())\n"
+"for (ssize_t i : llvm::seq(count))\n"
+"   

[PATCH] D116369: [clang][dataflow] Add parameterized map lattice.

2021-12-29 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked 3 inline comments as done.
ymandel added a comment.

In D116369#3212532 , @sgatev wrote:

> It seems unnecessary to deal with AST elements in the tests for `MapLattice`. 
> I think testing it with integer or string keys would be simpler. Given that 
> `VarMapLattice` is just an alias, I don't think it's necessary to add 
> dedicated tests for it. What do you think?

Yes, excellent point. I've stripped all of that out and think its much cleaner 
this way. Thanks!




Comment at: clang/include/clang/Analysis/FlowSensitive/MapLattice.h:33
+/// constructor of `ElementLattice` should produce the bottom element.
+template  class MapLattice {
+  using Container = llvm::DenseMap;

sgatev wrote:
> Please document the relation, the join operation, and the bottom element for 
> this lattice.
I wasn't sure which relation you had in mind, so documented the equality 
operation.



Comment at: clang/include/clang/Analysis/FlowSensitive/MapLattice.h:50
+  void insert(const std::pair ) {
+(void)C.insert(P);
+  }

sgatev wrote:
> Is `(void)` necessary? Is it a convention?
not necessary -- I'll sometimes do it when I'm ignoring a result. But, no need 
-- i dropped it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116369

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


[PATCH] D116369: [clang][dataflow] Add parameterized map lattice.

2021-12-29 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 396570.
ymandel marked 2 inline comments as done.
ymandel added a comment.

update comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116369

Files:
  clang/include/clang/Analysis/FlowSensitive/MapLattice.h
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp
@@ -0,0 +1,156 @@
+#include "clang/Analysis/FlowSensitive/MapLattice.h"
+#include "clang/Analysis/FlowSensitive/DataflowLattice.h"
+#include "llvm/Support/Error.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+using namespace clang;
+using namespace dataflow;
+
+namespace {
+// A simple lattice for basic tests.
+class BooleanLattice {
+public:
+  BooleanLattice() : Value(false) {}
+  explicit BooleanLattice(bool B) : Value(B) {}
+
+  static BooleanLattice bottom() { return BooleanLattice(false); }
+
+  static BooleanLattice top() { return BooleanLattice(true); }
+
+  LatticeJoinEffect join(BooleanLattice Other) {
+auto Prev = Value;
+Value = Value || Other.Value;
+return Prev == Value ? LatticeJoinEffect::Unchanged
+ : LatticeJoinEffect::Changed;
+  }
+
+  friend bool operator==(BooleanLattice LHS, BooleanLattice RHS) {
+return LHS.Value == RHS.Value;
+  }
+
+  friend bool operator!=(BooleanLattice LHS, BooleanLattice RHS) {
+return LHS.Value != RHS.Value;
+  }
+
+  friend std::ostream <<(std::ostream , const BooleanLattice ) {
+Os << B.Value;
+return Os;
+  }
+
+  bool value() const { return Value; }
+
+private:
+  bool Value;
+};
+} // namespace
+
+static constexpr int Key1 = 0;
+static constexpr int Key2 = 1;
+
+namespace {
+using ::testing::Pair;
+using ::testing::UnorderedElementsAre;
+
+TEST(MapLatticeTest, InsertWorks) {
+  MapLattice Lattice;
+  Lattice.insert({Key1, BooleanLattice(false)});
+  Lattice.insert({Key2, BooleanLattice(false)});
+
+  EXPECT_THAT(Lattice, UnorderedElementsAre(Pair(Key1, BooleanLattice(false)),
+Pair(Key2, BooleanLattice(false;
+}
+
+TEST(MapLatticeTest, ComparisonWorks) {
+  MapLattice Lattice1;
+  Lattice1.insert({Key1, BooleanLattice(true)});
+  Lattice1.insert({Key2, BooleanLattice(false)});
+  MapLattice Lattice2 = Lattice1;
+  EXPECT_EQ(Lattice1, Lattice2);
+
+  Lattice2.find(Key2)->second = BooleanLattice(true);
+  EXPECT_NE(Lattice1, Lattice2);
+}
+
+TEST(MapLatticeTest, JoinChange) {
+  MapLattice Lattice1;
+  Lattice1.insert({Key1, BooleanLattice(false)});
+  Lattice1.insert({Key2, BooleanLattice(false)});
+
+  MapLattice Lattice2;
+  Lattice2.insert({Key1, BooleanLattice(true)});
+  Lattice2.insert({Key2, BooleanLattice(true)});
+
+  ASSERT_THAT(Lattice1,
+  UnorderedElementsAre(Pair(Key1, BooleanLattice(false)),
+   Pair(Key2, BooleanLattice(false;
+
+  ASSERT_EQ(Lattice1.join(Lattice2), LatticeJoinEffect::Changed);
+  EXPECT_THAT(Lattice1, UnorderedElementsAre(Pair(Key1, BooleanLattice(true)),
+ Pair(Key2, BooleanLattice(true;
+}
+
+TEST(MapLatticeTest, JoinEqNoChange) {
+  MapLattice Lattice;
+  Lattice.insert({Key1, BooleanLattice(false)});
+  Lattice.insert({Key2, BooleanLattice(false)});
+
+  ASSERT_EQ(Lattice.join(Lattice), LatticeJoinEffect::Unchanged);
+  EXPECT_THAT(Lattice, UnorderedElementsAre(Pair(Key1, BooleanLattice(false)),
+Pair(Key2, BooleanLattice(false;
+}
+
+TEST(MapLatticeTest, JoinLtNoChange) {
+  MapLattice Lattice1;
+  Lattice1.insert({Key1, BooleanLattice(false)});
+  Lattice1.insert({Key2, BooleanLattice(false)});
+
+  MapLattice Lattice2;
+  Lattice2.insert({Key1, BooleanLattice(true)});
+  Lattice2.insert({Key2, BooleanLattice(true)});
+
+  ASSERT_THAT(Lattice1,
+  UnorderedElementsAre(Pair(Key1, BooleanLattice(false)),
+   Pair(Key2, BooleanLattice(false;
+
+  ASSERT_THAT(Lattice2, UnorderedElementsAre(Pair(Key1, BooleanLattice(true)),
+ Pair(Key2, BooleanLattice(true;
+
+  ASSERT_EQ(Lattice2.join(Lattice1), LatticeJoinEffect::Unchanged);
+  EXPECT_THAT(Lattice2, UnorderedElementsAre(Pair(Key1, BooleanLattice(true)),
+ Pair(Key2, BooleanLattice(true;
+}
+
+TEST(MapLatticeTest, JoinDifferentDomainsProducesUnion) {
+  MapLattice Lattice1;
+  Lattice1.insert({Key1, BooleanLattice(true)});
+  MapLattice Lattice2;
+  Lattice2.insert({Key2, BooleanLattice(true)});
+
+  ASSERT_EQ(Lattice1.join(Lattice2), LatticeJoinEffect::Changed);
+  EXPECT_THAT(Lattice1, 

[PATCH] D116385: [clangd] Code action for creating an ObjC initializer

2021-12-29 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 396569.
dgoldman added a comment.

Remove debug log statement


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116385

Files:
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp
  clang-tools-extra/clangd/unittests/CMakeLists.txt
  clang-tools-extra/clangd/unittests/tweaks/ObjCMemberwiseInitializerTests.cpp

Index: clang-tools-extra/clangd/unittests/tweaks/ObjCMemberwiseInitializerTests.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/unittests/tweaks/ObjCMemberwiseInitializerTests.cpp
@@ -0,0 +1,150 @@
+//===-- ObjCMemberwiseInitializerTests.cpp --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestTU.h"
+#include "TweakTesting.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+TWEAK_TEST(ObjCMemberwiseInitializer);
+
+TEST_F(ObjCMemberwiseInitializerTest, TestAvailability) {
+  FileName = "TestTU.m";
+
+  // Ensure the action can't be triggered since arc is disabled.
+  EXPECT_UNAVAILABLE(R"cpp(
+@interface Fo^o
+@end
+  )cpp");
+
+  ExtraArgs.push_back("-fobjc-arc");
+
+  // Ensure the action can be initiated on the interface and implementation.
+  EXPECT_AVAILABLE(R"cpp(
+@interface Fo^o
+@end
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo
+@end
+
+@implementation F^oo
+@end
+  )cpp");
+
+  // Ensure that the action can be triggered on ivars and properties,
+  // including selecting both.
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo {
+  id _fi^eld;
+}
+@end
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo
+@property(nonatomic) id fi^eld;
+@end
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo {
+  id _fi^eld;
+}
+@property(nonatomic) id pr^op;
+@end
+  )cpp");
+
+  // Ensure that the action can't be triggered on property synthesis
+  // and methods.
+  EXPECT_UNAVAILABLE(R"cpp(
+@interface Foo
+@property(nonatomic) id prop;
+@end
+
+@implementation Foo
+@dynamic pr^op;
+@end
+  )cpp");
+  EXPECT_UNAVAILABLE(R"cpp(
+@interface Foo
+@end
+
+@implementation Foo
+- (void)fo^o {}
+@end
+  )cpp");
+}
+
+TEST_F(ObjCMemberwiseInitializerTest, Test) {
+  FileName = "TestTU.m";
+  ExtraArgs.push_back("-fobjc-arc");
+
+  const char *Input = R"cpp(
+@interface Foo {
+  id [[_field;
+}
+@property(nonatomic) id prop]];
+@property(nonatomic) id notSelected;
+@end)cpp";
+  const char *Output = R"cpp(
+@interface Foo {
+  id _field;
+}
+@property(nonatomic) id prop;
+@property(nonatomic) id notSelected;
+
+- (instancetype)initWithField:(id)field prop:(id)prop;
+
+@end)cpp";
+  EXPECT_EQ(apply(Input), Output);
+
+  Input = R"cpp(
+@interface Foo
+@property(nonatomic, nullable) id somePrettyLongPropertyName;
+@property(nonatomic, nonnull) id someReallyLongPropertyName;
+@end
+
+@implementation F^oo
+
+- (instancetype)init {
+  return self;
+}
+
+@end)cpp";
+  Output = R"cpp(
+@interface Foo
+@property(nonatomic, nullable) id somePrettyLongPropertyName;
+@property(nonatomic, nonnull) id someReallyLongPropertyName;
+@end
+
+@implementation Foo
+
+- (instancetype)init {
+  return self;
+}
+
+- (instancetype)initWithSomePrettyLongPropertyName:(nullable id)somePrettyLongPropertyName someReallyLongPropertyName:(nonnull id)someReallyLongPropertyName {
+  self = [super init];
+  if (self) {
+_somePrettyLongPropertyName = somePrettyLongPropertyName;
+_someReallyLongPropertyName = someReallyLongPropertyName;
+  }
+  return self;
+}
+
+@end)cpp";
+  EXPECT_EQ(apply(Input), Output);
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
Index: clang-tools-extra/clangd/unittests/CMakeLists.txt
===
--- clang-tools-extra/clangd/unittests/CMakeLists.txt
+++ clang-tools-extra/clangd/unittests/CMakeLists.txt
@@ -117,6 +117,7 @@
   tweaks/ExtractFunctionTests.cpp
   tweaks/ExtractVariableTests.cpp
   tweaks/ObjCLocalizeStringLiteralTests.cpp
+  tweaks/ObjCMemberwiseInitializerTests.cpp
   tweaks/PopulateSwitchTests.cpp
   tweaks/RawStringLiteralTests.cpp
   tweaks/RemoveUsingNamespaceTests.cpp
Index: clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp
@@ -0,0 +1,332 @@
+//===--- 

[PATCH] D116385: [clangd] Code action for creating an ObjC initializer

2021-12-29 Thread David Goldman via Phabricator via cfe-commits
dgoldman created this revision.
Herald added subscribers: usaxena95, kadircet, arphaman, mgorny.
dgoldman requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

The code action creates an initializer for the selected
ivars/properties, defaulting to all if only the interface/implementation
container is selected.

We add it based on the position of the first non initializer that we
see, and default to adding it where the @end token is.

We also use the ObjC parameter form of (nullable id) instead of
(id _Nullable) if the property has the nullable attribute.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116385

Files:
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp
  clang-tools-extra/clangd/unittests/CMakeLists.txt
  clang-tools-extra/clangd/unittests/tweaks/ObjCMemberwiseInitializerTests.cpp

Index: clang-tools-extra/clangd/unittests/tweaks/ObjCMemberwiseInitializerTests.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/unittests/tweaks/ObjCMemberwiseInitializerTests.cpp
@@ -0,0 +1,150 @@
+//===-- ObjCMemberwiseInitializerTests.cpp --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestTU.h"
+#include "TweakTesting.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+TWEAK_TEST(ObjCMemberwiseInitializer);
+
+TEST_F(ObjCMemberwiseInitializerTest, TestAvailability) {
+  FileName = "TestTU.m";
+
+  // Ensure the action can't be triggered since arc is disabled.
+  EXPECT_UNAVAILABLE(R"cpp(
+@interface Fo^o
+@end
+  )cpp");
+
+  ExtraArgs.push_back("-fobjc-arc");
+
+  // Ensure the action can be initiated on the interface and implementation.
+  EXPECT_AVAILABLE(R"cpp(
+@interface Fo^o
+@end
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo
+@end
+
+@implementation F^oo
+@end
+  )cpp");
+
+  // Ensure that the action can be triggered on ivars and properties,
+  // including selecting both.
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo {
+  id _fi^eld;
+}
+@end
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo
+@property(nonatomic) id fi^eld;
+@end
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo {
+  id _fi^eld;
+}
+@property(nonatomic) id pr^op;
+@end
+  )cpp");
+
+  // Ensure that the action can't be triggered on property synthesis
+  // and methods.
+  EXPECT_UNAVAILABLE(R"cpp(
+@interface Foo
+@property(nonatomic) id prop;
+@end
+
+@implementation Foo
+@dynamic pr^op;
+@end
+  )cpp");
+  EXPECT_UNAVAILABLE(R"cpp(
+@interface Foo
+@end
+
+@implementation Foo
+- (void)fo^o {}
+@end
+  )cpp");
+}
+
+TEST_F(ObjCMemberwiseInitializerTest, Test) {
+  FileName = "TestTU.m";
+  ExtraArgs.push_back("-fobjc-arc");
+
+  const char *Input = R"cpp(
+@interface Foo {
+  id [[_field;
+}
+@property(nonatomic) id prop]];
+@property(nonatomic) id notSelected;
+@end)cpp";
+  const char *Output = R"cpp(
+@interface Foo {
+  id _field;
+}
+@property(nonatomic) id prop;
+@property(nonatomic) id notSelected;
+
+- (instancetype)initWithField:(id)field prop:(id)prop;
+
+@end)cpp";
+  EXPECT_EQ(apply(Input), Output);
+
+  Input = R"cpp(
+@interface Foo
+@property(nonatomic, nullable) id somePrettyLongPropertyName;
+@property(nonatomic, nonnull) id someReallyLongPropertyName;
+@end
+
+@implementation F^oo
+
+- (instancetype)init {
+  return self;
+}
+
+@end)cpp";
+  Output = R"cpp(
+@interface Foo
+@property(nonatomic, nullable) id somePrettyLongPropertyName;
+@property(nonatomic, nonnull) id someReallyLongPropertyName;
+@end
+
+@implementation Foo
+
+- (instancetype)init {
+  return self;
+}
+
+- (instancetype)initWithSomePrettyLongPropertyName:(nullable id)somePrettyLongPropertyName someReallyLongPropertyName:(nonnull id)someReallyLongPropertyName {
+  self = [super init];
+  if (self) {
+_somePrettyLongPropertyName = somePrettyLongPropertyName;
+_someReallyLongPropertyName = someReallyLongPropertyName;
+  }
+  return self;
+}
+
+@end)cpp";
+  EXPECT_EQ(apply(Input), Output);
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
Index: clang-tools-extra/clangd/unittests/CMakeLists.txt
===
--- clang-tools-extra/clangd/unittests/CMakeLists.txt
+++ clang-tools-extra/clangd/unittests/CMakeLists.txt
@@ -117,6 +117,7 @@
   tweaks/ExtractFunctionTests.cpp
   tweaks/ExtractVariableTests.cpp
   

[PATCH] D116369: [clang][dataflow] Add parameterized map lattice.

2021-12-29 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 396565.
ymandel added a comment.

addressed comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116369

Files:
  clang/include/clang/Analysis/FlowSensitive/MapLattice.h
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp
@@ -0,0 +1,156 @@
+#include "clang/Analysis/FlowSensitive/MapLattice.h"
+#include "clang/Analysis/FlowSensitive/DataflowLattice.h"
+#include "llvm/Support/Error.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+using namespace clang;
+using namespace dataflow;
+
+namespace {
+// A simple lattice for basic tests.
+class BooleanLattice {
+public:
+  BooleanLattice() : Value(false) {}
+  explicit BooleanLattice(bool B) : Value(B) {}
+
+  static BooleanLattice bottom() { return BooleanLattice(false); }
+
+  static BooleanLattice top() { return BooleanLattice(true); }
+
+  LatticeJoinEffect join(BooleanLattice Other) {
+auto Prev = Value;
+Value = Value || Other.Value;
+return Prev == Value ? LatticeJoinEffect::Unchanged
+ : LatticeJoinEffect::Changed;
+  }
+
+  friend bool operator==(BooleanLattice LHS, BooleanLattice RHS) {
+return LHS.Value == RHS.Value;
+  }
+
+  friend bool operator!=(BooleanLattice LHS, BooleanLattice RHS) {
+return LHS.Value != RHS.Value;
+  }
+
+  friend std::ostream <<(std::ostream , const BooleanLattice ) {
+Os << B.Value;
+return Os;
+  }
+
+  bool value() const { return Value; }
+
+private:
+  bool Value;
+};
+} // namespace
+
+static constexpr int Key1 = 0;
+static constexpr int Key2 = 1;
+
+namespace {
+using ::testing::Pair;
+using ::testing::UnorderedElementsAre;
+
+TEST(MapLatticeTest, InsertWorks) {
+  MapLattice Lattice;
+  Lattice.insert({Key1, BooleanLattice(false)});
+  Lattice.insert({Key2, BooleanLattice(false)});
+
+  EXPECT_THAT(Lattice, UnorderedElementsAre(Pair(Key1, BooleanLattice(false)),
+Pair(Key2, BooleanLattice(false;
+}
+
+TEST(MapLatticeTest, ComparisonWorks) {
+  MapLattice Lattice1;
+  Lattice1.insert({Key1, BooleanLattice(true)});
+  Lattice1.insert({Key2, BooleanLattice(false)});
+  MapLattice Lattice2 = Lattice1;
+  EXPECT_EQ(Lattice1, Lattice2);
+
+  Lattice2.find(Key2)->second = BooleanLattice(true);
+  EXPECT_NE(Lattice1, Lattice2);
+}
+
+TEST(MapLatticeTest, JoinChange) {
+  MapLattice Lattice1;
+  Lattice1.insert({Key1, BooleanLattice(false)});
+  Lattice1.insert({Key2, BooleanLattice(false)});
+
+  MapLattice Lattice2;
+  Lattice2.insert({Key1, BooleanLattice(true)});
+  Lattice2.insert({Key2, BooleanLattice(true)});
+
+  ASSERT_THAT(Lattice1,
+  UnorderedElementsAre(Pair(Key1, BooleanLattice(false)),
+   Pair(Key2, BooleanLattice(false;
+
+  ASSERT_EQ(Lattice1.join(Lattice2), LatticeJoinEffect::Changed);
+  EXPECT_THAT(Lattice1, UnorderedElementsAre(Pair(Key1, BooleanLattice(true)),
+ Pair(Key2, BooleanLattice(true;
+}
+
+TEST(MapLatticeTest, JoinEqNoChange) {
+  MapLattice Lattice;
+  Lattice.insert({Key1, BooleanLattice(false)});
+  Lattice.insert({Key2, BooleanLattice(false)});
+
+  ASSERT_EQ(Lattice.join(Lattice), LatticeJoinEffect::Unchanged);
+  EXPECT_THAT(Lattice, UnorderedElementsAre(Pair(Key1, BooleanLattice(false)),
+Pair(Key2, BooleanLattice(false;
+}
+
+TEST(MapLatticeTest, JoinLtNoChange) {
+  MapLattice Lattice1;
+  Lattice1.insert({Key1, BooleanLattice(false)});
+  Lattice1.insert({Key2, BooleanLattice(false)});
+
+  MapLattice Lattice2;
+  Lattice2.insert({Key1, BooleanLattice(true)});
+  Lattice2.insert({Key2, BooleanLattice(true)});
+
+  ASSERT_THAT(Lattice1,
+  UnorderedElementsAre(Pair(Key1, BooleanLattice(false)),
+   Pair(Key2, BooleanLattice(false;
+
+  ASSERT_THAT(Lattice2, UnorderedElementsAre(Pair(Key1, BooleanLattice(true)),
+ Pair(Key2, BooleanLattice(true;
+
+  ASSERT_EQ(Lattice2.join(Lattice1), LatticeJoinEffect::Unchanged);
+  EXPECT_THAT(Lattice2, UnorderedElementsAre(Pair(Key1, BooleanLattice(true)),
+ Pair(Key2, BooleanLattice(true;
+}
+
+TEST(MapLatticeTest, JoinDifferentDomainsProducesUnion) {
+  MapLattice Lattice1;
+  Lattice1.insert({Key1, BooleanLattice(true)});
+  MapLattice Lattice2;
+  Lattice2.insert({Key2, BooleanLattice(true)});
+
+  ASSERT_EQ(Lattice1.join(Lattice2), LatticeJoinEffect::Changed);
+  EXPECT_THAT(Lattice1, UnorderedElementsAre(Pair(Key1, BooleanLattice(true)),
+  

[PATCH] D115604: [Support] Expand `` as the base directory in configuration files.

2021-12-29 Thread Jack Andersen via Phabricator via cfe-commits
jackoalan updated this revision to Diff 396561.
jackoalan retitled this revision from "[Support] Expand `` as the base 
directory in response files." to "[Support] Expand `` as the base 
directory in configuration files.".
jackoalan added a comment.

Make `` constant at point of expansion. Use bool parameter to activate 
`` expansion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115604

Files:
  clang/docs/ReleaseNotes.rst
  clang/docs/UsersManual.rst
  llvm/include/llvm/Support/CommandLine.h
  llvm/lib/Support/CommandLine.cpp
  llvm/unittests/Support/CommandLineTest.cpp

Index: llvm/unittests/Support/CommandLineTest.cpp
===
--- llvm/unittests/Support/CommandLineTest.cpp
+++ llvm/unittests/Support/CommandLineTest.cpp
@@ -827,7 +827,7 @@
   llvm::BumpPtrAllocator A;
   llvm::StringSaver Saver(A);
   ASSERT_TRUE(llvm::cl::ExpandResponseFiles(
-  Saver, llvm::cl::TokenizeGNUCommandLine, Argv, false, true,
+  Saver, llvm::cl::TokenizeGNUCommandLine, Argv, false, true, false,
   /*CurrentDir=*/StringRef(TestRoot), FS));
   EXPECT_THAT(Argv, testing::Pointwise(
 StringEquality(),
@@ -889,9 +889,9 @@
 #else
   cl::TokenizerCallback Tokenizer = cl::TokenizeGNUCommandLine;
 #endif
-  ASSERT_FALSE(cl::ExpandResponseFiles(Saver, Tokenizer, Argv, false, false,
-   /*CurrentDir=*/llvm::StringRef(TestRoot),
-   FS));
+  ASSERT_FALSE(
+  cl::ExpandResponseFiles(Saver, Tokenizer, Argv, false, false, false,
+  /*CurrentDir=*/llvm::StringRef(TestRoot), FS));
 
   EXPECT_THAT(Argv,
   testing::Pointwise(StringEquality(),
@@ -929,7 +929,7 @@
   BumpPtrAllocator A;
   StringSaver Saver(A);
   ASSERT_FALSE(cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv,
-   false, false,
+   false, false, false,
/*CurrentDir=*/StringRef(TestRoot), FS));
 
   // ASSERT instead of EXPECT to prevent potential out-of-bounds access.
@@ -964,7 +964,7 @@
   BumpPtrAllocator A;
   StringSaver Saver(A);
   ASSERT_TRUE(cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv,
-  false, true,
+  false, true, false,
   /*CurrentDir=*/StringRef(TestRoot), FS));
   EXPECT_THAT(Argv,
   testing::Pointwise(StringEquality(), {"test/test", "-flag"}));
@@ -984,7 +984,7 @@
   BumpPtrAllocator A;
   StringSaver Saver(A);
   ASSERT_TRUE(cl::ExpandResponseFiles(Saver, cl::TokenizeWindowsCommandLine,
-  Argv, true, true,
+  Argv, true, true, false,
   /*CurrentDir=*/StringRef(TestRoot), FS));
   const char *Expected[] = {"clang", "-Xclang", "-Wno-whatever", nullptr,
 "input.cpp"};
@@ -1038,25 +1038,34 @@
   llvm::SmallVector Argv;
 
   TempDir TestDir("unittest", /*Unique*/ true);
+  TempDir TestSubDir(TestDir.path("subdir"), /*Unique*/ false);
 
-  llvm::SmallString<128> TestCfg;
-  llvm::sys::path::append(TestCfg, TestDir.path(), "foo");
-
+  llvm::SmallString<128> TestCfg = TestDir.path("foo");
   TempFile ConfigFile(TestCfg, "",
   "# Comment\n"
   "-option_1\n"
+  "-option_2=/dir1\n"
   "@subconfig\n"
-  "-option_3=abcd\n"
-  "-option_4=\\\n"
+  "-option_7=abcd\n"
+  "-option_8=\\\n"
   "cdef\n");
 
-  llvm::SmallString<128> TestCfg2;
-  llvm::sys::path::append(TestCfg2, TestDir.path(), "subconfig");
+  llvm::SmallString<128> TestCfg2 = TestDir.path("subconfig");
   TempFile ConfigFile2(TestCfg2, "",
-   "-option_2\n"
+   "-option_3\n"
+   "-option_4=/dir2\n"
+   "@subdir/subfoo\n"
"\n"
"   # comment\n");
 
+  llvm::SmallString<128> TestCfg3 = TestSubDir.path("subfoo");
+  TempFile ConfigFile3(TestCfg3, "",
+   "-option_5=/dir3\n"
+   "@/subfoo2\n");
+
+  llvm::SmallString<128> TestCfg4 = TestSubDir.path("subfoo2");
+  TempFile ConfigFile4(TestCfg4, "", "-option_6=qwerty\n");
+
   // Make sure the current directory is not the directory where config files
   // resides. In this case the code that expands response files will not find
   // 'subconfig' unless it resolves nested inclusions relative to the including
@@ -1071,11 +1080,18 @@
   bool Result = llvm::cl::readConfigFile(ConfigFile.path(), Saver, Argv);
 
   EXPECT_TRUE(Result);
-  

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

2021-12-29 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea added inline comments.



Comment at: clang/lib/CodeGen/MicrosoftCXXABI.cpp:2470
+// Dynamic TLS initialization works by checking the state of a
+// guard varibale (__tls_guard) to see whether TLS initialization
+// for a thread has happend yet.

s/varibale/variable/



Comment at: clang/lib/CodeGen/MicrosoftCXXABI.cpp:2477
+
+  // Emit the variable just like any regular global variable
+

Missing period at the end of the sentence please.



Comment at: clang/test/CodeGenCXX/ms-thread_local.cpp:1
-// RUN: %clang_cc1 %s -std=c++1y -triple=i686-pc-win32 -emit-llvm -o - | 
FileCheck %s
-// RUN: %clang_cc1 %s  -std=c++1y -triple=i686-pc-win32 
-ftls-model=local-dynamic -emit-llvm -o - | FileCheck %s -check-prefix=CHECK-LD
+// RUN: %clang_cc1 %s -std=c++1y -triple=i686-pc-win32 
-fms-compatibility-version=1925 -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 %s -std=c++1y -triple=i686-pc-win32 
-fms-compatibility-version=1925 -ftls-model=local-dynamic -emit-llvm -o - | 
FileCheck %s -check-prefix=CHECK-LD

Also please check with `-fms-compatibility-version=1920` to ensure that the 
dynamic initialization isn't generated.


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

https://reviews.llvm.org/D115456

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


[PATCH] D116370: [clang][dataflow] Add multi-variable constant propagation example.

2021-12-29 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added inline comments.



Comment at: 
clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp:375-376
+  Pair("p2", HoldsCPLattice(UnorderedElementsAre(
+ Pair(Var("target"), HasConstantVal(2)),
+ Pair(Var("other"), HasConstantVal(3)));
+}

sgatev wrote:
> This seems incorrect. The lattice elements for `target` and `other` should be 
> `top` at `p2`.
Yes, great point. I've updated the tests and fixed handling of uninitialized 
variables.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116370

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


[PATCH] D116370: [clang][dataflow] Add multi-variable constant propagation example.

2021-12-29 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 396557.
ymandel marked an inline comment as done.
ymandel added a comment.

Fix handling of uninitialized variables.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116370

Files:
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
@@ -0,0 +1,483 @@
+//===- unittests/Analysis/FlowSensitive/SingelVarConstantPropagation.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 defines a simplistic version of Constant Propagation as an example
+// of a forward, monotonic dataflow analysis. The analysis tracks all
+// variables in the scope, but lacks escape analysis.
+//
+//===--===//
+
+#include "TestingSupport.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/DataflowLattice.h"
+#include "clang/Analysis/FlowSensitive/MapLattice.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/Twine.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Testing/Support/Annotations.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace clang {
+namespace dataflow {
+namespace {
+using namespace ast_matchers;
+
+// Models the value of an expression at a program point, for all paths through
+// the program.
+struct ValueLattice {
+  enum class ValueState : bool {
+Undefined,
+Defined,
+  };
+  // `State` determines the meaning of the lattice when `Value` is `None`:
+  //  * `Undefined` -> bottom,
+  //  * `Defined` -> top.
+  ValueState State;
+
+  // When `None`, the lattice is either at top or bottom, based on `State`.
+  llvm::Optional Value;
+
+  constexpr ValueLattice() : State(ValueState::Undefined), Value(llvm::None) {}
+  constexpr ValueLattice(int64_t V) : State(ValueState::Defined), Value(V) {}
+  constexpr ValueLattice(ValueState S) : State(S), Value(llvm::None) {}
+
+  static constexpr ValueLattice bottom() {
+return ValueLattice(ValueState::Undefined);
+  }
+  static constexpr ValueLattice top() {
+return ValueLattice(ValueState::Defined);
+  }
+
+  friend bool operator==(const ValueLattice , const ValueLattice ) {
+return Lhs.State == Rhs.State && Lhs.Value == Rhs.Value;
+  }
+  friend bool operator!=(const ValueLattice , const ValueLattice ) {
+return !(Lhs == Rhs);
+  }
+
+  LatticeJoinEffect join(const ValueLattice ) {
+if (*this == Other || Other == bottom() || *this == top())
+  return LatticeJoinEffect::Unchanged;
+
+if (*this == bottom()) {
+  *this = Other;
+  return LatticeJoinEffect::Changed;
+}
+
+*this = top();
+return LatticeJoinEffect::Changed;
+  }
+};
+
+std::ostream <<(std::ostream , const ValueLattice ) {
+  if (L.Value.hasValue())
+return OS << *L.Value;
+  switch (L.State) {
+  case ValueLattice::ValueState::Undefined:
+return OS << "None";
+  case ValueLattice::ValueState::Defined:
+return OS << "Any";
+  }
+}
+
+using ConstantPropagationLattice = VarMapLattice;
+
+constexpr char kDecl[] = "decl";
+constexpr char kVar[] = "var";
+constexpr char kInit[] = "init";
+constexpr char kJustAssignment[] = "just-assignment";
+constexpr char kAssignment[] = "assignment";
+constexpr char kRHS[] = "rhs";
+
+auto refToVar() { return declRefExpr(to(varDecl().bind(kVar))); }
+
+// N.B. This analysis is deliberately simplistic, leaving out many important
+// details needed for a real analysis. Most notably, the transfer function does
+// not account for the variable's address possibly escaping, which would
+// invalidate the analysis. It also could be optimized to drop out-of-scope
+// variables from the map.
+class ConstantPropagationAnalysis
+: public DataflowAnalysis {
+public:
+  explicit ConstantPropagationAnalysis(ASTContext )
+  : DataflowAnalysis(Context) {}
+
+  static ConstantPropagationLattice initialElement() {
+return ConstantPropagationLattice::bottom();
+  }
+

[PATCH] D116328: [ast-matchers] Add hasSubstmt() traversal matcher for caseStmt(), defaultStmt(), labelStmt()

2021-12-29 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood updated this revision to Diff 396556.
LegalizeAdulthood added a comment.

clang-format


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

https://reviews.llvm.org/D116328

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -145,6 +145,23 @@
 HasDescendantVariableI));
 }
 
+TEST_P(ASTMatchersTest, HasCaseSubstmt) {
+  EXPECT_TRUE(matches(
+  "void f() { switch (1) { case 1: return; break; default: break; } }",
+  traverse(TK_AsIs, caseStmt(hasSubstmt(returnStmt());
+}
+
+TEST_P(ASTMatchersTest, HasDefaultSubstmt) {
+  EXPECT_TRUE(matches(
+  "void f() { switch (1) { case 1: return; break; default: break; } }",
+  traverse(TK_AsIs, defaultStmt(hasSubstmt(breakStmt());
+}
+
+TEST_P(ASTMatchersTest, HasLabelSubstmt) {
+  EXPECT_TRUE(matches("void f() { while (1) { bar: break; foo: return; } }",
+  traverse(TK_AsIs, labelStmt(hasSubstmt(breakStmt());
+}
+
 TEST(TypeMatcher, MatchesClassType) {
   TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
 
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -66,7 +66,7 @@
 
 #define REGISTER_MATCHER(name) \
   registerMatcher(#name, internal::makeMatcherAutoMarshall(\
- ::clang::ast_matchers::name, #name));
+ ::clang::ast_matchers::name, #name))
 
 #define REGISTER_MATCHER_OVERLOAD(name)\
   registerMatcher(#name,   \
@@ -143,7 +143,7 @@
   REGISTER_MATCHER(atomicType);
   REGISTER_MATCHER(attr);
   REGISTER_MATCHER(autoType);
-  REGISTER_MATCHER(autoreleasePoolStmt)
+  REGISTER_MATCHER(autoreleasePoolStmt);
   REGISTER_MATCHER(binaryConditionalOperator);
   REGISTER_MATCHER(binaryOperator);
   REGISTER_MATCHER(binaryOperation);
@@ -355,6 +355,7 @@
   REGISTER_MATCHER(hasSpecializedTemplate);
   REGISTER_MATCHER(hasStaticStorageDuration);
   REGISTER_MATCHER(hasStructuredBlock);
+  REGISTER_MATCHER(hasSubstmt);
   REGISTER_MATCHER(hasSyntacticForm);
   REGISTER_MATCHER(hasTargetDecl);
   REGISTER_MATCHER(hasTemplateArgument);
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -2429,6 +2429,7 @@
 /// Matches co_await expressions where the type of the promise is dependent
 extern const internal::VariadicDynCastAllOfMatcher
 dependentCoawaitExpr;
+
 /// Matches co_yield expressions.
 ///
 /// Given
@@ -7716,6 +7717,29 @@
   return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
 }
 
+/// Matches the substatement associated with a case, default or label statement.
+///
+/// Given
+/// \code
+///   switch (1) { case 1: break; case 2: return; break; default: return; break;
+///   }
+///   foo: return;
+///   bar: break;
+/// \endcode
+///
+/// caseStmt(hasSubstmt(returnStmt()))
+///   matches "case 2: return;"
+/// defaultStmt(hasSubstmt(returnStmt()))
+///   matches "default: return;"
+/// labelStmt(hasSubstmt(breakStmt()))
+///   matches "bar: break;"
+AST_POLYMORPHIC_MATCHER_P(hasSubstmt,
+  AST_POLYMORPHIC_SUPPORTED_TYPES(CaseStmt, DefaultStmt,
+  LabelStmt),
+  internal::Matcher, InnerMatcher) {
+  return InnerMatcher.matches(*Node.getSubStmt(), Finder, Builder);
+}
+
 /// Matches declaration that has a given attribute.
 ///
 /// Given
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/LibASTMatchersReference.html
@@ -7298,6 +7298,16 @@
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CaseStmt.html;>CaseStmthasSubstmtMatcherhttps://clang.llvm.org/doxygen/classclang_1_1Stmt.html;>Stmt InnerMatcher
+Matches the substatement associated with a case statement.
+
+Given
+  switch (1) { case 1: break; case 2: return; break; default: return; break; }
+caseStmt(hasSubstmt(returnStmt()))
+  matches "case 2: return;"
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CastExpr.html;>CastExprhasSourceExpressionMatcherhttps://clang.llvm.org/doxygen/classclang_1_1Expr.html;>Expr InnerMatcher
 

[PATCH] D111081: [clang] [MinGW] Fix paths on Gentoo

2021-12-29 Thread Michał Górny via Phabricator via cfe-commits
mgorny added a comment.

Well, I dunno how MinGW works, so can't judge that part. Furthermore, I'm 
thoroughly confused why this works on top of existing (non-Gentoo?) test tree. 
Could you explain it a bit more?


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

https://reviews.llvm.org/D111081

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


[PATCH] D116170: [clang-format] Add penalty for breaking after '('

2021-12-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116170

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


[PATCH] D116170: [clang-format] Add penalty for breaking after '('

2021-12-29 Thread G Pery via Phabricator via cfe-commits
GPery added a comment.

Fixed and marked :D


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116170

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


[PATCH] D116170: [clang-format] Add penalty for breaking after '('

2021-12-29 Thread G Pery via Phabricator via cfe-commits
GPery updated this revision to Diff 396547.
GPery marked 4 inline comments as done.
GPery added a comment.

Now using verifyFormat!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116170

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -18512,6 +18512,66 @@
 format("int a = /* long block comment */ 42;", Style));
 }
 
+TEST_F(FormatTest, BreakPenaltyAfterLParen) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 8;
+  Style.PenaltyExcessCharacter = 15;
+  verifyFormat("int foo(\n"
+   "int );",
+   Style);
+  Style.PenaltyBreakOpenParenthesis = 200;
+  EXPECT_EQ("int foo(int );",
+format("int foo(\n"
+   "int );",
+   Style));
+}
+
+TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 5;
+  Style.PenaltyExcessCharacter = 150;
+  verifyFormat("foo((\n"
+   "int));",
+
+   Style);
+  Style.PenaltyBreakOpenParenthesis = 10;
+  EXPECT_EQ("foo((int)\n"
+");",
+format("foo((\n"
+   "int));",
+   Style));
+}
+
+TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 4;
+  Style.PenaltyExcessCharacter = 100;
+  verifyFormat("for (\n"
+   "int i =\n"
+   "0;\n"
+   "i <\n"
+   "2;\n"
+   "i++) {\n"
+   "}",
+
+   Style);
+  Style.PenaltyBreakOpenParenthesis = 1250;
+  EXPECT_EQ("for (int i =\n"
+" 0;\n"
+" i <\n"
+" 2;\n"
+" i++) {\n"
+"}",
+format("for (\n"
+   "int i =\n"
+   "0;\n"
+   "i <\n"
+   "2;\n"
+   "i++) {\n"
+   "}",
+   Style));
+}
+
 #define EXPECT_ALL_STYLES_EQUAL(Styles)\
   for (size_t i = 1; i < Styles.size(); ++i)   \
   EXPECT_EQ(Styles[0], Styles[i])  \
@@ -18717,6 +18777,8 @@
   PenaltyBreakBeforeFirstCallParameter, 1234u);
   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
   PenaltyBreakTemplateDeclaration, 1234u);
+  CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
+  1234u);
   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
   PenaltyReturnTypeOnItsOwnLine, 1234u);
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2857,6 +2857,8 @@
   Left.Previous->isOneOf(tok::identifier, tok::greater))
 return 500;
 
+  if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0)
+return Style.PenaltyBreakOpenParenthesis;
   if (Left.is(tok::l_paren) && InFunctionDecl &&
   Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
 return 100;
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -756,6 +756,8 @@
 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
 IO.mapOptional("PenaltyBreakFirstLessLess",
Style.PenaltyBreakFirstLessLess);
+IO.mapOptional("PenaltyBreakOpenParenthesis",
+   Style.PenaltyBreakOpenParenthesis);
 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
 IO.mapOptional("PenaltyBreakTemplateDeclaration",
Style.PenaltyBreakTemplateDeclaration);
@@ -1232,6 +1234,7 @@
   LLVMStyle.PenaltyExcessCharacter = 100;
   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
   LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
+  LLVMStyle.PenaltyBreakOpenParenthesis = 0;
   LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational;
   LLVMStyle.PenaltyIndentedWhitespace = 0;
 

[PATCH] D115604: [Support] Expand `` as the base directory in response files.

2021-12-29 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added a comment.

The name of the patch could be more precise if you change `response files` to 
`configuration files`.




Comment at: clang/docs/UsersManual.rst:926-927
+
+A potential `` use-case may be search paths in a portable (i.e. not
+installed) SDK directory for embedded development. The user may only need to
+specify a root configuration file to establish every aspect of the SDK with the

It does not describe the use case clearly. Such macro is useful in the cases 
when configuration file is kept together with SDK content so that location of 
various SDK component can be expressed using the file location. Something about 
that could be provided here.



Comment at: llvm/include/llvm/Support/CommandLine.h:2117
+ llvm::vfs::FileSystem ,
+ StringRef ExpandBasePathToken = {});
 

It seems that this parameter can be boolean. It only instructs to call 
`ExpandBasePaths`, which knows what to expand.



Comment at: llvm/include/llvm/Support/CommandLine.h:2126
+llvm::Optional CurrentDir = llvm::None,
+StringRef ExpandBasePathToken = {});
 

The same about boolean parameter.



Comment at: llvm/lib/Support/CommandLine.cpp:1082
+// Substitute token with the file's base path.
+static void ExpandBasePaths(StringRef BasePath, StringRef Token,
+StringSaver , const char *) {

It seems that the parameter `Token` is not needed, as it is always ``.



Comment at: llvm/lib/Support/CommandLine.cpp:1118
+  llvm::vfs::FileSystem ,
+  StringRef ExpandBasePathToken) {
   assert(sys::path::is_absolute(FName));

It also could be boolean.



Comment at: llvm/lib/Support/CommandLine.cpp:1184
+ llvm::vfs::FileSystem ,
+ StringRef ExpandBasePathToken) {
   bool AllExpanded = true;

It could be boolean.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115604

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


[clang] ee3f557 - [Basic] Drop unnecessary const from return types (NFC)

2021-12-29 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2021-12-29T08:55:37-08:00
New Revision: ee3f557a9cfefdcf07d4fc1394cb05098a2c2508

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

LOG: [Basic] Drop unnecessary const from return types (NFC)

Identified with readability-const-return-type.

Added: 


Modified: 
clang/include/clang/Basic/TargetID.h
clang/lib/Basic/TargetID.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/TargetID.h 
b/clang/include/clang/Basic/TargetID.h
index a55b15e9b92c0..2579276fc0340 100644
--- a/clang/include/clang/Basic/TargetID.h
+++ b/clang/include/clang/Basic/TargetID.h
@@ -21,7 +21,7 @@ namespace clang {
 /// postfixed by a plus or minus sign delimited by colons, e.g.
 /// gfx908:xnack+:sramecc-. Each processor have a limited
 /// number of predefined features when showing up in a target ID.
-const llvm::SmallVector
+llvm::SmallVector
 getAllPossibleTargetIDFeatures(const llvm::Triple ,
llvm::StringRef Processor);
 

diff  --git a/clang/lib/Basic/TargetID.cpp b/clang/lib/Basic/TargetID.cpp
index 59d416f0e015d..3b8f4c13b9bf0 100644
--- a/clang/lib/Basic/TargetID.cpp
+++ b/clang/lib/Basic/TargetID.cpp
@@ -15,7 +15,7 @@
 
 namespace clang {
 
-static const llvm::SmallVector
+static llvm::SmallVector
 getAllPossibleAMDGPUTargetIDFeatures(const llvm::Triple ,
  llvm::StringRef Proc) {
   // Entries in returned vector should be in alphabetical order.
@@ -33,7 +33,7 @@ getAllPossibleAMDGPUTargetIDFeatures(const llvm::Triple ,
   return Ret;
 }
 
-const llvm::SmallVector
+llvm::SmallVector
 getAllPossibleTargetIDFeatures(const llvm::Triple ,
llvm::StringRef Processor) {
   llvm::SmallVector Ret;



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


[PATCH] D116328: [ast-matchers] Add hasSubstmt() traversal matcher for caseStmt(), defaultStmt(), labelStmt()

2021-12-29 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood updated this revision to Diff 396543.
LegalizeAdulthood added a comment.

Correct HTML copy/paste error for labelStmt() traversal


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

https://reviews.llvm.org/D116328

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -145,6 +145,24 @@
 HasDescendantVariableI));
 }
 
+TEST_P(ASTMatchersTest, HasCaseSubstmt) {
+EXPECT_TRUE(matches(
+"void f() { switch (1) { case 1: return; break; default: break; } }",
+traverse(TK_AsIs, caseStmt(hasSubstmt(returnStmt());
+}
+
+TEST_P(ASTMatchersTest, HasDefaultSubstmt) {
+EXPECT_TRUE(matches(
+"void f() { switch (1) { case 1: return; break; default: break; } }",
+traverse(TK_AsIs, defaultStmt(hasSubstmt(breakStmt());
+}
+
+TEST_P(ASTMatchersTest, HasLabelSubstmt) {
+EXPECT_TRUE(matches(
+"void f() { while (1) { bar: break; foo: return; } }",
+traverse(TK_AsIs, labelStmt(hasSubstmt(breakStmt());
+}
+
 TEST(TypeMatcher, MatchesClassType) {
   TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
 
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -66,7 +66,7 @@
 
 #define REGISTER_MATCHER(name) \
   registerMatcher(#name, internal::makeMatcherAutoMarshall(\
- ::clang::ast_matchers::name, #name));
+ ::clang::ast_matchers::name, #name))
 
 #define REGISTER_MATCHER_OVERLOAD(name)\
   registerMatcher(#name,   \
@@ -143,7 +143,7 @@
   REGISTER_MATCHER(atomicType);
   REGISTER_MATCHER(attr);
   REGISTER_MATCHER(autoType);
-  REGISTER_MATCHER(autoreleasePoolStmt)
+  REGISTER_MATCHER(autoreleasePoolStmt);
   REGISTER_MATCHER(binaryConditionalOperator);
   REGISTER_MATCHER(binaryOperator);
   REGISTER_MATCHER(binaryOperation);
@@ -355,6 +355,7 @@
   REGISTER_MATCHER(hasSpecializedTemplate);
   REGISTER_MATCHER(hasStaticStorageDuration);
   REGISTER_MATCHER(hasStructuredBlock);
+  REGISTER_MATCHER(hasSubstmt);
   REGISTER_MATCHER(hasSyntacticForm);
   REGISTER_MATCHER(hasTargetDecl);
   REGISTER_MATCHER(hasTemplateArgument);
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -2429,6 +2429,7 @@
 /// Matches co_await expressions where the type of the promise is dependent
 extern const internal::VariadicDynCastAllOfMatcher
 dependentCoawaitExpr;
+
 /// Matches co_yield expressions.
 ///
 /// Given
@@ -7716,6 +7717,29 @@
   return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
 }
 
+/// Matches the substatement associated with a case, default or label statement.
+///
+/// Given
+/// \code
+///   switch (1) { case 1: break; case 2: return; break; default: return; break;
+///   }
+///   foo: return;
+///   bar: break;
+/// \endcode
+///
+/// caseStmt(hasSubstmt(returnStmt()))
+///   matches "case 2: return;"
+/// defaultStmt(hasSubstmt(returnStmt()))
+///   matches "default: return;"
+/// labelStmt(hasSubstmt(breakStmt()))
+///   matches "bar: break;"
+AST_POLYMORPHIC_MATCHER_P(hasSubstmt,
+  AST_POLYMORPHIC_SUPPORTED_TYPES(CaseStmt, DefaultStmt,
+  LabelStmt),
+  internal::Matcher, InnerMatcher) {
+  return InnerMatcher.matches(*Node.getSubStmt(), Finder, Builder);
+}
+
 /// Matches declaration that has a given attribute.
 ///
 /// Given
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/LibASTMatchersReference.html
@@ -7298,6 +7298,16 @@
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CaseStmt.html;>CaseStmthasSubstmtMatcherhttps://clang.llvm.org/doxygen/classclang_1_1Stmt.html;>Stmt InnerMatcher
+Matches the substatement associated with a case statement.
+
+Given
+  switch (1) { case 1: break; case 2: return; break; default: return; break; }
+caseStmt(hasSubstmt(returnStmt()))
+  matches "case 2: return;"
+
+
+
 

[PATCH] D116328: [ast-matchers] Add hasSubstmt() traversal matcher for caseStmt(), defaultStmt(), labelStmt()

2021-12-29 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood updated this revision to Diff 396542.
LegalizeAdulthood retitled this revision from "[ast-matchers] Add hasSubstmt() 
traversal matcher for caseStmt(), defaultStmt()" to "[ast-matchers] Add 
hasSubstmt() traversal matcher for caseStmt(), defaultStmt(), labelStmt()".
LegalizeAdulthood edited the summary of this revision.
LegalizeAdulthood added a comment.

Update to include labelStmt()
Move the unit tests to ASTMatchersTraversalTest.cpp


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

https://reviews.llvm.org/D116328

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -145,6 +145,24 @@
 HasDescendantVariableI));
 }
 
+TEST_P(ASTMatchersTest, HasCaseSubstmt) {
+EXPECT_TRUE(matches(
+"void f() { switch (1) { case 1: return; break; default: break; } }",
+traverse(TK_AsIs, caseStmt(hasSubstmt(returnStmt());
+}
+
+TEST_P(ASTMatchersTest, HasDefaultSubstmt) {
+EXPECT_TRUE(matches(
+"void f() { switch (1) { case 1: return; break; default: break; } }",
+traverse(TK_AsIs, defaultStmt(hasSubstmt(breakStmt());
+}
+
+TEST_P(ASTMatchersTest, HasLabelSubstmt) {
+EXPECT_TRUE(matches(
+"void f() { while (1) { bar: break; foo: return; } }",
+traverse(TK_AsIs, labelStmt(hasSubstmt(breakStmt());
+}
+
 TEST(TypeMatcher, MatchesClassType) {
   TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
 
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -66,7 +66,7 @@
 
 #define REGISTER_MATCHER(name) \
   registerMatcher(#name, internal::makeMatcherAutoMarshall(\
- ::clang::ast_matchers::name, #name));
+ ::clang::ast_matchers::name, #name))
 
 #define REGISTER_MATCHER_OVERLOAD(name)\
   registerMatcher(#name,   \
@@ -143,7 +143,7 @@
   REGISTER_MATCHER(atomicType);
   REGISTER_MATCHER(attr);
   REGISTER_MATCHER(autoType);
-  REGISTER_MATCHER(autoreleasePoolStmt)
+  REGISTER_MATCHER(autoreleasePoolStmt);
   REGISTER_MATCHER(binaryConditionalOperator);
   REGISTER_MATCHER(binaryOperator);
   REGISTER_MATCHER(binaryOperation);
@@ -355,6 +355,7 @@
   REGISTER_MATCHER(hasSpecializedTemplate);
   REGISTER_MATCHER(hasStaticStorageDuration);
   REGISTER_MATCHER(hasStructuredBlock);
+  REGISTER_MATCHER(hasSubstmt);
   REGISTER_MATCHER(hasSyntacticForm);
   REGISTER_MATCHER(hasTargetDecl);
   REGISTER_MATCHER(hasTemplateArgument);
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -2429,6 +2429,7 @@
 /// Matches co_await expressions where the type of the promise is dependent
 extern const internal::VariadicDynCastAllOfMatcher
 dependentCoawaitExpr;
+
 /// Matches co_yield expressions.
 ///
 /// Given
@@ -7716,6 +7717,29 @@
   return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
 }
 
+/// Matches the substatement associated with a case, default or label statement.
+///
+/// Given
+/// \code
+///   switch (1) { case 1: break; case 2: return; break; default: return; break;
+///   }
+///   foo: return;
+///   bar: break;
+/// \endcode
+///
+/// caseStmt(hasSubstmt(returnStmt()))
+///   matches "case 2: return;"
+/// defaultStmt(hasSubstmt(returnStmt()))
+///   matches "default: return;"
+/// labelStmt(hasSubstmt(breakStmt()))
+///   matches "bar: break;"
+AST_POLYMORPHIC_MATCHER_P(hasSubstmt,
+  AST_POLYMORPHIC_SUPPORTED_TYPES(CaseStmt, DefaultStmt,
+  LabelStmt),
+  internal::Matcher, InnerMatcher) {
+  return InnerMatcher.matches(*Node.getSubStmt(), Finder, Builder);
+}
+
 /// Matches declaration that has a given attribute.
 ///
 /// Given
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/LibASTMatchersReference.html
@@ -7298,6 +7298,16 @@
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CaseStmt.html;>CaseStmthasSubstmtMatcherhttps://clang.llvm.org/doxygen/classclang_1_1Stmt.html;>Stmt InnerMatcher
+Matches the substatement 

[PATCH] D116378: Disable clang-tidy warnings from system macros

2021-12-29 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp created this revision.
carlosgalvezp added reviewers: aaron.ballman, whisperity, salman-javed-nz.
carlosgalvezp added a project: clang-tools-extra.
Herald added subscribers: rnkovacs, kbarton, nemanjai.
carlosgalvezp requested review of this revision.
Herald added a subscriber: cfe-commits.

Currently, it's inconsistent that warnings are disabled if they
come from system headers, unless they come from macros.
Typically a user cannot act upon these warnings coming from
system macros, so clang-tidy should ignore them unless the
user specifically requests warnings from system headers
via the corresponding configuration.

Update the cppcoreguidelines check to use a PP callback
in order to find the problematic macro at macro expansion
time instead. The old AST matcher is kept for Windows
compatibility.

Add unit test that ensures warnings from macros are disabled
when not using the -system-headers flag. Document the change
in the Release Notes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116378

Files:
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/infrastructure/Inputs/file-filter/system/system-header.h
  clang-tools-extra/test/clang-tidy/infrastructure/file-filter.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/file-filter.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/file-filter.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/file-filter.cpp
@@ -9,6 +9,8 @@
 //   file-filter\header*.h due to code order between '/' and '\\'.
 // RUN: clang-tidy -checks='-*,google-explicit-constructor' -header-filter='.*' -system-headers %s -- -I %S/Inputs/file-filter/system/.. -isystem %S/Inputs/file-filter/system 2>&1 | FileCheck --check-prefix=CHECK4 %s
 // RUN: clang-tidy -checks='-*,google-explicit-constructor' -header-filter='.*' -system-headers -quiet %s -- -I %S/Inputs/file-filter/system/.. -isystem %S/Inputs/file-filter/system 2>&1 | FileCheck --check-prefix=CHECK4-QUIET %s
+// RUN: clang-tidy -checks='-*,cppcoreguidelines-pro-type-cstyle-cast' -header-filter='.*' -system-headers %s -- -I %S/Inputs/file-filter/system/.. -isystem %S/Inputs/file-filter/system 2>&1 | FileCheck --check-prefix=CHECK5 %s
+// RUN: clang-tidy -checks='-*,cppcoreguidelines-pro-type-cstyle-cast' -header-filter='.*' %s -- -I %S/Inputs/file-filter/system/.. -isystem %S/Inputs/file-filter/system 2>&1 | FileCheck --check-prefix=CHECK5-NO-SYSTEM-HEADERS %s
 
 #include "header1.h"
 // CHECK-NOT: warning:
@@ -71,3 +73,8 @@
 // CHECK4-NOT: Suppressed {{.*}} warnings
 // CHECK4-NOT: Use -header-filter=.* {{.*}}
 // CHECK4-QUIET-NOT: Suppressed
+
+int x = 123;
+auto x_ptr = TO_FLOAT_PTR();
+// CHECK5: :[[@LINE-1]]:14: warning: do not use C-style cast to convert between unrelated types
+// CHECK5-NO-SYSTEM-HEADERS-NOT: :[[@LINE-2]]:14: warning: do not use C-style cast to convert between unrelated types
Index: clang-tools-extra/test/clang-tidy/infrastructure/Inputs/file-filter/system/system-header.h
===
--- clang-tools-extra/test/clang-tidy/infrastructure/Inputs/file-filter/system/system-header.h
+++ clang-tools-extra/test/clang-tidy/infrastructure/Inputs/file-filter/system/system-header.h
@@ -1 +1,3 @@
 class A0 { A0(int); };
+
+#define TO_FLOAT_PTR(x) ((float *)(x))
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -67,10 +67,13 @@
 Improvements to clang-tidy
 --
 
-- Added support for globbing in `NOLINT*` expressions, to simplify suppressing
+- Ignore warnings from macros defined in system headers, if not using
+  the ``-system-headers`` flag.
+
+- Added support for globbing in ``NOLINT*`` expressions, to simplify suppressing
   multiple warnings in the same line.
 
-- Added support for `NOLINTBEGIN` ... `NOLINTEND` comments to suppress
+- Added support for ``NOLINTBEGIN`` ... ``NOLINTEND`` comments to suppress
   Clang-Tidy warnings over multiple lines.
 
 New checks
@@ -148,7 +151,7 @@
 
 - Fixed a false positive in :doc:`fuchsia-trailing-return
   ` for C++17 deduction guides.
-  
+
 - Fixed a false positive in :doc:`bugprone-throw-keyword-missing
   ` when creating an exception object
   using placement new
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.h
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.h
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.h
@@ -28,6 +28,8 @@
 return 

[clang] 298367e - [clang] Use nullptr instead of 0 or NULL (NFC)

2021-12-29 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2021-12-29T08:34:20-08:00
New Revision: 298367ee6e36eeb1b193ad9fa92082c2ef2345a3

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

LOG: [clang] Use nullptr instead of 0 or NULL (NFC)

Identified with modernize-use-nullptr.

Added: 


Modified: 
clang/lib/AST/ASTContext.cpp
clang/lib/AST/Type.cpp
clang/lib/CodeGen/CodeGenFunction.cpp
clang/lib/CodeGen/TargetInfo.cpp
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChains/WebAssembly.cpp
clang/lib/Interpreter/IncrementalParser.cpp
clang/lib/Lex/Lexer.cpp
clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
clang/tools/libclang/CIndex.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 008b703d4c1a9..ac6f98e91f755 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -8476,8 +8476,8 @@ static TypedefDecl *CreateHexagonBuiltinVaListDecl(const 
ASTContext *Context) {
 FieldDecl *Field = FieldDecl::Create(
 const_cast(*Context), VaListTagDecl, SourceLocation(),
 SourceLocation(), >Idents.get(FieldNames[i]), FieldTypes[i],
-/*TInfo=*/0,
-/*BitWidth=*/0,
+/*TInfo=*/nullptr,
+/*BitWidth=*/nullptr,
 /*Mutable=*/false, ICIS_NoInit);
 Field->setAccess(AS_public);
 VaListTagDecl->addDecl(Field);

diff  --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index c771fe264b0c8..774b3e94159db 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -194,7 +194,7 @@ void ConstantArrayType::Profile(llvm::FoldingSetNodeID ,
   ID.AddInteger(ArraySize.getZExtValue());
   ID.AddInteger(SizeMod);
   ID.AddInteger(TypeQuals);
-  ID.AddBoolean(SizeExpr != 0);
+  ID.AddBoolean(SizeExpr != nullptr);
   if (SizeExpr)
 SizeExpr->Profile(ID, Context, true);
 }

diff  --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index e6adec6948aff..4814962a472d4 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1595,9 +1595,9 @@ void CodeGenFunction::EmitBranchToCounterBlock(
   if (!InstrumentRegions || !isInstrumentedCondition(Cond))
 return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
 
-  llvm::BasicBlock *ThenBlock = NULL;
-  llvm::BasicBlock *ElseBlock = NULL;
-  llvm::BasicBlock *NextBlock = NULL;
+  llvm::BasicBlock *ThenBlock = nullptr;
+  llvm::BasicBlock *ElseBlock = nullptr;
+  llvm::BasicBlock *NextBlock = nullptr;
 
   // Create the block we'll use to increment the appropriate counter.
   llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");

diff  --git a/clang/lib/CodeGen/TargetInfo.cpp 
b/clang/lib/CodeGen/TargetInfo.cpp
index 85089cdb2200e..d0ba4e44bffa5 100644
--- a/clang/lib/CodeGen/TargetInfo.cpp
+++ b/clang/lib/CodeGen/TargetInfo.cpp
@@ -8693,7 +8693,7 @@ Address 
HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction ,
 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
 "__new_saved_reg_area_pointer");
 
-  llvm::Value *UsingStack = 0;
+  llvm::Value *UsingStack = nullptr;
   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
  __saved_reg_area_end_pointer);
 

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 3b551ea94cc24..a4a53d989851c 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -437,7 +437,7 @@ DerivedArgList *Driver::TranslateInputArgs(const 
InputArgList ) const {
 
   // Enforce -static if -miamcu is present.
   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
-DAL->AddFlagArg(0, Opts.getOption(options::OPT_static));
+DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_static));
 
 // Add a default value of -mlinker-version=, if one was given and the user
 // didn't specify one.

diff  --git a/clang/lib/Driver/ToolChains/WebAssembly.cpp 
b/clang/lib/Driver/ToolChains/WebAssembly.cpp
index a7298a9a71bfb..3614272a5f747 100644
--- a/clang/lib/Driver/ToolChains/WebAssembly.cpp
+++ b/clang/lib/Driver/ToolChains/WebAssembly.cpp
@@ -76,7 +76,7 @@ void wasm::Linker::ConstructJob(Compilation , const 
JobAction ,
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
   const char *Crt1 = "crt1.o";
-  const char *Entry = NULL;
+  const char *Entry = nullptr;
 
   // If crt1-command.o exists, it supports new-style commands, so use it.
   // Otherwise, use the old crt1.o. This is a temporary transition measure.

diff  --git a/clang/lib/Interpreter/IncrementalParser.cpp 
b/clang/lib/Interpreter/IncrementalParser.cpp
index 84eabc3a210f7..4ade8b8bb0741 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ 

[clang] 1b329fe - [clang] Remove unused "using" (NFC)

2021-12-29 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2021-12-29T08:27:29-08:00
New Revision: 1b329fe28206287e8a496b66cc68f4c1838a0230

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

LOG: [clang] Remove unused "using" (NFC)

Added: 


Modified: 
clang/lib/AST/FormatString.cpp
clang/lib/Driver/ToolChains/PS4CPU.cpp

Removed: 




diff  --git a/clang/lib/AST/FormatString.cpp b/clang/lib/AST/FormatString.cpp
index 83b952116a5e0..102bcca96a389 100644
--- a/clang/lib/AST/FormatString.cpp
+++ b/clang/lib/AST/FormatString.cpp
@@ -21,7 +21,6 @@ using clang::analyze_format_string::FormatStringHandler;
 using clang::analyze_format_string::FormatSpecifier;
 using clang::analyze_format_string::LengthModifier;
 using clang::analyze_format_string::OptionalAmount;
-using clang::analyze_format_string::PositionContext;
 using clang::analyze_format_string::ConversionSpecifier;
 using namespace clang;
 

diff  --git a/clang/lib/Driver/ToolChains/PS4CPU.cpp 
b/clang/lib/Driver/ToolChains/PS4CPU.cpp
index 5783a733983a9..bcf9147833ddf 100644
--- a/clang/lib/Driver/ToolChains/PS4CPU.cpp
+++ b/clang/lib/Driver/ToolChains/PS4CPU.cpp
@@ -23,8 +23,6 @@ using namespace clang::driver;
 using namespace clang;
 using namespace llvm::opt;
 
-using clang::driver::tools::AddLinkerInputs;
-
 void tools::PS4cpu::addProfileRTArgs(const ToolChain , const ArgList ,
  ArgStringList ) {
   if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,



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


[PATCH] D116283: [clang-format] Add an option to add a space between operator overloading and opening parentheses

2021-12-29 Thread Rajat Bajpai via Phabricator via cfe-commits
rajatbajpai added a comment.

In D116283#3211590 , 
@HazardyKnusperkeks wrote:

> Does it affect calling code? `a.operator++(5);` Should it? But please add 
> tests for that.

Yes, it does affect the calling code as well. However, I am not sure if we 
should separate the two. Sure, I'll add a test case for it.




Comment at: clang/docs/ClangFormatStyleOptions.rst:3755
 
+  * ``bool AfterOperatorOverloading`` If ``true``, put a space between 
operator overloading and opening parentheses.
+

MyDeveloperDay wrote:
> curdeius wrote:
> > I'm not fond of the current name, exactly the "Overloading" part (but have 
> > no better suggestion right now). It seems a bit misleading to me.
> > 
> > Maybe AfterOverloadedOperator(Name)??? At least it would match the token 
> > kind name.
> +1 here,  AfterOperator?
@MyDeveloperDay Initially, I thought about using //AfterOperator// but it also 
seems a bit misleading. However, @curdeius suggestion seems reasonable given it 
matches with the token kind.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116283

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


[PATCH] D116377: [libTooling] Adds more support for constructing object access expressions.

2021-12-29 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added a reviewer: gribozavr2.
ymandel requested review of this revision.
Herald added a project: clang.

This patch adds a `buildAccess` function, which constructs a string with the
proper operator to use based on the expression's form and type. It also adds two
predicates related to smart pointers, which are needed by `buildAccess` but are
also of general value.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116377

Files:
  clang/include/clang/Tooling/Transformer/SourceCodeBuilders.h
  clang/lib/Tooling/Transformer/SourceCodeBuilders.cpp
  clang/lib/Tooling/Transformer/Stencil.cpp
  clang/unittests/Tooling/SourceCodeBuildersTest.cpp

Index: clang/unittests/Tooling/SourceCodeBuildersTest.cpp
===
--- clang/unittests/Tooling/SourceCodeBuildersTest.cpp
+++ clang/unittests/Tooling/SourceCodeBuildersTest.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang/Tooling/Transformer/SourceCodeBuilders.h"
+#include "clang/AST/Type.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Tooling/Tooling.h"
@@ -24,8 +25,16 @@
 
 // Create a valid translation unit from a statement.
 static std::string wrapSnippet(StringRef StatementCode) {
-  return ("struct S { S(); S(int); int field; };\n"
+  return ("namespace std {\n"
+  "template  class unique_ptr {};\n"
+  "template  class shared_ptr {};\n"
+  "}\n"
+  "struct S { S(); S(int); int field; };\n"
   "S operator+(const S , const S );\n"
+  "struct Smart {\n"
+  "  S* operator->() const;\n"
+  "  S& operator*() const;\n"
+  "};\n"
   "auto test_snippet = []{" +
   StatementCode + "};")
   .str();
@@ -126,6 +135,69 @@
   testPredicateOnArg(mayEverNeedParens, "void f(S); f(3 + 5);", true);
 }
 
+TEST(SourceCodeBuildersTest, isSmartPointerTypeUniquePtr) {
+  std::string Snippet = "std::unique_ptr P; P;";
+  auto StmtMatch = matchStmt(Snippet, expr(hasType(qualType().bind("ty";
+  ASSERT_TRUE(StmtMatch) << "Snippet: " << Snippet;
+  EXPECT_TRUE(
+  isSmartPointerType(*StmtMatch->Result.Nodes.getNodeAs("ty"),
+ *StmtMatch->Result.Context))
+  << "Snippet: " << Snippet;
+}
+
+TEST(SourceCodeBuildersTest, isSmartPointerTypeSharedPtr) {
+  std::string Snippet = "std::shared_ptr P; P;";
+  auto StmtMatch = matchStmt(Snippet, expr(hasType(qualType().bind("ty";
+  ASSERT_TRUE(StmtMatch) << "Snippet: " << Snippet;
+  EXPECT_TRUE(
+  isSmartPointerType(*StmtMatch->Result.Nodes.getNodeAs("ty"),
+ *StmtMatch->Result.Context))
+  << "Snippet: " << Snippet;
+}
+
+TEST(SourceCodeBuildersTest, isSmartPointerTypeDuckType) {
+  std::string Snippet = "Smart P; P;";
+  auto StmtMatch = matchStmt(Snippet, expr(hasType(qualType().bind("ty";
+  ASSERT_TRUE(StmtMatch) << "Snippet: " << Snippet;
+  EXPECT_TRUE(
+  isSmartPointerType(*StmtMatch->Result.Nodes.getNodeAs("ty"),
+ *StmtMatch->Result.Context))
+  << "Snippet: " << Snippet;
+}
+
+TEST(SourceCodeBuildersTest, isSmartPointerTypeNormalTypeFalse) {
+  std::string Snippet = "int *P; P;";
+  auto StmtMatch = matchStmt(Snippet, expr(hasType(qualType().bind("ty";
+  ASSERT_TRUE(StmtMatch) << "Snippet: " << Snippet;
+  EXPECT_FALSE(
+  isSmartPointerType(*StmtMatch->Result.Nodes.getNodeAs("ty"),
+ *StmtMatch->Result.Context))
+  << "Snippet: " << Snippet;
+}
+
+TEST(SourceCodeBuildersTest, isSmartDereferenceTrue) {
+  std::string Snippet = "Smart P; *P;";
+  auto StmtMatch = matchStmt(
+  Snippet, expr(cxxOperatorCallExpr(hasUnaryOperand(expr().bind("arg"
+   .bind("expr"));
+  ASSERT_TRUE(StmtMatch) << "Snippet: " << Snippet;
+  const auto *Arg = StmtMatch->Result.Nodes.getNodeAs("arg");
+  EXPECT_EQ(Arg,
+isSmartDereference(*StmtMatch->Result.Nodes.getNodeAs("expr"),
+   *StmtMatch->Result.Context))
+  << "Snippet: " << Snippet;
+}
+
+TEST(SourceCodeBuildersTest, isSmartDereferenceFalse) {
+  std::string Snippet = "int *P; *P;";
+  auto StmtMatch = matchStmt(Snippet, expr().bind("expr"));
+  ASSERT_TRUE(StmtMatch) << "Snippet: " << Snippet;
+  EXPECT_EQ(nullptr,
+isSmartDereference(*StmtMatch->Result.Nodes.getNodeAs("expr"),
+   *StmtMatch->Result.Context))
+  << "Snippet: " << Snippet;
+}
+
 static void testBuilder(
 llvm::Optional (*Builder)(const Expr &, const ASTContext &),
 StringRef Snippet, StringRef Expected) {
@@ -136,6 +208,16 @@
   ValueIs(std::string(Expected)));
 }
 
+static void testBuilder(llvm::Optional (*Builder)(const Expr &,
+   ASTContext &),
+ 

[PATCH] D116368: [clang][dataflow] Add transfer function for VarDecl statements

2021-12-29 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 396537.
sgatev added a comment.

Convert pointers to references.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116368

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
  clang/include/clang/Analysis/FlowSensitive/Transfer.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Value.h
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/NoopAnalysis.h
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TestingSupportTest.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -6,12 +6,14 @@
 //
 //===--===//
 
+#include "NoopAnalysis.h"
 #include "TestingSupport.h"
 #include "clang/AST/Decl.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Tooling/Tooling.h"
@@ -28,6 +30,8 @@
 #include 
 #include 
 
+namespace {
+
 using namespace clang;
 using namespace dataflow;
 using ::testing::IsEmpty;
@@ -50,7 +54,8 @@
 ControlFlowContext::build(nullptr, Body, Result.Context));
 
 AnalysisT Analysis(*Result.Context);
-Environment Env;
+DataflowAnalysisContext DACtx;
+Environment Env(DACtx);
 BlockStates = runDataflowAnalysis(CFCtx, Analysis, Env);
   }
 
@@ -75,27 +80,6 @@
   return Callback.BlockStates;
 }
 
-class NoopLattice {
-public:
-  bool operator==(const NoopLattice &) const { return true; }
-
-  LatticeJoinEffect join(const NoopLattice &) {
-return LatticeJoinEffect::Unchanged;
-  }
-};
-
-class NoopAnalysis : public DataflowAnalysis {
-public:
-  NoopAnalysis(ASTContext )
-  : DataflowAnalysis(Context) {}
-
-  static NoopLattice initialElement() { return {}; }
-
-  NoopLattice transfer(const Stmt *S, const NoopLattice , Environment ) {
-return {};
-  }
-};
-
 TEST(DataflowAnalysisTest, NoopAnalysis) {
   auto BlockStates = runAnalysis(R"(
 void target() {}
@@ -314,3 +298,5 @@
   UnorderedElementsAre("baz", "foo"));
   // FIXME: Called functions at point `p` should contain only "foo".
 }
+
+} // namespace
Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -0,0 +1,618 @@
+//===- unittests/Analysis/FlowSensitive/TransferTest.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
+//
+//===--===//
+
+#include "NoopAnalysis.h"
+#include "TestingSupport.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/StorageLocation.h"
+#include "clang/Analysis/FlowSensitive/Value.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+#include 
+
+namespace {
+
+using namespace clang;
+using namespace dataflow;
+using ::testing::_;
+using ::testing::ElementsAre;
+using ::testing::IsNull;
+using ::testing::NotNull;
+using ::testing::Pair;
+
+class TransferTest : public ::testing::Test {
+protected:
+  template 
+  void runDataflow(llvm::StringRef Code, Matcher Match) {
+test::checkDataflow(
+Code, "target",
+[](ASTContext , Environment &) { return 

[PATCH] D116170: [clang-format] Add penalty for breaking after '('

2021-12-29 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

Looks good, use the `verifyFormat` and please mark comments as done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116170

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


[PATCH] D72326: [clang-format] Add option to explicitly specify a config file

2021-12-29 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks accepted this revision.
HazardyKnusperkeks added a comment.

Although there is no context. Maybe still update the uploaded diff for the 
archive.


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

https://reviews.llvm.org/D72326

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


[PATCH] D116351: Update Bug report URL to Github Issues

2021-12-29 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone accepted this revision.
Quuxplusone added a comment.

Tweaked English wording throughout. LGTM with all these modifications made.

Orthogonally, it does occur to me that one might save a //lot// of this churn 
(and also the next time the bug tracker moves, e.g. if we go from GitHub to 
something else) by simply HTTP-redirecting the front page of 
https://bugs.llvm.org/ to https://github.com/llvm/llvm-project/issues/ . Then 
we'd have a stable URL https://bugs.llvm.org/ for "reporting LLVM bugs, 
forever," and we could just use that stable URL everywhere. But OTOH, that's a 
devops task, whereas updating a bunch of documentation in the repo is easy. :)




Comment at: clang-tools-extra/docs/clang-doc.rst:15
 crashes. Submitting reports with information about how to reproduce the issue
-to `the LLVM bugtracker `_ will definitely help the
+to `the LLVM Issues `_ will 
definitely help the
 project. If you have any ideas or suggestions, please to put a feature request

Please leave the English wording as "the LLVM bugtracker" (or "the LLVM bug 
tracker" — really it should be two words). There is no such noun in English as 
"an Issues," which means that the reader won't have any idea what you're 
talking about here unless they click on the link to see where it goes.



Comment at: clang/www/c_status.html:75-76
 
-The https://bugs.llvm.org/;>LLVM bug tracker contains a
-Clang C component that tracks known bugs with Clang's language
+The https://github.com/llvm/llvm-project/issues/;>LLVM Issues 
contains
+issuses labeled with c/c11/c18/c2x that tracks known bugs with Clang's language
 conformance.





Comment at: clang/www/cxx_status.html:79-81
+The https://github.com/llvm/llvm-project/issues/;>LLVM Issues 
contains
+issues labelled with c++/c++11/c++14/c++17/c++20 that track known bugs with 
Clang's
+language conformance labelled in each language mode.

(I think `, "C++17", "C++20", "C++23"` would just be redundant/noise here, and 
would imply a thankless task for someone to go update this list every 3 years. 
Better to just cap it at one or two labels. The reader can be trusted to figure 
out that C++20 issues should be labeled with `C++20`.)



Comment at: clang/www/get_involved.html:68
 href="OpenProjects.html">Open Projects page or look through the https://bugs.llvm.org/;>Bugzilla bug database.
+href="https://github.com/llvm/llvm-project/issues/;>LLVM Issues.
 





Comment at: clang/www/get_started.html:22
 involved with the Clang community.  If you run into problems, please file
-bugs in https://bugs.llvm.org/;>LLVM Bugzilla.
+bugs in https://github.com/llvm/llvm-project/issues;>LLVM 
Issues.
 





Comment at: libcxx/docs/index.rst:220
 * `libc++abi Homepage `_
-* `LLVM Bugzilla `_
+* `LLVM Issues `_
 * `libcxx-commits Mailing List`_





Comment at: libunwind/docs/index.rst:101
 * `LLVM Homepage `_
-* `LLVM Bugzilla `_
+* `LLVM Issues `_
 * `cfe-commits Mailing List`_





Comment at: lld/docs/_templates/indexsidebar.html:3-4
 
 lld bugs should be reported at the
-  LLVM https://bugs.llvm.org/;>Bugzilla.
+  LLVM https://github.com/llvm/llvm-project/issues/;>Issues.




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

https://reviews.llvm.org/D116351

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


[PATCH] D116370: [clang][dataflow] Add multi-variable constant propagation example.

2021-12-29 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev added inline comments.



Comment at: 
clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp:375-376
+  Pair("p2", HoldsCPLattice(UnorderedElementsAre(
+ Pair(Var("target"), HasConstantVal(2)),
+ Pair(Var("other"), HasConstantVal(3)));
+}

This seems incorrect. The lattice elements for `target` and `other` should be 
`top` at `p2`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116370

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


[PATCH] D116368: [clang][dataflow] Add transfer function for VarDecl statements

2021-12-29 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev added inline comments.



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:56
+
+  /// Assigns `Loc` to `D`.
+  ///

ymandel wrote:
> The term "assignment" is overloaded. :) Maybe instead "Associates `Loc` with 
> `D`"? Or, expand on the meaning of the assignment? e.g. "Assigns `Loc` as the 
> storage location of `D`?
I opted for "Assigns `Loc` as the storage location of `D`."



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h:41
+  /// Creates a storage location appropriate for `Type`. Does not assign a 
value
+  /// to the returned storage location in the environment. Never returns null.
+  ///

ymandel wrote:
> here and below. If it never returns null, why not return a ref?
> For that matter, all of the pointer parameters with comments "must not be 
> null" -- can we just make those refs?
I replaced the pointers with references where possible.



Comment at: clang/include/clang/Analysis/FlowSensitive/StorageLocation.h:40-42
+private:
+  Kind LocKind;
+  QualType Type;

ymandel wrote:
> I don't think its required, but LLVM style typically puts private field decls 
> at the beginning of the class, without the explicit "private:" decl.
Ack. I prefer this order because it puts the public interface higher so the 
important bits can be found more easily. If this goes against the LLVM coding 
style I'd be happy to change it, but I prefer to do this separately because I 
already used this style in some of the other dataflow classes.



Comment at: clang/include/clang/Analysis/FlowSensitive/StorageLocation.h:52
+
+  static bool classof(const StorageLocation *Loc) {
+return Loc->getKind() == Kind::Scalar;

ymandel wrote:
> ref?
I believe this needs to accept a pointer to be compatible with operations 
defined in `llvm/Support/Casting.h`.



Comment at: clang/include/clang/Analysis/FlowSensitive/Value.h:37-38
+
+private:
+  Kind ValKind;
+};

ymandel wrote:
> Move to beginning of class decl?
Ack. I'll apply this separately if necessary.



Comment at: clang/include/clang/Analysis/FlowSensitive/Value.h:41
+
+/// Class that models an integer.
+class IntegerValue : public Value {

ymandel wrote:
> nit: Here and below. I think that "Models..." would be as good or better than 
> "Class that models...".
Yeap, that's better. Updated all comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116368

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


[PATCH] D105297: [OPENMP]Fix PR50347: Mapping of global scope deep object fails.

2021-12-29 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev updated this revision to Diff 396531.
ABataev added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105297

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/reduction_implicit_map.cpp
  clang/test/OpenMP/target_codegen.cpp
  clang/test/OpenMP/target_data_codegen.cpp
  clang/test/OpenMP/target_data_map_codegen_hold.cpp
  clang/test/OpenMP/target_data_map_pointer_array_subscript_codegen.cpp
  clang/test/OpenMP/target_data_use_device_addr_codegen.cpp
  clang/test/OpenMP/target_defaultmap_codegen_01.cpp
  clang/test/OpenMP/target_enter_data_codegen.cpp
  clang/test/OpenMP/target_enter_data_depend_codegen.cpp
  clang/test/OpenMP/target_exit_data_codegen.cpp
  clang/test/OpenMP/target_exit_data_depend_codegen.cpp
  clang/test/OpenMP/target_firstprivate_codegen.cpp
  clang/test/OpenMP/target_map_codegen_12.cpp
  clang/test/OpenMP/target_map_codegen_13.cpp
  clang/test/OpenMP/target_map_codegen_14.cpp
  clang/test/OpenMP/target_map_codegen_18.inc
  clang/test/OpenMP/target_map_codegen_20.cpp
  clang/test/OpenMP/target_map_codegen_23.cpp
  clang/test/OpenMP/target_map_codegen_28.cpp
  clang/test/OpenMP/target_map_codegen_29.cpp
  clang/test/OpenMP/target_map_codegen_31.cpp
  clang/test/OpenMP/target_map_codegen_32.cpp
  clang/test/OpenMP/target_map_codegen_34.cpp
  clang/test/OpenMP/target_map_codegen_35.cpp
  clang/test/OpenMP/target_map_codegen_hold.cpp
  clang/test/OpenMP/target_map_member_expr_array_section_codegen.cpp
  clang/test/OpenMP/target_parallel_codegen.cpp
  clang/test/OpenMP/target_parallel_for_codegen.cpp
  clang/test/OpenMP/target_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/target_simd_codegen.cpp
  clang/test/OpenMP/target_teams_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_collapse_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_dist_schedule_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_parallel_for_collapse_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_dist_schedule_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_parallel_for_schedule_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_collapse_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_dist_schedule_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_schedule_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_simd_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_simd_collapse_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_simd_dist_schedule_codegen.cpp
  clang/test/OpenMP/target_update_codegen.cpp
  clang/test/OpenMP/target_update_depend_codegen.cpp
  clang/test/OpenMP/teams_distribute_codegen.cpp
  clang/test/OpenMP/teams_distribute_collapse_codegen.cpp
  clang/test/OpenMP/teams_distribute_dist_schedule_codegen.cpp
  clang/test/OpenMP/teams_distribute_parallel_for_codegen.cpp
  clang/test/OpenMP/teams_distribute_parallel_for_collapse_codegen.cpp
  clang/test/OpenMP/teams_distribute_parallel_for_dist_schedule_codegen.cpp
  clang/test/OpenMP/teams_distribute_parallel_for_schedule_codegen.cpp
  clang/test/OpenMP/teams_distribute_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/teams_distribute_parallel_for_simd_collapse_codegen.cpp
  clang/test/OpenMP/teams_distribute_parallel_for_simd_dist_schedule_codegen.cpp
  clang/test/OpenMP/teams_distribute_parallel_for_simd_schedule_codegen.cpp
  clang/test/OpenMP/teams_distribute_simd_codegen.cpp
  clang/test/OpenMP/teams_distribute_simd_collapse_codegen.cpp
  clang/test/OpenMP/teams_distribute_simd_dist_schedule_codegen.cpp
  clang/test/OpenMP/teams_firstprivate_codegen.cpp

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


[PATCH] D93844: [clang-format] Add possibility to be based on parent directory

2021-12-29 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks marked an inline comment as done.
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/Format.cpp:3067
+  if (!ChildFormatTextToApply.empty()) {
+assert(ChildFormatTextToApply.size() == 1);
+

zwliew wrote:
> zwliew wrote:
> > HazardyKnusperkeks wrote:
> > > zwliew wrote:
> > > > HazardyKnusperkeks wrote:
> > > > > zwliew wrote:
> > > > > > Is there a reason behind limiting the number of children configs to 
> > > > > > 1 in this case? When the fallback is not used, more than 1 children 
> > > > > > configs are allowed (line 3036).
> > > > > > 
> > > > > > Sorry for digging this up, I came across this seemingly arbitrary 
> > > > > > decision when working on some changes to 
> > > > > > https://reviews.llvm.org/D72326
> > > > > Yeah but it doesn't happen, there is at most only one `.clang-format` 
> > > > > in the parent directory path which is found. So we assert on that and 
> > > > > then don't need to loop over what is exactly one element big.
> > > > Thanks for the reply. However, I don't think that's true. Yes, it's 
> > > > only possible to find one `.clang-format` file in the first parent 
> > > > directory. But if it has `BasedOnStyle: InheritParentConfig` set, then 
> > > > we could find another `.clang-format` file in the "grandparent" 
> > > > directory. In this case, we'll have 2 elements in 
> > > > `ChildFormatTextToApply`, but only the very first one will actually be 
> > > > applied.
> > > > 
> > > > To illustrate, suppose we have the following file structure:
> > > > ```
> > > > - .clang-format
> > > > - foo
> > > >   |- .clang-format
> > > >   |- input.cpp
> > > > ```
> > > > 
> > > > Both `.clang-format` files have `BasedOnStyle: InheritParentConfig` 
> > > > set. When running `clang-format --style=file foo/input.cpp`, only the 
> > > > inner config is applied on the fallback style, while the outer config 
> > > > is ignored. When testing on a debug build, I encountered a crash due to 
> > > > the failed assert. When removing the assert, and using a loop to apply 
> > > > the configs, both the inner and outer configs are applied, which I 
> > > > believe is the expected behaviour.
> > > > 
> > > I can not explain it to you anymore, I would have to dig into it again. 
> > > But if my tests are correct everything works. You can see that for `Test 
> > > 9.4` I create a `.clang-format` in `/e/sub/sub/` which is based on 
> > > `/e/sub/.clang-format` which again is based on `/e/.clang-format`.
> > > 
> > > The tests do not fail, the parsed style is as the three files suggest, 
> > > and the assert holds. I'm pretty sure I have thought about that case, it 
> > > happens in some kind of recursion.
> > I took a look through `Test 9.4`, and it doesn't test the case I'm thinking 
> > of, as it doesn't execute the fallback case.
> > 
> > In ` Test 9.4` the file structure is as follows:
> > ```
> > - e/
> >   |- .clang-format (BasedOnStyle: Google) <-- outermost config
> >   |- sub/
> > |- .clang-format (BasedOnStyle: `InheritParentConfig)
> > |- sub/
> >   |- .clang-format (BasedOnStyle: InheritParentConfig)
> >   |- code.cpp
> > ```
> > 
> > The reason it doesn't execute the fallback case is that the outermost 
> > config file doesn't have `BasedOnStyle: InheritParentConfig` set.
> > 
> > On the other hand, in the following directory structure, the fallback case 
> > would execute, the assert would fail (on debug builds), and only the 
> > innermost config would be applied (on release builds):
> > ```
> > - e/
> >   |- .clang-format (BasedOnStyle: InheritParentConfig) <-- outermost config
> >   |- sub/
> > |- .clang-format (BasedOnStyle: `InheritParentConfig)
> > |- sub/
> >   |- .clang-format (BasedOnStyle: InheritParentConfig)
> >   |- code.cpp
> > ```
> > 
> > In order to verify my claims, I think I should write a new test case for 
> > this. However, I do not know how to run test cases for only clang-format. 
> > Is there a way to do so? Thanks! 
> I added a new test case for the latter scenario and ran all the regression 
> test cases with `make check-clang`. The test case does indeed fail due to the 
> assertion failure. I've updated https://reviews.llvm.org/D72326 with the test 
> case and the fix for it. Please have a look, thanks!
In that case thanks for catching that.

But I think it should be a different patch for the fix. Do not put a bug fix 
with a new feature in one commit.
There should be a target FormatTests, which builds and runs only the tests for 
clang-format.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93844

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


[PATCH] D72326: [clang-format] Add option to explicitly specify a config file

2021-12-29 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.

LGTM


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

https://reviews.llvm.org/D72326

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


[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2021-12-29 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2338
+  KeepAncestorBraces();
+  NestedTooDeep.push_back(false);
   if (FormatTok->is(tok::l_brace)) {

owenpan wrote:
> HazardyKnusperkeks wrote:
> > I think it is worth to create a RAII type for that.
> Can you explain why an RAII type would be beneficial here?
You have a lot of push/pop pairs. There is the risk someone (in the future) may 
misuse it.


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

https://reviews.llvm.org/D116316

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


[PATCH] D116368: [clang][dataflow] Add transfer function for VarDecl statements

2021-12-29 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 396529.
sgatev marked 8 inline comments as done.
sgatev added a comment.

Address reviewers' comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116368

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
  clang/include/clang/Analysis/FlowSensitive/Transfer.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Value.h
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/NoopAnalysis.h
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TestingSupportTest.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -6,12 +6,14 @@
 //
 //===--===//
 
+#include "NoopAnalysis.h"
 #include "TestingSupport.h"
 #include "clang/AST/Decl.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Tooling/Tooling.h"
@@ -28,6 +30,8 @@
 #include 
 #include 
 
+namespace {
+
 using namespace clang;
 using namespace dataflow;
 using ::testing::IsEmpty;
@@ -50,7 +54,8 @@
 ControlFlowContext::build(nullptr, Body, Result.Context));
 
 AnalysisT Analysis(*Result.Context);
-Environment Env;
+DataflowAnalysisContext DACtx;
+Environment Env(DACtx);
 BlockStates = runDataflowAnalysis(CFCtx, Analysis, Env);
   }
 
@@ -75,27 +80,6 @@
   return Callback.BlockStates;
 }
 
-class NoopLattice {
-public:
-  bool operator==(const NoopLattice &) const { return true; }
-
-  LatticeJoinEffect join(const NoopLattice &) {
-return LatticeJoinEffect::Unchanged;
-  }
-};
-
-class NoopAnalysis : public DataflowAnalysis {
-public:
-  NoopAnalysis(ASTContext )
-  : DataflowAnalysis(Context) {}
-
-  static NoopLattice initialElement() { return {}; }
-
-  NoopLattice transfer(const Stmt *S, const NoopLattice , Environment ) {
-return {};
-  }
-};
-
 TEST(DataflowAnalysisTest, NoopAnalysis) {
   auto BlockStates = runAnalysis(R"(
 void target() {}
@@ -314,3 +298,5 @@
   UnorderedElementsAre("baz", "foo"));
   // FIXME: Called functions at point `p` should contain only "foo".
 }
+
+} // namespace
Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -0,0 +1,617 @@
+//===- unittests/Analysis/FlowSensitive/TransferTest.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
+//
+//===--===//
+
+#include "NoopAnalysis.h"
+#include "TestingSupport.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/StorageLocation.h"
+#include "clang/Analysis/FlowSensitive/Value.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+#include 
+
+namespace {
+
+using namespace clang;
+using namespace dataflow;
+using ::testing::_;
+using ::testing::ElementsAre;
+using ::testing::IsNull;
+using ::testing::NotNull;
+using ::testing::Pair;
+
+class TransferTest : public ::testing::Test {
+protected:
+  template 
+  void runDataflow(llvm::StringRef Code, Matcher Match) {
+test::checkDataflow(
+Code, "target",
+[](ASTContext , 

[PATCH] D116170: [clang-format] Add penalty for breaking after '('

2021-12-29 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:18519
+  Style.PenaltyExcessCharacter = 15;
+  EXPECT_EQ("int foo(\n"
+"int );",

any reason you are not using verifyFormat here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116170

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


[PATCH] D116314: [clang-format] Add style to separate definition blocks

2021-12-29 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/DefinitionBlockSeparator.h:38-39
+};
+} // end namespace format
+} // end namespace clang
+

HazardyKnusperkeks wrote:
> I know you copied it. It is wrong where you copied it from. :)
Not done.


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

https://reviews.llvm.org/D116314

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


[PATCH] D116170: [clang-format] Add penalty for breaking after '('

2021-12-29 Thread G Pery via Phabricator via cfe-commits
GPery updated this revision to Diff 396527.
GPery added a comment.

Resorted everything and added more tests, thanks for the comments <3


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116170

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -18512,6 +18512,75 @@
 format("int a = /* long block comment */ 42;", Style));
 }
 
+TEST_F(FormatTest, BreakPenaltyAfterLParen) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 8;
+  Style.PenaltyExcessCharacter = 15;
+  EXPECT_EQ("int foo(\n"
+"int );",
+format("int foo(\n"
+   "int );",
+   Style));
+  Style.PenaltyBreakOpenParenthesis = 200;
+  EXPECT_EQ("int foo(int );",
+format("int foo(\n"
+   "int );",
+   Style));
+}
+
+TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 5;
+  Style.PenaltyExcessCharacter = 150;
+  EXPECT_EQ("foo((\n"
+"int));",
+format("foo((\n"
+   "int));",
+   Style));
+  Style.PenaltyBreakOpenParenthesis = 10;
+  EXPECT_EQ("foo((int)\n"
+");",
+format("foo((\n"
+   "int));",
+   Style));
+}
+
+TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 4;
+  Style.PenaltyExcessCharacter = 100;
+  EXPECT_EQ("for (\n"
+"int i =\n"
+"0;\n"
+"i <\n"
+"2;\n"
+"i++) {\n"
+"}",
+format("for (\n"
+   "int i =\n"
+   "0;\n"
+   "i <\n"
+   "2;\n"
+   "i++) {\n"
+   "}",
+   Style));
+  Style.PenaltyBreakOpenParenthesis = 1250;
+  EXPECT_EQ("for (int i =\n"
+" 0;\n"
+" i <\n"
+" 2;\n"
+" i++) {\n"
+"}",
+format("for (\n"
+   "int i =\n"
+   "0;\n"
+   "i <\n"
+   "2;\n"
+   "i++) {\n"
+   "}",
+   Style));
+}
+
 #define EXPECT_ALL_STYLES_EQUAL(Styles)\
   for (size_t i = 1; i < Styles.size(); ++i)   \
   EXPECT_EQ(Styles[0], Styles[i])  \
@@ -18717,6 +18786,8 @@
   PenaltyBreakBeforeFirstCallParameter, 1234u);
   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
   PenaltyBreakTemplateDeclaration, 1234u);
+  CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
+  1234u);
   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
   PenaltyReturnTypeOnItsOwnLine, 1234u);
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2857,6 +2857,8 @@
   Left.Previous->isOneOf(tok::identifier, tok::greater))
 return 500;
 
+  if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0)
+return Style.PenaltyBreakOpenParenthesis;
   if (Left.is(tok::l_paren) && InFunctionDecl &&
   Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
 return 100;
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -756,6 +756,8 @@
 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
 IO.mapOptional("PenaltyBreakFirstLessLess",
Style.PenaltyBreakFirstLessLess);
+IO.mapOptional("PenaltyBreakOpenParenthesis",
+   Style.PenaltyBreakOpenParenthesis);
 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
 

[PATCH] D116374: [clang-format] Add penalty for breaking after '('

2021-12-29 Thread G Pery via Phabricator via cfe-commits
GPery updated this revision to Diff 396526.
GPery added a comment.

Resorted everything and added more tests, thanks for the comments <3


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116374

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -18512,6 +18512,75 @@
 format("int a = /* long block comment */ 42;", Style));
 }
 
+TEST_F(FormatTest, BreakPenaltyAfterLParen) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 8;
+  Style.PenaltyExcessCharacter = 15;
+  EXPECT_EQ("int foo(\n"
+"int );",
+format("int foo(\n"
+   "int );",
+   Style));
+  Style.PenaltyBreakOpenParenthesis = 200;
+  EXPECT_EQ("int foo(int );",
+format("int foo(\n"
+   "int );",
+   Style));
+}
+
+TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 5;
+  Style.PenaltyExcessCharacter = 150;
+  EXPECT_EQ("foo((\n"
+"int));",
+format("foo((\n"
+   "int));",
+   Style));
+  Style.PenaltyBreakOpenParenthesis = 10;
+  EXPECT_EQ("foo((int)\n"
+");",
+format("foo((\n"
+   "int));",
+   Style));
+}
+
+TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 4;
+  Style.PenaltyExcessCharacter = 100;
+  EXPECT_EQ("for (\n"
+"int i =\n"
+"0;\n"
+"i <\n"
+"2;\n"
+"i++) {\n"
+"}",
+format("for (\n"
+   "int i =\n"
+   "0;\n"
+   "i <\n"
+   "2;\n"
+   "i++) {\n"
+   "}",
+   Style));
+  Style.PenaltyBreakOpenParenthesis = 1250;
+  EXPECT_EQ("for (int i =\n"
+" 0;\n"
+" i <\n"
+" 2;\n"
+" i++) {\n"
+"}",
+format("for (\n"
+   "int i =\n"
+   "0;\n"
+   "i <\n"
+   "2;\n"
+   "i++) {\n"
+   "}",
+   Style));
+}
+
 #define EXPECT_ALL_STYLES_EQUAL(Styles)\
   for (size_t i = 1; i < Styles.size(); ++i)   \
   EXPECT_EQ(Styles[0], Styles[i])  \
@@ -18717,6 +18786,8 @@
   PenaltyBreakBeforeFirstCallParameter, 1234u);
   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
   PenaltyBreakTemplateDeclaration, 1234u);
+  CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
+  1234u);
   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
   PenaltyReturnTypeOnItsOwnLine, 1234u);
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2857,6 +2857,8 @@
   Left.Previous->isOneOf(tok::identifier, tok::greater))
 return 500;
 
+  if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0)
+return Style.PenaltyBreakOpenParenthesis;
   if (Left.is(tok::l_paren) && InFunctionDecl &&
   Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
 return 100;
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -756,6 +756,8 @@
 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
 IO.mapOptional("PenaltyBreakFirstLessLess",
Style.PenaltyBreakFirstLessLess);
+IO.mapOptional("PenaltyBreakOpenParenthesis",
+   Style.PenaltyBreakOpenParenthesis);
 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
 

[PATCH] D116374: [clang-format] Add penalty for breaking after '('

2021-12-29 Thread G Pery via Phabricator via cfe-commits
GPery created this revision.
GPery requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Resorted and added tests, thanks for the comments <3


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116374

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -18512,6 +18512,75 @@
 format("int a = /* long block comment */ 42;", Style));
 }
 
+TEST_F(FormatTest, BreakPenaltyAfterLParen) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 8;
+  Style.PenaltyExcessCharacter = 15;
+  EXPECT_EQ("int foo(\n"
+"int );",
+format("int foo(\n"
+   "int );",
+   Style));
+  Style.PenaltyBreakOpenParenthesis = 200;
+  EXPECT_EQ("int foo(int );",
+format("int foo(\n"
+   "int );",
+   Style));
+}
+
+TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 5;
+  Style.PenaltyExcessCharacter = 150;
+  EXPECT_EQ("foo((\n"
+"int));",
+format("foo((\n"
+   "int));",
+   Style));
+  Style.PenaltyBreakOpenParenthesis = 10;
+  EXPECT_EQ("foo((int)\n"
+");",
+format("foo((\n"
+   "int));",
+   Style));
+}
+
+TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 4;
+  Style.PenaltyExcessCharacter = 100;
+  EXPECT_EQ("for (\n"
+"int i =\n"
+"0;\n"
+"i <\n"
+"2;\n"
+"i++) {\n"
+"}",
+format("for (\n"
+   "int i =\n"
+   "0;\n"
+   "i <\n"
+   "2;\n"
+   "i++) {\n"
+   "}",
+   Style));
+  Style.PenaltyBreakOpenParenthesis = 1250;
+  EXPECT_EQ("for (int i =\n"
+" 0;\n"
+" i <\n"
+" 2;\n"
+" i++) {\n"
+"}",
+format("for (\n"
+   "int i =\n"
+   "0;\n"
+   "i <\n"
+   "2;\n"
+   "i++) {\n"
+   "}",
+   Style));
+}
+
 #define EXPECT_ALL_STYLES_EQUAL(Styles)\
   for (size_t i = 1; i < Styles.size(); ++i)   \
   EXPECT_EQ(Styles[0], Styles[i])  \
@@ -18717,6 +18786,8 @@
   PenaltyBreakBeforeFirstCallParameter, 1234u);
   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
   PenaltyBreakTemplateDeclaration, 1234u);
+  CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
+  1234u);
   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
   PenaltyReturnTypeOnItsOwnLine, 1234u);
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2857,6 +2857,8 @@
   Left.Previous->isOneOf(tok::identifier, tok::greater))
 return 500;
 
+  if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0)
+return Style.PenaltyBreakOpenParenthesis;
   if (Left.is(tok::l_paren) && InFunctionDecl &&
   Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
 return 100;
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -756,6 +756,8 @@
 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
 IO.mapOptional("PenaltyBreakFirstLessLess",
Style.PenaltyBreakFirstLessLess);
+IO.mapOptional("PenaltyBreakOpenParenthesis",
+   Style.PenaltyBreakOpenParenthesis);
 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
 

[PATCH] D99436: [OPENMP]Fix PR49366: crash on VLAs in task untied regions.

2021-12-29 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev updated this revision to Diff 396524.
ABataev added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D99436

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/OpenMP/task_messages.cpp
  clang/test/OpenMP/taskloop_loop_messages.cpp

Index: clang/test/OpenMP/taskloop_loop_messages.cpp
===
--- clang/test/OpenMP/taskloop_loop_messages.cpp
+++ clang/test/OpenMP/taskloop_loop_messages.cpp
@@ -691,7 +691,7 @@
 
 void test_loop_eh() {
   const int N = 100;
-  float a[N], b[N], c[N];
+  float a[N], b[N], c[N]; // expected-note {{declared here}}
 #pragma omp parallel
 #pragma omp taskloop
   for (int i = 0; i < 10; i++) {
@@ -729,6 +729,13 @@
   void g() { throw 0; }
 };
   }
+// expected-error@+5 {{variable length arrays are not supported in OpenMP tasking regions with 'untied' clause}}
+// expected-note@+4 {{read of non-constexpr variable 'c' is not allowed in a constant expression}}
+#pragma omp taskloop untied
+  {
+  for (int i = 0; i < 10; ++i)
+int array[(int)c[0]];
+  }
 }
 
 void test_loop_firstprivate_lastprivate() {
Index: clang/test/OpenMP/task_messages.cpp
===
--- clang/test/OpenMP/task_messages.cpp
+++ clang/test/OpenMP/task_messages.cpp
@@ -173,7 +173,7 @@
   int  = a;
   S sa;
   S  = sa;
-  int r;
+  int r; // expected-note {{declared here}}
 #pragma omp task { // expected-warning {{extra tokens at the end of '#pragma omp task' are ignored}}
   foo();
 #pragma omp task( // expected-warning {{extra tokens at the end of '#pragma omp task' are ignored}}
@@ -330,6 +330,12 @@
 // expected-error@+1 {{directive '#pragma omp task' cannot contain more than one 'mergeable' clause}}
 #pragma omp task mergeable mergeable
   ++r;
+// expected-error@+4 {{variable length arrays are not supported in OpenMP tasking regions with 'untied' clause}}
+// expected-note@+3 {{read of non-const variable 'r' is not allowed in a constant expression}}
+#pragma omp task untied
+  {
+int array[r];
+  }
   volatile omp_event_handle_t evt;
   omp_event_handle_t sevt;
   const omp_event_handle_t cevt = evt;
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -2456,6 +2456,9 @@
   } else if (isSFINAEContext()) {
 VLADiag = diag::err_vla_in_sfinae;
 VLAIsError = true;
+  } else if (getLangOpts().OpenMP && isInOpenMPTaskUntiedContext()) {
+VLADiag = diag::err_openmp_vla_in_task_untied;
+VLAIsError = true;
   } else {
 VLADiag = diag::ext_vla;
 VLAIsError = false;
Index: clang/lib/Sema/SemaOpenMP.cpp
===
--- clang/lib/Sema/SemaOpenMP.cpp
+++ clang/lib/Sema/SemaOpenMP.cpp
@@ -175,6 +175,7 @@
 bool HasMutipleLoops = false;
 const Decl *PossiblyLoopCounter = nullptr;
 bool NowaitRegion = false;
+bool UntiedRegion = false;
 bool CancelRegion = false;
 bool LoopStart = false;
 bool BodyComplete = false;
@@ -850,6 +851,15 @@
   return Parent->NowaitRegion;
 return false;
   }
+  /// Marks current region as untied (it has a 'untied' clause).
+  void setUntiedRegion(bool IsUntied = true) {
+getTopOfStack().UntiedRegion = IsUntied;
+  }
+  /// Return true if current region is untied.
+  bool isUntiedRegion() const {
+const SharingMapTy *Top = getTopOfStackOrNull();
+return Top ? Top->UntiedRegion : false;
+  }
   /// Marks parent region as cancel region.
   void setParentCancelRegion(bool Cancel = true) {
 if (SharingMapTy *Parent = getSecondOnStackOrNull())
@@ -2157,6 +2167,11 @@
   return DSAStack->getNestingLevel();
 }
 
+bool Sema::isInOpenMPTaskUntiedContext() const {
+  return isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
+ DSAStack->isUntiedRegion();
+}
+
 bool Sema::isInOpenMPTargetExecutionDirective() const {
   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
   !DSAStack->isClauseParsingMode()) ||
@@ -15391,6 +15406,7 @@
 
 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  SourceLocation EndLoc) {
+  DSAStack->setUntiedRegion();
   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
 }
 
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -10649,6 +10649,10 @@
   void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
  const FunctionDecl *Callee,
  SourceLocation Loc);
+
+  /// Return true if 

[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2021-12-29 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added inline comments.



Comment at: clang/docs/ClangFormatStyleOptions.rst:3398
 
+**RemoveBracesLLVM** (``Boolean``) :versionbadge:`clang-format 14`
+  Remove optional braces of control statements (``if``, ``else``, ``for``,

Can we agree on one set of options that can be used for both insertion and 
removal even if this patch only does removal 



Comment at: clang/unittests/Format/FormatTest.cpp:23224
+
+  EXPECT_EQ("if (a)\n"
+"  if (b)\n"

any reason these can't be verifyFormats?


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

https://reviews.llvm.org/D116316

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


[PATCH] D116351: Update Bug report URL to Github Issues

2021-12-29 Thread Louis Dionne via Phabricator via cfe-commits
ldionne accepted this revision as: libc++, libunwind.
ldionne added a comment.

Libc++ and libunwind changes LGTM


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

https://reviews.llvm.org/D116351

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


[PATCH] D116369: [clang][dataflow] Add parameterized map lattice.

2021-12-29 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev added a comment.

It seems unnecessary to deal with AST elements in the tests for `MapLattice`. I 
think testing it with integer or string keys would be simpler. Given that 
`VarMapLattice` is just an alias, I don't think it's necessary to add dedicated 
tests for it. What do you think?




Comment at: clang/include/clang/Analysis/FlowSensitive/MapLattice.h:1
+//===- DataflowAnalysis.h ---*- C++ 
-*-===//
+//

The comment needs to be updated.



Comment at: clang/include/clang/Analysis/FlowSensitive/MapLattice.h:15
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE__MAPLATTICE_H_
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE__MAPLATTICE_H_

Remove the last underscore for consistency.



Comment at: clang/include/clang/Analysis/FlowSensitive/MapLattice.h:33
+/// constructor of `ElementLattice` should produce the bottom element.
+template  class MapLattice {
+  using Container = llvm::DenseMap;

Please document the relation, the join operation, and the bottom element for 
this lattice.



Comment at: clang/include/clang/Analysis/FlowSensitive/MapLattice.h:50
+  void insert(const std::pair ) {
+(void)C.insert(P);
+  }

Is `(void)` necessary? Is it a convention?



Comment at: clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp:12-13
+
+namespace clang {
+namespace dataflow {
+namespace {

```
using namespace clang;
using namespace dataflow;
```



Comment at: clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp:22
+MATCHER_P(Var, name,
+  (llvm::Twine(negation ? "isn't" : "is") + " a variable named `" +
+   name + "`")

`#include "llvm/ADT/Twine.h"`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116369

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


[PATCH] D116368: [clang][dataflow] Add transfer function for VarDecl statements

2021-12-29 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

Nice!  A few small comments on the headers...




Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:56
+
+  /// Assigns `Loc` to `D`.
+  ///

The term "assignment" is overloaded. :) Maybe instead "Associates `Loc` with 
`D`"? Or, expand on the meaning of the assignment? e.g. "Assigns `Loc` as the 
storage location of `D`?



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h:41
+  /// Creates a storage location appropriate for `Type`. Does not assign a 
value
+  /// to the returned storage location in the environment. Never returns null.
+  ///

here and below. If it never returns null, why not return a ref?
For that matter, all of the pointer parameters with comments "must not be null" 
-- can we just make those refs?



Comment at: clang/include/clang/Analysis/FlowSensitive/StorageLocation.h:9
+//
+// This file defines classes that represent elements of the local variable 
store
+// and of the heap during dataflow analysis.

Indent two spaces? (vs 1) same below.



Comment at: clang/include/clang/Analysis/FlowSensitive/StorageLocation.h:40-42
+private:
+  Kind LocKind;
+  QualType Type;

I don't think its required, but LLVM style typically puts private field decls 
at the beginning of the class, without the explicit "private:" decl.



Comment at: clang/include/clang/Analysis/FlowSensitive/StorageLocation.h:52
+
+  static bool classof(const StorageLocation *Loc) {
+return Loc->getKind() == Kind::Scalar;

ref?



Comment at: clang/include/clang/Analysis/FlowSensitive/StorageLocation.h:83
+auto It = Children.find(D);
+// FIXME: A missing child member means that the sorage location was not
+// created correctly. Change the following to assert(it != children_.end())





Comment at: clang/include/clang/Analysis/FlowSensitive/Value.h:37-38
+
+private:
+  Kind ValKind;
+};

Move to beginning of class decl?



Comment at: clang/include/clang/Analysis/FlowSensitive/Value.h:41
+
+/// Class that models an integer.
+class IntegerValue : public Value {

nit: Here and below. I think that "Models..." would be as good or better than 
"Class that models...".


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116368

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


[PATCH] D116351: Update Bug report URL to Github Issues

2021-12-29 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu marked 7 inline comments as done.
ChuanqiXu added inline comments.



Comment at: clang/www/c_status.html:76
+The https://bugs.llvm.org/;>LLVM bug tracker and 
+https://github.com/llvm/llvm-project/issues/;>LLVM Issues contain
+a Clang C component that tracks known bugs with Clang's language

asl wrote:
> asl wrote:
> > The component got mapped to dedicated label in GitHub. So, it will be great 
> > to get rid of bugzilla-centric definition and switch to GitHub terms
> As I said – there is no "Clang C component" in github. We need to reword 
> everything in terms of labels and mention correct label here.
My bad. I didn't realize "Clang C Component" is specific to bugzilla.



Comment at: clang/www/cxx_status.html:81
+https://github.com/llvm/llvm-project/issues/;>LLVM Issues contain
+Clang C++ components that track known bugs with Clang's language conformance in
 each language mode.

asl wrote:
> asl wrote:
> > Ditto. Also, there are separate labels for C++11 / 14 / 20 / 23. It might 
> > make sense to mention them here
> See above
BTW, I checked that there isn't c++23 labels now.


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

https://reviews.llvm.org/D116351

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


[PATCH] D116351: Update Bug report URL to Github Issues

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

Address comments.


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

https://reviews.llvm.org/D116351

Files:
  clang-tools-extra/docs/clang-doc.rst
  clang/docs/CommandGuide/clang.rst
  clang/www/c_status.html
  clang/www/cxx_status.html
  clang/www/get_involved.html
  clang/www/get_started.html
  clang/www/menu.html.incl
  libcxx/docs/index.rst
  libunwind/docs/index.rst
  lld/docs/_templates/indexsidebar.html
  lldb/docs/index.rst
  llvm/CMakeLists.txt
  llvm/docs/CommandGuide/llvm-install-name-tool.rst
  llvm/docs/CommandGuide/llvm-libtool-darwin.rst
  llvm/docs/CommandGuide/llvm-lipo.rst
  llvm/docs/CommandGuide/llvm-objcopy.rst
  llvm/docs/CommandGuide/llvm-objdump.rst
  llvm/docs/CommandGuide/llvm-otool.rst
  llvm/docs/CommandGuide/llvm-size.rst
  llvm/docs/CommandGuide/llvm-strings.rst
  llvm/docs/CommandGuide/llvm-strip.rst
  llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
  llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
  utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
  utils/bazel/llvm-project-overlay/llvm/include/llvm/Config/config.h

Index: utils/bazel/llvm-project-overlay/llvm/include/llvm/Config/config.h
===
--- utils/bazel/llvm-project-overlay/llvm/include/llvm/Config/config.h
+++ utils/bazel/llvm-project-overlay/llvm/include/llvm/Config/config.h
@@ -24,7 +24,7 @@
 #include "llvm/Config/llvm-config.h"
 
 /* Bug report URL. */
-#define BUG_REPORT_URL "https://bugs.llvm.org/;
+#define BUG_REPORT_URL "https://github.com/llvm/llvm-project/issues/;
 
 /* Define to 1 to enable backtraces, and to 0 otherwise. */
 #define ENABLE_BACKTRACES 1
@@ -332,7 +332,7 @@
 /* LTDL_SHLIB_EXT defined in Bazel */
 
 /* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "https://bugs.llvm.org/;
+#define PACKAGE_BUGREPORT "https://github.com/llvm/llvm-project/issues/;
 
 /* Define to the full name of this package. */
 #define PACKAGE_NAME "LLVM"
Index: utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
===
--- utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
+++ utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
@@ -20,7 +20,7 @@
 #define CLANG_CONFIG_H
 
 /* Bug report URL. */
-#define BUG_REPORT_URL "https://bugs.llvm.org/;
+#define BUG_REPORT_URL "https://github.com/llvm/llvm-project/issues/;
 
 /* Default to -fPIE and -pie on Linux. */
 #define CLANG_DEFAULT_PIE_ON_LINUX 0
Index: llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
===
--- llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
+++ llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
@@ -72,7 +72,7 @@
   input = "config.h.cmake"
   output = "$target_gen_dir/config.h"
   values = [
-"BUG_REPORT_URL=https://bugs.llvm.org/;,
+"BUG_REPORT_URL=https://github.com/llvm/llvm-project/issues/;,
 "ENABLE_BACKTRACES=1",
 "ENABLE_CRASH_OVERRIDES=1",
 "BACKTRACE_HEADER=execinfo.h",
@@ -120,7 +120,7 @@
 "LLVM_VERSION_INFO=",
 "LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO=1",
 "LLVM_WINDOWS_PREFER_FORWARD_SLASH=",
-"PACKAGE_BUGREPORT=https://bugs.llvm.org/;,
+"PACKAGE_BUGREPORT=https://github.com/llvm/llvm-project/issues/;,
 "PACKAGE_NAME=LLVM",
 "PACKAGE_STRING=LLVM ${llvm_version}git",
 "PACKAGE_VERSION=${llvm_version}git",
Index: llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
===
--- llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
+++ llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
@@ -8,7 +8,7 @@
   input = "config.h.cmake"
   output = "$target_gen_dir/config.h"
   values = [
-"BUG_REPORT_URL=https://bugs.llvm.org/;,
+"BUG_REPORT_URL=https://github.com/llvm/llvm-project/issues/;,
 "CLANG_DEFAULT_PIE_ON_LINUX=",
 "CLANG_DEFAULT_LINKER=",
 "CLANG_DEFAULT_STD_C=",
Index: llvm/docs/CommandGuide/llvm-strip.rst
===
--- llvm/docs/CommandGuide/llvm-strip.rst
+++ llvm/docs/CommandGuide/llvm-strip.rst
@@ -194,7 +194,7 @@
 BUGS
 
 
-To report bugs, please visit .
+To report bugs, please visit .
 
 SEE ALSO
 
Index: llvm/docs/CommandGuide/llvm-strings.rst
===
--- llvm/docs/CommandGuide/llvm-strings.rst
+++ llvm/docs/CommandGuide/llvm-strings.rst
@@ -123,4 +123,4 @@
 BUGS
 
 
-To report bugs, please visit .
+To report bugs, please visit .
Index: 

[PATCH] D116351: Update Bug report URL to Github Issues

2021-12-29 Thread Anton Korobeynikov via Phabricator via cfe-commits
asl requested changes to this revision.
asl added a comment.
This revision now requires changes to proceed.

Will you please check the comments and reword everything using proper 
terminology and new things we're having on GitHub?




Comment at: clang/www/c_status.html:76
+The https://bugs.llvm.org/;>LLVM bug tracker and 
+https://github.com/llvm/llvm-project/issues/;>LLVM Issues contain
+a Clang C component that tracks known bugs with Clang's language

asl wrote:
> The component got mapped to dedicated label in GitHub. So, it will be great 
> to get rid of bugzilla-centric definition and switch to GitHub terms
As I said – there is no "Clang C component" in github. We need to reword 
everything in terms of labels and mention correct label here.



Comment at: clang/www/cxx_status.html:81
+https://github.com/llvm/llvm-project/issues/;>LLVM Issues contain
+Clang C++ components that track known bugs with Clang's language conformance in
 each language mode.

asl wrote:
> Ditto. Also, there are separate labels for C++11 / 14 / 20 / 23. It might 
> make sense to mention them here
See above


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

https://reviews.llvm.org/D116351

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


[PATCH] D116351: Update Bug report URL to Github Issues

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

Address comments.


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

https://reviews.llvm.org/D116351

Files:
  clang-tools-extra/docs/clang-doc.rst
  clang/docs/CommandGuide/clang.rst
  clang/www/c_status.html
  clang/www/cxx_status.html
  clang/www/get_involved.html
  clang/www/get_started.html
  clang/www/menu.html.incl
  libcxx/docs/index.rst
  libunwind/docs/index.rst
  lld/docs/_templates/indexsidebar.html
  lldb/docs/index.rst
  llvm/CMakeLists.txt
  llvm/docs/CommandGuide/llvm-install-name-tool.rst
  llvm/docs/CommandGuide/llvm-libtool-darwin.rst
  llvm/docs/CommandGuide/llvm-lipo.rst
  llvm/docs/CommandGuide/llvm-objcopy.rst
  llvm/docs/CommandGuide/llvm-objdump.rst
  llvm/docs/CommandGuide/llvm-otool.rst
  llvm/docs/CommandGuide/llvm-size.rst
  llvm/docs/CommandGuide/llvm-strings.rst
  llvm/docs/CommandGuide/llvm-strip.rst
  llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
  llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
  utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
  utils/bazel/llvm-project-overlay/llvm/include/llvm/Config/config.h

Index: utils/bazel/llvm-project-overlay/llvm/include/llvm/Config/config.h
===
--- utils/bazel/llvm-project-overlay/llvm/include/llvm/Config/config.h
+++ utils/bazel/llvm-project-overlay/llvm/include/llvm/Config/config.h
@@ -24,7 +24,7 @@
 #include "llvm/Config/llvm-config.h"
 
 /* Bug report URL. */
-#define BUG_REPORT_URL "https://bugs.llvm.org/;
+#define BUG_REPORT_URL "https://github.com/llvm/llvm-project/issues/;
 
 /* Define to 1 to enable backtraces, and to 0 otherwise. */
 #define ENABLE_BACKTRACES 1
@@ -332,7 +332,7 @@
 /* LTDL_SHLIB_EXT defined in Bazel */
 
 /* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "https://bugs.llvm.org/;
+#define PACKAGE_BUGREPORT "https://github.com/llvm/llvm-project/issues/;
 
 /* Define to the full name of this package. */
 #define PACKAGE_NAME "LLVM"
Index: utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
===
--- utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
+++ utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
@@ -20,7 +20,7 @@
 #define CLANG_CONFIG_H
 
 /* Bug report URL. */
-#define BUG_REPORT_URL "https://bugs.llvm.org/;
+#define BUG_REPORT_URL "https://github.com/llvm/llvm-project/issues/;
 
 /* Default to -fPIE and -pie on Linux. */
 #define CLANG_DEFAULT_PIE_ON_LINUX 0
Index: llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
===
--- llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
+++ llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
@@ -72,7 +72,7 @@
   input = "config.h.cmake"
   output = "$target_gen_dir/config.h"
   values = [
-"BUG_REPORT_URL=https://bugs.llvm.org/;,
+"BUG_REPORT_URL=https://github.com/llvm/llvm-project/issues/;,
 "ENABLE_BACKTRACES=1",
 "ENABLE_CRASH_OVERRIDES=1",
 "BACKTRACE_HEADER=execinfo.h",
@@ -120,7 +120,7 @@
 "LLVM_VERSION_INFO=",
 "LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO=1",
 "LLVM_WINDOWS_PREFER_FORWARD_SLASH=",
-"PACKAGE_BUGREPORT=https://bugs.llvm.org/;,
+"PACKAGE_BUGREPORT=https://github.com/llvm/llvm-project/issues/;,
 "PACKAGE_NAME=LLVM",
 "PACKAGE_STRING=LLVM ${llvm_version}git",
 "PACKAGE_VERSION=${llvm_version}git",
Index: llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
===
--- llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
+++ llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
@@ -8,7 +8,7 @@
   input = "config.h.cmake"
   output = "$target_gen_dir/config.h"
   values = [
-"BUG_REPORT_URL=https://bugs.llvm.org/;,
+"BUG_REPORT_URL=https://github.com/llvm/llvm-project/issues/;,
 "CLANG_DEFAULT_PIE_ON_LINUX=",
 "CLANG_DEFAULT_LINKER=",
 "CLANG_DEFAULT_STD_C=",
Index: llvm/docs/CommandGuide/llvm-strip.rst
===
--- llvm/docs/CommandGuide/llvm-strip.rst
+++ llvm/docs/CommandGuide/llvm-strip.rst
@@ -194,7 +194,7 @@
 BUGS
 
 
-To report bugs, please visit .
+To report bugs, please visit .
 
 SEE ALSO
 
Index: llvm/docs/CommandGuide/llvm-strings.rst
===
--- llvm/docs/CommandGuide/llvm-strings.rst
+++ llvm/docs/CommandGuide/llvm-strings.rst
@@ -123,4 +123,4 @@
 BUGS
 
 
-To report bugs, please visit .
+To report bugs, please visit .
Index: 

[PATCH] D116351: Update Bug report URL to Github Issues

2021-12-29 Thread Anton Korobeynikov via Phabricator via cfe-commits
asl requested changes to this revision.
asl added a subscriber: tstellar.
asl added a comment.
This revision now requires changes to proceed.

Thanks for doing this! I added few notes on the way.




Comment at: clang/www/c_status.html:76
+The https://bugs.llvm.org/;>LLVM bug tracker and 
+https://github.com/llvm/llvm-project/issues/;>LLVM Issues contain
+a Clang C component that tracks known bugs with Clang's language

The component got mapped to dedicated label in GitHub. So, it will be great to 
get rid of bugzilla-centric definition and switch to GitHub terms



Comment at: clang/www/cxx_status.html:81
+https://github.com/llvm/llvm-project/issues/;>LLVM Issues contain
+Clang C++ components that track known bugs with Clang's language conformance in
 each language mode.

Ditto. Also, there are separate labels for C++11 / 14 / 20 / 23. It might make 
sense to mention them here



Comment at: clang/www/get_involved.html:69
+href="https://bugs.llvm.org/;>Bugzilla bug database or https://github.com/llvm/llvm-project/issues/;>LLVM Issues.
 

I think it would make sense to get rid of bz here. For new contributors 
everything should be GitHub-centric



Comment at: libcxx/docs/index.rst:220
 * `libc++abi Homepage `_
 * `LLVM Bugzilla `_
+* `LLVM Issues `_

I'd remove bugzilla here



Comment at: libunwind/docs/index.rst:101
 * `LLVM Homepage `_
 * `LLVM Bugzilla `_
+* `LLVM Issues `_

And here



Comment at: llvm/docs/HowToReleaseLLVM.rst:280
 
+.. FIXME: Edit for LLVM Issues in Github.
 .. _bug: https://bugs.llvm.org/

This is for @tstellar :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116351

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


[PATCH] D116351: Update Bug report URL to Github Issues

2021-12-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.
Herald added a subscriber: JDevlieghere.



Comment at: llvm/docs/DeveloperPolicy.rst:64
 
+.. FIXME: Edit for LLVM Issues in Github.
+

You can drop this and let others fix this paragraph.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116351

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


[PATCH] D116351: Update Bug report URL to Github Issues

2021-12-29 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu created this revision.
ChuanqiXu added reviewers: aaron.ballman, asl.
Herald added subscribers: libcxx-commits, ormris, arphaman, mgorny.
Herald added a reviewer: alexander-shaposhnikov.
Herald added a reviewer: MaskRay.
Herald added a project: libunwind.
Herald added a reviewer: libunwind.
ChuanqiXu requested review of this revision.
Herald added projects: clang, LLDB, libc++, LLVM, clang-tools-extra.
Herald added subscribers: cfe-commits, llvm-commits, lldb-commits.
Herald added a reviewer: libc++.

I found that although we moved to Github Issues. The bug report message refers 
to Bugzilla still. This patch tries to update these URLs. I left FIXME for 
places where I am not sure how to do wording.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116351

Files:
  clang-tools-extra/docs/clang-doc.rst
  clang/docs/CommandGuide/clang.rst
  clang/www/c_status.html
  clang/www/cxx_status.html
  clang/www/get_involved.html
  clang/www/get_started.html
  clang/www/menu.html.incl
  libcxx/docs/index.rst
  libunwind/docs/index.rst
  lld/docs/_templates/indexsidebar.html
  lldb/docs/index.rst
  llvm/CMakeLists.txt
  llvm/docs/CommandGuide/llvm-install-name-tool.rst
  llvm/docs/CommandGuide/llvm-libtool-darwin.rst
  llvm/docs/CommandGuide/llvm-lipo.rst
  llvm/docs/CommandGuide/llvm-objcopy.rst
  llvm/docs/CommandGuide/llvm-objdump.rst
  llvm/docs/CommandGuide/llvm-otool.rst
  llvm/docs/CommandGuide/llvm-size.rst
  llvm/docs/CommandGuide/llvm-strings.rst
  llvm/docs/CommandGuide/llvm-strip.rst
  llvm/docs/DeveloperPolicy.rst
  llvm/docs/HowToReleaseLLVM.rst
  llvm/docs/HowToSubmitABug.rst
  llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
  llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
  utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
  utils/bazel/llvm-project-overlay/llvm/include/llvm/Config/config.h

Index: utils/bazel/llvm-project-overlay/llvm/include/llvm/Config/config.h
===
--- utils/bazel/llvm-project-overlay/llvm/include/llvm/Config/config.h
+++ utils/bazel/llvm-project-overlay/llvm/include/llvm/Config/config.h
@@ -24,7 +24,7 @@
 #include "llvm/Config/llvm-config.h"
 
 /* Bug report URL. */
-#define BUG_REPORT_URL "https://bugs.llvm.org/;
+#define BUG_REPORT_URL "https://github.com/llvm/llvm-project/issues/;
 
 /* Define to 1 to enable backtraces, and to 0 otherwise. */
 #define ENABLE_BACKTRACES 1
@@ -332,7 +332,7 @@
 /* LTDL_SHLIB_EXT defined in Bazel */
 
 /* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "https://bugs.llvm.org/;
+#define PACKAGE_BUGREPORT "https://github.com/llvm/llvm-project/issues/;
 
 /* Define to the full name of this package. */
 #define PACKAGE_NAME "LLVM"
Index: utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
===
--- utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
+++ utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
@@ -20,7 +20,7 @@
 #define CLANG_CONFIG_H
 
 /* Bug report URL. */
-#define BUG_REPORT_URL "https://bugs.llvm.org/;
+#define BUG_REPORT_URL "https://github.com/llvm/llvm-project/issues/;
 
 /* Default to -fPIE and -pie on Linux. */
 #define CLANG_DEFAULT_PIE_ON_LINUX 0
Index: llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
===
--- llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
+++ llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
@@ -72,7 +72,7 @@
   input = "config.h.cmake"
   output = "$target_gen_dir/config.h"
   values = [
-"BUG_REPORT_URL=https://bugs.llvm.org/;,
+"BUG_REPORT_URL=https://github.com/llvm/llvm-project/issues/;,
 "ENABLE_BACKTRACES=1",
 "ENABLE_CRASH_OVERRIDES=1",
 "BACKTRACE_HEADER=execinfo.h",
@@ -120,7 +120,7 @@
 "LLVM_VERSION_INFO=",
 "LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO=1",
 "LLVM_WINDOWS_PREFER_FORWARD_SLASH=",
-"PACKAGE_BUGREPORT=https://bugs.llvm.org/;,
+"PACKAGE_BUGREPORT=https://github.com/llvm/llvm-project/issues/;,
 "PACKAGE_NAME=LLVM",
 "PACKAGE_STRING=LLVM ${llvm_version}git",
 "PACKAGE_VERSION=${llvm_version}git",
Index: llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
===
--- llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
+++ llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
@@ -8,7 +8,7 @@
   input = "config.h.cmake"
   output = "$target_gen_dir/config.h"
   values = [
-"BUG_REPORT_URL=https://bugs.llvm.org/;,
+"BUG_REPORT_URL=https://github.com/llvm/llvm-project/issues/;,
 "CLANG_DEFAULT_PIE_ON_LINUX=",
 "CLANG_DEFAULT_LINKER=",
 "CLANG_DEFAULT_STD_C=",
Index: llvm/docs/HowToSubmitABug.rst
===

[PATCH] D72326: [clang-format] Add option to explicitly specify a config file

2021-12-29 Thread Zhao Wei Liew via Phabricator via cfe-commits
zwliew added a comment.

Thanks for the review. I've moved the unrelated change to 
https://reviews.llvm.org/D116371 instead.


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

https://reviews.llvm.org/D72326

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


[PATCH] D72326: [clang-format] Add option to explicitly specify a config file

2021-12-29 Thread Zhao Wei Liew via Phabricator via cfe-commits
zwliew updated this revision to Diff 396519.
zwliew retitled this revision from "[clang-format] Rebased on master: Add 
option to specify explicit config file" to "[clang-format] Add option to 
explicitly specify a config file".
zwliew edited the summary of this revision.
zwliew added a comment.

Addressed the comments on the previous diff:

1. Adjusted some comments; suffixed each comment with a period.
2. Removed the changes unrelated to this revision (the ones the issue mentioned 
in the latest comments in https://reviews.llvm.org/D93844)


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

https://reviews.llvm.org/D72326

Files:
  clang/docs/ClangFormat.rst
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -21584,6 +21584,70 @@
 Style.IndentWidth = 7;
 return Style;
   }());
+
+  // Test 9.9: use inheritance from a specific config file.
+  Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
+"none", "", );
+  ASSERT_TRUE(static_cast(Style9));
+  ASSERT_EQ(*Style9, SubSubStyle);
+}
+
+TEST(FormatStyle, GetStyleOfSpecificFile) {
+  llvm::vfs::InMemoryFileSystem FS;
+  // Specify absolute path to a format file in a parent directory.
+  ASSERT_TRUE(
+  FS.addFile("/e/.clang-format", 0,
+ llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
+  ASSERT_TRUE(
+  FS.addFile("/e/explicit.clang-format", 0,
+ llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
+  ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
+ llvm::MemoryBuffer::getMemBuffer("int i;")));
+  auto Style = getStyle("file:/e/explicit.clang-format",
+"/e/sub/sub/sub/test.cpp", "LLVM", "", );
+  ASSERT_TRUE(static_cast(Style));
+  ASSERT_EQ(*Style, getGoogleStyle());
+
+  // Specify relative path to a format file.
+  ASSERT_TRUE(
+  FS.addFile("../../e/explicit.clang-format", 0,
+ llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
+  Style = getStyle("file:../../e/explicit.clang-format",
+   "/e/sub/sub/sub/test.cpp", "LLVM", "", );
+  ASSERT_TRUE(static_cast(Style));
+  ASSERT_EQ(*Style, getGoogleStyle());
+
+  // Specify path to a format file that does not exist.
+  Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
+   "LLVM", "", );
+  ASSERT_FALSE(static_cast(Style));
+  llvm::consumeError(Style.takeError());
+
+  // Specify path to a file on the filesystem.
+  SmallString<128> FormatFilePath;
+  std::error_code ECF = llvm::sys::fs::createTemporaryFile(
+  "FormatFileTest", "tpl", FormatFilePath);
+  EXPECT_FALSE((bool)ECF);
+  llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
+  EXPECT_FALSE((bool)ECF);
+  FormatFileTest << "BasedOnStyle: Google\n";
+  FormatFileTest.close();
+
+  SmallString<128> TestFilePath;
+  std::error_code ECT =
+  llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
+  EXPECT_FALSE((bool)ECT);
+  llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
+  CodeFileTest << "int i;\n";
+  CodeFileTest.close();
+
+  std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
+  Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
+
+  llvm::sys::fs::remove(FormatFilePath.c_str());
+  llvm::sys::fs::remove(TestFilePath.c_str());
+  ASSERT_TRUE(static_cast(Style));
+  ASSERT_EQ(*Style, getGoogleStyle());
 }
 
 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -3181,6 +3181,8 @@
 ".clang-format file located in one of the parent\n"
 "directories of the source file (or current\n"
 "directory for stdin).\n"
+"Use -style=file: to explicitly specify"
+"the configuration file.\n"
 "Use -style=\"{key: value, ...}\" to set specific\n"
 "parameters, e.g.:\n"
 "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
@@ -3233,6 +3235,18 @@
 
 const char *DefaultFallbackStyle = "LLVM";
 
+llvm::ErrorOr>
+loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
+   FormatStyle *Style, bool AllowUnknownOptions) {
+  llvm::ErrorOr> Text =
+  FS->getBufferForFile(ConfigFile.str());
+  if (auto EC = Text.getError())
+return EC;
+  if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions))
+return EC;
+  return Text;
+}
+
 llvm::Expected getStyle(StringRef StyleName, StringRef FileName,
  StringRef 

[PATCH] D116370: [clang][dataflow] Add multi-variable constant propagation example.

2021-12-29 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added reviewers: xazax.hun, gribozavr2, sgatev.
Herald added subscribers: rnkovacs, mgorny.
ymandel requested review of this revision.
Herald added a project: clang.

Adds another constant-propagation analysis that covers all variables in
the scope (vs the existing single-variable demo). But, the analysis is still
unsuited to use, in that ignores issues of escaping variables.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116370

Files:
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
@@ -0,0 +1,470 @@
+//===- unittests/Analysis/FlowSensitive/SingelVarConstantPropagation.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 defines a simplistic version of Constant Propagation as an example
+// of a forward, monotonic dataflow analysis. The analysis tracks all
+// variables in the scope, but lacks escape analysis.
+//
+//===--===//
+
+#include "TestingSupport.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/DataflowLattice.h"
+#include "clang/Analysis/FlowSensitive/MapLattice.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/Twine.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Testing/Support/Annotations.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace clang {
+namespace dataflow {
+namespace {
+using namespace ast_matchers;
+
+// Models the value of an expression at a program point, for all paths through
+// the program.
+struct ValueLattice {
+  enum class ValueState : bool {
+Undefined,
+Defined,
+  };
+  // `State` determines the meaning of the lattice when `Value` is `None`:
+  //  * `Undefined` -> bottom,
+  //  * `Defined` -> top.
+  ValueState State;
+
+  // When `None`, the lattice is either at top or bottom, based on `State`.
+  llvm::Optional Value;
+
+  constexpr ValueLattice() : State(ValueState::Undefined), Value(llvm::None) {}
+  constexpr ValueLattice(int64_t V) : State(ValueState::Defined), Value(V) {}
+  constexpr ValueLattice(ValueState S) : State(S), Value(llvm::None) {}
+
+  static constexpr ValueLattice bottom() {
+return ValueLattice(ValueState::Undefined);
+  }
+  static constexpr ValueLattice top() {
+return ValueLattice(ValueState::Defined);
+  }
+
+  friend bool operator==(const ValueLattice , const ValueLattice ) {
+return Lhs.State == Rhs.State && Lhs.Value == Rhs.Value;
+  }
+  friend bool operator!=(const ValueLattice , const ValueLattice ) {
+return !(Lhs == Rhs);
+  }
+
+  LatticeJoinEffect join(const ValueLattice ) {
+if (*this == Other || Other == bottom() || *this == top())
+  return LatticeJoinEffect::Unchanged;
+
+if (*this == bottom()) {
+  *this = Other;
+  return LatticeJoinEffect::Changed;
+}
+
+*this = top();
+return LatticeJoinEffect::Changed;
+  }
+};
+
+std::ostream <<(std::ostream , const ValueLattice ) {
+  if (L.Value.hasValue())
+return OS << *L.Value;
+  switch (L.State) {
+  case ValueLattice::ValueState::Undefined:
+return OS << "None";
+  case ValueLattice::ValueState::Defined:
+return OS << "Any";
+  }
+}
+
+using ConstantPropagationLattice = VarMapLattice;
+
+constexpr char kVar[] = "var";
+constexpr char kInit[] = "init";
+constexpr char kJustAssignment[] = "just-assignment";
+constexpr char kAssignment[] = "assignment";
+constexpr char kRHS[] = "rhs";
+
+auto refToVar() { return declRefExpr(to(varDecl().bind(kVar))); }
+
+// N.B. This analysis is deliberately simplistic, leaving out many important
+// details needed for a real analysis. Most notably, the transfer function does
+// not account for the variable's address possibly escaping, which would
+// invalidate the analysis. It also could be optimized to drop out-of-scope
+// variables from the map.
+class ConstantPropagationAnalysis
+: public DataflowAnalysis {
+public:
+  explicit 

[PATCH] D116369: [clang][dataflow] Add parameterized map lattice.

2021-12-29 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added reviewers: xazax.hun, gribozavr2, sgatev.
Herald added subscribers: rnkovacs, mgorny.
ymandel requested review of this revision.
Herald added a project: clang.

This patchs adds a `MapLattice` template for lifting a lattice to a keyed map. A
typical use is for modeling variables in a scope with a partcular lattice.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116369

Files:
  clang/include/clang/Analysis/FlowSensitive/MapLattice.h
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp
@@ -0,0 +1,224 @@
+#include "clang/Analysis/FlowSensitive/MapLattice.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/FlowSensitive/DataflowLattice.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/Support/Error.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace clang {
+namespace dataflow {
+namespace {
+
+using ::testing::Pair;
+using ::testing::UnorderedElementsAre;
+
+using namespace ast_matchers;
+
+MATCHER_P(Var, name,
+  (llvm::Twine(negation ? "isn't" : "is") + " a variable named `" +
+   name + "`")
+  .str()) {
+  return arg->getName() == name;
+}
+
+// A simple lattice for basic tests.
+class BooleanLattice {
+public:
+  BooleanLattice() : Value(false) {}
+  explicit BooleanLattice(bool B) : Value(B) {}
+
+  static BooleanLattice bottom() { return BooleanLattice(false); }
+
+  static BooleanLattice top() { return BooleanLattice(true); }
+
+  LatticeJoinEffect join(BooleanLattice Other) {
+auto Prev = Value;
+Value = Value || Other.Value;
+return Prev == Value ? LatticeJoinEffect::Unchanged
+ : LatticeJoinEffect::Changed;
+  }
+
+  friend bool operator==(BooleanLattice LHS, BooleanLattice RHS) {
+return LHS.Value == RHS.Value;
+  }
+
+  friend bool operator!=(BooleanLattice LHS, BooleanLattice RHS) {
+return LHS.Value != RHS.Value;
+  }
+
+  friend std::ostream <<(std::ostream , const BooleanLattice ) {
+Os << B.Value;
+return Os;
+  }
+
+  bool value() const { return Value; }
+
+private:
+  bool Value;
+};
+
+// Two `VarDecls` and the AST they are taken from.
+struct ValidVarDecls {
+  // The AST from which the var-decls are drawn. Needs to be kept in the struct
+  // so that `var1`, `var2` will be valid.
+  std::unique_ptr Unit;
+  const VarDecl *Var1;
+  const VarDecl *Var2;
+};
+
+// Generates two valid `VarDecl`s named "test_var_1" and "test_var_2".
+ValidVarDecls getVarDecls() {
+  std::string Code = R"cc(
+void fun() {
+  int test_var_1;
+  int test_var_2;
+}
+  )cc";
+
+  ValidVarDecls Result;
+  Result.Unit = tooling::buildASTFromCodeWithArgs(Code, {"-Wno-unused-value"});
+  assert(Result.Unit != nullptr && "AST construction failed");
+
+  ASTContext  = Result.Unit->getASTContext();
+  auto Matches = match(
+  functionDecl(hasBody(compoundStmt(
+  hasAnySubstatement(declStmt(
+  hasSingleDecl(varDecl(hasName("test_var_1")).bind("var1",
+  hasAnySubstatement(declStmt(
+  hasSingleDecl(varDecl(hasName("test_var_2")).bind("var2"))),
+  Context);
+  assert(Matches.size() == 1);
+
+  Result.Var1 = Matches[0].getNodeAs("var1");
+  Result.Var2 = Matches[0].getNodeAs("var2");
+  assert(Result.Var1 != nullptr);
+  assert(Result.Var2 != nullptr);
+
+  return Result;
+}
+
+TEST(VarMapLatticeTest, InsertWorks) {
+  auto Decls = getVarDecls();
+
+  VarMapLattice Lattice;
+  Lattice.insert({Decls.Var1, BooleanLattice(false)});
+  Lattice.insert({Decls.Var2, BooleanLattice(false)});
+
+  EXPECT_THAT(Lattice, UnorderedElementsAre(
+   Pair(Var("test_var_1"), BooleanLattice(false)),
+   Pair(Var("test_var_2"), BooleanLattice(false;
+}
+
+TEST(VarMapLatticeTest, ComparisonWorks) {
+  auto Decls = getVarDecls();
+
+  VarMapLattice Lattice1;
+  Lattice1.insert({Decls.Var1, BooleanLattice(true)});
+  Lattice1.insert({Decls.Var2, BooleanLattice(false)});
+  VarMapLattice Lattice2 = Lattice1;
+
+  EXPECT_EQ(Lattice1, Lattice2);
+  Lattice2[Decls.Var2] = BooleanLattice(true);
+  EXPECT_NE(Lattice1, Lattice2);
+}
+
+TEST(VarMapLatticeTest, JoinChange) {
+  auto Decls = getVarDecls();
+
+  VarMapLattice Lattice1;
+  Lattice1.insert({Decls.Var1, BooleanLattice(false)});
+  Lattice1.insert({Decls.Var2, BooleanLattice(false)});
+
+  VarMapLattice Lattice2;
+  Lattice2.insert({Decls.Var1, BooleanLattice(true)});
+  Lattice2.insert({Decls.Var2, BooleanLattice(true)});
+
+  ASSERT_THAT(Lattice1, UnorderedElementsAre(
+

[PATCH] D116368: [clang][dataflow] Add transfer function for VarDecl statements

2021-12-29 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 396516.
sgatev added a comment.

Minor changes to names and comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116368

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
  clang/include/clang/Analysis/FlowSensitive/Transfer.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Value.h
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/NoopAnalysis.h
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TestingSupportTest.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -6,12 +6,14 @@
 //
 //===--===//
 
+#include "NoopAnalysis.h"
 #include "TestingSupport.h"
 #include "clang/AST/Decl.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Tooling/Tooling.h"
@@ -28,6 +30,8 @@
 #include 
 #include 
 
+namespace {
+
 using namespace clang;
 using namespace dataflow;
 using ::testing::IsEmpty;
@@ -50,7 +54,8 @@
 ControlFlowContext::build(nullptr, Body, Result.Context));
 
 AnalysisT Analysis(*Result.Context);
-Environment Env;
+DataflowAnalysisContext DACtx;
+Environment Env(DACtx);
 BlockStates = runDataflowAnalysis(CFCtx, Analysis, Env);
   }
 
@@ -75,27 +80,6 @@
   return Callback.BlockStates;
 }
 
-class NoopLattice {
-public:
-  bool operator==(const NoopLattice &) const { return true; }
-
-  LatticeJoinEffect join(const NoopLattice &) {
-return LatticeJoinEffect::Unchanged;
-  }
-};
-
-class NoopAnalysis : public DataflowAnalysis {
-public:
-  NoopAnalysis(ASTContext )
-  : DataflowAnalysis(Context) {}
-
-  static NoopLattice initialElement() { return {}; }
-
-  NoopLattice transfer(const Stmt *S, const NoopLattice , Environment ) {
-return {};
-  }
-};
-
 TEST(DataflowAnalysisTest, NoopAnalysis) {
   auto BlockStates = runAnalysis(R"(
 void target() {}
@@ -314,3 +298,5 @@
   UnorderedElementsAre("baz", "foo"));
   // FIXME: Called functions at point `p` should contain only "foo".
 }
+
+} // namespace
Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -0,0 +1,617 @@
+//===- unittests/Analysis/FlowSensitive/TransferTest.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
+//
+//===--===//
+
+#include "NoopAnalysis.h"
+#include "TestingSupport.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/StorageLocation.h"
+#include "clang/Analysis/FlowSensitive/Value.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+#include 
+
+namespace {
+
+using namespace clang;
+using namespace dataflow;
+using ::testing::_;
+using ::testing::ElementsAre;
+using ::testing::IsNull;
+using ::testing::NotNull;
+using ::testing::Pair;
+
+class TransferTest : public ::testing::Test {
+protected:
+  template 
+  void runDataflow(llvm::StringRef Code, Matcher Match) {
+test::checkDataflow(
+Code, "target",
+[](ASTContext , Environment &) { return 

[PATCH] D116290: [clang-format] Add enforcement of consistent `class`/typename` keyword for template arguments

2021-12-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/lib/Format/TemplateArgumentKeywordFixer.cpp:55
+// For `auto` language version, be conservative and assume we are < C++17
+KeepTemplateTemplateKW = (Style.Standard == FormatStyle::LS_Auto) ||
+ (Style.Standard < FormatStyle::LS_Cpp17);

Quuxplusone wrote:
> curdeius wrote:
> > avogelsgesang wrote:
> > > curdeius wrote:
> > > > Isn't it a better name?
> > > This flag is actually about the usage of the `class` keyword instead of 
> > > the `typename` keyword for template-template arguments.
> > > `true` means: "Keep using the `class` instead of the `typename` keyword 
> > > for template-template arguments."
> > > 
> > > I think the name `KeepTemplateTypenameKW` is wrong. "[...]TypenameKW = 
> > > true" would mean "use `typename` instead of `class`" to me, and that's 
> > > exactly the opposite way around.
> > > 
> > > As such, I think `KeepTemplateTemplateKW` is in fact the better name. If 
> > > we want to make it even more explicit, we could also use 
> > > `KeepTemplateTemplateClassKW`. What do you think?
> > I did understand it correctly that it is about class keyword in template 
> > template parameters, but my brain somehow melted down the road:). You can 
> > keep the name as is.
> IIUC, it feels like the boolean should be named 
> `UseClassKWInTemplateTemplates`, and it shouldn't have anything to do with 
> `Keep`ing the human's choice. If the human feeds you some C++17 code using 
> `template typename T>` and asks you to format it as C++14 
> with `TAS_Typename`, I think it would be quite appropriate to output 
> `template class T>`. (Change `class` to `typename` because 
> the human asked for `TAS_Typename`; change `typename` to `class` because 
> C++14 implies `UseClassKWInTemplateTemplates`.)
> Anyway, this should have a unit test too.
> IIUC, it feels like the boolean should be named 
> `UseClassKWInTemplateTemplates`, and it shouldn't have anything to do with 
> `Keep`ing the human's choice. If the human feeds you some C++17 code using 
> `template typename T>` and asks you to format it as C++14 
> with `TAS_Typename`, I think it would be quite appropriate to output 
> `template class T>`. (Change `class` to `typename` because 
> the human asked for `TAS_Typename`; change `typename` to `class` because 
> C++14 implies `UseClassKWInTemplateTemplates`.)
> Anyway, this should have a unit test too.





Comment at: clang/lib/Format/TemplateArgumentKeywordFixer.cpp:55
+// For `auto` language version, be conservative and assume we are < C++17
+KeepTemplateTemplateKW = (Style.Standard == FormatStyle::LS_Auto) ||
+ (Style.Standard < FormatStyle::LS_Cpp17);

curdeius wrote:
> Quuxplusone wrote:
> > curdeius wrote:
> > > avogelsgesang wrote:
> > > > curdeius wrote:
> > > > > Isn't it a better name?
> > > > This flag is actually about the usage of the `class` keyword instead of 
> > > > the `typename` keyword for template-template arguments.
> > > > `true` means: "Keep using the `class` instead of the `typename` keyword 
> > > > for template-template arguments."
> > > > 
> > > > I think the name `KeepTemplateTypenameKW` is wrong. "[...]TypenameKW = 
> > > > true" would mean "use `typename` instead of `class`" to me, and that's 
> > > > exactly the opposite way around.
> > > > 
> > > > As such, I think `KeepTemplateTemplateKW` is in fact the better name. 
> > > > If we want to make it even more explicit, we could also use 
> > > > `KeepTemplateTemplateClassKW`. What do you think?
> > > I did understand it correctly that it is about class keyword in template 
> > > template parameters, but my brain somehow melted down the road:). You can 
> > > keep the name as is.
> > IIUC, it feels like the boolean should be named 
> > `UseClassKWInTemplateTemplates`, and it shouldn't have anything to do with 
> > `Keep`ing the human's choice. If the human feeds you some C++17 code using 
> > `template typename T>` and asks you to format it as C++14 
> > with `TAS_Typename`, I think it would be quite appropriate to output 
> > `template class T>`. (Change `class` to `typename` 
> > because the human asked for `TAS_Typename`; change `typename` to `class` 
> > because C++14 implies `UseClassKWInTemplateTemplates`.)
> > Anyway, this should have a unit test too.
> > IIUC, it feels like the boolean should be named 
> > `UseClassKWInTemplateTemplates`, and it shouldn't have anything to do with 
> > `Keep`ing the human's choice. If the human feeds you some C++17 code using 
> > `template typename T>` and asks you to format it as C++14 
> > with `TAS_Typename`, I think it would be quite appropriate to output 
> > `template class T>`. (Change `class` to `typename` 
> > because the human asked for `TAS_Typename`; change `typename` to `class` 
> > because C++14 implies `UseClassKWInTemplateTemplates`.)
> > Anyway, this should have a unit test 

[clang] 52e8f58 - [SYCL] Diagnose uses of zero length arrays

2021-12-29 Thread Mariya Podchishchaeva via cfe-commits

Author: Mariya Podchishchaeva
Date: 2021-12-29T15:30:18+03:00
New Revision: 52e8f58d49e63aaf6f4c1682bb787bcbfd240009

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

LOG: [SYCL] Diagnose uses of zero length arrays

Adds diagnosing on attempt to use zero length arrays, pointers, refs, arrays
of them and structs/classes containing all of it.
In case a struct/class with zero length array is used this emits a set
of notes pointing out how zero length array got into used struct, like
this:
```
struct ContainsArr {
  int A[0]; // note: field of illegal type declared here
};
struct Wrapper {
  ContainsArr F; // note: within field of type ContainsArr declared here
  // ...
}

// Device code
Wrapper W;
W.use(); // error: zero-length arrays are not permitted

```
Total deep check of each used declaration may result in double
diagnosing at the same location.

Reviewed By: aaron.ballman

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

Added: 
clang/test/SemaSYCL/zero-length-arrays.cpp

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaSYCL.cpp
clang/lib/Sema/SemaType.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index f2089bfda04dc..8ef9195944d56 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5785,7 +5785,7 @@ def err_typecheck_invalid_restrict_invalid_pointee : 
Error<
 def ext_typecheck_zero_array_size : Extension<
   "zero size arrays are an extension">, InGroup;
 def err_typecheck_zero_array_size : Error<
-  "zero-length arrays are not permitted in C++">;
+  "zero-length arrays are not permitted in %select{C++|SYCL device code}0">;
 def err_array_size_non_int : Error<"size of array has non-integer type %0">;
 def err_init_element_not_constant : Error<
   "initializer element is not a compile-time constant">;

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 79834554a50d9..6758e7ef2c30a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13142,6 +13142,9 @@ class Sema final {
   /// Adds Callee to DeviceCallGraph if we don't know if its caller will be
   /// codegen'ed yet.
   bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
+  void deepTypeCheckForSYCLDevice(SourceLocation UsedAt,
+  llvm::DenseSet Visited,
+  ValueDecl *DeclToCheck);
 };
 
 /// RAII object that enters a new expression evaluation context.

diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 734ed0f62ec65..ba69400fdbbfc 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1858,6 +1858,15 @@ void Sema::checkTypeSupport(QualType Ty, SourceLocation 
Loc, ValueDecl *D) {
   if (isUnevaluatedContext() || Ty.isNull())
 return;
 
+  // The original idea behind checkTypeSupport function is that unused
+  // declarations can be replaced with an array of bytes of the same size 
during
+  // codegen, such replacement doesn't seem to be possible for types without
+  // constant byte size like zero length arrays. So, do a deep check for SYCL.
+  if (D && LangOpts.SYCLIsDevice) {
+llvm::DenseSet Visited;
+deepTypeCheckForSYCLDevice(Loc, Visited, D);
+  }
+
   Decl *C = cast(getCurLexicalContext());
 
   // Memcpy operations for structs containing a member with unsupported type

diff  --git a/clang/lib/Sema/SemaSYCL.cpp b/clang/lib/Sema/SemaSYCL.cpp
index 815463307ecc7..f8c713c8545d9 100644
--- a/clang/lib/Sema/SemaSYCL.cpp
+++ b/clang/lib/Sema/SemaSYCL.cpp
@@ -48,3 +48,101 @@ bool Sema::checkSYCLDeviceFunction(SourceLocation Loc, 
FunctionDecl *Callee) {
   return DiagKind != SemaDiagnosticBuilder::K_Immediate &&
  DiagKind != SemaDiagnosticBuilder::K_ImmediateWithCallStack;
 }
+
+static bool isZeroSizedArray(Sema , QualType Ty) {
+  if (const auto *CAT = SemaRef.getASTContext().getAsConstantArrayType(Ty))
+return CAT->getSize() == 0;
+  return false;
+}
+
+void Sema::deepTypeCheckForSYCLDevice(SourceLocation UsedAt,
+  llvm::DenseSet Visited,
+  ValueDecl *DeclToCheck) {
+  assert(getLangOpts().SYCLIsDevice &&
+ "Should only be called during SYCL compilation");
+  // Emit notes only for the first discovered declaration of unsupported type
+  // to avoid mess of notes. This flag is to track that error already happened.
+  bool NeedToEmitNotes = true;
+
+  auto Check = [&](QualType TypeToCheck, const ValueDecl *D) {
+bool ErrorFound = false;
+if 

[PATCH] D114080: [SYCL] Diagnose uses of zero length arrays

2021-12-29 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG52e8f58d49e6: [SYCL] Diagnose uses of zero length arrays 
(authored by Fznamznon).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114080

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaSYCL.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/SemaSYCL/zero-length-arrays.cpp

Index: clang/test/SemaSYCL/zero-length-arrays.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/zero-length-arrays.cpp
@@ -0,0 +1,125 @@
+// RUN: %clang_cc1 -fsycl-is-device -triple spir64 -fsyntax-only -verify %s
+//
+// This test checks if compiler reports compilation error on an attempt to use
+// a zero-length array inside device code.
+
+template 
+__attribute__((sycl_kernel)) void kernel(const Func ) {
+  // expected-note@+1 5{{called by 'kernel}}
+  kernelFunc(); // #KernelObjCall
+}
+
+typedef float ZEROARR[0];
+
+struct Wrapper {
+  int A;
+  int BadArray[0]; // expected-note 3{{field of illegal type 'int[0]' declared here}}
+};
+
+struct WrapperOfWrapper { // expected-error 2{{zero-length arrays are not permitted in SYCL device code}}
+  Wrapper F;  // expected-note 2{{within field of type 'Wrapper' declared here}}
+  ZEROARR *Ptr;   //expected-note 5{{field of illegal pointer type 'ZEROARR *' (aka 'float (*)[0]') declared here}}
+};
+
+template  struct InnerTemplated {
+  double Array[Size]; // expected-note 8{{field of illegal type 'double[0]' declared here}}
+};
+
+template  struct Templated {
+  unsigned A;
+  Ty Arr[Size];
+  InnerTemplated Array[Size + 1]; // expected-note 8{{within field of type 'InnerTemplated<0U>[1]' declared here}}
+};
+
+struct KernelSt {
+  int A;
+  int BadArray[0]; // expected-note {{field of illegal type 'int[0]' declared here}}
+  void operator()() const {}
+};
+
+WrapperOfWrapper offendingFoo() {
+  // expected-note@+1 {{called by 'offendingFoo'}}
+  return WrapperOfWrapper{};
+}
+
+template 
+void templatedContext() {
+  Templated Var;
+  // expected-error@#KernelObjCall 2{{zero-length arrays are not permitted in SYCL device code}}
+  // expected-note@#KernelObjCall {{called by 'kernel([=] {
+// expected-note@+1 {{within field of type 'Templated<0U, float>' declared here}}
+(void)Var; // expected-error 2{{zero-length arrays are not permitted in SYCL device code}}
+  });
+  // expected-error@#KernelObjCall {{zero-length arrays are not permitted in SYCL device code}}
+  // expected-note@+2 {{in instantiation of function template specialization}}
+  // expected-note@+1 {{within field of type 'Templated<0U, float>' declared here}}
+  kernel([Var] {
+  });
+}
+
+void foo(const unsigned X) {
+  int Arr[0];  // expected-note 2{{declared here}}
+  ZEROARR TypeDef; // expected-note {{declared here}}
+  ZEROARR *Ptr;// expected-note {{declared here}}
+   // expected-error@#KernelObjCall 3{{zero-length arrays are not permitted in SYCL device code}}
+  // expected-note@+1 {{in instantiation of function template specialization}}
+  kernel([=]() {
+(void)Arr; // expected-error {{zero-length arrays are not permitted in SYCL device code}}
+(void)TypeDef; // expected-error {{zero-length arrays are not permitted in SYCL device code}}
+// expected-note@+1 {{field of illegal pointer type 'ZEROARR *' (aka 'float (*)[0]') declared here}}
+(void)Ptr; // expected-error {{zero-length arrays are not permitted in SYCL device code}}
+  });
+  // expected-error@#KernelObjCall {{zero-length arrays are not permitted in SYCL device code}}
+  // expected-note@+2 {{in instantiation of function template specialization}}
+  // expected-note@+1 {{field of illegal type 'int[0]' declared here}}
+  kernel([Arr] { // expected-error {{zero-length arrays are not permitted in SYCL device code}}
+  });
+  WrapperOfWrapper St;
+  // expected-error@#KernelObjCall 2{{zero-length arrays are not permitted in SYCL device code}}
+  // expected-note@+1 {{in instantiation of function template specialization}}
+  kernel([=] {
+// expected-note@+1 {{within field of type 'WrapperOfWrapper' declared here}}
+(void)St.F.BadArray; // expected-error 4{{zero-length arrays are not permitted in SYCL device code}}
+  });
+  // expected-error@#KernelObjCall 2{{zero-length arrays are not permitted in SYCL device code}}
+  // expected-note@+2 {{in instantiation of function template specialization}}
+  // expected-note@+1 {{within field of type 'WrapperOfWrapper' declared here}}
+  kernel([St] { // expected-error 2{{zero-length arrays are not permitted in SYCL device code}}
+  });
+
+  Templated<1, int> OK;
+  Templated<1 - 1, double> Weirdo;
+  Templated<0, float> Zero;
+  // expected-error@#KernelObjCall 4{{zero-length arrays are not permitted in SYCL device 

[clang] 3ad32df - Fix lit feature name in 9dc4af327b12d

2021-12-29 Thread via cfe-commits

Author: Sam McCall
Date: 2021-12-29T13:18:11+01:00
New Revision: 3ad32df72eb2063ba45ec2956a815e1bbb6e6012

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

LOG: Fix lit feature name in 9dc4af327b12d

Added: 


Modified: 
clang/test/SemaCXX/PR51712-large-array-constexpr-check-oom.cpp

Removed: 




diff  --git a/clang/test/SemaCXX/PR51712-large-array-constexpr-check-oom.cpp 
b/clang/test/SemaCXX/PR51712-large-array-constexpr-check-oom.cpp
index 859b1ac3fb2b..f84cab8dc33e 100644
--- a/clang/test/SemaCXX/PR51712-large-array-constexpr-check-oom.cpp
+++ b/clang/test/SemaCXX/PR51712-large-array-constexpr-check-oom.cpp
@@ -2,7 +2,7 @@
 // (There's nothing really platform-specific being tested, this is just 
ulimit).
 //
 // REQUIRES: shell
-// REQUIRES: linux
+// REQUIRES: system-linux
 // UNSUPPORTED: msan
 // UNSUPPORTED: asan
 //



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


[clang] 9dc4af3 - Re-land "[clang] Add early exit when checking for const init of arrays."

2021-12-29 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-12-29T13:07:30+01:00
New Revision: 9dc4af327b12dfbcf90fde1641cd649c6814bf98

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

LOG: Re-land "[clang] Add early exit when checking for const init of arrays."

This reverts commit 6d09aaecdfe51e13fc64d539aa7c9a790de341d7.

The test uses ulimit and ran into problems on some bots. Run on linux only.
There's nothing platform-specific about the code we're testing, so this
should be enough to ensure correctness.

Added: 
clang/test/SemaCXX/PR51712-large-array-constexpr-check-oom.cpp

Modified: 
clang/lib/AST/ExprConstant.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 469339e8cd624..105cd7a3506dd 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -10680,28 +10680,55 @@ bool ArrayExprEvaluator::VisitCXXConstructExpr(const 
CXXConstructExpr *E,
   bool HadZeroInit = Value->hasValue();
 
   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
-unsigned N = CAT->getSize().getZExtValue();
+unsigned FinalSize = CAT->getSize().getZExtValue();
 
 // Preserve the array filler if we had prior zero-initialization.
 APValue Filler =
   HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  : APValue();
 
-*Value = APValue(APValue::UninitArray(), N, N);
-
-if (HadZeroInit)
-  for (unsigned I = 0; I != N; ++I)
-Value->getArrayInitializedElt(I) = Filler;
+*Value = APValue(APValue::UninitArray(), 0, FinalSize);
+if (FinalSize == 0)
+  return true;
 
-// Initialize the elements.
 LValue ArrayElt = Subobject;
 ArrayElt.addArray(Info, E, CAT);
-for (unsigned I = 0; I != N; ++I)
-  if (!VisitCXXConstructExpr(E, ArrayElt, 
>getArrayInitializedElt(I),
- CAT->getElementType()) ||
-  !HandleLValueArrayAdjustment(Info, E, ArrayElt, 
CAT->getElementType(),
-   1))
-return false;
+// We do the whole initialization in two passes, first for just one 
element,
+// then for the whole array. It's possible we may find out we can't do 
const
+// init in the first pass, in which case we avoid allocating a potentially
+// large array. We don't do more passes because expanding array requires
+// copying the data, which is wasteful.
+for (const unsigned N : {1u, FinalSize}) {
+  unsigned OldElts = Value->getArrayInitializedElts();
+  if (OldElts == N)
+break;
+
+  // Expand the array to appropriate size.
+  APValue NewValue(APValue::UninitArray(), N, FinalSize);
+  for (unsigned I = 0; I < OldElts; ++I)
+NewValue.getArrayInitializedElt(I).swap(
+Value->getArrayInitializedElt(I));
+  Value->swap(NewValue);
+
+  if (HadZeroInit)
+for (unsigned I = OldElts; I < N; ++I)
+  Value->getArrayInitializedElt(I) = Filler;
+
+  // Initialize the elements.
+  for (unsigned I = OldElts; I < N; ++I) {
+if (!VisitCXXConstructExpr(E, ArrayElt,
+   >getArrayInitializedElt(I),
+   CAT->getElementType()) ||
+!HandleLValueArrayAdjustment(Info, E, ArrayElt,
+ CAT->getElementType(), 1))
+  return false;
+// When checking for const initilization any diagnostic is considered
+// an error.
+if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
+!Info.keepEvaluatingAfterFailure())
+  return false;
+  }
+}
 
 return true;
   }

diff  --git a/clang/test/SemaCXX/PR51712-large-array-constexpr-check-oom.cpp 
b/clang/test/SemaCXX/PR51712-large-array-constexpr-check-oom.cpp
new file mode 100644
index 0..859b1ac3fb2be
--- /dev/null
+++ b/clang/test/SemaCXX/PR51712-large-array-constexpr-check-oom.cpp
@@ -0,0 +1,17 @@
+// Only run this test where ulimit is known to work well.
+// (There's nothing really platform-specific being tested, this is just 
ulimit).
+//
+// REQUIRES: shell
+// REQUIRES: linux
+// UNSUPPORTED: msan
+// UNSUPPORTED: asan
+//
+// RUN: ulimit -v 1048576
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify -triple=x86_64 %s
+// expected-no-diagnostics
+
+// This used to require too much memory and crash with OOM.
+struct {
+  int a, b, c, d;
+} arr[1<<30];
+



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


[PATCH] D116368: [clang][dataflow] Add transfer function for VarDecl statements

2021-12-29 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev created this revision.
sgatev added reviewers: ymandel, xazax.hun, gribozavr2.
Herald added subscribers: rnkovacs, mgorny.
sgatev requested review of this revision.
Herald added a project: clang.

This is part of the implementation of the dataflow analysis framework.
See "[RFC] A dataflow analysis framework for Clang AST" on cfe-dev.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116368

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/StorageLocation.h
  clang/include/clang/Analysis/FlowSensitive/Transfer.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Value.h
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/NoopAnalysis.h
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TestingSupportTest.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -6,12 +6,14 @@
 //
 //===--===//
 
+#include "NoopAnalysis.h"
 #include "TestingSupport.h"
 #include "clang/AST/Decl.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Tooling/Tooling.h"
@@ -28,6 +30,8 @@
 #include 
 #include 
 
+namespace {
+
 using namespace clang;
 using namespace dataflow;
 using ::testing::IsEmpty;
@@ -50,7 +54,8 @@
 ControlFlowContext::build(nullptr, Body, Result.Context));
 
 AnalysisT Analysis(*Result.Context);
-Environment Env;
+DataflowAnalysisContext DACtx;
+Environment Env(DACtx);
 BlockStates = runDataflowAnalysis(CFCtx, Analysis, Env);
   }
 
@@ -75,27 +80,6 @@
   return Callback.BlockStates;
 }
 
-class NoopLattice {
-public:
-  bool operator==(const NoopLattice &) const { return true; }
-
-  LatticeJoinEffect join(const NoopLattice &) {
-return LatticeJoinEffect::Unchanged;
-  }
-};
-
-class NoopAnalysis : public DataflowAnalysis {
-public:
-  NoopAnalysis(ASTContext )
-  : DataflowAnalysis(Context) {}
-
-  static NoopLattice initialElement() { return {}; }
-
-  NoopLattice transfer(const Stmt *S, const NoopLattice , Environment ) {
-return {};
-  }
-};
-
 TEST(DataflowAnalysisTest, NoopAnalysis) {
   auto BlockStates = runAnalysis(R"(
 void target() {}
@@ -314,3 +298,5 @@
   UnorderedElementsAre("baz", "foo"));
   // FIXME: Called functions at point `p` should contain only "foo".
 }
+
+} // namespace
Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -0,0 +1,617 @@
+//===- unittests/Analysis/FlowSensitive/TransferTest.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
+//
+//===--===//
+
+#include "NoopAnalysis.h"
+#include "TestingSupport.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/StorageLocation.h"
+#include "clang/Analysis/FlowSensitive/Value.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+#include 
+
+namespace {
+
+using namespace clang;
+using namespace dataflow;
+using ::testing::_;
+using ::testing::ElementsAre;
+using ::testing::IsNull;
+using ::testing::NotNull;
+using ::testing::Pair;
+
+class TransferTest : public ::testing::Test {
+protected:
+  template 

[PATCH] D72326: [clang-format] Rebased on master: Add option to specify explicit config file

2021-12-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

Oh, and please rename the patch before landing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72326

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


[PATCH] D72326: [clang-format] Rebased on master: Add option to specify explicit config file

2021-12-29 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 but please wait for the green light from other involved reviewers.
Also, as noted in a comment, I'd like to see unrelated changes in a different 
patch (unless you convince me that it's overly complicated or too much 
dependent on this patch).




Comment at: clang/lib/Format/Format.cpp:3298
+// Search for parent configs starting from the parent directory of
+// ConfigFile
+FileName = ConfigFile;

Here and elsewhere: please end the comments with a full stop.



Comment at: clang/unittests/Format/FormatTest.cpp:21483
 
-  // Test 9.1: overwriting a file style, when parent no file exists with no
+  // Test 9.1.1: overwriting a file style, when parent no file exists with no
   // fallback style

?



Comment at: clang/unittests/Format/FormatTest.cpp:21499
 
+  // Test 9.1.2: propagate more than one level with no parent file
+  ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,

Can we split changes unrelated to the specific configuration file 
(fixing/testing the inherited config) to another patch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72326

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


[PATCH] D116314: [clang-format] Add style to separate definition blocks

2021-12-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius requested changes to this revision.
curdeius added a comment.
This revision now requires changes to proceed.

Nice job. Some minor comments.
Please don't forget to reformat too.




Comment at: clang/docs/ClangFormatStyleOptions.rst:3415
+
+ SeparateDefinitions
+ Neverv.s.   Always

Keep it consistent please.



Comment at: clang/docs/ClangFormatStyleOptions.rst:3418
+ #include   #include 
+ struct Foo{
+   int a,b,c;struct Foo {

Please reformat the code, e.g. on the left misses spaces (near braces and 
commas for instance). The difference between left and right should only be 
blank lines between blocks.
Of course, do it in Format.h and regenerate the RST.



Comment at: clang/include/clang/Format/Format.h:3054
+  enum SeparateDefinitionStyle {
+/// Leave definition blocks separated as they are without changing 
anything.
+SDS_Leave,





Comment at: clang/include/clang/Format/Format.h:3063
+  /// Specifies the use of empty lines to separate definition blocks, including
+  /// classes, structs, enum, and functions, for C++ language.
+  /// \code

Why not C and other similar languages?
Also, you don't seem to be limiting the pass to C++. Please add some tests to 
other languages.



Comment at: clang/include/clang/Format/Format.h:3065
+  /// \code
+  ///SeparateDefinitions
+  ///Neverv.s.   Always

Actuay, do you need this line?



Comment at: clang/include/clang/Format/Format.h:4080
+/// Use empty line to separate definition blocks including classes, structs,
+/// functions, namespaces, and enum in the given \p Ranges in \p Code.
+///





Comment at: clang/include/clang/Format/Format.h:4082
+///
+/// Returns the ``Replacements`` that inserts empty lines to separate 
definition
+/// blocks in all \p Ranges in \p Code.

?



Comment at: clang/unittests/Format/DefinitionBlockSeparatorTest.cpp:48
+  Style.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  EXPECT_EQ("int foo() {\n"
+"  int i, j;\n"

Maybe you can add `verifyFormat` helper as in other files? So that you don't 
need to repeat the code in some cases and we test the code formatting stability 
as well.


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

https://reviews.llvm.org/D116314

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


[PATCH] D108694: [RISCV] Add the zvl extension according to the v1.0 spec

2021-12-29 Thread Yueh-Ting Chen via Phabricator via cfe-commits
eopXD added inline comments.



Comment at: llvm/lib/Support/RISCVISAInfo.cpp:741-751
+{{"zvl1024b"}, {ImpliedExtsZvl1024b}},
+{{"zvl128b"}, {ImpliedExtsZvl128b}},
+{{"zvl16384b"}, {ImpliedExtsZvl16384b}},
+{{"zvl2048b"}, {ImpliedExtsZvl2048b}},
+{{"zvl256b"}, {ImpliedExtsZvl256b}},
+{{"zvl32768b"}, {ImpliedExtsZvl32768b}},
+{{"zvl4096b"}, {ImpliedExtsZvl4096b}},

achieveartificialintelligence wrote:
> Can we compress the code?
Hi,

Thank you for leaving a comment. Do you mean to embed the list of implied 
extensions into the declaration of `ImpliedExts`? Like:

```
static constexpr ImpliedExtsEntry ImpliedExts[] = {
{{"v"}, {{"zvlsseg", "zvl128b"}}},
   ...
```

In my opinion I think compressing here may not help because the indirection is 
intended to have the implications be in more sorted order that is more human 
readable since `ImpliedExts` are required to be in lexicographical order.

I am just stating my opinion on my current implementation since I think this is 
a coding style problem. What do you think?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108694

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


[PATCH] D108694: [RISCV] Add the zvl extension according to the v1.0 spec

2021-12-29 Thread Yueh-Ting Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 396505.
eopXD added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108694

Files:
  clang/lib/Basic/Targets/RISCV.cpp
  clang/test/Driver/riscv-arch.c
  clang/test/Preprocessor/riscv-target-features.c
  llvm/include/llvm/Support/RISCVISAInfo.h
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/RISCV.td
  llvm/lib/Target/RISCV/RISCVSubtarget.cpp
  llvm/lib/Target/RISCV/RISCVSubtarget.h
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/MC/RISCV/attribute-arch.s

Index: llvm/test/MC/RISCV/attribute-arch.s
===
--- llvm/test/MC/RISCV/attribute-arch.s
+++ llvm/test/MC/RISCV/attribute-arch.s
@@ -36,7 +36,7 @@
 ## Experimental extensions require version string to be explicitly specified
 
 .attribute arch, "rv32iv0p10"
-# CHECK: attribute  5, "rv32i2p0_v0p10_zvlsseg0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl128b0p10_zvl32b0p10_zvl64b0p10_zvlsseg0p10"
 
 .attribute arch, "rv32izba1p0"
 # CHECK: attribute  5, "rv32i2p0_zba1p0"
@@ -75,4 +75,40 @@
 # CHECK: attribute  5, "rv32i2p0_f2p0_zfh0p1_zfhmin0p1"
 
 .attribute arch, "rv32iv0p10zvamo0p10_zvlsseg0p10"
-# CHECK: attribute  5, "rv32i2p0_v0p10_zvamo0p10_zvlsseg0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvamo0p10_zvl128b0p10_zvl32b0p10_zvl64b0p10_zvlsseg0p10"
+
+.attribute arch, "rv32iv0p10zvl32b0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl128b0p10_zvl32b0p10_zvl64b0p10_zvlsseg0p10"
+
+.attribute arch, "rv32iv0p10zvl64b0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl128b0p10_zvl32b0p10_zvl64b0p10_zvlsseg0p10"
+
+.attribute arch, "rv32iv0p10zvl128b0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl128b0p10_zvl32b0p10_zvl64b0p10_zvlsseg0p10"
+
+.attribute arch, "rv32iv0p10zvl256b0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl128b0p10_zvl256b0p10_zvl32b0p10_zvl64b0p10_zvlsseg0p10"
+
+.attribute arch, "rv32iv0p10zvl512b0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl128b0p10_zvl256b0p10_zvl32b0p10_zvl512b0p10_zvl64b0p10_zvlsseg0p10"
+
+.attribute arch, "rv32iv0p10zvl1024b0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl1024b0p10_zvl128b0p10_zvl256b0p10_zvl32b0p10_zvl512b0p10_zvl64b0p10_zvlsseg0p10"
+
+.attribute arch, "rv32iv0p10zvl2048b0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl1024b0p10_zvl128b0p10_zvl2048b0p10_zvl256b0p10_zvl32b0p10_zvl512b0p10_zvl64b0p10_zvlsseg0p10"
+
+.attribute arch, "rv32iv0p10zvl4096b0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl1024b0p10_zvl128b0p10_zvl2048b0p10_zvl256b0p10_zvl32b0p10_zvl4096b0p10_zvl512b0p10_zvl64b0p10_zvlsseg0p10"
+
+.attribute arch, "rv32iv0p10zvl8192b0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl1024b0p10_zvl128b0p10_zvl2048b0p10_zvl256b0p10_zvl32b0p10_zvl4096b0p10_zvl512b0p10_zvl64b0p10_zvl8192b0p10_zvlsseg0p10"
+
+.attribute arch, "rv32iv0p10zvl16384b0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl1024b0p10_zvl128b0p10_zvl16384b0p10_zvl2048b0p10_zvl256b0p10_zvl32b0p10_zvl4096b0p10_zvl512b0p10_zvl64b0p10_zvl8192b0p10_zvlsseg0p10"
+
+.attribute arch, "rv32iv0p10zvl32768b0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl1024b0p10_zvl128b0p10_zvl16384b0p10_zvl2048b0p10_zvl256b0p10_zvl32768b0p10_zvl32b0p10_zvl4096b0p10_zvl512b0p10_zvl64b0p10_zvl8192b0p10_zvlsseg0p10"
+
+.attribute arch, "rv32iv0p10zvl65536b0p10"
+# CHECK: attribute  5, "rv32i2p0_v0p10_zvl1024b0p10_zvl128b0p10_zvl16384b0p10_zvl2048b0p10_zvl256b0p10_zvl32768b0p10_zvl32b0p10_zvl4096b0p10_zvl512b0p10_zvl64b0p10_zvl65536b0p10_zvl8192b0p10_zvlsseg0p10"
Index: llvm/test/CodeGen/RISCV/attributes.ll
===
--- llvm/test/CodeGen/RISCV/attributes.ll
+++ llvm/test/CodeGen/RISCV/attributes.ll
@@ -18,7 +18,7 @@
 ; RUN: llc -mtriple=riscv32 -mattr=+experimental-zbr %s -o - | FileCheck --check-prefix=RV32ZBR %s
 ; RUN: llc -mtriple=riscv32 -mattr=+experimental-zbs %s -o - | FileCheck --check-prefix=RV32ZBS %s
 ; RUN: llc -mtriple=riscv32 -mattr=+experimental-zbt %s -o - | FileCheck --check-prefix=RV32ZBT %s
-; RUN: llc -mtriple=riscv32 -mattr=+experimental-zbb,+experimental-zfh,+experimental-zvamo,+experimental-v,+f,+experimental-zvlsseg %s -o - | FileCheck --check-prefix=RV32COMBINED %s
+; RUN: llc -mtriple=riscv32 -mattr=+experimental-zbb,+experimental-zfh,+experimental-zvamo,+experimental-v,+experimental-zvlsseg %s -o - | FileCheck --check-prefix=RV32COMBINED %s
 ; RUN: llc -mtriple=riscv64 -mattr=+m %s -o - | FileCheck --check-prefix=RV64M %s
 ; RUN: llc -mtriple=riscv64 -mattr=+a %s -o - | FileCheck --check-prefix=RV64A %s
 ; RUN: llc -mtriple=riscv64 -mattr=+f %s -o - | FileCheck --check-prefix=RV64F %s
@@ -37,14 +37,14 @@
 ; RUN: llc -mtriple=riscv64 -mattr=+experimental-zbr %s -o - | FileCheck --check-prefix=RV64ZBR %s
 ; RUN: llc -mtriple=riscv64 -mattr=+experimental-zbs %s -o - | FileCheck 

[PATCH] D116318: [clang-format][NFC] Fix a bug in getPreviousToken() in the parser

2021-12-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

On another note, you can fix the comment typo without a review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116318

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


[PATCH] D116318: [clang-format][NFC] Fix a bug in getPreviousToken() in the parser

2021-12-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

I'm in the same position as @hazardyknusperkeks.
If you need something to simplify the code you can add a helper 
`getPreviousTokenOrNull` or something like that in your patch.
But we certainly don't want to pay for the `if` check each time we call 
`getPreviousToken`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116318

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


[PATCH] D108694: [RISCV] Add the zvl extension according to the v1.0 spec

2021-12-29 Thread Shao-Ce SUN via Phabricator via cfe-commits
achieveartificialintelligence added inline comments.



Comment at: llvm/lib/Support/RISCVISAInfo.cpp:741-751
+{{"zvl1024b"}, {ImpliedExtsZvl1024b}},
+{{"zvl128b"}, {ImpliedExtsZvl128b}},
+{{"zvl16384b"}, {ImpliedExtsZvl16384b}},
+{{"zvl2048b"}, {ImpliedExtsZvl2048b}},
+{{"zvl256b"}, {ImpliedExtsZvl256b}},
+{{"zvl32768b"}, {ImpliedExtsZvl32768b}},
+{{"zvl4096b"}, {ImpliedExtsZvl4096b}},

Can we compress the code?



Comment at: llvm/lib/Target/RISCV/RISCV.td:153-186
+def FeatureStdExtZvl32b : SubtargetFeature<"experimental-zvl32b", "ZvlLen", 
"ExtZvl::Zvl32b",
+   "'Zvl' (Minimum Vector Length) 32">;
+def FeatureStdExtZvl64b : SubtargetFeature<"experimental-zvl64b", "ZvlLen", 
"ExtZvl::Zvl64b",
+   "'Zvl' (Minimum Vector Length) 64",
+   [FeatureStdExtZvl32b]>;
+def FeatureStdExtZvl128b : SubtargetFeature<"experimental-zvl128b", "ZvlLen", 
"ExtZvl::Zvl128b",
+   "'Zvl' (Minimum Vector Length) 128",

Same as here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108694

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


[PATCH] D108694: [RISCV] Add the zvl extension according to the v1.0 spec

2021-12-29 Thread Yueh-Ting Chen via Phabricator via cfe-commits
eopXD added a comment.

Ping, thank you.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108694

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


[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2021-12-29 Thread Owen Pan via Phabricator via cfe-commits
owenpan marked 2 inline comments as done.
owenpan added a comment.

In D116316#3211269 , @curdeius wrote:

> Could you have a look at preceding reviews and see if there wasn't a similar 
> patch before?

I conversed  with @MyDeveloperDay in 
D95168 . In fact, that was one of the main 
reasons that I put in extra effort to get this patch done.

> I think that this option is a bit too limited.
> Only removing braces doesn't seem enough.

I wanted to implement as many features as possible using the limited parser of 
clang-format, and the LLVM style would be a very high bar to clear. Only 
focusing on LLVM now will actually make this option less limited if and when we 
are ready to support other styles. It would be mostly configuring/packaging 
what have already worked for LLVM.

> Also, one should probably be able to decide when to add/remove them by e.g. 
> setting the number of lines in what's considered short blocks.

Agreed, but if clang-format can't do insertion well independent of removal and 
vice versa, we probably will never get there.

So far, this patch has successfully applied to clang/lib/Format, i.e., it 
builds successfully and passes FormatTests.


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

https://reviews.llvm.org/D116316

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


[clang] 8de2d06 - [clang] Fix crash in bug52905

2021-12-29 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2021-12-29T16:22:26+08:00
New Revision: 8de2d06251c30751bdc0fd7b89133610797759e6

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

LOG: [clang] Fix crash in bug52905

The root cause for the crash is the incorrect use of `cast`.
The actual type and cast-to type is different. This patch fixes the
crash by converting the `cast` to `dyn_cast`.

Added: 


Modified: 
clang/lib/Sema/SemaOverload.cpp
clang/test/SemaTemplate/constraints.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 42b1340f9a65d..a268837b3cc86 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -14322,8 +14322,7 @@ ExprResult Sema::BuildCallToMemberFunction(Scope *S, 
Expr *MemExprE,
 FoundDecl = MemExpr->getFoundDecl();
 Qualifier = MemExpr->getQualifier();
 UnbridgedCasts.restore();
-  } else {
-UnresolvedMemberExpr *UnresExpr = cast(NakedMemExpr);
+  } else if (auto *UnresExpr = dyn_cast(NakedMemExpr)) {
 Qualifier = UnresExpr->getQualifier();
 
 QualType ObjectType = UnresExpr->getBaseType();
@@ -14436,7 +14435,9 @@ ExprResult Sema::BuildCallToMemberFunction(Scope *S, 
Expr *MemExprE,
 }
 
 MemExpr = cast(MemExprE->IgnoreParens());
-  }
+  } else
+// Unimaged NakedMemExpr type.
+return ExprError();
 
   QualType ResultType = Method->getReturnType();
   ExprValueKind VK = Expr::getValueKindForType(ResultType);

diff  --git a/clang/test/SemaTemplate/constraints.cpp 
b/clang/test/SemaTemplate/constraints.cpp
index 0bc4727245f6a..e2bb6552fdb1c 100644
--- a/clang/test/SemaTemplate/constraints.cpp
+++ b/clang/test/SemaTemplate/constraints.cpp
@@ -24,3 +24,35 @@ namespace PR45589 {
   // FIXME: These diagnostics are excessive.
   static_assert(test == 1); // expected-note 2{{while}} 
expected-note 2{{during}}
 }
+
+namespace PR52905 {
+// A mock for std::convertible_to. Not complete support.
+template 
+concept convertible_to = __is_convertible_to(_From, _To); // expected-note 
{{evaluated to false}}
+
+template 
+class A {
+public:
+  using iterator = void **;
+
+  iterator begin();
+  const iterator begin() const;
+};
+
+template 
+concept Beginable1 = requires(T t) {
+  { t.begin }
+  ->convertible_to; // expected-note {{not satisfied}}
+};
+
+static_assert(Beginable1>); // expected-error {{static_assert failed}}
+   // expected-note@-1 {{does not satisfy 
'Beginable1'}}
+
+template 
+concept Beginable2 = requires(T t) {
+  { t.begin() }
+  ->convertible_to;
+};
+
+static_assert(Beginable2>);
+} // namespace PR52905



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


[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2021-12-29 Thread Owen Pan via Phabricator via cfe-commits
owenpan marked 4 inline comments as done.
owenpan added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2173
+void UnwrappedLineParser::KeepAncestorBraces() {
+  const int MaxNestingLevels = 2;
+  const int Size = NestedTooDeep.size();

HazardyKnusperkeks wrote:
> constexpr or configurable?
It will be configurable when we expand removing braces to other styles.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2338
+  KeepAncestorBraces();
+  NestedTooDeep.push_back(false);
   if (FormatTok->is(tok::l_brace)) {

HazardyKnusperkeks wrote:
> I think it is worth to create a RAII type for that.
Can you explain why an RAII type would be beneficial here?



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2937
   // Parse the class body after the enum's ";" if any.
-  parseLevel(/*HasOpeningBrace=*/true);
+  parseLevel();
   nextToken();

HazardyKnusperkeks wrote:
> I would like it better if you insert both arguments.
> I don't really like default arguments.
I'm the opposite, and `parseBlock()`is a good example. However, I restored the 
previously non-default argument.



Comment at: clang/lib/Format/UnwrappedLineParser.h:196
   bool isOnNewLine(const FormatToken );
+  bool precededByCommentOrPPDirective();
+  void KeepAncestorBraces();

HazardyKnusperkeks wrote:
> I find it nicely if the order of functions in the cpp is the same as in the 
> hpp.
Me too although some of the functions (e.g. `parseCSharpGenericTypeConstraint` 
and `parseCSharpAttribute`) were already out of order.


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

https://reviews.llvm.org/D116316

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


[clang] b468281 - [clang] Fix header guards (NFC)

2021-12-29 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2021-12-29T00:16:40-08:00
New Revision: b4682816bc6e35fb4e207227f73b88b2603d4363

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

LOG: [clang] Fix header guards (NFC)

Identified with llvm-header-guard.

Added: 


Modified: 
clang/include/clang/AST/AbstractBasicReader.h
clang/include/clang/AST/AbstractBasicWriter.h
clang/include/clang/AST/AbstractTypeReader.h
clang/include/clang/AST/AbstractTypeWriter.h
clang/include/clang/AST/ComputeDependence.h
clang/include/clang/AST/CurrentSourceLocExprScope.h
clang/include/clang/AST/DeclObjCCommon.h
clang/include/clang/AST/FormatString.h
clang/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
clang/include/clang/AST/LocInfoType.h
clang/include/clang/AST/NonTrivialTypeVisitor.h
clang/include/clang/AST/OSLog.h
clang/include/clang/AST/QualTypeNames.h
clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
clang/include/clang/ASTMatchers/Dynamic/Parser.h
clang/include/clang/ASTMatchers/Dynamic/Registry.h
clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
clang/include/clang/Analysis/Analyses/ThreadSafetyUtil.h
clang/include/clang/Analysis/AnyCall.h
clang/include/clang/Analysis/BodyFarm.h
clang/include/clang/Analysis/CloneDetection.h
clang/include/clang/Analysis/FlowSensitive/DataflowWorklist.h
clang/include/clang/Analysis/IssueHash.h
clang/include/clang/Analysis/PathDiagnostic.h
clang/include/clang/Analysis/RetainSummaryManager.h
clang/include/clang/Analysis/SelectorExtras.h
clang/include/clang/Basic/AlignedAllocation.h
clang/include/clang/Basic/AttrSubjectMatchRules.h
clang/include/clang/Basic/DarwinSDKInfo.h
clang/include/clang/Basic/DiagnosticError.h
clang/include/clang/Basic/OperatorPrecedence.h
clang/include/clang/Basic/PragmaKinds.h
clang/include/clang/Basic/ProfileList.h
clang/include/clang/Basic/TargetID.h
clang/include/clang/CodeGen/ObjectFilePCHContainerOperations.h
clang/include/clang/Frontend/PCHContainerOperations.h
clang/include/clang/Frontend/PrecompiledPreamble.h
clang/include/clang/Frontend/SerializedDiagnostics.h
clang/include/clang/IndexSerialization/SerializablePathCollection.h
clang/include/clang/Lex/DependencyDirectivesSourceMinimizer.h

clang/include/clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h
clang/include/clang/Parse/RAIIObjectsForParser.h
clang/include/clang/Sema/CleanupInfo.h
clang/include/clang/Sema/ParsedAttr.h
clang/include/clang/Sema/SemaConcept.h
clang/include/clang/Sema/TemplateInstCallback.h
clang/include/clang/Serialization/ModuleFileExtension.h
clang/include/clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h
clang/include/clang/StaticAnalyzer/Checkers/MPIFunctionClassifier.h

clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
clang/include/clang/StaticAnalyzer/Frontend/ModelConsumer.h
clang/include/clang/Tooling/CommonOptionsParser.h

clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
clang/include/clang/Tooling/FixIt.h
clang/include/clang/Tooling/Refactoring/ASTSelection.h
clang/include/clang/Tooling/Refactoring/AtomicChange.h
clang/include/clang/Tooling/Refactoring/Extract/Extract.h
clang/include/clang/Tooling/Refactoring/Extract/SourceExtraction.h
clang/include/clang/Tooling/Refactoring/Lookup.h
clang/include/clang/Tooling/Refactoring/RecursiveSymbolVisitor.h
clang/include/clang/Tooling/Refactoring/RefactoringAction.h
clang/include/clang/Tooling/Refactoring/RefactoringActionRule.h
clang/include/clang/Tooling/Refactoring/RefactoringActionRuleRequirements.h
clang/include/clang/Tooling/Refactoring/RefactoringActionRules.h
clang/include/clang/Tooling/Refactoring/RefactoringActionRulesInternal.h
clang/include/clang/Tooling/Refactoring/RefactoringOption.h
clang/include/clang/Tooling/Refactoring/RefactoringOptionVisitor.h
clang/include/clang/Tooling/Refactoring/RefactoringOptions.h
clang/include/clang/Tooling/Refactoring/RefactoringResultConsumer.h
clang/include/clang/Tooling/Refactoring/RefactoringRuleContext.h
clang/include/clang/Tooling/Refactoring/Rename/RenamingAction.h
clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h
clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h

[PATCH] D116316: [clang-format] Add an experimental option to remove optional control statement braces in LLVM C++ code

2021-12-29 Thread Owen Pan via Phabricator via cfe-commits
owenpan updated this revision to Diff 396493.
owenpan added a comment.

Addresses review comments.


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

https://reviews.llvm.org/D116316

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  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
@@ -18682,6 +18682,7 @@
   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
   CHECK_PARSE_BOOL(ReflowComments);
+  CHECK_PARSE_BOOL(RemoveBracesLLVM);
   CHECK_PARSE_BOOL(SortUsingDeclarations);
   CHECK_PARSE_BOOL(SpacesInParentheses);
   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
@@ -23020,6 +23021,297 @@
Style);
 }
 
+TEST_F(FormatTest, RemoveBraces) {
+  FormatStyle Style = getLLVMStyle();
+  Style.RemoveBracesLLVM = true;
+
+  // The following eight test cases are fully-braced versions of the examples at
+  // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
+  // statement-bodies-of-if-else-loop-statements".
+
+  // 1. Omit the braces, since the body is simple and clearly associated with
+  // the if.
+  EXPECT_EQ("if (isa(D))\n"
+"  handleFunctionDecl(D);\n"
+"else if (isa(D))\n"
+"  handleVarDecl(D);",
+format("if (isa(D)) {\n"
+   "  handleFunctionDecl(D);\n"
+   "} else if (isa(D)) {\n"
+   "  handleVarDecl(D);\n"
+   "}",
+   Style));
+
+  // 2. Here we document the condition itself and not the body.
+  verifyFormat("if (isa(D)) {\n"
+   "  // It is necessary that we explain the situation with this\n"
+   "  // surprisingly long comment, so it would be unclear\n"
+   "  // without the braces whether the following statement is in\n"
+   "  // the scope of the `if`.\n"
+   "  // Because the condition is documented, we can't really\n"
+   "  // hoist this comment that applies to the body above the\n"
+   "  // if.\n"
+   "  handleOtherDecl(D);\n"
+   "}",
+   Style);
+
+  // 3. Use braces on the outer `if` to avoid a potential dangling else
+  // situation.
+  EXPECT_EQ("if (isa(D)) {\n"
+"  for (auto *A : D.attrs())\n"
+"if (shouldProcessAttr(A))\n"
+"  handleAttr(A);\n"
+"}",
+format("if (isa(D)) {\n"
+   "  for (auto *A : D.attrs()) {\n"
+   "if (shouldProcessAttr(A)) {\n"
+   "  handleAttr(A);\n"
+   "}\n"
+   "  }\n"
+   "}",
+   Style));
+
+  // 4. Use braces for the `if` block to keep it uniform with the else block.
+  verifyFormat("if (isa(D)) {\n"
+   "  handleFunctionDecl(D);\n"
+   "} else {\n"
+   "  // In this else case, it is necessary that we explain the\n"
+   "  // situation with this surprisingly long comment, so it\n"
+   "  // would be unclear without the braces whether the\n"
+   "  // following statement is in the scope of the `if`.\n"
+   "  handleOtherDecl(D);\n"
+   "}",
+   Style);
+
+  // 5. This should also omit braces.  The `for` loop contains only a single
+  // statement, so it shouldn't have braces.  The `if` also only contains a
+  // single simple statement (the for loop), so it also should omit braces.
+  EXPECT_EQ("if (isa(D))\n"
+"  for (auto *A : D.attrs())\n"
+"handleAttr(A);",
+format("if (isa(D)) {\n"
+   "  for (auto *A : D.attrs()) {\n"
+   "handleAttr(A);\n"
+   "  }\n"
+   "}",
+   Style));
+
+  // 6. Use braces for the outer `if` since the nested `for` is braced.
+  verifyFormat("if (isa(D)) {\n"
+   "  for (auto *A : D.attrs()) {\n"
+   "// In this for loop body, it is necessary that we explain\n"
+   "// the situation with this surprisingly long comment,\n"
+   "// forcing braces on the `for` block.\n"
+   "handleAttr(A);\n"
+   "  }\n"
+   "}",
+   Style);
+
+  // 7. Use braces on the outer block because there are more than two levels of
+  // nesting.
+  EXPECT_EQ("if (isa(D)) {\n"
+"  for (auto *A : D.attrs())\n"
+"for (ssize_t i : llvm::seq(count))\n"
+"