[clang] 80e20f9 - [clang-format] [docs] Fix Mozilla coding style URL.

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

Author: Marek Kurdej
Date: 2022-01-03T09:10:37+01:00
New Revision: 80e20f9cbdd534b49785f24aa6fd05b70a6bd79d

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

LOG: [clang-format] [docs] Fix Mozilla coding style URL.

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 111ebd90d95b5..c2f85d564ba96 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -152,7 +152,7 @@ the configuration (without a prefix: ``Auto``).
 
`_
   * ``Mozilla``
 A style complying with `Mozilla's style guide
-`_
+
`_
   * ``WebKit``
 A style complying with `WebKit's style guide
 `_

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 0f97e80d425e3..f6b4926de846b 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -3888,7 +3888,7 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind 
Language);
 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
 
 /// Returns a format style complying with Mozilla's style guide:
-/// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
+/// 
https://firefox-source-docs.mozilla.org/code-quality/coding-style/index.html.
 FormatStyle getMozillaStyle();
 
 /// Returns a format style complying with Webkit's style guide:



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


[PATCH] D116521: [llvm][clang][cmake] Factor out config prefix finding logic

2022-01-03 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 updated this revision to Diff 397015.
Ericson2314 added a comment.
Herald added a reviewer: sscalpone.
Herald added a project: Flang.

Oh, Flang and LLD are the same. Just do them now then


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116521

Files:
  clang/CMakeLists.txt
  clang/cmake/modules/CMakeLists.txt
  cmake/Modules/FindPrefixFromConfig.cmake
  flang/cmake/modules/CMakeLists.txt
  lld/cmake/modules/CMakeLists.txt
  llvm/CMakeLists.txt
  llvm/cmake/modules/CMakeLists.txt

Index: llvm/cmake/modules/CMakeLists.txt
===
--- llvm/cmake/modules/CMakeLists.txt
+++ llvm/cmake/modules/CMakeLists.txt
@@ -1,4 +1,5 @@
 include(LLVMDistributionSupport)
+include(FindPrefixFromConfig)
 
 set(LLVM_INSTALL_PACKAGE_DIR lib${LLVM_LIBDIR_SUFFIX}/cmake/llvm)
 set(llvm_cmake_builddir "${LLVM_BINARY_DIR}/${LLVM_INSTALL_PACKAGE_DIR}")
@@ -99,16 +100,7 @@
   )
 
 # Generate LLVMConfig.cmake for the install tree.
-set(LLVM_CONFIG_CODE "
-# Compute the installation prefix from this LLVMConfig.cmake file location.
-get_filename_component(LLVM_INSTALL_PREFIX \"\${CMAKE_CURRENT_LIST_FILE}\" PATH)")
-# Construct the proper number of get_filename_component(... PATH)
-# calls to compute the installation prefix.
-string(REGEX REPLACE "/" ";" _count "${LLVM_INSTALL_PACKAGE_DIR}")
-foreach(p ${_count})
-  set(LLVM_CONFIG_CODE "${LLVM_CONFIG_CODE}
-get_filename_component(LLVM_INSTALL_PREFIX \"\${LLVM_INSTALL_PREFIX}\" PATH)")
-endforeach(p)
+find_prefix_from_config(LLVM_CONFIG_CODE LLVM_INSTALL_PREFIX "${LLVM_INSTALL_PACKAGE_DIR}")
 set(LLVM_CONFIG_INCLUDE_DIRS "\${LLVM_INSTALL_PREFIX}/include")
 set(LLVM_CONFIG_INCLUDE_DIR "${LLVM_CONFIG_INCLUDE_DIRS}")
 set(LLVM_CONFIG_MAIN_INCLUDE_DIR "${LLVM_CONFIG_INCLUDE_DIRS}")
Index: llvm/CMakeLists.txt
===
--- llvm/CMakeLists.txt
+++ llvm/CMakeLists.txt
@@ -196,11 +196,13 @@
   set(LLVM_GISEL_COV_PREFIX "${CMAKE_BINARY_DIR}/gisel-coverage-" CACHE STRING "Provide a filename prefix to collect the GlobalISel rule coverage")
 endif()
 
+set(LLVM_COMMON_CMAKE_UTILS ${CMAKE_CURRENT_SOURCE_DIR}/../cmake)
+
 # Add path for custom modules
-set(CMAKE_MODULE_PATH
-  ${CMAKE_MODULE_PATH}
+list(INSERT CMAKE_MODULE_PATH 0
   "${CMAKE_CURRENT_SOURCE_DIR}/cmake"
   "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules"
+  "${LLVM_COMMON_CMAKE_UTILS}/Modules"
   )
 
 # Generate a CompilationDatabase (compile_commands.json file) for our build,
@@ -308,7 +310,6 @@
 set(LLVM_BINARY_DIR   ${CMAKE_CURRENT_BINARY_DIR}  ) # --prefix
 
 set(LLVM_THIRD_PARTY_DIR  ${CMAKE_CURRENT_SOURCE_DIR}/../third-party)
-set(LLVM_COMMON_CMAKE_UTILS ${CMAKE_CURRENT_SOURCE_DIR}/../cmake)
 
 # Note: LLVM_CMAKE_DIR does not include generated files
 set(LLVM_CMAKE_DIR ${LLVM_MAIN_SRC_DIR}/cmake/modules)
Index: lld/cmake/modules/CMakeLists.txt
===
--- lld/cmake/modules/CMakeLists.txt
+++ lld/cmake/modules/CMakeLists.txt
@@ -29,16 +29,7 @@
 set(LLD_CONFIG_LLVM_CMAKE_DIR)
 
 # Generate LLDConfig.cmake for the install tree.
-set(LLD_CONFIG_CODE "
-# Compute the installation prefix from this LLVMConfig.cmake file location.
-get_filename_component(LLD_INSTALL_PREFIX \"\${CMAKE_CURRENT_LIST_FILE}\" PATH)")
-# Construct the proper number of get_filename_component(... PATH)
-# calls to compute the installation prefix.
-string(REGEX REPLACE "/" ";" _count "${LLD_INSTALL_PACKAGE_DIR}")
-foreach(p ${_count})
-  set(LLD_CONFIG_CODE "${LLD_CONFIG_CODE}
-get_filename_component(LLD_INSTALL_PREFIX \"\${LLD_INSTALL_PREFIX}\" PATH)")
-endforeach(p)
+find_prefix_from_config(LLD_CONFIG_CODE LLD_INSTALL_PREFIX "${LLD_INSTALL_PACKAGE_DIR}")
 set(LLD_CONFIG_CMAKE_DIR "\${LLD_INSTALL_PREFIX}/${LLD_INSTALL_PACKAGE_DIR}")
 set(LLD_CONFIG_LLVM_CMAKE_DIR "\${LLD_INSTALL_PREFIX}/${LLVM_INSTALL_PACKAGE_DIR}")
 get_config_exports_includes(LLD LLD_CONFIG_INCLUDE_EXPORTS)
Index: flang/cmake/modules/CMakeLists.txt
===
--- flang/cmake/modules/CMakeLists.txt
+++ flang/cmake/modules/CMakeLists.txt
@@ -29,16 +29,7 @@
 set(FLANG_CONFIG_LLVM_CMAKE_DIR)
 
 # Generate FlangConfig.cmake for the install tree.
-set(FLANG_CONFIG_CODE "
-  # Compute the installation prefix from this LLVMConfig.cmake file location.
-  get_filename_component(FLANG_INSTALL_PREFIX \"\${CMAKE_CURRENT_LIST_FILE}\" PATH)")
-# Construct the proper number of get_filename_component(... PATH)
-# calls to compute the installation prefix.
-string(REGEX REPLACE "/" ";" _count "${FLANG_INSTALL_PACKAGE_DIR}")
-foreach(p ${_count})
-  set(FLANG_CONFIG_CODE "${FLANG_CONFIG_CODE}
-  get_filename_component(FLANG_INSTALL_PREFIX \"\${FLANG_INSTALL_PREFIX}\" PATH)")
-endforeach(p)
+find_prefix_from_config(FLANG_CONFIG_CODE FLANG_INSTALL_PREFIX "${FLANG_INSTALL_PACKAGE_DIR}")
 

[clang] ab0bfbd - [clang-format] Use get*StyleWithColumns helper. NFC.

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

Author: Marek Kurdej
Date: 2022-01-03T09:45:33+01:00
New Revision: ab0bfbdaaa5189377a605e0584d9ba9b1fc49e75

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

LOG: [clang-format] Use get*StyleWithColumns helper. NFC.

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 374f3865acc3b..005fc4db9159b 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -2758,10 +2758,9 @@ TEST_F(FormatTest, FormatsLabels) {
 }
 
 TEST_F(FormatTest, MultiLineControlStatements) {
-  FormatStyle Style = getLLVMStyle();
+  FormatStyle Style = getLLVMStyleWithColumns(20);
   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
-  Style.ColumnLimit = 20;
   // Short lines should keep opening brace on same line.
   EXPECT_EQ("if (foo) {\n"
 "  bar();\n"
@@ -3328,8 +3327,7 @@ TEST_F(FormatTest, FormatsEnumTypes) {
 }
 
 TEST_F(FormatTest, FormatsTypedefEnum) {
-  FormatStyle Style = getLLVMStyle();
-  Style.ColumnLimit = 40;
+  FormatStyle Style = getLLVMStyleWithColumns(40);
   verifyFormat("typedef enum {} EmptyEnum;");
   verifyFormat("typedef enum { A, B, C } ShortEnum;");
   verifyFormat("typedef enum {\n"
@@ -4808,9 +4806,8 @@ TEST_F(FormatTest, 
LayoutMacroDefinitionsStatementsSpanningBlocks) {
 }
 
 TEST_F(FormatTest, IndentPreprocessorDirectives) {
-  FormatStyle Style = getLLVMStyle();
+  FormatStyle Style = getLLVMStyleWithColumns(40);
   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
-  Style.ColumnLimit = 40;
   verifyFormat("#ifdef _WIN32\n"
"#define A 0\n"
"#ifdef VAR2\n"
@@ -6000,10 +5997,9 @@ TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
 }
 
 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
-  FormatStyle Style = getLLVMStyle();
+  FormatStyle Style = getLLVMStyleWithColumns(40);
   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
   Style.BinPackArguments = false;
-  Style.ColumnLimit = 40;
   verifyFormat("void test() {\n"
"  someFunction(\n"
"  this + argument + is + quite\n"
@@ -6182,9 +6178,8 @@ TEST_F(FormatTest, ConstructorInitializers) {
 }
 
 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
-  FormatStyle Style = getLLVMStyle();
+  FormatStyle Style = getLLVMStyleWithColumns(60);
   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
-  Style.ColumnLimit = 60;
   Style.BinPackParameters = false;
 
   for (int i = 0; i < 4; ++i) {
@@ -6312,8 +6307,7 @@ TEST_F(FormatTest, 
AllowAllConstructorInitializersOnNextLine) {
 }
 
 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
-  FormatStyle Style = getLLVMStyle();
-  Style.ColumnLimit = 60;
+  FormatStyle Style = getLLVMStyleWithColumns(60);
   Style.BinPackArguments = false;
   for (int i = 0; i < 4; ++i) {
 // Test all combinations of parameters that should not have an effect.
@@ -6367,8 +6361,7 @@ TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
   // and BAS_Align.
-  auto Style = getLLVMStyle();
-  Style.ColumnLimit = 35;
+  FormatStyle Style = getLLVMStyleWithColumns(35);
   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
 "void functionDecl(int A, int B, int C);";
   Style.AllowAllArgumentsOnNextLine = false;
@@ -6869,8 +6862,7 @@ TEST_F(FormatTest, DeductionGuides) {
 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
   // Avoid breaking before trailing 'const' or other trailing annotations, if
   // they are not function-like.
-  FormatStyle Style = getGoogleStyle();
-  Style.ColumnLimit = 47;
+  FormatStyle Style = getGoogleStyleWithColumns(47);
   verifyFormat("void someLongFunction(\n"
"int someLoongParameter) const {\n}",
getLLVMStyleWithColumns(47));
@@ -7689,8 +7681,7 @@ TEST_F(FormatTest, BreaksConditionalExpressions) {
" : a;");
 
   // Chained conditionals
-  FormatStyle Style = getLLVMStyle();
-  Style.ColumnLimit = 70;
+  FormatStyle Style = getLLVMStyleWithColumns(70);
   Style.AlignOperands = FormatStyle::OAS_Align;
   verifyFormat("return  ? \n"
"   : bb ? \n"
@@ -7843,9 +7834,8 @@ TEST_F(FormatTest, BreaksConditionalExpressions) {
 }
 
 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
-  FormatStyle Style = getLLVMStyle();
+  FormatStyle Style

[PATCH] D116502: [clangd] Helper for determining member insertion point.

2022-01-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

We have some logic in AddUsing tweak to determine insertion point based on AST. 
i think it makes sense to migrate it to these helpers too. There's some more 
logic in extract variable/function too. Extract variable seems too elaborate as 
it actually looks at statements, rather than decls and extract function is 
quite simple already as we already figure out current function's range and 
whatnot, but having another usage might help.

(thinking out loud)
We've got some helpers in SourceCode.h to determine insertion point in the 
absence of ASTs. Concepts here and there around an "insertion point" seems to 
be quite different (it's just a sourcelocation here and a set of locations + a 
namespace in SourceCode.h).
I suppose those two are somewhat hard to merge and serve different purposes, so 
It's better to keep them separate.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116502

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


[PATCH] D116271: [Docs] Document C++ for OpenCL 2021 support in clang

2022-01-03 Thread Justas Janickas via Phabricator via cfe-commits
Topotuna accepted this revision.
Topotuna added a comment.
This revision is now accepted and ready to land.

LGTM!


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

https://reviews.llvm.org/D116271

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


[PATCH] D116502: [clangd] Helper for determining member insertion point.

2022-01-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/refactor/InsertionPoint.cpp:51
+} else {
+  assert(A.Direction == Anchor::Below);
+  if (LastMatched && !Matches)

nit: use a switch?



Comment at: clang-tools-extra/clangd/refactor/InsertionPoint.cpp:134
+  // Fallback: insert at the end of the class. Check if protection matches!
+  if (Loc.isInvalid()) {
+Loc = InClass.getBraceRange().getEnd();

what if we had:
```
class Foo {
public:
  void foo();
};
```

and wanted to insert a `private` member/field?
I suppose we should check for the specifier of last decl in `InClass` instead.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116502

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


[PATCH] D116527: [clang-format] Fix indentation for array variables with alignment of consecutive assignments and declarations.

2022-01-03 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius created this revision.
curdeius added reviewers: MyDeveloperDay, HazardyKnusperkeks, owenpan.
curdeius requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116527

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -15170,9 +15170,9 @@
"int   i  = 0;\n"
"float i2 = 0;\n"
"auto  v  = type{\n"
-   "i = 1,   //\n"
-   "(i = 2), //\n"
-   "i = 3//\n"
+   "  i = 1,   //\n"
+   "  (i = 2), //\n"
+   "  i = 3//\n"
"};",
Style);
 
@@ -16402,6 +16402,11 @@
"  doublebar();\n"
"};\n",
Alignment);
+  // http://llvm.org/PR52914
+  verifyFormat("char *a[] = {\"a\", // comment\n"
+   " \"bb\"};\n"
+   "int   bbb = 0;",
+   Alignment);
 
   // PAS_Right
   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
@@ -16660,9 +16665,9 @@
"int   i  = 0;\n"
"float i2 = 0;\n"
"auto  v  = type{\n"
-   "i = 1,   //\n"
-   "(i = 2), //\n"
-   "i = 3//\n"
+   "  i = 1,   //\n"
+   "  (i = 2), //\n"
+   "  i = 3//\n"
"};",
Alignment);
   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -362,6 +362,11 @@
 Changes[i].Tok->Previous->is(TT_ConditionalExpr))
   return true;
 
+// Continued braced list.
+if (Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
+Changes[i].Tok->isNot(tok::r_brace))
+  return true;
+
 return false;
   };
 


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -15170,9 +15170,9 @@
"int   i  = 0;\n"
"float i2 = 0;\n"
"auto  v  = type{\n"
-   "i = 1,   //\n"
-   "(i = 2), //\n"
-   "i = 3//\n"
+   "  i = 1,   //\n"
+   "  (i = 2), //\n"
+   "  i = 3//\n"
"};",
Style);
 
@@ -16402,6 +16402,11 @@
"  doublebar();\n"
"};\n",
Alignment);
+  // http://llvm.org/PR52914
+  verifyFormat("char *a[] = {\"a\", // comment\n"
+   " \"bb\"};\n"
+   "int   bbb = 0;",
+   Alignment);
 
   // PAS_Right
   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
@@ -16660,9 +16665,9 @@
"int   i  = 0;\n"
"float i2 = 0;\n"
"auto  v  = type{\n"
-   "i = 1,   //\n"
-   "(i = 2), //\n"
-   "i = 3//\n"
+   "  i = 1,   //\n"
+   "  (i = 2), //\n"
+   "  i = 3//\n"
"};",
Alignment);
   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -362,6 +362,11 @@
 Changes[i].Tok->Previous->is(TT_ConditionalExpr))
   return true;
 
+// Continued braced list.
+if (Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
+Changes[i].Tok->isNot(tok::r_brace))
+  return true;
+
 return false;
   };
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116478: [clang-tidy] A comma-separated list of the names of functions or methods to be considered as not having side-effects

2022-01-03 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added inline comments.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:141
 ^^
+- Added a setting ``bugprone-assert-side-effect.FunctionExceptions`` for
+  a comma-separated list of the names of functions or methods to be considered

carlosgalvezp wrote:
> Eugene.Zelenko wrote:
> > carlosgalvezp wrote:
> > > Eugene.Zelenko wrote:
> > > > Please separate with newline and use single back-ticks for options.
> > > I introduced those double backticks due to review comments. As it turns 
> > > out, single backticks are only for links, not for formatted text. Should 
> > > they be brought back?
> > Double back-ticks are for language constructs, single back-ticks for 
> > options, tool names, etc.
> Hm, I see. I think visually it's much more helpful to have options rendered 
> as formatted code (just like you'd see them in the .clang-tidy file in a code 
> editor) instead of in italic, which is what is rendered with single backticks.
Also note that the main clang-tidy doc page uses doble backticks for options, 
not just language constructs, so I think it would be good to keep consistency 
with that:

https://raw.githubusercontent.com/llvm/llvm-project/main/clang-tools-extra/docs/clang-tidy/index.rst

Single backticks are used there only for links and together with the 
`:program:` keyword.


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

https://reviews.llvm.org/D116478

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


[PATCH] D116527: [clang-format] Fix indentation for array variables with alignment of consecutive assignments and declarations.

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

I know I changed existing tests. I'm not sure what we really want here.
If you have ideas, I'm open to suggestions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116527

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


[PATCH] D116478: [clang-tidy] A comma-separated list of the names of functions or methods to be considered as not having side-effects

2022-01-03 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added inline comments.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:141
 ^^
+- Added a setting ``bugprone-assert-side-effect.FunctionExceptions`` for
+  a comma-separated list of the names of functions or methods to be considered

carlosgalvezp wrote:
> carlosgalvezp wrote:
> > Eugene.Zelenko wrote:
> > > carlosgalvezp wrote:
> > > > Eugene.Zelenko wrote:
> > > > > Please separate with newline and use single back-ticks for options.
> > > > I introduced those double backticks due to review comments. As it turns 
> > > > out, single backticks are only for links, not for formatted text. 
> > > > Should they be brought back?
> > > Double back-ticks are for language constructs, single back-ticks for 
> > > options, tool names, etc.
> > Hm, I see. I think visually it's much more helpful to have options rendered 
> > as formatted code (just like you'd see them in the .clang-tidy file in a 
> > code editor) instead of in italic, which is what is rendered with single 
> > backticks.
> Also note that the main clang-tidy doc page uses doble backticks for options, 
> not just language constructs, so I think it would be good to keep consistency 
> with that:
> 
> https://raw.githubusercontent.com/llvm/llvm-project/main/clang-tools-extra/docs/clang-tidy/index.rst
> 
> Single backticks are used there only for links and together with the 
> `:program:` keyword.
Unless there's some documented style convention that says otherwise, of course. 
I haven't found anything in the [[ https://llvm.org/docs/CodingStandards.html | 
LLVM Coding Standards ]].


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

https://reviews.llvm.org/D116478

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


[PATCH] D116218: [clangd] Fix selection on multi-dimensional array.

2022-01-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/Selection.cpp:526
+  // the traversal order of SizeExpr and ElementTypeLoc, which gives a chance
+  // for the SizeExpr to claim its tokens.
+  bool TraverseConstantArrayTypeLoc(ConstantArrayTypeLoc X) {

sammccall wrote:
> I don't think this is a complete solution: won't the inner ArrayTypeLoc still 
> end up owning both sets of brackets?
> 
> I think maybe a better solution is making getSourceRange(ArrayTypeLoc) return 
> only ATL.getBracketRange(), and then modify canSafelySkipNode to to avoid 
> pruning based on this small range.
> 
> This is vaguely similar to how DeclTypeLoc works today (though in that case 
> the reduced range is the one reported by the AST).
> won't the inner ArrayTypeLoc still end up owning both sets of brackets?

yes, unfortunately, the inner ATL still owns both sets of brackets, that means 
go-to-def (etc) won't work on an overloaded subscript operator [], I don't have 
a better solution to fix that. I guess it is ok to live with that as it might 
be a rare case in practice.

> I think maybe a better solution is making getSourceRange(ArrayTypeLoc) return 
> only ATL.getBracketRange(), and then modify canSafelySkipNode to to avoid 
> pruning based on this small range.

yeah, indeed I tried this approach before coming up the current approach, and I 
didn't find a satisfied solution (BracketRange is not enough, otherwise we will 
lose the array type `int`). 


```
 // int array[Size][100];
 // ~~~  [-2 -]~  ConstantArrayTypeLoc int[Size][100]
 // [1][-3-]  |-ConstantArrayTypeLoc int[100]

```
Ideally, the inner ATL should own tokens `int` ([1]) and tokens `[100]` ([3]). 
And in the `canSafelySkipNode`, we want to skip the inner ATL if the cursor is 
in the source range of ` array[Size]`, it seems quite tricky to get the source 
range (the range of `int` [1] in particular). Of course we could use some lexer 
hacks or call `ATL.getElementLoc()` recursively until we hit a non-array type 
loc (it can easily go up to  O(n^2) for super-multi-dimensional arrays).





Comment at: clang-tools-extra/clangd/Selection.cpp:527
+  // for the SizeExpr to claim its tokens.
+  bool TraverseConstantArrayTypeLoc(ConstantArrayTypeLoc X) {
+if (!Base::TraverseStmt(X.getSizeExpr()))

sammccall wrote:
> ConstantArrayType isn't the only kind of array, see the other subclasses of 
> ArrayType
oh, right. There are three others, we could do similar for them. Will do that 
if we agree on the current approach. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116218

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


[PATCH] D116352: [CodeCompletion] Signature help for template argument lists

2022-01-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

thanks this looks great! just a question around rendering of the result type 
chunk. feel free to leave a fixme if there's no easy way of doing that.




Comment at: clang/lib/Parse/ParseTemplate.cpp:1237
+///
+/// \param NameHint is not required, and merely affects code completion.
+bool Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,

`s/NameHint/Template` ?



Comment at: clang/lib/Sema/SemaCodeComplete.cpp:3785
+  if (const auto *FTD = dyn_cast(TD))
+return FTD->getTemplatedDecl()->getType().getAsString(Policy);
+  if (isa(TD))

the rendering looks a little bit surprising to me `foo -> bool 
(float)` we might consider printing parameters first, e.g. 
`foo(float) -> bool`. i think this also looks more natural for the 
following signature help on function parameters.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116352

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


[PATCH] D115355: Fix build failure with GCC 11 in C++20 mode

2022-01-03 Thread Evgeny Mandrikov via Phabricator via cfe-commits
Godin added a comment.

ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115355

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


[clang] 0090cd4 - [clang-format] Support inheriting from more than 1 parents in the fallback case

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

Author: Zhao Wei Liew
Date: 2022-01-03T11:36:00+01:00
New Revision: 0090cd4e7a24bedeb24dfe5b3b55167ad74e231e

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

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

Currently, we are unable to inherit from a chain of parent configs where the 
outermost parent config has `BasedOnStyle: InheritParentConfig` set. This patch 
adds a test case for this scenario, and adds support for it.

To illustrate, suppose we have the following directory structure:
```
- e/
  |- .clang-format (BasedOnStyle: InheritParentConfig) <-- outermost config
  |- sub/
|- .clang-format (BasedOnStyle: InheritParentConfig)
|- sub/
  |- .clang-format (BasedOnStyle: InheritParentConfig)
  |- code.cpp
```
Now consider what happens when we run `clang-format --style=file 
/e/sub/sub/code.cpp`.

Without this patch, on a release build, only the innermost config will be 
applied. On a debug build, clang-format crashes due to an assertion failure.
With this patch, clang-format behaves as we'd expect, applying all 3 configs.

Reviewed By: HazardyKnusperkeks, curdeius

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index be01daa38929d..f3c337a928228 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3288,6 +3288,16 @@ llvm::Expected getStyle(StringRef 
StyleName, StringRef FileName,
 
   auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
 
+  auto applyChildFormatTexts = [&](FormatStyle *Style) {
+for (const auto &MemBuf : 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)) {
 
@@ -3330,14 +3340,7 @@ llvm::Expected getStyle(StringRef 
StyleName, StringRef FileName,
 return Style;
 
   LLVM_DEBUG(llvm::dbgs() << "Applying child configurations\n");
-
-  for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
-auto Ec = parseConfiguration(*MemBuf, &Style, AllowUnknownOptions,
- dropDiagnosticHandler);
-// It was already correctly parsed.
-assert(!Ec);
-static_cast(Ec);
-  }
+  applyChildFormatTexts(&Style);
 
   return Style;
 }
@@ -3363,17 +3366,9 @@ llvm::Expected getStyle(StringRef 
StyleName, StringRef FileName,
  UnsuitableConfigFiles);
 
   if (!ChildFormatTextToApply.empty()) {
-assert(ChildFormatTextToApply.size() == 1);
-
 LLVM_DEBUG(llvm::dbgs()
-   << "Applying child configuration on fallback style\n");
-
-auto Ec =
-parseConfiguration(*ChildFormatTextToApply.front(), &FallbackStyle,
-   AllowUnknownOptions, dropDiagnosticHandler);
-// It was already correctly parsed.
-assert(!Ec);
-static_cast(Ec);
+   << "Applying child configurations on fallback style\n");
+applyChildFormatTexts(&FallbackStyle);
   }
 
   return FallbackStyle;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 005fc4db9159b..bb344d4383ea6 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -21464,8 +21464,8 @@ TEST(FormatStyle, GetStyleOfFile) {
   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"
@@ -21480,6 +21480,25 @@ TEST(FormatStyle, GetStyleOfFile) {
 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::

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

2022-01-03 Thread Marek Kurdej via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0090cd4e7a24: [clang-format] Support inheriting from more 
than 1 parents in the fallback case (authored by zwliew, committed by curdeius).

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
@@ -21464,8 +21464,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"
@@ -21480,6 +21480,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", "", &FS);
+  ASSERT_TRUE(static_cast(Style9));
+  ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
+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", "", &FS);
   ASSERT_TRUE(static_cast(Style9));
@@ -21503,15 +21522,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 = [&NonDefaultWhiteSpaceMacros] {
 auto Style = getGoogleStyle();
 Style.ColumnLimit = 20;
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -3288,6 +3288,16 @@
 
   auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
 
+  auto applyChildFormatTexts = [&](FormatStyle *Style) {
+for (const auto &MemBuf : 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)) {
 
@@ -3330,14 +3340,7 @@
 return Style;
 
   LLVM_DEBUG(llvm::dbgs() << "Applying child configurations\n");
-
-  for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
-auto Ec = parseConfiguration(*MemBuf, &Style, AllowUnknownOptions,
- dropDiagnosticHandler);
-// It was already correctly parsed.
-assert(!Ec);
-static_cast(Ec);
-  }
+  applyChildFormatTexts(&Style);
 
   return Style;
 }
@@ -3363,17 +3366,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(), &FallbackStyle,
-   AllowUnknownOptions, dropDiagnosticHandler);
-// It was already correctly parsed.
-assert(!Ec);
-static_cast(Ec);
+   << "Applying child configurations on fallback style\n");
+applyChildFormatTexts(&FallbackStyle);
   }
 
   return FallbackStyle;

[clang] b9e173f - [clang-format] Add option to explicitly specify a config file

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

Author: Zhao Wei Liew
Date: 2022-01-03T11:43:25+01:00
New Revision: b9e173fcd46b336b5589f577a74de9472d4deae3

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

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

This diff extends the -style=file option to allow a config file to be specified 
explicitly. This is useful (for instance) when adding IDE commands to reformat 
code to a personal style.

Usage: `clang-format -style=file: ...`

Reviewed By: HazardyKnusperkeks, curdeius, MyDeveloperDay, zwliew

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

Added: 


Modified: 
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

Removed: 




diff  --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index 4a1422e85b06c..8c0273c8eb3c3 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -82,6 +82,10 @@ to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# 
code.
  .clang-format file located in one of the 
parent
  directories of the source file (or current
  directory for stdin).
+ Use -style=file: to load 
style
+ configuration from a format file located at
+ . This path can be absolute 
or
+ relative to the working directory.
  Use -style="{key: value, ...}" to set specific
  parameters, e.g.:
-style="{BasedOnStyle: llvm, IndentWidth: 
8}"

diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index c2f85d564ba96..07c77acb84810 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -32,6 +32,10 @@ try to find the ``.clang-format`` file located in the 
closest parent directory
 of the input file. When the standard input is used, the search is started from
 the current directory.
 
+When using ``-style=file:``, :program:`clang-format` for
+each input file will use the format file located at ``.
+The path may be absolute or relative to the working directory.
+
 The ``.clang-format`` file uses YAML format:
 
 .. code-block:: yaml

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ce9b3547155af..20e7e6cc26ce9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -301,6 +301,10 @@ clang-format
   space before parentheses. The custom options can be set using
   ``SpaceBeforeParensOptions``.
 
+- The command line argument `-style=` has been extended so that a 
specific
+  format file at location  can be selected. This is supported
+  via the syntax: `-style=file:`.
+
 - Improved C++20 Modules and Coroutines support.
 
 libclang

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index f6b4926de846b..dbc406417ba19 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -4066,6 +4066,8 @@ extern const char *DefaultFallbackStyle;
 /// * "file" - Load style configuration from a file called ``.clang-format``
 /// located in one of the parent directories of ``FileName`` or the current
 /// directory if ``FileName`` is empty.
+/// * "file:" to explicitly specify the configuration file to
+/// use.
 ///
 /// \param[in] StyleName Style name to interpret according to the description
 /// above.

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index f3c337a928228..0ae9fa60d3376 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3181,6 +3181,8 @@ const char *StyleOptionHelpDescription =
 ".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 *DefaultFormatStyle = "file";
 
 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, AllowUnknownOptio

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

2022-01-03 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/docs/ClangFormatStyleOptions.rst:3760
+   true:  false:
+   void operator++ (int a);vs.void operator++(int a);
+

Please add operator call as well to the example (`object.operator++ (0)`).


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] D116170: [clang-format] Add penalty for breaking after '('

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

@GPery, do you need help landing this?
If so, please indicate the name and email you'd like to be used for the commit.


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


[clang] 694e6bc - [clang-format][NFC] Correct comment about checking merging of blocks

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

Author: Gabriel Smith
Date: 2022-01-03T11:51:13+01:00
New Revision: 694e6bcd525f9ceae6f377faa43115e22e839244

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

LOG: [clang-format][NFC] Correct comment about checking merging of blocks

Reviewed By: HazardyKnusperkeks, MyDeveloperDay, owenpan

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineFormatter.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index f652a4e7088f..89f87f0375cd 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -391,7 +391,7 @@ class LineJoiner {
   }
 }
 
-// Try to merge a block with left brace wrapped that wasn't yet covered
+// Try to merge a block with left brace unwrapped that wasn't yet covered
 if (TheLine->Last->is(tok::l_brace)) {
   const FormatToken *Tok = TheLine->First;
   bool ShouldMerge = false;



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


[PATCH] D116189: [clang-format][NFC] Correct comment about checking merging of blocks

2022-01-03 Thread Marek Kurdej via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG694e6bcd525f: [clang-format][NFC] Correct comment about 
checking merging of blocks (authored by yodaldevoid, committed by curdeius).

Changed prior to commit:
  https://reviews.llvm.org/D116189?vs=396064&id=397028#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116189

Files:
  clang/lib/Format/UnwrappedLineFormatter.cpp


Index: clang/lib/Format/UnwrappedLineFormatter.cpp
===
--- clang/lib/Format/UnwrappedLineFormatter.cpp
+++ clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -391,7 +391,7 @@
   }
 }
 
-// Try to merge a block with left brace wrapped that wasn't yet covered
+// Try to merge a block with left brace unwrapped that wasn't yet covered
 if (TheLine->Last->is(tok::l_brace)) {
   const FormatToken *Tok = TheLine->First;
   bool ShouldMerge = false;


Index: clang/lib/Format/UnwrappedLineFormatter.cpp
===
--- clang/lib/Format/UnwrappedLineFormatter.cpp
+++ clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -391,7 +391,7 @@
   }
 }
 
-// Try to merge a block with left brace wrapped that wasn't yet covered
+// Try to merge a block with left brace unwrapped that wasn't yet covered
 if (TheLine->Last->is(tok::l_brace)) {
   const FormatToken *Tok = TheLine->First;
   bool ShouldMerge = false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D106349: [clang-format] respect AfterEnum for enums

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

LGTM. If nobody objects, I'll land this today.


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

https://reviews.llvm.org/D106349

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


[PATCH] D116527: [clang-format] Fix indentation for array variables with alignment of consecutive assignments and declarations.

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

The fix looks ok, butr I don't understand the cause of the side effect? is it 
explicitly aligning to the v of `auto v`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116527

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


[PATCH] D106349: [clang-format] respect AfterEnum for enums

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

no objection from me, we need to clean up the non landed accepted reviews or it 
wastes our time in the first place.


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

https://reviews.llvm.org/D106349

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


[clang] cd2b050 - [clang-format] spacesRequiredBetween is not honouring clang-format off/on

2022-01-03 Thread via cfe-commits

Author: mydeveloperday
Date: 2022-01-03T11:19:02Z
New Revision: cd2b050fa4995b75b9c36fae16c0d9f105b67585

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

LOG: [clang-format] spacesRequiredBetween is not honouring clang-format off/on

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

It seems that clang-format off/on is not being honoured in regard to adding 
spaces.

My understanding of clang-format off/on is that it marks the token as finalized 
based on whether formatting is currently enabled or disabled.

This was causing a space to be added between the `<` and `<<`  in the Cuda 
kernel `foo<<<1, 1>>>();`

This if doesn't solve this actual issue but ensure that clang-format is at 
least honoured.

Reviewed By: curdeius, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 505a7250572b..914997a54989 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3294,6 +3294,11 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
   };
 
+  // If the token is finalized don't touch it (as it could be in a
+  // clang-format-off section).
+  if (Left.Finalized)
+return HasExistingWhitespace();
+
   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
 return true; // Never ever merge two identifiers.
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 7160c7a90073..7a7976c8b081 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -21156,6 +21156,16 @@ TEST_F(FormatTest, SpacesInAngles) {
   verifyFormat("A< A< int > >();", Spaces);
   verifyFormat("A >();", Spaces);
   verifyFormat("A< A< int>>();", Spaces);
+
+  Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
+  verifyFormat("// clang-format off\n"
+   "foo<<<1, 1>>>();\n"
+   "// clang-format on\n",
+   Spaces);
+  verifyFormat("// clang-format off\n"
+   "foo< < <1, 1> > >();\n"
+   "// clang-format on\n",
+   Spaces);
 }
 
 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {



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


[PATCH] D116494: [clang-format] spacesRequiredBetween is not honouring clang-format off/on

2022-01-03 Thread MyDeveloperDay 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 rGcd2b050fa499: [clang-format] spacesRequiredBetween is not 
honouring clang-format off/on (authored by MyDeveloperDay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116494

Files:
  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
@@ -21156,6 +21156,16 @@
   verifyFormat("A< A< int > >();", Spaces);
   verifyFormat("A >();", Spaces);
   verifyFormat("A< A< int>>();", Spaces);
+
+  Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
+  verifyFormat("// clang-format off\n"
+   "foo<<<1, 1>>>();\n"
+   "// clang-format on\n",
+   Spaces);
+  verifyFormat("// clang-format off\n"
+   "foo< < <1, 1> > >();\n"
+   "// clang-format on\n",
+   Spaces);
 }
 
 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3294,6 +3294,11 @@
 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
   };
 
+  // If the token is finalized don't touch it (as it could be in a
+  // clang-format-off section).
+  if (Left.Finalized)
+return HasExistingWhitespace();
+
   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
 return true; // Never ever merge two identifiers.
 


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -21156,6 +21156,16 @@
   verifyFormat("A< A< int > >();", Spaces);
   verifyFormat("A >();", Spaces);
   verifyFormat("A< A< int>>();", Spaces);
+
+  Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
+  verifyFormat("// clang-format off\n"
+   "foo<<<1, 1>>>();\n"
+   "// clang-format on\n",
+   Spaces);
+  verifyFormat("// clang-format off\n"
+   "foo< < <1, 1> > >();\n"
+   "// clang-format on\n",
+   Spaces);
 }
 
 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3294,6 +3294,11 @@
 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
   };
 
+  // If the token is finalized don't touch it (as it could be in a
+  // clang-format-off section).
+  if (Left.Finalized)
+return HasExistingWhitespace();
+
   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
 return true; // Never ever merge two identifiers.
 
___
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

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

LGTM.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/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] D116502: [clangd] Helper for determining member insertion point.

2022-01-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 397037.
sammccall added a comment.

Fix access protection bug, add more tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116502

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/refactor/InsertionPoint.cpp
  clang-tools-extra/clangd/refactor/InsertionPoint.h
  clang-tools-extra/clangd/unittests/CMakeLists.txt
  clang-tools-extra/clangd/unittests/InsertionPointTests.cpp

Index: clang-tools-extra/clangd/unittests/InsertionPointTests.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/unittests/InsertionPointTests.cpp
@@ -0,0 +1,210 @@
+//===-- InsertionPointTess.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 "Annotations.h"
+#include "Protocol.h"
+#include "SourceCode.h"
+#include "TestTU.h"
+#include "TestWorkspace.h"
+#include "XRefs.h"
+#include "refactor/InsertionPoint.h"
+#include "clang/AST/DeclBase.h"
+#include "llvm/Testing/Support/Error.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+using llvm::HasValue;
+
+TEST(InsertionPointTests, Generic) {
+  Annotations Code(R"cpp(
+  namespace ns {
+$a^int a1;
+$b^// leading comment
+int b;
+$c^int c1; // trailing comment
+int c2;
+$a2^int a2;
+  $end^};
+  )cpp");
+
+  auto StartsWith =
+  [&](llvm::StringLiteral S) -> std::function {
+return [S](const Decl *D) {
+  if (const auto *ND = llvm::dyn_cast(D))
+return llvm::StringRef(ND->getNameAsString()).startswith(S);
+  return false;
+};
+  };
+
+  auto AST = TestTU::withCode(Code.code()).build();
+  auto &NS = cast(findDecl(AST, "ns"));
+
+  // Test single anchors.
+  auto Point = [&](llvm::StringLiteral Prefix, Anchor::Dir Direction) {
+auto Loc = insertionPoint(NS, {Anchor{StartsWith(Prefix), Direction}});
+return sourceLocToPosition(AST.getSourceManager(), Loc);
+  };
+  EXPECT_EQ(Point("a", Anchor::Above), Code.point("a"));
+  EXPECT_EQ(Point("a", Anchor::Below), Code.point("b"));
+  EXPECT_EQ(Point("b", Anchor::Above), Code.point("b"));
+  EXPECT_EQ(Point("b", Anchor::Below), Code.point("c"));
+  EXPECT_EQ(Point("c", Anchor::Above), Code.point("c"));
+  EXPECT_EQ(Point("c", Anchor::Below), Code.point("a2"));
+  EXPECT_EQ(Point("", Anchor::Above), Code.point("a"));
+  EXPECT_EQ(Point("", Anchor::Below), Code.point("end"));
+  EXPECT_EQ(Point("no_match", Anchor::Below), Position{});
+
+  // Test anchor chaining.
+  auto Chain = [&](llvm::StringLiteral P1, llvm::StringLiteral P2) {
+auto Loc = insertionPoint(NS, {Anchor{StartsWith(P1), Anchor::Above},
+   Anchor{StartsWith(P2), Anchor::Above}});
+return sourceLocToPosition(AST.getSourceManager(), Loc);
+  };
+  EXPECT_EQ(Chain("a", "b"), Code.point("a"));
+  EXPECT_EQ(Chain("b", "a"), Code.point("b"));
+  EXPECT_EQ(Chain("no_match", "a"), Code.point("a"));
+
+  // Test edit generation.
+  auto Edit = insertDecl("foo;", NS, {Anchor{StartsWith("a"), Anchor::Below}});
+  ASSERT_THAT_EXPECTED(Edit, llvm::Succeeded());
+  EXPECT_EQ(offsetToPosition(Code.code(), Edit->getOffset()), Code.point("b"));
+  EXPECT_EQ(Edit->getReplacementText(), "foo;");
+  // If no match, the edit is inserted at the end.
+  Edit = insertDecl("x;", NS, {Anchor{StartsWith("no_match"), Anchor::Below}});
+  ASSERT_THAT_EXPECTED(Edit, llvm::Succeeded());
+  EXPECT_EQ(offsetToPosition(Code.code(), Edit->getOffset()),
+Code.point("end"));
+}
+
+// For CXX, we should check:
+// - special handling for access specifiers
+// - unwrapping of template decls
+TEST(InsertionPointTests, CXX) {
+  Annotations Code(R"cpp(
+class C {
+public:
+  $Method^void pubMethod();
+  $Field^int PubField;
+
+$private^private:
+  $field^int PrivField;
+  $method^void privMethod();
+  template  void privTemplateMethod();
+$end^};
+  )cpp");
+
+  auto AST = TestTU::withCode(Code.code()).build();
+  const CXXRecordDecl &C = cast(findDecl(AST, "C"));
+
+  auto IsMethod = [](const Decl *D) { return llvm::isa(D); };
+  auto Any = [](const Decl *D) { return true; };
+
+  // Test single anchors.
+  auto Point = [&](Anchor A, AccessSpecifier Protection) {
+auto Loc = insertionPoint(C, {A}, Protection);
+return sourceLocToPosition(AST.getSourceManager(), Loc);
+  };
+  EXPECT_EQ(Point({IsMethod, Anchor::Above}, AS_public), Code.point("Method"));
+  EXPECT_EQ(Point({IsMethod, Anchor::Below}, AS_public), Code.point("Field"));
+  EXPECT_EQ(Point({Any, Anchor::Above}, AS_public), Code.point

[PATCH] D116502: [clangd] Helper for determining member insertion point.

2022-01-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 2 inline comments as done.
sammccall added a comment.

In D116502#3217084 , @kadircet wrote:

> We have some logic in AddUsing tweak to determine insertion point based on 
> AST. i think it makes sense to migrate it to these helpers too.

Thanks, I'd forgotten about those. I might tackle those next?

> There's some more logic in extract variable/function too. Extract variable 
> seems too elaborate as it actually looks at statements, rather than decls and 
> extract function is quite simple already as we already figure out current 
> function's range and whatnot, but having another usage might help.

Yeah I wasn't sure I could do a good job of generalizing these ones yet (and we 
haven't needed it yet).

> We've got some helpers in SourceCode.h to determine insertion point in the 
> absence of ASTs. Concepts here and there around an "insertion point" seems to 
> be quite different (it's just a sourcelocation here and a set of locations + 
> a namespace in SourceCode.h).
> I suppose those two are somewhat hard to merge and serve different purposes, 
> so It's better to keep them separate.

For sure ast-based and pseudoparsing-based cases are going to be different 
APIs, but I would like to move those into this header too.
The problem I hit was they share private infrastructure (in SourceCode.cpp) 
with other functionality (the namespace pseudoparsing for completion, I think). 
So it's a bit of work to extract.




Comment at: clang-tools-extra/clangd/refactor/InsertionPoint.cpp:134
+  // Fallback: insert at the end of the class. Check if protection matches!
+  if (Loc.isInvalid()) {
+Loc = InClass.getBraceRange().getEnd();

kadircet wrote:
> what if we had:
> ```
> class Foo {
> public:
>   void foo();
> };
> ```
> 
> and wanted to insert a `private` member/field?
> I suppose we should check for the specifier of last decl in `InClass` instead.
Oops, good catch.

In that particular case, you could make a case for inserting at the very top of 
the class (no access specifier needed). But some coding styles want the 
opposite.
I think using the presence/absence of decls in the chunk before the first 
access specifier is a reasonable hint, and it happens to be the easiest thing 
to implement :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116502

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


[PATCH] D100810: [llvm] Use `GNUInstallDirs` to support custom installation dirs

2022-01-03 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 updated this revision to Diff 396972.
Ericson2314 added a comment.

Remove off topic bits


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D100810

Files:
  llvm/CMakeLists.txt
  llvm/cmake/modules/AddLLVM.cmake
  llvm/cmake/modules/AddSphinxTarget.cmake
  llvm/cmake/modules/CMakeLists.txt
  llvm/cmake/modules/LLVMInstallSymlink.cmake
  llvm/docs/CMake.rst
  llvm/examples/Bye/CMakeLists.txt
  llvm/tools/llvm-config/BuildVariables.inc.in
  llvm/tools/llvm-config/llvm-config.cpp
  llvm/tools/lto/CMakeLists.txt
  llvm/tools/opt-viewer/CMakeLists.txt
  llvm/tools/remarks-shlib/CMakeLists.txt

Index: llvm/tools/remarks-shlib/CMakeLists.txt
===
--- llvm/tools/remarks-shlib/CMakeLists.txt
+++ llvm/tools/remarks-shlib/CMakeLists.txt
@@ -19,7 +19,7 @@
   endif()
   
   install(FILES ${LLVM_MAIN_INCLUDE_DIR}/llvm-c/Remarks.h
-DESTINATION include/llvm-c
+DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/llvm-c"
 COMPONENT Remarks)
 
   if (APPLE)
Index: llvm/tools/opt-viewer/CMakeLists.txt
===
--- llvm/tools/opt-viewer/CMakeLists.txt
+++ llvm/tools/opt-viewer/CMakeLists.txt
@@ -8,7 +8,7 @@
 
 foreach (file ${files})
   install(PROGRAMS ${file}
-DESTINATION share/opt-viewer
+DESTINATION "${CMAKE_INSTALL_DATADIR}/opt-viewer"
 COMPONENT opt-viewer)
 endforeach (file)
 
Index: llvm/tools/lto/CMakeLists.txt
===
--- llvm/tools/lto/CMakeLists.txt
+++ llvm/tools/lto/CMakeLists.txt
@@ -33,7 +33,7 @@
 ${SOURCES} DEPENDS intrinsics_gen)
 
 install(FILES ${LLVM_MAIN_INCLUDE_DIR}/llvm-c/lto.h
-  DESTINATION include/llvm-c
+  DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/llvm-c"
   COMPONENT LTO)
 
 if (APPLE)
Index: llvm/tools/llvm-config/llvm-config.cpp
===
--- llvm/tools/llvm-config/llvm-config.cpp
+++ llvm/tools/llvm-config/llvm-config.cpp
@@ -357,10 +357,16 @@
 ("-I" + ActiveIncludeDir + " " + "-I" + ActiveObjRoot + "/include");
   } else {
 ActivePrefix = CurrentExecPrefix;
-ActiveIncludeDir = ActivePrefix + "/include";
-SmallString<256> path(LLVM_TOOLS_INSTALL_DIR);
-sys::fs::make_absolute(ActivePrefix, path);
-ActiveBinDir = std::string(path.str());
+{
+  SmallString<256> Path(LLVM_INSTALL_INCLUDEDIR);
+  sys::fs::make_absolute(ActivePrefix, Path);
+  ActiveIncludeDir = std::string(Path.str());
+}
+{
+  SmallString<256> Path(LLVM_TOOLS_INSTALL_DIR);
+  sys::fs::make_absolute(ActivePrefix, Path);
+  ActiveBinDir = std::string(Path.str());
+}
 ActiveLibDir = ActivePrefix + "/lib" + LLVM_LIBDIR_SUFFIX;
 ActiveCMakeDir = ActiveLibDir + "/cmake/llvm";
 ActiveIncludeOption = "-I" + ActiveIncludeDir;
Index: llvm/tools/llvm-config/BuildVariables.inc.in
===
--- llvm/tools/llvm-config/BuildVariables.inc.in
+++ llvm/tools/llvm-config/BuildVariables.inc.in
@@ -23,6 +23,7 @@
 #define LLVM_CXXFLAGS "@LLVM_CXXFLAGS@"
 #define LLVM_BUILDMODE "@LLVM_BUILDMODE@"
 #define LLVM_LIBDIR_SUFFIX "@LLVM_LIBDIR_SUFFIX@"
+#define LLVM_INSTALL_INCLUDEDIR "@CMAKE_INSTALL_INCLUDEDIR@"
 #define LLVM_TARGETS_BUILT "@LLVM_TARGETS_BUILT@"
 #define LLVM_SYSTEM_LIBS "@LLVM_SYSTEM_LIBS@"
 #define LLVM_BUILD_SYSTEM "@LLVM_BUILD_SYSTEM@"
Index: llvm/examples/Bye/CMakeLists.txt
===
--- llvm/examples/Bye/CMakeLists.txt
+++ llvm/examples/Bye/CMakeLists.txt
@@ -14,6 +14,6 @@
 BUILDTREE_ONLY
)
 
-  install(TARGETS ${name} RUNTIME DESTINATION examples)
+  install(TARGETS ${name} RUNTIME DESTINATION "${LLVM_EXAMPLES_INSTALL_DIR}")
   set_target_properties(${name} PROPERTIES FOLDER "Examples")
 endif()
Index: llvm/docs/CMake.rst
===
--- llvm/docs/CMake.rst
+++ llvm/docs/CMake.rst
@@ -252,6 +252,22 @@
   Sets the C++ standard to conform to when building LLVM.  Possible values are
   14, 17, 20.  LLVM Requires C++ 14 or higher.  This defaults to 14.
 
+**CMAKE_INSTALL_BINDIR**:PATH
+  The path to install executables, relative to the *CMAKE_INSTALL_PREFIX*.
+  Defaults to "bin".
+
+**CMAKE_INSTALL_INCLUDEDIR**:PATH
+  The path to install header files, relative to the *CMAKE_INSTALL_PREFIX*.
+  Defaults to "include".
+
+**CMAKE_INSTALL_DOCDIR**:PATH
+  The path to install documentation, relative to the *CMAKE_INSTALL_PREFIX*.
+  Defaults to "share/doc".
+
+**CMAKE_INSTALL_MANDIR**:PATH
+  The path to install manpage files, relative to the *CMAKE_INSTALL_PREFIX*.
+  Defaults to "share/man".
+
 .. _LLVM-related variables:
 
 LLVM-related variables
@@ -598,12 +614,12 @@
 **LLVM_INSTALL_OCAMLDOC_HTML_DIR**:STRING
   The path to install OCamldo

[PATCH] D100810: [llvm] Use `GNUInstallDirs` to support custom installation dirs

2022-01-03 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 marked 4 inline comments as done.
Ericson2314 added inline comments.



Comment at: llvm/CMakeLists.txt:75
 set(LLVM_ENABLE_PROJECTS "" CACHE STRING
-   "Semicolon-separated list of projects to build 
(${LLVM_KNOWN_PROJECTS}), or \"all\".")
+   "Semicolon-separated list of projects to build (${LLVM_KNOWN_PROJECTS}), or 
\"all\".")
 foreach(proj ${LLVM_ENABLE_PROJECTS})

mstorsjo wrote:
> Nit: This looks like a spurious unrelated change to whitespace?
Doing in D116510 instead.



Comment at: llvm/CMakeLists.txt:164
   set(LLVM_CCACHE_MAXSIZE "" CACHE STRING "Size of ccache")
-  set(LLVM_CCACHE_DIR "" CACHE STRING "Directory to keep ccached data")
+  set(LLVM_CCACHE_DIR "" CACHE PATH "Directory to keep ccached data")
   set(LLVM_CCACHE_PARAMS "CCACHE_CPP2=yes CCACHE_HASHDIR=yes"

mstorsjo wrote:
> Could this bit be split out to separate change, to keep this as small as 
> possible - unless it's strictly needed and tied to this one?
Doing that, I will post the revision later as it is not that important.



Comment at: llvm/CMakeLists.txt:294
 
-set(LLVM_UTILS_INSTALL_DIR "${LLVM_TOOLS_INSTALL_DIR}" CACHE STRING
+set(LLVM_UTILS_INSTALL_DIR "${LLVM_TOOLS_INSTALL_DIR}" CACHE PATH
 "Path to install LLVM utilities (enabled by LLVM_INSTALL_UTILS=ON) 
(defaults to LLVM_TOOLS_INSTALL_DIR)")

mstorsjo wrote:
> Nit: Unrelated and can be split out?
Yes, will do later.



Comment at: llvm/CMakeLists.txt:408
 
-set(LLVM_Z3_INSTALL_DIR "" CACHE STRING "Install directory of the Z3 solver.")
+set(LLVM_Z3_INSTALL_DIR "" CACHE PATH "Install directory of the Z3 solver.")
 

mstorsjo wrote:
> Unrelated?
Yes, see above.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D100810

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


[PATCH] D116352: [CodeCompletion] Signature help for template argument lists

2022-01-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang/lib/Sema/SemaCodeComplete.cpp:3785
+  if (const auto *FTD = dyn_cast(TD))
+return FTD->getTemplatedDecl()->getType().getAsString(Policy);
+  if (isa(TD))

kadircet wrote:
> the rendering looks a little bit surprising to me `foo -> bool 
> (float)` we might consider printing parameters first, e.g. 
> `foo(float) -> bool`. i think this also looks more natural for the 
> following signature help on function parameters.
Yeah. There are a few things going on here I wasn't sure how to square:

1) the "arrow" rendering is clangd-specific, and it reorders chunks by kind 
(moving the ResultType chunk to the end). So if we want a specific rendering in 
clangd we need to be able to infer it from the chunk sequence
2) the chunk sequence should make sense when rendered as text more directly. I 
think the current version fails this test: `bool(float) foo`.
3) the rendering you suggest requires us to reverse the order of bool and float 
somehow, ideally without some fragile coupling/assumptions in clangd

I think the "natural" chunk sequence is `bool` `foo<` `arg1` `,` `arg2` `>` 
`(float)`. The `bool` chunk is definitely ResultType.

If we make `(float)` also ResultType, we know have two RT chunks we have to 
stick in the signature in the right place. So maybe it's best to make it 
`CK_Text` or `CK_Informative`. I'll give this a spin...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116352

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


[PATCH] D116326: [CodeCompletion] Signature help for aggregate initialization.

2022-01-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/CodeComplete.cpp:1184
-  auto Name = Ident->getName();
-  if (!Name.empty())
-ParamNames.insert(Name.str());

we were never recording unnamed params before, now they'll be surfaced during 
comment code completions. can you either keep dropping them here or on the code 
completion generation side (~line 1997)



Comment at: clang/include/clang/Sema/CodeCompleteConsumer.h:1057
+: Kind(CK_Aggregate), AggregateType(Aggregate) {
+  assert(Aggregate != nullptr);
+}

we don't have assertions in other cases, why here? (i think we should have it 
in other cases too, just wondering if there are any valid states where we 
construct an overloadcandidate from nullptr)



Comment at: clang/lib/Sema/CodeCompleteConsumer.cpp:522
+if (const auto *CRD = dyn_cast(AggregateType))
+  Count += CRD->getNumBases();
+return Count;

i think this is only valid for c++17 onwards `If the number of initializer 
clauses exceeds the number of members and bases (since C++17) to initialize, 
the program is ill-formed.` (same for param type/decl)

it gets even more complicated, since one doesn't have to nest initialization of 
base class fields, e.g this is valid:
```
struct X
{
int a;
int b;
};

struct Y : X
{
int c;
};

Y y1{ {1,2}, 3};
Y y2{ 1, 2, 3 }; // both of these set a=1, b=2, c=3
```



Comment at: clang/lib/Sema/SemaCodeComplete.cpp:6031
+ ArrayRef Args) {
+  constexpr unsigned Invalid = std::numeric_limits::max();
+

also `static`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116326

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


[PATCH] D116159: [ARM][AArch64] clang support for Armv9.3-A

2022-01-03 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson updated this revision to Diff 397044.
tmatheson added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116159

Files:
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Basic/Targets/AArch64.h
  clang/lib/Basic/Targets/ARM.cpp
  clang/lib/Driver/ToolChains/Arch/AArch64.cpp
  clang/test/Driver/aarch64-cpus.c
  clang/test/Driver/arm-cortex-cpus.c
  clang/test/Preprocessor/arm-target-features.c

Index: clang/test/Preprocessor/arm-target-features.c
===
--- clang/test/Preprocessor/arm-target-features.c
+++ clang/test/Preprocessor/arm-target-features.c
@@ -879,6 +879,11 @@
 // CHECK-V92A: #define __ARM_ARCH_9_2A__ 1
 // CHECK-V92A: #define __ARM_ARCH_PROFILE 'A'
 
+// RUN: %clang -target armv9.3a-none-none-eabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V93A %s
+// CHECK-V93A: #define __ARM_ARCH 9
+// CHECK-V93A: #define __ARM_ARCH_9_3A__ 1
+// CHECK-V93A: #define __ARM_ARCH_PROFILE 'A'
+
 // RUN: %clang -target arm-none-none-eabi -march=armv7-m -mfpu=softvfp -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-SOFTVFP %s
 // CHECK-SOFTVFP-NOT: #define __ARM_FP 0x
 
Index: clang/test/Driver/arm-cortex-cpus.c
===
--- clang/test/Driver/arm-cortex-cpus.c
+++ clang/test/Driver/arm-cortex-cpus.c
@@ -437,6 +437,22 @@
 // RUN: %clang -target arm -march=armebv9.2-a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V92A %s
 // CHECK-BE-V92A: "-cc1"{{.*}} "-triple" "armebv9.2{{.*}}" "-target-cpu" "generic"
 
+// RUN: %clang -target armv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V93A %s
+// RUN: %clang -target arm -march=armv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V93A %s
+// RUN: %clang -target arm -march=armv9.3-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V93A %s
+// RUN: %clang -target armv9.3a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V93A %s
+// RUN: %clang -target arm -march=armv9.3a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V93A %s
+// RUN: %clang -target arm -march=armv9.3-a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V93A %s
+// CHECK-V93A: "-cc1"{{.*}} "-triple" "armv9.3{{.*}}" "-target-cpu" "generic"
+
+// RUN: %clang -target armebv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V93A %s
+// RUN: %clang -target armv9.3a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V93A %s
+// RUN: %clang -target armeb -march=armebv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V93A %s
+// RUN: %clang -target armeb -march=armebv9.3-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V93A %s
+// RUN: %clang -target arm -march=armebv9.3a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V93A %s
+// RUN: %clang -target arm -march=armebv9.3-a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V93A %s
+// CHECK-BE-V93A: "-cc1"{{.*}} "-triple" "armebv9.3{{.*}}" "-target-cpu" "generic"
+
 // Once we have CPUs with optional v8.2-A FP16, we will need a way to turn it
 // on and off. Cortex-A53 is a placeholder for now.
 // RUN: %clang -target armv8a-linux-eabi -mcpu=cortex-a53+fp16 -### -c %s 2>&1 | FileCheck --check-prefix CHECK-CORTEX-A53-FP16 %s
Index: clang/test/Driver/aarch64-cpus.c
===
--- clang/test/Driver/aarch64-cpus.c
+++ clang/test/Driver/aarch64-cpus.c
@@ -876,6 +876,22 @@
 // RUN: %clang -target aarch64_be -mbig-endian -march=armv9.2-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV92A-BE %s
 // GENERICV92A-BE: "-cc1"{{.*}} "-triple" "aarch64_be{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v9.2a" "-target-feature" "+i8mm" "-target-feature" "+bf16" "-target-feature" "+sve" "-target-feature" "+sve2"
 
+// RUN: %clang -target aarch64 -march=armv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A %s
+// RUN: %clang -target aarch64 -march=armv9.3-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A %s
+// RUN: %clang -target aarch64 -mlittle-endian -march=armv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A %s
+// RUN: %clang -target aarch64 -mlittle-endian -march=armv9.3-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A %s
+// RUN: %clang -target aarch64_be -mlittle-endian -march=armv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A %s
+// RUN: %clang -target aarch64_be -mlittle-endian -march=armv9.3-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A %s
+// GENERICV93A: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v9.3a"
+
+// RUN: %clang -target aarch64_be -march=armv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A-BE %s
+// RUN: %clang -target aarch64_be -march=armv9.3-a -### -c %s 2>&1 |

[PATCH] D112221: Mark ATOMIC_VAR_INIT and ATOMIC_FLAG_INIT as deprecated

2022-01-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Ping @Quuxplusone for feedback on the `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS` 
macro that was added.


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

https://reviews.llvm.org/D112221

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


[PATCH] D115253: [C2x] Support the *_WIDTH macros in limits.h and stdint.h

2022-01-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Ping


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

https://reviews.llvm.org/D115253

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


[PATCH] D116502: [clangd] Helper for determining member insertion point.

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

Thanks, LGTM!

In D116502#3217270 , @sammccall wrote:

> In D116502#3217084 , @kadircet 
> wrote:
>
>> We have some logic in AddUsing tweak to determine insertion point based on 
>> AST. i think it makes sense to migrate it to these helpers too.
>
> Thanks, I'd forgotten about those. I might tackle those next?

SGTM.

>> We've got some helpers in SourceCode.h to determine insertion point in the 
>> absence of ASTs. Concepts here and there around an "insertion point" seems 
>> to be quite different (it's just a sourcelocation here and a set of 
>> locations + a namespace in SourceCode.h).
>> I suppose those two are somewhat hard to merge and serve different purposes, 
>> so It's better to keep them separate.
>
> For sure ast-based and pseudoparsing-based cases are going to be different 
> APIs, but I would like to move those into this header too.

Makes sense.

> The problem I hit was they share private infrastructure (in SourceCode.cpp) 
> with other functionality (the namespace pseudoparsing for completion, I 
> think). So it's a bit of work to extract.

Ah I see :/


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116502

___
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 '('

2022-01-03 Thread G Pery via Phabricator via cfe-commits
GPery added a comment.

In D116170#3217198 , @curdeius wrote:

> @GPery, do you need help landing this?
> If so, please indicate the name and email you'd like to be used for the 
> commit.

Oh, sure, I didn't realise this part wasn't automatic.
It's "gpery" and gp...@pm.me, thanks!


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] D116459: [Clang][Sema] Adjust formatting (NFC)

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

LGTM, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116459

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


[PATCH] D112718: Add intrinsics and builtins for PTX atomics with semantic orders

2022-01-03 Thread Tadej Ciglarič via Phabricator via cfe-commits
t4c1 updated this revision to Diff 397047.
t4c1 added a comment.

Updated to the latest version that was merged into intel/llvm repo.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112718

Files:
  clang/include/clang/Basic/BuiltinsNVPTX.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtins-nvptx.c
  llvm/include/llvm/IR/IntrinsicsNVVM.td
  llvm/lib/Target/NVPTX/NVPTXInstrInfo.td
  llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
  llvm/lib/Target/NVPTX/NVPTXSubtarget.h
  llvm/test/CodeGen/NVPTX/atomics-with-semantics.ll

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


[PATCH] D116352: [CodeCompletion] Signature help for template argument lists

2022-01-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 397049.
sammccall added a comment.

Change ResultType handling for template functions. Given:

  template  string getName(int count) const &

We return the signature:

  {ResultType=string} getName<{placeholder=typename T}>()

Clangd renders this as:

  getName<$(0:typename T)>() -> string

We drop the function parameter list because

- it's potentially long and distracts from the template args we're showing
- there's no convenient way to print it!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116352

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/test/initialize-params.test
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/CodeCompleteConsumer.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Parse/ParseTemplate.cpp
  clang/lib/Sema/CodeCompleteConsumer.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/template-signature.cpp

Index: clang/test/CodeCompletion/template-signature.cpp
===
--- /dev/null
+++ clang/test/CodeCompletion/template-signature.cpp
@@ -0,0 +1,28 @@
+template  float overloaded(int);
+template  bool overloaded(char);
+
+auto m = overloaded<1, 2>(0);
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:4:21 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
+// CHECK-CC1: OPENING_PAREN_LOC: {{.*}}4:20
+// CHECK-CC1-DAG: OVERLOAD: [#float#]overloaded<<#int#>, char y>[#()#]
+// CHECK-CC1-DAG: OVERLOAD: [#bool#]overloaded<<#class#>, int x>[#()#]
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:4:24 %s -o - | FileCheck -check-prefix=CHECK-CC2 %s
+// CHECK-CC2-NOT: OVERLOAD: {{.*}}int x
+// CHECK-CC2: OVERLOAD: [#float#]overloaded>[#()#]
+
+template  int n = 0;
+int val = n;
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:14:18 %s -o - | FileCheck -check-prefix=CHECK-CC3 %s
+// CHECK-CC3: OVERLOAD: [#int#]n>
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:14:24 %s -o - | FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: OVERLOAD: [#int#]n
+
+template  struct Vector {};
+template  class Container = Vector>
+struct Collection { Container container; };
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:22:31 %s -o - | FileCheck -check-prefix=CHECK-CC5 %s
+// CHECK-CC5: OVERLOAD: [#class#]Container<<#typename E#>>
+Collection collection;
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:25:12 %s -o - | FileCheck -check-prefix=CHECK-CC6 %s
+// CHECK-CC6: OVERLOAD: [#struct#]Collection<<#typename Element#>>
+
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -36,6 +36,7 @@
 #include "clang/Sema/Lookup.h"
 #include "clang/Sema/Overload.h"
 #include "clang/Sema/ParsedAttr.h"
+#include "clang/Sema/ParsedTemplate.h"
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/Sema.h"
@@ -3758,6 +3759,86 @@
   }
 }
 
+static std::string
+formatTemplateParameterPlaceholder(const NamedDecl *Param, bool &Optional,
+   const PrintingPolicy &Policy) {
+  if (const auto *Type = dyn_cast(Param)) {
+Optional = Type->hasDefaultArgument();
+  } else if (const auto *NonType = dyn_cast(Param)) {
+Optional = NonType->hasDefaultArgument();
+  } else if (const auto *Template = dyn_cast(Param)) {
+Optional = Template->hasDefaultArgument();
+  }
+  std::string Result;
+  llvm::raw_string_ostream OS(Result);
+  Param->print(OS, Policy);
+  return Result;
+}
+
+// A string describing the result of a template.
+//
+// If the template is for a function `bool foo(int)`, then returns
+// `bool` and sets Suffix to `(int)`.
+static std::string templateResultType(const TemplateDecl *TD,
+  const PrintingPolicy &Policy,
+  std::string &Suffix) {
+  if (const auto *CTD = dyn_cast(TD))
+return CTD->getTemplatedDecl()->getKindName().str();
+  if (const auto *VTD = dyn_cast(TD))
+return VTD->getTemplatedDecl()->getType().getAsString(Policy);
+  if (const auto *FTD = dyn_cast(TD)) {
+// For now, indicate this is a function, but don't attempt to list args.
+// It's fiddly and potentially bulky/distracting.
+Suffix = "()";
+return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy);
+  }
+  if (isa(TD))
+return "type";
+  if (isa(TD))
+return "class";
+  if (isa(TD))
+return "concept";
+  return "";
+}
+
+static CodeCompletionString *createTemplateSignatureString(
+const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg,
+const PrintingPolicy &Policy) {
+  

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

2022-01-03 Thread Rajat Bajpai via Phabricator via cfe-commits
rajatbajpai added a comment.

In D116283#3216235 , @MyDeveloperDay 
wrote:

> LGTM, could you add a release note into docs/ReleaseNotes.rst?

Sure, will do.




Comment at: clang/docs/ClangFormatStyleOptions.rst:3760
+   true:  false:
+   void operator++ (int a);vs.void operator++(int a);
+

curdeius wrote:
> Please add operator call as well to the example (`object.operator++ (0)`).
Sure, will add.


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] D116535: [clang-tidy] Fix false positive in modernize-pass-by-value

2022-01-03 Thread Clement Courbet via Phabricator via cfe-commits
courbet created this revision.
courbet added reviewers: alexfh, flx, aaron.ballman.
Herald added subscribers: carlosgalvezp, xazax.hun.
courbet requested review of this revision.
Herald added a project: clang-tools-extra.

The check should not trigger on lvalue/rvalue overload pairs:

  struct S {
S(const A& a) : a(a) {}
S(A&& a) : a(std::move(a)) {}
  
A a;
  }


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116535

Files:
  clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-pass-by-value.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-pass-by-value.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-pass-by-value.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-pass-by-value.cpp
@@ -246,3 +246,20 @@
 V::V(const Movable &M) : M(M) {}
 // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: pass by value and use std::move
 // CHECK-FIXES: V::V(const Movable &M) : M(M) {}
+
+// Test with paired lvalue/rvalue overloads.
+struct W1 {
+  W1(const Movable &M) : M(M) {}
+  W1(Movable &&M);
+  Movable M;
+};
+struct W2 {
+  W2(const Movable &M, int) : M(M) {}
+  W2(Movable &&M, int);
+  Movable M;
+};
+struct W3 {
+  W3(const W1 &, const Movable &M) : M(M) {}
+  W3(W1 &&, Movable &&M);
+  Movable M;
+};
Index: clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
@@ -105,6 +105,73 @@
   return ExactlyOneUsageVisitor(ParamDecl).hasExactlyOneUsageIn(Ctor);
 }
 
+/// Returns true the given constructor is part of a lvalue/rvalue reference
+/// pair, i.e. `Param` is of lvalue reference type, and there exists another
+/// constructor such that:
+///  - it has the same number of parameters as `Ctor`.
+///  - the parameter at the same index as `Param` is an rvalue reference
+///of the same pointee type
+///  - all other parameters have the same type as the corresponding parameter in
+///`Ctor` or are rvalue references with the same pointee type.
+/// Examples:
+///  A::A(const B& Param)
+///  A::A(B&&)
+///
+///  A::A(const B& Param, const C&)
+///  A::A(B&& Param, C&&)
+///
+///  A::A(const B&, const C& Param)
+///  A::A(B&&, C&& Param)
+///
+///  A::A(const B&, const C& Param)
+///  A::A(const B&, C&& Param)
+///
+///  A::A(const B& Param, int)
+///  A::A(B&& Param, int)
+static bool hasRValueOverload(const CXXConstructorDecl *Ctor,
+  const ParmVarDecl *Param) {
+  if (!Param->getType().getCanonicalType()->isLValueReferenceType()) {
+// The parameter is passed by value.
+return false;
+  }
+  const int ParamIdx = Param->getFunctionScopeIndex();
+  const CXXRecordDecl *Record = Ctor->getParent();
+
+  // Check whether a ctor `C` forms a pair with `Ctor` under the aforementionned
+  // rules.
+  const auto IsRValueOverload = [&Ctor, ParamIdx](const CXXConstructorDecl *C) {
+if (C == Ctor || C->isDeleted() ||
+C->getNumParams() != Ctor->getNumParams())
+  return false;
+for (int I = 0, E = C->getNumParams(); I < E; ++I) {
+  const clang::QualType CandidateParamType =
+  C->parameters()[I]->getType().getCanonicalType();
+  const clang::QualType CtorParamType =
+  Ctor->parameters()[I]->getType().getCanonicalType();
+  const bool IsLValueRValuePair =
+  CtorParamType->isLValueReferenceType() &&
+  CandidateParamType->isRValueReferenceType() &&
+  CandidateParamType->getPointeeType()->getUnqualifiedDesugaredType() ==
+  CtorParamType->getPointeeType()->getUnqualifiedDesugaredType();
+  if (I == ParamIdx) {
+if (!IsLValueRValuePair)
+  return false;
+  } else {
+if (!(CandidateParamType == CtorParamType || IsLValueRValuePair))
+  return false;
+  }
+}
+return true;
+  };
+
+  for (const auto *Candidate : Record->ctors()) {
+if (IsRValueOverload(Candidate)) {
+  return true;
+}
+  }
+  return false;
+}
+
 /// Find all references to \p ParamDecl across all of the
 /// redeclarations of \p Ctor.
 static SmallVector
@@ -188,6 +255,10 @@
   *Result.Context))
 return;
 
+  // Do not trigger if we find a paired constructor with an rvalue.
+  if (hasRValueOverload(Ctor, ParamDecl))
+return;
+
   auto Diag = diag(ParamDecl->getBeginLoc(), "pass by value and use std::move");
 
   // If we received a `const&` type, we need to rewrite the function
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116313: [MSVC] Silence -Wnon-virtual-dtor on DIA APIs

2022-01-03 Thread Hans Wennborg via Phabricator via cfe-commits
hans added inline comments.



Comment at: clang/lib/Driver/ToolChains/MSVC.cpp:54
+#endif
 #include "MSVCSetupApi.h"
+#ifdef __clang__

Since it's in our repository, would it be possible to fix 
clang/lib/Driver/ToolChains/MSVCSetupApi.h to be warning free? If it's not 
possible to fix the classes the warning refers to, I think it would at least be 
nicer to move the pragma into that file.



Comment at: llvm/include/llvm/DebugInfo/PDB/DIA/DIASupport.h:34
+#endif
 #include 
+#ifdef __clang__

I thought this warning should be suppressed for system headers. Isn't that 
working here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116313

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


[PATCH] D112221: Mark ATOMIC_VAR_INIT and ATOMIC_FLAG_INIT as deprecated

2022-01-03 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added a comment.

TLDR on `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`: I'm neutral. :)




Comment at: clang/docs/ReleaseNotes.rst:159-164
+ - The ``ATOMIC_VAR_INIT`` macro from  is now diagnosed as
+   deprecated in both C (C17 and later) and C++ (C++20 and later), and
+   ``ATOMIC_FLAG_INIT`` is now diagnosed as deprecated in C++ (C++20 and 
later).
+   The diagnostic can be disabled by defining the
+   ``_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`` macro prior to including the
+   header.

IIUC, `` is not relevant to C++20; libc++'s `` even 
`#error`s if you include both `` and `` in the same TU.
Defining `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS` won't affect the warnings in 
C++20; for those you need `_LIBCPP_DISABLE_DEPRECATION_WARNINGS`.
C++20 isn't relevant to this section on "C Language Changes in Clang"; arguably 
it could be listed under "C++ Language Changes in Clang," except that D115995 
didn't change anything about //Clang//. So I think it's fine not to mention 
D115995 anywhere in this file.



Comment at: clang/docs/UsersManual.rst:1128-1130
+  #include  // May include Clang CRT deprecation warnings
+  #define _CLANG_DISABLE_CRT_DEPRECATION_WARNINGS
+  #include  // Clang CRT deprecation warnings are disabled

It is //probably// sketchy to advise people to change the setting of 
`_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS` over the lifetime of a single TU. If 
`` transitively includes ``, this won't work. (Of course 
that's unlikely in this //specific// case, but in general, IMHO we shouldn't 
train people to think that this will always work.)
(In fact, `` transitively includes ``!)
We should train the programmer to think of 
`_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS` as all-or-nothing: set it in your 
build system, or set it at the very top of the TU.



Comment at: clang/lib/Headers/stdatomic.h:42-47
 #define ATOMIC_VAR_INIT(value) (value)
+#if __STDC_VERSION__ >= 201710L || __cplusplus >= 202002L
+/* ATOMIC_VAR_INIT was deprecated in C17 and C++20. */
+#pragma clang deprecated(ATOMIC_VAR_INIT)
+#endif
 #define atomic_init __c11_atomic_init

aaron.ballman wrote:
> Quuxplusone wrote:
> > Hmm, I do think there ought to be some way for the C++20 programmer to 
> > suppress the deprecation warning for these macros (specifically, not just 
> > via `-Wno-deprecated` in their whole project). For deprecations in the C++ 
> > standard library, libc++ offers an all-or-nothing flag: basically you'd do
> > ```
> > #if (__STDC_VERSION__ >= 201710L || __cplusplus >= 202002L) && 
> > !defined(_LIBCPP_DISABLE_DEPRECATION_WARNINGS)
> > /* ATOMIC_VAR_INIT was deprecated in C17 and C++20. */
> > #pragma clang deprecated(ATOMIC_VAR_INIT)
> > #endif
> > ```
> > (This also makes it easy for libcxx/test/ to suppress the deprecation 
> > warning for the purposes of testing.)
> > 
> > However, I'm not sure if it's appropriate to mention 
> > `_LIBCPP_DISABLE_DEPRECATION_WARNINGS` in this header located in 
> > clang/lib/Headers/ instead of libcxx/include/. Someone else will have to 
> > make that call.
> > 
> > It might be that the only way for the programmer (or libcxx/test/) to work 
> > around the warning will be for them to pass `-Wno-deprecated` globally; IMO 
> > that is suboptimal but quite far from disastrous.
> I think this is a reasonable idea. Microsoft has macros for a similar purpose 
> with `_CRT_SECURE_NO_WARNINGS` (IIRC). I would not want to use `_LIBCPP_`  
> for this purpose, but I could imagine it's useful to add something like 
> `_CLANG_DISABLE_DEPRECATION_WARNINGS`. (I'm guessing we don't want 
> per-deprecation granularity on the macro, but if we needed something like 
> that, I think we could add it.)
> 
> I went ahead and added `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS` to the next 
> version of the patch, and documented it in the release notes and user's 
> manual. We can quibble over the name if you have better suggestions.
Re `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`: This naming scheme looks novel — 
I don't see any other `_CLANG_{DIS,EN}ABLE.*` macros in `clang/lib/Headers/` — 
but that might just be because its purpose is also novel. I'm not saying it's a 
good idea, but I don't object to it nor have any particularly better idea.

Btw, where above I said `-Wno-deprecated`, it turns out that 
`-Wno-deprecated-pragma` is slightly finer-grained. Also, I'm like 95% sure 
that C++ is totally covered by D115995, which means whatever you do here is 
relevant only to C17, which means I have no personal stake in its ergonomics. :)


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

https://reviews.llvm.org/D112221

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


[PATCH] D116536: [clangd] Fix selection on multi-dimensional array. (alternate version)

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

based on D116218 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116536

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp


Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -318,6 +318,13 @@
   {"[[st^ruct {int x;}]] y;", "CXXRecordDecl"},
   {"[[struct {int x;} ^y]];", "VarDecl"},
   {"struct {[[int ^x]];} y;", "FieldDecl"},
+
+  // Tricky case: nested ConstantArrayTypeLocs have the same token range.
+  {"const int x = 1, y = 2; int array[^[[x]]][10][y];", "DeclRefExpr"},
+  {"const int x = 1, y = 2; int array[x][10][^[[y]]];", "DeclRefExpr"},
+  {"const int x = 1, y = 2; int array[x][^[[10]]][y];", "IntegerLiteral"},
+  {"const int x = 1, y = 2; [[i^nt]] array[x][10][y];", "BuiltinTypeLoc"},
+
   // FIXME: the AST has no location info for qualifiers.
   {"const [[a^uto]] x = 42;", "AutoTypeLoc"},
   {"[[co^nst auto x = 42]];", "VarDecl"},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -76,6 +76,10 @@
  ? getSourceRange(DynTypedNode::create(*ME->getBase()))
  : SourceRange();
   }
+  if (const auto *TL = N.get()) {
+if (const auto ATL = TL->getAs())
+  return ATL.getBracketsRange();
+  }
   return N.getSourceRange();
 }
 
@@ -510,6 +514,7 @@
   bool TraverseTypeLoc(TypeLoc X) {
 return traverseNode(&X, [&] { return Base::TraverseTypeLoc(X); });
   }
+
   bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &X) {
 return traverseNode(&X,
 [&] { return Base::TraverseTemplateArgumentLoc(X); });
@@ -661,6 +666,9 @@
   // type's range.
   if (auto AT = TL->getAs())
 S = AT.getModifiedLoc().getSourceRange();
+
+  if (auto AT = TL->getAs())
+S = AT.getSourceRange();
 }
 // SourceRange often doesn't manage to accurately cover attributes.
 // Fortunately, attributes are rare.


Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -318,6 +318,13 @@
   {"[[st^ruct {int x;}]] y;", "CXXRecordDecl"},
   {"[[struct {int x;} ^y]];", "VarDecl"},
   {"struct {[[int ^x]];} y;", "FieldDecl"},
+
+  // Tricky case: nested ConstantArrayTypeLocs have the same token range.
+  {"const int x = 1, y = 2; int array[^[[x]]][10][y];", "DeclRefExpr"},
+  {"const int x = 1, y = 2; int array[x][10][^[[y]]];", "DeclRefExpr"},
+  {"const int x = 1, y = 2; int array[x][^[[10]]][y];", "IntegerLiteral"},
+  {"const int x = 1, y = 2; [[i^nt]] array[x][10][y];", "BuiltinTypeLoc"},
+
   // FIXME: the AST has no location info for qualifiers.
   {"const [[a^uto]] x = 42;", "AutoTypeLoc"},
   {"[[co^nst auto x = 42]];", "VarDecl"},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -76,6 +76,10 @@
  ? getSourceRange(DynTypedNode::create(*ME->getBase()))
  : SourceRange();
   }
+  if (const auto *TL = N.get()) {
+if (const auto ATL = TL->getAs())
+  return ATL.getBracketsRange();
+  }
   return N.getSourceRange();
 }
 
@@ -510,6 +514,7 @@
   bool TraverseTypeLoc(TypeLoc X) {
 return traverseNode(&X, [&] { return Base::TraverseTypeLoc(X); });
   }
+
   bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &X) {
 return traverseNode(&X,
 [&] { return Base::TraverseTemplateArgumentLoc(X); });
@@ -661,6 +666,9 @@
   // type's range.
   if (auto AT = TL->getAs())
 S = AT.getModifiedLoc().getSourceRange();
+
+  if (auto AT = TL->getAs())
+S = AT.getSourceRange();
 }
 // SourceRange often doesn't manage to accurately cover attributes.
 // Fortunately, attributes are rare.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116224: Revert "[amdgpu] Enable selection of `s_cselect_b64`."

2022-01-03 Thread Louis Dionne via Phabricator via cfe-commits
ldionne commandeered this revision.
ldionne added a reviewer: david-salinas.
ldionne added a comment.

Yeah, I think you messed something up with your git commands. I'm going to 
commandeer and abandon this revision to get it out of the libc++ review queue 
since it's been 10 days since this has been open. Please re-open another review 
reverting just the intended commit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116224

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


[PATCH] D115521: [Templight] Don't display empty strings for names of unnamed template parameters

2022-01-03 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus updated this revision to Diff 397054.
Szelethus added a comment.

Add a default text, if another, unhandled unnamed identifier pops up.


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

https://reviews.llvm.org/D115521

Files:
  clang/lib/Frontend/FrontendActions.cpp
  clang/test/Templight/templight-empty-entries-fix.cpp

Index: clang/test/Templight/templight-empty-entries-fix.cpp
===
--- /dev/null
+++ clang/test/Templight/templight-empty-entries-fix.cpp
@@ -0,0 +1,333 @@
+// RUN: %clang_cc1 -templight-dump -Wno-unused-value %s 2>&1 | FileCheck %s
+
+void a() {
+  [] {};
+}
+
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+'lambda at .*templight-empty-entries-fix.cpp:4:3'$}}
+// CHECK: {{^kind:[ ]+Memoization$}}
+// CHECK: {{^event:[ ]+Begin$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:4:3'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:4:3'$}}
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+'lambda at .*templight-empty-entries-fix.cpp:4:3'$}}
+// CHECK: {{^kind:[ ]+Memoization$}}
+// CHECK: {{^event:[ ]+End$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:4:3'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:4:3'$}}
+
+template  void a() { a(); }
+
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+a$}}
+// CHECK: {{^kind:[ ]+DeducedTemplateArgumentSubstitution$}}
+// CHECK: {{^event:[ ]+Begin$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:20:25'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:20:31'$}}
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+unnamed template non-type parameter 0 of a$}}
+// CHECK: {{^kind:[ ]+DefaultTemplateArgumentInstantiation$}}
+// CHECK: {{^event:[ ]+Begin$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:20:15'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:20:25'$}}
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+unnamed template non-type parameter 0 of a$}}
+// CHECK: {{^kind:[ ]+DefaultTemplateArgumentInstantiation$}}
+// CHECK: {{^event:[ ]+End$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:20:15'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:20:25'$}}
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+a$}}
+// CHECK: {{^kind:[ ]+DeducedTemplateArgumentSubstitution$}}
+// CHECK: {{^event:[ ]+End$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:20:25'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:20:31'$}}
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+'a<0>'$}}
+// CHECK: {{^kind:[ ]+TemplateInstantiation$}}
+// CHECK: {{^event:[ ]+Begin$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:20:25'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:20:31'$}}
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+'a<0>'$}}
+// CHECK: {{^kind:[ ]+TemplateInstantiation$}}
+// CHECK: {{^event:[ ]+End$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:20:25'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:20:31'$}}
+
+template  struct b { typedef int c; };
+template ::c> void a() { a(); }
+
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+a$}}
+// CHECK: {{^kind:[ ]+DeducedTemplateArgumentSubstitution$}}
+// CHECK: {{^event:[ ]+Begin$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:60:57'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:60:63'$}}
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+d$}}
+// CHECK: {{^kind:[ ]+DefaultTemplateArgumentInstantiation$}}
+// CHECK: {{^event:[ ]+Begin$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:60:16'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:60:57'$}}
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+d$}}
+// CHECK: {{^kind:[ ]+DefaultTemplateArgumentInstantiation$}}
+// CHECK: {{^event:[ ]+End$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:60:16'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:60:57'$}}
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+unnamed template type parameter 1 of a$}}
+// CHECK: {{^kind:[ ]+DefaultTemplateArgumentInstantiation$}}
+// CHECK: {{^event:[ ]+Begin$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:60:32'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:60:57'$}}
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+'b<1>'$}}
+// CHECK: {{^kind:[ ]+TemplateInstantiation$}}
+// CHECK: {{^event:[ ]+Begin$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:59:23'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:60:43'$}}
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+'b<1>'$}}
+// CHECK: {{^kind:[ ]+TemplateInstantiation$}}
+// CHECK: {{^event:[ ]+End$}}
+// CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:59:23'$}}
+// CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:60:43'$}}
+// CHECK-LABEL: {{^---$}}
+// CHECK: {{^name:[ ]+'b<1>'$}}
+// CHECK: {{^kind:[ ]+TemplateInstantiation$}}

[PATCH] D114425: [clang] Add __builtin_bswap128

2022-01-03 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added a comment.

In D114425#3216802 , @majnemer wrote:

> OOC, how hard would it be to generalize this builtin a little? It is nice 
> that we have builtins like `__builtin_add_overflow` which do the right thing 
> regardless of their input.
>
> It seems like it would be nice if we started to expose more intrinsics which 
> did the right thing regardless of operand width; another bonus is that it 
> composes well with language features like `_BitInt`.

IMHO such builtins are nice iff the programmer can be 100% sure that the 
compiler will interpret them the same way as a human reader. 
`__builtin_add_overflow` is easy because its first two arguments are 
"mathematical integers" (where integer promotion doesn't matter) and its third 
argument is a pointer (where integer promotion can't happen). So you can really 
throw any combination of types at it, and it'll do "the right thing" 
https://godbolt.org/z/sa7b894oa (although I admit I was surprised that this 
worked).
For a hypothetical `__builtin_bswap`, you would probably need a similar 
pointer-based interface like

  short s16 = 0xFEDC;
  __builtin_bswap(&s16);  // hypothetically
  assert(s16 == 0xDCFE);
  
  assert(__builtin_bswap16(s16) == 0xDCFE);
  assert(__builtin_bswap32(s16) == 0xDCFE);  // the problem to solve: s16 
eagerly promotes to int, which changes the result

The downside is that the pointer-based interface is less ergonomic than today's 
value-based signatures, and probably worse codegen at `-O0` (because the 
programmer has to materialize the operand into a named variable, and then the 
compiler won't remove that variable because you might want to debug it). The 
upside (as you said) is that a generic builtin could work with `_ExtInt` types 
and so on.




Comment at: clang/lib/CodeGen/CGBuiltin.cpp:2930
+  }
+  [[fallthrough]];
   case Builtin::BI__builtin_bswap16:

Re clang-format's complaint: I would either move `[[fallthrough]];` inside the 
curly braces, or (probably better) just eliminate the fallthrough by either 
duplicating line 2934 or else doing
```
  case Builtin::BI__builtin_bswap64:
  case Builtin::BI__builtin_bswap128: {
if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_bswap128 && 
!Target.hasInt128Type())
  CGM.ErrorUnsupported(E, "__builtin_bswap128");
return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bswap));
  }
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114425

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


[PATCH] D116352: [CodeCompletion] Signature help for template argument lists

2022-01-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.

thanks! as discussed offline i think it's better to ignore function parameters 
for now.




Comment at: clang/lib/Sema/SemaCodeComplete.cpp:3781
+// If the template is for a function `bool foo(int)`, then returns
+// `bool` and sets Suffix to `(int)`.
+static std::string templateResultType(const TemplateDecl *TD,

the comments around the suffix seems to be out-of-date (maybe mention it as a 
fixme?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116352

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


[PATCH] D112221: Mark ATOMIC_VAR_INIT and ATOMIC_FLAG_INIT as deprecated

2022-01-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked 2 inline comments as done.
aaron.ballman added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:159-164
+ - The ``ATOMIC_VAR_INIT`` macro from  is now diagnosed as
+   deprecated in both C (C17 and later) and C++ (C++20 and later), and
+   ``ATOMIC_FLAG_INIT`` is now diagnosed as deprecated in C++ (C++20 and 
later).
+   The diagnostic can be disabled by defining the
+   ``_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`` macro prior to including the
+   header.

Quuxplusone wrote:
> IIUC, `` is not relevant to C++20; libc++'s `` even 
> `#error`s if you include both `` and `` in the same TU.
> Defining `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS` won't affect the warnings 
> in C++20; for those you need `_LIBCPP_DISABLE_DEPRECATION_WARNINGS`.
> C++20 isn't relevant to this section on "C Language Changes in Clang"; 
> arguably it could be listed under "C++ Language Changes in Clang," except 
> that D115995 didn't change anything about //Clang//. So I think it's fine not 
> to mention D115995 anywhere in this file.
The point I was trying to make is that including `` in C++20 and 
later mode will diagnose these as deprecated, independent of ``. I did 
this on the assumption that they're just as useless coming from `` 
as they are coming from ``, so they should also be diagnosed. I could 
make this more clear by mentioning `` explicitly in the release note.

As for whether this should be listed under the C++ section... meh. I'm not 
certain it matters that much as this is about the C header file. I can mention 
it in the C++ section though.



Comment at: clang/docs/UsersManual.rst:1128-1130
+  #include  // May include Clang CRT deprecation warnings
+  #define _CLANG_DISABLE_CRT_DEPRECATION_WARNINGS
+  #include  // Clang CRT deprecation warnings are disabled

Quuxplusone wrote:
> It is //probably// sketchy to advise people to change the setting of 
> `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS` over the lifetime of a single TU. 
> If `` transitively includes ``, this won't work. (Of 
> course that's unlikely in this //specific// case, but in general, IMHO we 
> shouldn't train people to think that this will always work.)
> (In fact, `` transitively includes ``!)
> We should train the programmer to think of 
> `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS` as all-or-nothing: set it in your 
> build system, or set it at the very top of the TU.
Thanks for the feedback, I've adjusted the text.



Comment at: clang/lib/Headers/stdatomic.h:42-47
 #define ATOMIC_VAR_INIT(value) (value)
+#if __STDC_VERSION__ >= 201710L || __cplusplus >= 202002L
+/* ATOMIC_VAR_INIT was deprecated in C17 and C++20. */
+#pragma clang deprecated(ATOMIC_VAR_INIT)
+#endif
 #define atomic_init __c11_atomic_init

Quuxplusone wrote:
> aaron.ballman wrote:
> > Quuxplusone wrote:
> > > Hmm, I do think there ought to be some way for the C++20 programmer to 
> > > suppress the deprecation warning for these macros (specifically, not just 
> > > via `-Wno-deprecated` in their whole project). For deprecations in the 
> > > C++ standard library, libc++ offers an all-or-nothing flag: basically 
> > > you'd do
> > > ```
> > > #if (__STDC_VERSION__ >= 201710L || __cplusplus >= 202002L) && 
> > > !defined(_LIBCPP_DISABLE_DEPRECATION_WARNINGS)
> > > /* ATOMIC_VAR_INIT was deprecated in C17 and C++20. */
> > > #pragma clang deprecated(ATOMIC_VAR_INIT)
> > > #endif
> > > ```
> > > (This also makes it easy for libcxx/test/ to suppress the deprecation 
> > > warning for the purposes of testing.)
> > > 
> > > However, I'm not sure if it's appropriate to mention 
> > > `_LIBCPP_DISABLE_DEPRECATION_WARNINGS` in this header located in 
> > > clang/lib/Headers/ instead of libcxx/include/. Someone else will have to 
> > > make that call.
> > > 
> > > It might be that the only way for the programmer (or libcxx/test/) to 
> > > work around the warning will be for them to pass `-Wno-deprecated` 
> > > globally; IMO that is suboptimal but quite far from disastrous.
> > I think this is a reasonable idea. Microsoft has macros for a similar 
> > purpose with `_CRT_SECURE_NO_WARNINGS` (IIRC). I would not want to use 
> > `_LIBCPP_`  for this purpose, but I could imagine it's useful to add 
> > something like `_CLANG_DISABLE_DEPRECATION_WARNINGS`. (I'm guessing we 
> > don't want per-deprecation granularity on the macro, but if we needed 
> > something like that, I think we could add it.)
> > 
> > I went ahead and added `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS` to the 
> > next version of the patch, and documented it in the release notes and 
> > user's manual. We can quibble over the name if you have better suggestions.
> Re `_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`: This naming scheme looks novel 
> — I don't see any other `_CLANG_{DIS,EN}ABLE.*` macros in 
> `clang/lib/Headers/` — but that might just be because its purpose is also 
> novel. I'm not saying it's

[PATCH] D112221: Mark ATOMIC_VAR_INIT and ATOMIC_FLAG_INIT as deprecated

2022-01-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 397061.
aaron.ballman marked 2 inline comments as done.
aaron.ballman added a comment.

Updated release notes and user's manual based on review feedback.


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

https://reviews.llvm.org/D112221

Files:
  clang/docs/ReleaseNotes.rst
  clang/docs/UsersManual.rst
  clang/lib/Headers/stdatomic.h
  clang/test/Headers/stdatomic-deprecations.c

Index: clang/test/Headers/stdatomic-deprecations.c
===
--- /dev/null
+++ clang/test/Headers/stdatomic-deprecations.c
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c11 %s -verify=okay
+// RUN: %clang_cc1 -fsyntax-only -std=c17 %s -verify
+// RUN: %clang_cc1 -fsyntax-only -std=c++11 -x c++ %s -verify=okay
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -x c++ %s -verify=cxx,expected
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -x c++ %s -verify=okay -D_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS
+// RUN: %clang_cc1 -fsyntax-only -std=c17 %s -verify=okay -D_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS
+//
+// okay-no-diagnostics
+
+#include 
+
+void func(void) {
+  _Atomic int i = ATOMIC_VAR_INIT(12); // expected-warning {{macro 'ATOMIC_VAR_INIT' has been marked as deprecated}} \
+   // expected-note@stdatomic.h:* {{macro marked 'deprecated' here}}
+  #if defined(ATOMIC_FLAG_INIT) // cxx-warning {{macro 'ATOMIC_FLAG_INIT' has been marked as deprecated}} \
+// cxx-note@stdatomic.h:* {{macro marked 'deprecated' here}}
+  #endif
+}
Index: clang/lib/Headers/stdatomic.h
===
--- clang/lib/Headers/stdatomic.h
+++ clang/lib/Headers/stdatomic.h
@@ -44,6 +44,11 @@
 /* 7.17.2 Initialization */
 
 #define ATOMIC_VAR_INIT(value) (value)
+#if (__STDC_VERSION__ >= 201710L || __cplusplus >= 202002L) && \
+!defined(_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS)
+/* ATOMIC_VAR_INIT was deprecated in C17 and C++20. */
+#pragma clang deprecated(ATOMIC_VAR_INIT)
+#endif
 #define atomic_init __c11_atomic_init
 
 /* 7.17.3 Order and consistency */
@@ -153,6 +158,10 @@
 typedef struct atomic_flag { atomic_bool _Value; } atomic_flag;
 
 #define ATOMIC_FLAG_INIT { 0 }
+#if __cplusplus >= 202002L && !defined(_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS)
+/* ATOMIC_FLAG_INIT was deprecated in C++20 but is not deprecated in C. */
+#pragma clang deprecated(ATOMIC_FLAG_INIT)
+#endif
 
 /* These should be provided by the libc implementation. */
 #ifdef __cplusplus
Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -1132,10 +1132,28 @@
 directory is treated as including a system header if the including file
 is treated as a system header.
 
+Controlling Deprecation Diagnostics in Clang-Provided C Runtime Headers
+^^^
+
+Clang is responsible for providing some of the C runtime headers that cannot be
+provided by a platform CRT, such as implementation limits or when compiling in
+freestanding mode. Define the ``_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`` macro
+prior to including such a C runtime header to disable the deprecation warnings.
+Note that the C Standard Library headers are allowed to transitively include
+other standard library headers (see 7.1.2p5), and so the most appropriate use
+of this macro is to set it within the build system using ``-D`` or before any
+include directives in the translation unit.
+
+.. code-block:: c
+
+  #define _CLANG_DISABLE_CRT_DEPRECATION_WARNINGS
+  #include // Clang CRT deprecation warnings are disabled.
+  #include  // Clang CRT deprecation warnings are disabled.
+
 .. _diagnostics_enable_everything:
 
 Enabling All Diagnostics
-^
+
 
 In addition to the traditional ``-W`` flags, one can enable **all** diagnostics
 by passing :option:`-Weverything`. This works as expected with
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -159,6 +159,11 @@
   stabilized, so this type should not yet be used in interfaces that require
   ABI stability.
 
+- The ``ATOMIC_VAR_INIT`` macro from  is now diagnosed as
+  deprecated in C17 and later. The diagnostic can be disabled by defining the
+  ``_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`` macro prior to including the
+  header.
+
 C++ Language Changes in Clang
 -
 
@@ -166,7 +171,15 @@
 
 C++20 Feature Support
 ^
-...
+
+- The ``ATOMIC_VAR_INIT`` and ``ATOMIC_FLAG_INIT`` macros from the C standard
+  library  header are now diagnosed as deprecated in C++20 and
+  later. Note, the behavior is specific to the inclusion of ```

[PATCH] D116536: [clangd] Fix selection on multi-dimensional array.

2022-01-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 397062.
sammccall retitled this revision from "[clangd] Fix selection on 
multi-dimensional array. (alternate version)" to "[clangd] Fix selection on 
multi-dimensional array.".
sammccall edited the summary of this revision.
sammccall added a comment.

cleaner, comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116536

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp

Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -318,6 +318,13 @@
   {"[[st^ruct {int x;}]] y;", "CXXRecordDecl"},
   {"[[struct {int x;} ^y]];", "VarDecl"},
   {"struct {[[int ^x]];} y;", "FieldDecl"},
+
+  // Tricky case: nested ConstantArrayTypeLocs have the same token range.
+  {"const int x = 1, y = 2; int array[^[[x]]][10][y];", "DeclRefExpr"},
+  {"const int x = 1, y = 2; int array[x][10][^[[y]]];", "DeclRefExpr"},
+  {"const int x = 1, y = 2; int array[x][^[[10]]][y];", "IntegerLiteral"},
+  {"const int x = 1, y = 2; [[i^nt]] array[x][10][y];", "BuiltinTypeLoc"},
+
   // FIXME: the AST has no location info for qualifiers.
   {"const [[a^uto]] x = 42;", "AutoTypeLoc"},
   {"[[co^nst auto x = 42]];", "VarDecl"},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -58,7 +58,24 @@
 SelectionUsedRecovery.record(0, LanguageLabel); // unused.
 }
 
+// Return the range covering a node and all its children.
 SourceRange getSourceRange(const DynTypedNode &N) {
+  // DeclTypeTypeLoc::getSourceRange() is incomplete, which would lead to
+  // failing
+  // to descend into the child expression.
+  // decltype(2+2);
+  // ~ <-- correct range
+  //   <-- range reported by getSourceRange()
+  //   <-- range with this hack(i.e, missing closing paren)
+  // FIXME: Alter DecltypeTypeLoc to contain parentheses locations and get
+  // rid of this patch.
+  if (const auto *TL = N.get()) {
+if (auto DT = TL->getAs()) {
+  SourceRange S = DT.getSourceRange();
+  S.setEnd(DT.getUnderlyingExpr()->getEndLoc());
+  return S;
+}
+  }
   // MemberExprs to implicitly access anonymous fields should not claim any
   // tokens for themselves. Given:
   //   struct A { struct { int b; }; };
@@ -646,17 +663,6 @@
   // heuristics. We should consider only pruning critical TypeLoc nodes, to
   // be more robust.
 
-  // DeclTypeTypeLoc::getSourceRange() is incomplete, which would lead to
-  // failing
-  // to descend into the child expression.
-  // decltype(2+2);
-  // ~ <-- correct range
-  //   <-- range reported by getSourceRange()
-  //   <-- range with this hack(i.e, missing closing paren)
-  // FIXME: Alter DecltypeTypeLoc to contain parentheses locations and get
-  // rid of this patch.
-  if (auto DT = TL->getAs())
-S.setEnd(DT.getUnderlyingExpr()->getEndLoc());
   // AttributedTypeLoc may point to the attribute's range, NOT the modified
   // type's range.
   if (auto AT = TL->getAs())
@@ -702,7 +708,7 @@
   void pop() {
 Node &N = *Stack.top();
 dlog("{1}pop: {0}", printNodeToString(N.ASTNode, PrintPolicy), indent(-1));
-claimRange(getSourceRange(N.ASTNode), N.Selected);
+claimTokensFor(N.ASTNode, N.Selected);
 if (N.Selected == NoTokens)
   N.Selected = SelectionTree::Unselected;
 if (N.Selected || !N.Children.empty()) {
@@ -744,6 +750,28 @@
 return SourceRange();
   }
 
+  // Claim tokens for N, after processing its children.
+  // By default this claims all unclaimed tokens in getSourceRange().
+  // We override this if we want to claim fewer tokens (e.g. there are gaps).
+  void claimTokensFor(const DynTypedNode &N, SelectionTree::Selection &Result) {
+if (const auto *TL = N.get()) {
+  // e.g. EltType Foo[OuterSize][InnerSize];
+  //  ~ ArrayType (Outer)
+  //  ~ |-ArrayType (Inner)
+  //  ~~~   | |-RecordType
+  // ~  | `-Expr
+  //  ~ `-Expr
+  // Inner must not claim its whole SourceRange, or it clobbers Outer.
+  if (TL->getAs()) {
+claimRange(TL->getLocalSourceRange(), Result);
+return;
+  }
+  // FIXME: maybe LocalSourceRange is a better default for TypeLocs.
+  // It doesn't seem to be usable for FunctionTypeLocs.
+}
+claimRange(getSourceRange(

[PATCH] D116511: [clang-cl] Support the /HOTPATCH flag

2022-01-03 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea updated this revision to Diff 397063.
aganea added a subscriber: saudi.
aganea added a comment.

Fix tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116511

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/patchable-function-entry.c
  clang/test/CodeGenCXX/debug-info-hotpatch.cpp
  clang/test/Driver/cl-options.c
  llvm/include/llvm/Target/TargetOptions.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp

Index: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -843,6 +843,8 @@
   if (MMI->getModule()->getProfileSummary(/*IsCS*/ false) != nullptr) {
 Flags |= static_cast(CompileSym3Flags::PGO);
   }
+  if (Asm->TM.Options.Hotpatch)
+Flags |= static_cast(CompileSym3Flags::HotPatch);
 
   OS.AddComment("Flags and language");
   OS.emitInt32(Flags);
Index: llvm/include/llvm/Target/TargetOptions.h
===
--- llvm/include/llvm/Target/TargetOptions.h
+++ llvm/include/llvm/Target/TargetOptions.h
@@ -140,9 +140,9 @@
   EnableMachineFunctionSplitter(false), SupportsDefaultOutlining(false),
   EmitAddrsig(false), EmitCallSiteInfo(false),
   SupportsDebugEntryValues(false), EnableDebugEntryValues(false),
-  ValueTrackingVariableLocations(false),
-  ForceDwarfFrameSection(false), XRayOmitFunctionIndex(false),
-  DebugStrictDwarf(false),
+  ValueTrackingVariableLocations(false), ForceDwarfFrameSection(false),
+  XRayOmitFunctionIndex(false), DebugStrictDwarf(false),
+  Hotpatch(false),
   FPDenormalMode(DenormalMode::IEEE, DenormalMode::IEEE) {}
 
 /// DisableFramePointerElim - This returns true if frame pointer elimination
@@ -342,6 +342,9 @@
 /// By default, it is set to false.
 unsigned DebugStrictDwarf : 1;
 
+/// Emit the hotpatch flag in CodeView debug.
+unsigned Hotpatch : 1;
+
 /// Name of the stack usage file (i.e., .su file) if user passes
 /// -fstack-usage. If empty, it can be implied that -fstack-usage is not
 /// passed on the command line.
Index: clang/test/Driver/cl-options.c
===
--- clang/test/Driver/cl-options.c
+++ clang/test/Driver/cl-options.c
@@ -118,6 +118,9 @@
 // RUN: %clang_cl /Gw /Gw- -### -- %s 2>&1 | FileCheck -check-prefix=Gw_ %s
 // Gw_-NOT: -fdata-sections
 
+// RUN: %clang_cl /hotpatch -### -- %s 2>&1 | FileCheck -check-prefix=hotpatch %s
+// hotpatch: -fhotpatch
+
 // RUN: %clang_cl /Imyincludedir -### -- %s 2>&1 | FileCheck -check-prefix=SLASH_I %s
 // RUN: %clang_cl /I myincludedir -### -- %s 2>&1 | FileCheck -check-prefix=SLASH_I %s
 // SLASH_I: "-I" "myincludedir"
Index: clang/test/CodeGenCXX/debug-info-hotpatch.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/debug-info-hotpatch.cpp
@@ -0,0 +1,13 @@
+// REQUIRES: x86-registered-target
+// RUN: %clang_cl --target=x86_64-windows-msvc /c /hotpatch /Z7 %s -o %t.obj
+// RUN: llvm-pdbutil dump -symbols %t.obj | FileCheck %s
+// RUN: %clang_cl --target=x86_64-windows-msvc /c /Z7 %s -o %t.obj
+// RUN: llvm-pdbutil dump -symbols %t.obj | FileCheck %s --check-prefix=NOHOTPATCH
+
+int main() {
+  return 0;
+}
+
+// CHECK: S_COMPILE3 [size = [[#]]]
+// CHECK: flags = hot patchable
+// NOHOTPATCH-NOT: flags = hot patchable
Index: clang/test/CodeGen/patchable-function-entry.c
===
--- clang/test/CodeGen/patchable-function-entry.c
+++ clang/test/CodeGen/patchable-function-entry.c
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -triple aarch64 -emit-llvm %s -o - | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64 -emit-llvm %s -fpatchable-function-entry=1 -o - | FileCheck --check-prefixes=CHECK,OPT %s
+// RUN: %clang_cc1 -triple x86_64 -emit-llvm %s -fhotpatch -o - | FileCheck --check-prefixes=HOTPATCH %s
 
 // CHECK: define{{.*}} void @f0() #0
 __attribute__((patchable_function_entry(0))) void f0() {}
@@ -34,3 +35,7 @@
 // CHECK: attributes #2 = { {{.*}} "patchable-function-entry"="0" "patchable-function-prefix"="4"
 // CHECK: attributes #3 = { {{.*}} "patchable-function-entry"="3" "patchable-function-prefix"="2"
 // OPT:   attributes #4 = { {{.*}} "patchable-function-entry"="1"
+// HOTPATCH: attributes #0 = { {{.*}} "patchable-function"="prologue-short-redirect"
+// HOTPATCH: attributes #1 = { {{.*}} "patchable-function"="prologue-short-redirect"
+// HOTPATCH: attributes #2 = { {{.*}} "patchable-function"="prologue-short-redirect"
+// HOTPATCH: attributes #

[clang] cd45e8c - [CodeCompletion] Signature help for template argument lists

2022-01-03 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-03T16:28:16+01:00
New Revision: cd45e8c7bc16dec2eeec9cc71eb3ba87d1bd6bab

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

LOG: [CodeCompletion] Signature help for template argument lists

Provide signature while typing template arguments: Foo< ^here >
Here the parameters are e.g. "typename x", and the result type is e.g.
"struct" (class template) or "int" (variable template) or "bool (std::string)"
(function template).

Multiple overloads are possible when a template name is used for several
overloaded function templates.

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

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

Added: 
clang/test/CodeCompletion/template-signature.cpp

Modified: 
clang-tools-extra/clangd/ClangdLSPServer.cpp
clang-tools-extra/clangd/CodeComplete.cpp
clang-tools-extra/clangd/test/initialize-params.test
clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/CodeCompleteConsumer.h
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParseExprCXX.cpp
clang/lib/Parse/ParseTemplate.cpp
clang/lib/Sema/CodeCompleteConsumer.cpp
clang/lib/Sema/SemaCodeComplete.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index 18539877ec976..774cdea218d00 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -555,7 +555,7 @@ void ClangdLSPServer::onInitialize(const InitializeParams 
&Params,
}},
   {"signatureHelpProvider",
llvm::json::Object{
-   {"triggerCharacters", {"(", ",", ")"}},
+   {"triggerCharacters", {"(", ",", ")", "<", ">"}},
}},
   {"declarationProvider", true},
   {"definitionProvider", true},

diff  --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 1c6b91e348280..bdfa1df194537 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -895,14 +895,12 @@ struct ScoredSignature {
 // part of it.
 int paramIndexForArg(const CodeCompleteConsumer::OverloadCandidate &Candidate,
  int Arg) {
-  int NumParams = 0;
+  int NumParams = Candidate.getNumParams();
   if (const auto *F = Candidate.getFunction()) {
-NumParams = F->getNumParams();
 if (F->isVariadic())
   ++NumParams;
   } else if (auto *T = Candidate.getFunctionType()) {
 if (auto *Proto = T->getAs()) {
-  NumParams = Proto->getNumParams();
   if (Proto->isVariadic())
 ++NumParams;
 }
@@ -1016,6 +1014,9 @@ class SignatureHelpCollector final : public 
CodeCompleteConsumer {
   return R.Quality.Kind != OC::CK_Function;
 case OC::CK_FunctionTemplate:
   return false;
+case OC::CK_Template:
+  assert(false && "Never see templates and other overloads mixed");
+  return false;
 }
 llvm_unreachable("Unknown overload candidate type.");
   }
@@ -1168,13 +1169,18 @@ class ParamNameCollector final : public 
CodeCompleteConsumer {
 
 for (unsigned I = 0; I < NumCandidates; ++I) {
   OverloadCandidate Candidate = Candidates[I];
-  auto *Func = Candidate.getFunction();
-  if (!Func || Func->getNumParams() <= CurrentArg)
-continue;
-  auto *PVD = Func->getParamDecl(CurrentArg);
-  if (!PVD)
+  NamedDecl *Param = nullptr;
+  if (auto *Func = Candidate.getFunction()) {
+if (CurrentArg < Func->getNumParams())
+  Param = Func->getParamDecl(CurrentArg);
+  } else if (auto *Template = Candidate.getTemplate()) {
+if (CurrentArg < Template->getTemplateParameters()->size())
+  Param = Template->getTemplateParameters()->getParam(CurrentArg);
+  }
+
+  if (!Param)
 continue;
-  auto *Ident = PVD->getIdentifier();
+  auto *Ident = Param->getIdentifier();
   if (!Ident)
 continue;
   auto Name = Ident->getName();

diff  --git a/clang-tools-extra/clangd/test/initialize-params.test 
b/clang-tools-extra/clangd/test/initialize-params.test
index a79f1075118ac..72823f3a0683d 100644
--- a/clang-tools-extra/clangd/test/initialize-params.test
+++ b/clang-tools-extra/clangd/test/initialize-params.test
@@ -108,7 +108,9 @@
 # CHECK-NEXT:"triggerCharacters": [
 # CHECK-NEXT:  "(",
 # CHECK-NEXT:  ",",
-# CHECK-NEXT:  ")"
+# CHECK-NEXT:  ")",
+# CHECK-NEXT:  "<",
+# CHECK-NEXT:  ">"
 # CHECK-NEXT:]
 # CHECK-NEXT:  },
 # CHECK-NEXT:  "textDocumentSync": {

diff  --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b

[PATCH] D116352: [CodeCompletion] Signature help for template argument lists

2022-01-03 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcd45e8c7bc16: [CodeCompletion] Signature help for template 
argument lists (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D116352?vs=397049&id=397064#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116352

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/test/initialize-params.test
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/CodeCompleteConsumer.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Parse/ParseTemplate.cpp
  clang/lib/Sema/CodeCompleteConsumer.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/template-signature.cpp

Index: clang/test/CodeCompletion/template-signature.cpp
===
--- /dev/null
+++ clang/test/CodeCompletion/template-signature.cpp
@@ -0,0 +1,28 @@
+template  float overloaded(int);
+template  bool overloaded(char);
+
+auto m = overloaded<1, 2>(0);
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:4:21 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
+// CHECK-CC1: OPENING_PAREN_LOC: {{.*}}4:20
+// CHECK-CC1-DAG: OVERLOAD: [#float#]overloaded<<#int#>, char y>[#()#]
+// CHECK-CC1-DAG: OVERLOAD: [#bool#]overloaded<<#class#>, int x>[#()#]
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:4:24 %s -o - | FileCheck -check-prefix=CHECK-CC2 %s
+// CHECK-CC2-NOT: OVERLOAD: {{.*}}int x
+// CHECK-CC2: OVERLOAD: [#float#]overloaded>[#()#]
+
+template  int n = 0;
+int val = n;
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:14:18 %s -o - | FileCheck -check-prefix=CHECK-CC3 %s
+// CHECK-CC3: OVERLOAD: [#int#]n>
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:14:24 %s -o - | FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: OVERLOAD: [#int#]n
+
+template  struct Vector {};
+template  class Container = Vector>
+struct Collection { Container container; };
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:22:31 %s -o - | FileCheck -check-prefix=CHECK-CC5 %s
+// CHECK-CC5: OVERLOAD: [#class#]Container<<#typename E#>>
+Collection collection;
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:25:12 %s -o - | FileCheck -check-prefix=CHECK-CC6 %s
+// CHECK-CC6: OVERLOAD: [#struct#]Collection<<#typename Element#>>
+
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -36,6 +36,7 @@
 #include "clang/Sema/Lookup.h"
 #include "clang/Sema/Overload.h"
 #include "clang/Sema/ParsedAttr.h"
+#include "clang/Sema/ParsedTemplate.h"
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/Sema.h"
@@ -3757,6 +3758,78 @@
   }
 }
 
+static std::string
+formatTemplateParameterPlaceholder(const NamedDecl *Param, bool &Optional,
+   const PrintingPolicy &Policy) {
+  if (const auto *Type = dyn_cast(Param)) {
+Optional = Type->hasDefaultArgument();
+  } else if (const auto *NonType = dyn_cast(Param)) {
+Optional = NonType->hasDefaultArgument();
+  } else if (const auto *Template = dyn_cast(Param)) {
+Optional = Template->hasDefaultArgument();
+  }
+  std::string Result;
+  llvm::raw_string_ostream OS(Result);
+  Param->print(OS, Policy);
+  return Result;
+}
+
+static std::string templateResultType(const TemplateDecl *TD,
+  const PrintingPolicy &Policy) {
+  if (const auto *CTD = dyn_cast(TD))
+return CTD->getTemplatedDecl()->getKindName().str();
+  if (const auto *VTD = dyn_cast(TD))
+return VTD->getTemplatedDecl()->getType().getAsString(Policy);
+  if (const auto *FTD = dyn_cast(TD))
+return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy);
+  if (isa(TD))
+return "type";
+  if (isa(TD))
+return "class";
+  if (isa(TD))
+return "concept";
+  return "";
+}
+
+static CodeCompletionString *createTemplateSignatureString(
+const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg,
+const PrintingPolicy &Policy) {
+  llvm::ArrayRef Params = TD->getTemplateParameters()->asArray();
+  CodeCompletionBuilder OptionalBuilder(Builder.getAllocator(),
+Builder.getCodeCompletionTUInfo());
+  std::string ResultType = templateResultType(TD, Policy);
+  if (!ResultType.empty())
+Builder.AddResultTypeChunk(Builder.getAllocator().CopyString(ResultType));
+  Builder.AddTextChunk(
+  Builder.getAllocator().CopyString(TD->getNameAsString()));
+  Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
+  // Initially we'

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

2022-01-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Mostly just minor nits at this point. Please be sure to update the 
documentation and add a release note about the changes.




Comment at: 
clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp:1
+
 //===--- UseDefaultMemberInitCheck.cpp - 
clang-tidy===//

Spurious newline?



Comment at: 
clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp:251
+  // it is hard to reconcile their sets of member initializers.
+  auto ClassDecl = dyn_cast(Field->getParent());
+  if (std::count_if(ClassDecl->ctors().begin(), ClassDecl->ctors().end(),





Comment at: 
clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp:252-253
+  auto ClassDecl = dyn_cast(Field->getParent());
+  if (std::count_if(ClassDecl->ctors().begin(), ClassDecl->ctors().end(),
+[](const auto Ctor) { return 
!Ctor->isCopyOrMoveConstructor(); }) > 1)
+return;




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114995

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


[PATCH] D116147: [clangd] Respect .clang-tidy ExtraArgs (-Wfoo only) when producing diagnostics

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

thanks, lgtm!




Comment at: clang-tools-extra/clangd/ParsedAST.cpp:270
+// We don't want this, so keep track of them to fix afterwards.
+llvm::DenseSet NeedsWerrorExclusion;
+for (diag::kind ID : Members) {

why do we need a set here, rather than a flag?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116147

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


[PATCH] D115936: [Clang] Add isInNamespace() to check if a Decl in a specific namespace

2022-01-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

These changes lack test coverage or uses of the new API, so it's a bit hard to 
tell whether it's being used correctly or not.




Comment at: clang/include/clang/AST/DeclBase.h:466
   bool isInStdNamespace() const;
+  bool isInNamespace(llvm::StringRef Namespace) const;
 

I think this API needs some comments and explanation. Is the given namespace 
expected to be fully qualified or will this match partial namespaces? Is it 
checking whether the declaration is lexically in the namespace or semantically? 
How does it handle inline namespaces? That sort of thing. e.g.,
```
namespace foo {
void decl();

namespace bar {
int x; // Does isInNamespace("foo") return true for this declaration?
}

inline namespace baz {
int y; // Does isInNamespace("foo") return true for this declaration?
}
}

void foo::decl() {} // Does isInNamespace("foo") return true for this specific 
declaration?
```



Comment at: clang/lib/AST/DeclBase.cpp:396
+
+bool Decl::isInNamespace(llvm::StringRef Namespace) const {
   const DeclContext *DC = getDeclContext();

Same concerns here as above. It's not at all clear what "in" means for this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115936

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


[clang] 4435d18 - [ARM][AArch64] clang support for Armv9.3-A

2022-01-03 Thread Tomas Matheson via cfe-commits

Author: Tomas Matheson
Date: 2022-01-03T16:02:36Z
New Revision: 4435d1819efec06e11461799fe83d6f148b098f4

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

LOG: [ARM][AArch64] clang support for Armv9.3-A

This patch introduces support for targetting the Armv9.3-A architecture,
which should map to the existing Armv8.8-A extensions.

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

Added: 


Modified: 
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/Basic/Targets/AArch64.h
clang/lib/Basic/Targets/ARM.cpp
clang/lib/Driver/ToolChains/Arch/AArch64.cpp
clang/test/Driver/aarch64-cpus.c
clang/test/Driver/arm-cortex-cpus.c
clang/test/Preprocessor/arm-target-features.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index d7eb770995cbb..334ff584c9e3a 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -45,6 +45,7 @@ static StringRef getArchVersionString(llvm::AArch64::ArchKind 
Kind) {
   case llvm::AArch64::ArchKind::ARMV9A:
   case llvm::AArch64::ArchKind::ARMV9_1A:
   case llvm::AArch64::ArchKind::ARMV9_2A:
+  case llvm::AArch64::ArchKind::ARMV9_3A:
 return "9";
   default:
 return "8";
@@ -247,6 +248,12 @@ void AArch64TargetInfo::getTargetDefinesARMV92A(const 
LangOptions &Opts,
   getTargetDefinesARMV87A(Opts, Builder);
 }
 
+void AArch64TargetInfo::getTargetDefinesARMV93A(const LangOptions &Opts,
+MacroBuilder &Builder) const {
+  // Armv9.3-A maps to Armv8.8-A
+  getTargetDefinesARMV88A(Opts, Builder);
+}
+
 void AArch64TargetInfo::getTargetDefines(const LangOptions &Opts,
  MacroBuilder &Builder) const {
   // Target identification.
@@ -464,6 +471,9 @@ void AArch64TargetInfo::getTargetDefines(const LangOptions 
&Opts,
   case llvm::AArch64::ArchKind::ARMV9_2A:
 getTargetDefinesARMV92A(Opts, Builder);
 break;
+  case llvm::AArch64::ArchKind::ARMV9_3A:
+getTargetDefinesARMV93A(Opts, Builder);
+break;
   }
 
   // All of the __sync_(bool|val)_compare_and_swap_(1|2|4|8) builtins work.
@@ -620,6 +630,8 @@ bool 
AArch64TargetInfo::handleTargetFeatures(std::vector &Features,
   ArchKind = llvm::AArch64::ArchKind::ARMV9_1A;
 if (Feature == "+v9.2a")
   ArchKind = llvm::AArch64::ArchKind::ARMV9_2A;
+if (Feature == "+v9.3a")
+  ArchKind = llvm::AArch64::ArchKind::ARMV9_3A;
 if (Feature == "+v8r")
   ArchKind = llvm::AArch64::ArchKind::ARMV8R;
 if (Feature == "+fullfp16")

diff  --git a/clang/lib/Basic/Targets/AArch64.h 
b/clang/lib/Basic/Targets/AArch64.h
index 6bc0ea4eb5e11..43e5b6fe2de09 100644
--- a/clang/lib/Basic/Targets/AArch64.h
+++ b/clang/lib/Basic/Targets/AArch64.h
@@ -100,6 +100,8 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
MacroBuilder &Builder) const;
   void getTargetDefinesARMV92A(const LangOptions &Opts,
MacroBuilder &Builder) const;
+  void getTargetDefinesARMV93A(const LangOptions &Opts,
+   MacroBuilder &Builder) const;
   void getTargetDefines(const LangOptions &Opts,
 MacroBuilder &Builder) const override;
 

diff  --git a/clang/lib/Basic/Targets/ARM.cpp b/clang/lib/Basic/Targets/ARM.cpp
index bb0044bdc5961..478a0233398dc 100644
--- a/clang/lib/Basic/Targets/ARM.cpp
+++ b/clang/lib/Basic/Targets/ARM.cpp
@@ -220,6 +220,8 @@ StringRef ARMTargetInfo::getCPUAttr() const {
 return "9_1A";
   case llvm::ARM::ArchKind::ARMV9_2A:
 return "9_2A";
+  case llvm::ARM::ArchKind::ARMV9_3A:
+return "9_3A";
   case llvm::ARM::ArchKind::ARMV8MBaseline:
 return "8M_BASE";
   case llvm::ARM::ArchKind::ARMV8MMainline:
@@ -936,6 +938,7 @@ void ARMTargetInfo::getTargetDefines(const LangOptions 
&Opts,
   case llvm::ARM::ArchKind::ARMV9A:
   case llvm::ARM::ArchKind::ARMV9_1A:
   case llvm::ARM::ArchKind::ARMV9_2A:
+  case llvm::ARM::ArchKind::ARMV9_3A:
 getTargetDefinesARMV83A(Opts, Builder);
 break;
   }

diff  --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp 
b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
index 8cb9318df4cd3..9ffb5d73b2aad 100644
--- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -104,7 +104,8 @@ static bool DecodeAArch64Features(const Driver &D, 
StringRef text,
  ArchKind == llvm::AArch64::ArchKind::ARMV8_7A ||
  ArchKind == llvm::AArch64::ArchKind::ARMV8_8A ||
  ArchKind == llvm::AArch64::ArchKind::ARMV9_1A ||
- ArchKind == llvm::AArch64::ArchKind::ARMV9_2A) &&
+ ArchKind == llvm::AArch64::ArchKind::ARMV9_2A ||
+ ArchKind == llvm::A

[PATCH] D116159: [ARM][AArch64] clang support for Armv9.3-A

2022-01-03 Thread Tomas Matheson 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 rG4435d1819efe: [ARM][AArch64] clang support for Armv9.3-A 
(authored by tmatheson).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116159

Files:
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Basic/Targets/AArch64.h
  clang/lib/Basic/Targets/ARM.cpp
  clang/lib/Driver/ToolChains/Arch/AArch64.cpp
  clang/test/Driver/aarch64-cpus.c
  clang/test/Driver/arm-cortex-cpus.c
  clang/test/Preprocessor/arm-target-features.c

Index: clang/test/Preprocessor/arm-target-features.c
===
--- clang/test/Preprocessor/arm-target-features.c
+++ clang/test/Preprocessor/arm-target-features.c
@@ -879,6 +879,11 @@
 // CHECK-V92A: #define __ARM_ARCH_9_2A__ 1
 // CHECK-V92A: #define __ARM_ARCH_PROFILE 'A'
 
+// RUN: %clang -target armv9.3a-none-none-eabi -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-V93A %s
+// CHECK-V93A: #define __ARM_ARCH 9
+// CHECK-V93A: #define __ARM_ARCH_9_3A__ 1
+// CHECK-V93A: #define __ARM_ARCH_PROFILE 'A'
+
 // RUN: %clang -target arm-none-none-eabi -march=armv7-m -mfpu=softvfp -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-SOFTVFP %s
 // CHECK-SOFTVFP-NOT: #define __ARM_FP 0x
 
Index: clang/test/Driver/arm-cortex-cpus.c
===
--- clang/test/Driver/arm-cortex-cpus.c
+++ clang/test/Driver/arm-cortex-cpus.c
@@ -437,6 +437,22 @@
 // RUN: %clang -target arm -march=armebv9.2-a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V92A %s
 // CHECK-BE-V92A: "-cc1"{{.*}} "-triple" "armebv9.2{{.*}}" "-target-cpu" "generic"
 
+// RUN: %clang -target armv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V93A %s
+// RUN: %clang -target arm -march=armv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V93A %s
+// RUN: %clang -target arm -march=armv9.3-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V93A %s
+// RUN: %clang -target armv9.3a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V93A %s
+// RUN: %clang -target arm -march=armv9.3a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V93A %s
+// RUN: %clang -target arm -march=armv9.3-a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V93A %s
+// CHECK-V93A: "-cc1"{{.*}} "-triple" "armv9.3{{.*}}" "-target-cpu" "generic"
+
+// RUN: %clang -target armebv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V93A %s
+// RUN: %clang -target armv9.3a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V93A %s
+// RUN: %clang -target armeb -march=armebv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V93A %s
+// RUN: %clang -target armeb -march=armebv9.3-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V93A %s
+// RUN: %clang -target arm -march=armebv9.3a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V93A %s
+// RUN: %clang -target arm -march=armebv9.3-a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V93A %s
+// CHECK-BE-V93A: "-cc1"{{.*}} "-triple" "armebv9.3{{.*}}" "-target-cpu" "generic"
+
 // Once we have CPUs with optional v8.2-A FP16, we will need a way to turn it
 // on and off. Cortex-A53 is a placeholder for now.
 // RUN: %clang -target armv8a-linux-eabi -mcpu=cortex-a53+fp16 -### -c %s 2>&1 | FileCheck --check-prefix CHECK-CORTEX-A53-FP16 %s
Index: clang/test/Driver/aarch64-cpus.c
===
--- clang/test/Driver/aarch64-cpus.c
+++ clang/test/Driver/aarch64-cpus.c
@@ -876,6 +876,22 @@
 // RUN: %clang -target aarch64_be -mbig-endian -march=armv9.2-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV92A-BE %s
 // GENERICV92A-BE: "-cc1"{{.*}} "-triple" "aarch64_be{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v9.2a" "-target-feature" "+i8mm" "-target-feature" "+bf16" "-target-feature" "+sve" "-target-feature" "+sve2"
 
+// RUN: %clang -target aarch64 -march=armv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A %s
+// RUN: %clang -target aarch64 -march=armv9.3-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A %s
+// RUN: %clang -target aarch64 -mlittle-endian -march=armv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A %s
+// RUN: %clang -target aarch64 -mlittle-endian -march=armv9.3-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A %s
+// RUN: %clang -target aarch64_be -mlittle-endian -march=armv9.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A %s
+// RUN: %clang -target aarch64_be -mlittle-endian -march=armv9.3-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV93A %s
+// GENERICV93A: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v9.3a"
+
+// RUN: %clang -target aarch64_

[clang] 7505aee - [clang] Pacify GCC warning. NFC.

2022-01-03 Thread Michael Liao via cfe-commits

Author: Michael Liao
Date: 2022-01-03T11:05:36-05:00
New Revision: 7505aeefc4e615520e2c822b9647dad4a48276b9

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

LOG: [clang] Pacify GCC warning. NFC.

- This partially reverts d677a7cb056b17145a50ec8ca2ab6d5f4c494749 to
  pacify GCC warnings like
  ```
  base class should be explicitly initialized in the copy constructor
  ```
- Shall we keep turning on option `IgnoreBaseInCopyConstructors` when
  enabling `readability-redundant-member-init` check?

Added: 


Modified: 
clang/include/clang/Basic/Diagnostic.h
clang/include/clang/Basic/PartialDiagnostic.h

Removed: 




diff  --git a/clang/include/clang/Basic/Diagnostic.h 
b/clang/include/clang/Basic/Diagnostic.h
index 6a80823d12422..e5577e74fa639 100644
--- a/clang/include/clang/Basic/Diagnostic.h
+++ b/clang/include/clang/Basic/Diagnostic.h
@@ -1326,7 +1326,7 @@ class DiagnosticBuilder : public StreamingDiagnostic {
 public:
   /// Copy constructor.  When copied, this "takes" the diagnostic info from the
   /// input and neuters it.
-  DiagnosticBuilder(const DiagnosticBuilder &D) {
+  DiagnosticBuilder(const DiagnosticBuilder &D) : StreamingDiagnostic() {
 DiagObj = D.DiagObj;
 DiagStorage = D.DiagStorage;
 IsActive = D.IsActive;

diff  --git a/clang/include/clang/Basic/PartialDiagnostic.h 
b/clang/include/clang/Basic/PartialDiagnostic.h
index 217441979869b..9fb70bff7fee1 100644
--- a/clang/include/clang/Basic/PartialDiagnostic.h
+++ b/clang/include/clang/Basic/PartialDiagnostic.h
@@ -49,7 +49,8 @@ class PartialDiagnostic : public StreamingDiagnostic {
   PartialDiagnostic(unsigned DiagID, DiagStorageAllocator &Allocator_)
   : StreamingDiagnostic(Allocator_), DiagID(DiagID) {}
 
-  PartialDiagnostic(const PartialDiagnostic &Other) : DiagID(Other.DiagID) {
+  PartialDiagnostic(const PartialDiagnostic &Other)
+  : StreamingDiagnostic(), DiagID(Other.DiagID) {
 Allocator = Other.Allocator;
 if (Other.DiagStorage) {
   DiagStorage = getStorage();



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


[PATCH] D116488: Add a misc-unused-parameters.CommentOutUnusedParameters to clang-tidy

2022-01-03 Thread Jeff Niu via Phabricator via cfe-commits
Mogball added inline comments.



Comment at: clang-tools-extra/clang-tidy/misc/UnusedParametersCheck.cpp:157
 // will clean this up afterwards.
-MyDiag << FixItHint::CreateReplacement(
-RemovalRange, (Twine(" /*") + Param->getName() + "*/").str());
+if (Options.get("CommentOutUnusedParameters", true))
+  MyDiag << FixItHint::CreateReplacement(

Oh I was thinking that the option would disable editing the parameter at all. 
I.e. it would leave unused parameters untouched or remove the parameter from 
the function signature altogether (if it can).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116488

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


[PATCH] D116313: [MSVC] Silence -Wnon-virtual-dtor on DIA APIs

2022-01-03 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea updated this revision to Diff 397069.
aganea marked 2 inline comments as done.
aganea added a comment.
Herald added subscribers: hiraditya, mgorny.

As suggested by @hans


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116313

Files:
  clang/lib/Driver/ToolChains/MSVCSetupApi.h
  llvm/lib/DebugInfo/PDB/CMakeLists.txt


Index: llvm/lib/DebugInfo/PDB/CMakeLists.txt
===
--- llvm/lib/DebugInfo/PDB/CMakeLists.txt
+++ llvm/lib/DebugInfo/PDB/CMakeLists.txt
@@ -4,7 +4,7 @@
 endmacro()
 
 if(LLVM_ENABLE_DIA_SDK)
-  include_directories(${MSVC_DIA_SDK_DIR}/include)
+  include_directories(SYSTEM ${MSVC_DIA_SDK_DIR}/include)
   set(LIBPDB_LINK_FOLDERS "${MSVC_DIA_SDK_DIR}\\lib")
 
   if ("$ENV{VSCMD_ARG_TGT_ARCH}" STREQUAL "arm64")
Index: clang/lib/Driver/ToolChains/MSVCSetupApi.h
===
--- clang/lib/Driver/ToolChains/MSVCSetupApi.h
+++ clang/lib/Driver/ToolChains/MSVCSetupApi.h
@@ -28,6 +28,11 @@
 
 #pragma once
 
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wnon-virtual-dtor"
+#endif
+
 // Constants
 //
 #ifndef E_NOTFOUND
@@ -512,3 +517,7 @@
 #ifdef __cplusplus
 }
 #endif
+
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif


Index: llvm/lib/DebugInfo/PDB/CMakeLists.txt
===
--- llvm/lib/DebugInfo/PDB/CMakeLists.txt
+++ llvm/lib/DebugInfo/PDB/CMakeLists.txt
@@ -4,7 +4,7 @@
 endmacro()
 
 if(LLVM_ENABLE_DIA_SDK)
-  include_directories(${MSVC_DIA_SDK_DIR}/include)
+  include_directories(SYSTEM ${MSVC_DIA_SDK_DIR}/include)
   set(LIBPDB_LINK_FOLDERS "${MSVC_DIA_SDK_DIR}\\lib")
 
   if ("$ENV{VSCMD_ARG_TGT_ARCH}" STREQUAL "arm64")
Index: clang/lib/Driver/ToolChains/MSVCSetupApi.h
===
--- clang/lib/Driver/ToolChains/MSVCSetupApi.h
+++ clang/lib/Driver/ToolChains/MSVCSetupApi.h
@@ -28,6 +28,11 @@
 
 #pragma once
 
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wnon-virtual-dtor"
+#endif
+
 // Constants
 //
 #ifndef E_NOTFOUND
@@ -512,3 +517,7 @@
 #ifdef __cplusplus
 }
 #endif
+
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116313: [MSVC] Silence -Wnon-virtual-dtor on DIA APIs

2022-01-03 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea added inline comments.



Comment at: llvm/include/llvm/DebugInfo/PDB/DIA/DIASupport.h:34
+#endif
 #include 
+#ifdef __clang__

hans wrote:
> I thought this warning should be suppressed for system headers. Isn't that 
> working here?
Good point, because it wasn't included as a system header in the first place.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116313

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


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

2022-01-03 Thread Maurice Heumann via Phabricator via cfe-commits
momo5502 added a comment.

In D115456#3216811 , @majnemer wrote:

> This is looking great! Just a few more questions.
>
> What is the behavior with something like:
>
>   thread_local int x = 2;
>   int f() {
> return x;
>   }
>
> I'm wondering if we need to move this logic 
> 
>  into the generic C++ ABI implementation.

The MS compiler only emits the dynamic initializers for variables with 
constructors/destructors, just like it is currently done here for the Itanium 
ABI.
I also thought about adopting that behaviour, but I think threre are edge-cases 
when triggering dynamic TLS initialization even for constant variables is 
useful.
For example there might be custom TLS callbacks that can affect the value of 
this variable.

If desired, I can change it to match the behaviour of MS, but I thought it 
could be beneficial to diverge in this case.


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] D116154: [ARM] Adding macros for coprocessor intrinsics as per ACLE

2022-01-03 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson updated this revision to Diff 397071.
tmatheson added a comment.

Add 8.8 and 9.3; patches adding these were merged first in the end.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116154

Files:
  clang/lib/Basic/Targets/ARM.cpp
  clang/lib/Headers/arm_acle.h
  clang/test/CodeGen/arm-acle-coproc.c
  clang/test/Preprocessor/aarch64-target-features.c

Index: clang/test/Preprocessor/aarch64-target-features.c
===
--- clang/test/Preprocessor/aarch64-target-features.c
+++ clang/test/Preprocessor/aarch64-target-features.c
@@ -43,6 +43,7 @@
 // CHECK-NOT: __ARM_PCS_VFP 1
 // CHECK-NOT: __ARM_SIZEOF_MINIMAL_ENUM 1
 // CHECK-NOT: __ARM_SIZEOF_WCHAR_T 2
+// CHECK-NOT: __ARM_TARGET_COPROC 1
 // CHECK-NOT: __ARM_FEATURE_SVE
 // CHECK-NOT: __ARM_FEATURE_DOTPROD
 // CHECK-NOT: __ARM_FEATURE_PAC_DEFAULT
Index: clang/test/CodeGen/arm-acle-coproc.c
===
--- /dev/null
+++ clang/test/CodeGen/arm-acle-coproc.c
@@ -0,0 +1,350 @@
+// RUN: %clang_cc1 -triple armv4 %s -E -dD -o - | FileCheck --check-prefix=CHECK-V4 %s
+// RUN: %clang_cc1 -triple armv4t %s -E -dD -o - | FileCheck --check-prefix=CHECK-V4 %s
+// RUN: %clang_cc1 -triple armv5 %s -E -dD -o - | FileCheck --check-prefix=CHECK-V5 %s
+// RUN: %clang_cc1 -triple armv5te %s -E -dD -o - | FileCheck --check-prefix=CHECK-V5-TE %s
+// RUN: %clang_cc1 -triple armv5tej %s -E -dD -o - | FileCheck --check-prefix=CHECK-V5-TE %s
+// RUN: %clang_cc1 -triple armv6 %s -E -dD -o - | FileCheck --check-prefix=CHECK-V6 %s
+// RUN: %clang_cc1 -triple armv6m %s -E -dD -o - | FileCheck --check-prefix=CHECK-V6M %s
+// RUN: %clang_cc1 -triple armv7a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V7 %s
+// RUN: %clang_cc1 -triple armv7r %s -E -dD -o - | FileCheck --check-prefix=CHECK-V7 %s
+// RUN: %clang_cc1 -triple armv7m %s -E -dD -o - | FileCheck --check-prefix=CHECK-V7 %s
+// RUN: %clang_cc1 -triple armv8a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple armv8r %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple armv8.1a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple armv8.2a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple armv8.3a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple armv8.4a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple armv8.5a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple armv8.6a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple armv8.7a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple thumbv4 %s -E -dD -o - | FileCheck --check-prefix=CHECK-V4-THUMB %s
+// RUN: %clang_cc1 -triple thumbv4t %s -E -dD -o - | FileCheck --check-prefix=CHECK-V4-THUMB %s
+// RUN: %clang_cc1 -triple thumbv5 %s -E -dD -o - | FileCheck --check-prefix=CHECK-V5-THUMB %s
+// RUN: %clang_cc1 -triple thumbv5te %s -E -dD -o - | FileCheck --check-prefix=CHECK-V5-TE-THUMB %s
+// RUN: %clang_cc1 -triple thumbv5tej %s -E -dD -o - | FileCheck --check-prefix=CHECK-V5-TE-THUMB %s
+// RUN: %clang_cc1 -triple thumbv6 %s -E -dD -o - | FileCheck --check-prefix=CHECK-V6-THUMB %s
+// RUN: %clang_cc1 -triple thumbv6k %s -E -dD -o - | FileCheck --check-prefix=CHECK-V6-THUMB %s
+// RUN: %clang_cc1 -triple thumbv6kz %s -E -dD -o - | FileCheck --check-prefix=CHECK-V6-THUMB %s
+// RUN: %clang_cc1 -triple thumbv6m %s -E -dD -o - | FileCheck --check-prefix=CHECK-V6M %s
+// RUN: %clang_cc1 -triple thumbv7a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V7 %s
+// RUN: %clang_cc1 -triple thumbv7r %s -E -dD -o - | FileCheck --check-prefix=CHECK-V7 %s
+// RUN: %clang_cc1 -triple thumbv7m %s -E -dD -o - | FileCheck --check-prefix=CHECK-V7 %s
+// RUN: %clang_cc1 -triple thumbv8a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple thumbv8.1a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple thumbv8.2a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple thumbv8.3a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple thumbv8.4a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple thumbv8.5a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple thumbv8.6a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple thumbv8.7a %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple thumbv8r %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8 %s
+// RUN: %clang_cc1 -triple thumbv8m.base %s -E -dD -o - | FileCheck --check-prefix=CHECK-V8-BASE %s
+// RUN: %clang_cc1 -triple thumbv8m.main %s -E -dD -o - | 

[PATCH] D111545: [Clang][NFC] Fix multiline comment prefixes in function headers

2022-01-03 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam updated this revision to Diff 397073.
saiislam added a comment.

Updated comments as per suggestion. Apologies for the delay.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111545

Files:
  clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp


Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -752,8 +752,9 @@
 
 addOpenMPDeviceRTL(getDriver(), DriverArgs, CC1Args, BitcodeSuffix,
getTriple());
-AddStaticDeviceLibsPostLinking(getDriver(), DriverArgs, CC1Args, "nvptx", 
GpuArch,
-/* bitcode SDL?*/ true, /* PostClang Link? */ true);
+AddStaticDeviceLibsPostLinking(getDriver(), DriverArgs, CC1Args, "nvptx",
+   GpuArch, /*bitcode SDL=*/true,
+   /*PostClang Link=*/true);
   }
 }
 
Index: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
+++ clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
@@ -131,9 +131,8 @@
   }
 
   AddStaticDeviceLibsLinking(C, *this, JA, Inputs, Args, CmdArgs, "amdgcn",
-  SubArchName,
-  /* bitcode SDL?*/ true,
-  /* PostClang Link? */ false);
+ SubArchName, /* bitcode SDL=*/true,
+ /* PostClang Link=*/false);
   // Add an intermediate output file.
   CmdArgs.push_back("-o");
   const char *OutputFileName =


Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -752,8 +752,9 @@
 
 addOpenMPDeviceRTL(getDriver(), DriverArgs, CC1Args, BitcodeSuffix,
getTriple());
-AddStaticDeviceLibsPostLinking(getDriver(), DriverArgs, CC1Args, "nvptx", GpuArch,
-/* bitcode SDL?*/ true, /* PostClang Link? */ true);
+AddStaticDeviceLibsPostLinking(getDriver(), DriverArgs, CC1Args, "nvptx",
+   GpuArch, /*bitcode SDL=*/true,
+   /*PostClang Link=*/true);
   }
 }
 
Index: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
+++ clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
@@ -131,9 +131,8 @@
   }
 
   AddStaticDeviceLibsLinking(C, *this, JA, Inputs, Args, CmdArgs, "amdgcn",
-  SubArchName,
-  /* bitcode SDL?*/ true,
-  /* PostClang Link? */ false);
+ SubArchName, /* bitcode SDL=*/true,
+ /* PostClang Link=*/false);
   // Add an intermediate output file.
   CmdArgs.push_back("-o");
   const char *OutputFileName =
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116326: [CodeCompletion] Signature help for aggregate initialization.

2022-01-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 397075.
sammccall marked an inline comment as done.
sammccall added a comment.

address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116326

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang/include/clang/Sema/CodeCompleteConsumer.h
  clang/lib/Sema/CodeCompleteConsumer.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/ctor-signature.cpp

Index: clang/test/CodeCompletion/ctor-signature.cpp
===
--- clang/test/CodeCompletion/ctor-signature.cpp
+++ clang/test/CodeCompletion/ctor-signature.cpp
@@ -42,13 +42,29 @@
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:41:22 %s | FileCheck -check-prefix=CHECK-BRACED %s
 
 struct Aggregate {
-  // FIXME: no support for aggregates yet.
-  // CHECK-AGGREGATE-NOT: OVERLOAD: Aggregate{<#const Aggregate &#>}
-  // CHECK-AGGREGATE-NOT: OVERLOAD: {{.*}}first
   int first;
   int second;
+  int third;
 };
 
-Aggregate a{};
-// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:52:13 %s | FileCheck -check-prefix=CHECK-AGGREGATE %s
+Aggregate a{1, 2, 3};
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:50:13 %s | FileCheck -check-prefix=CHECK-AGGREGATE-1 %s
+// CHECK-AGGREGATE-1: OVERLOAD: Aggregate{<#int first#>, int second, int third}
+// CHECK-AGGREGATE-1: OVERLOAD: Aggregate{<#const Aggregate &#>}
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:50:16 %s | FileCheck -check-prefix=CHECK-AGGREGATE-2 %s
+// CHECK-AGGREGATE-2: OVERLOAD: Aggregate{int first, <#int second#>, int third}
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:50:18 %s | FileCheck -check-prefix=CHECK-AGGREGATE-3 %s
+// CHECK-AGGREGATE-3: OVERLOAD: Aggregate{int first, int second, <#int third#>}
 
+Aggregate d{.second=1, .first=2, 3, 4, };
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:59:13 %s | FileCheck -check-prefix=CHECK-DESIG-1 %s
+// CHECK-DESIG-1: OVERLOAD: Aggregate{<#int first#>, int second, int third}
+// CHECK-DESIG-1: OVERLOAD: Aggregate{<#const Aggregate &#>}
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:59:24 %s | FileCheck -check-prefix=CHECK-DESIG-2 %s
+// CHECK-DESIG-2: OVERLOAD: Aggregate{int first, int second, <#int third#>}
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:59:34 %s | FileCheck -check-prefix=CHECK-DESIG-3 %s
+// CHECK-DESIG-3: OVERLOAD: Aggregate{int first, <#int second#>, int third}
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:59:37 %s | FileCheck -check-prefix=CHECK-DESIG-4 %s
+// CHECK-DESIG-4: OVERLOAD: Aggregate{int first, int second, <#int third#>}
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:59:38 %s | FileCheck -check-prefix=CHECK-DESIG-5 %s --allow-empty
+// CHECK-DESIG-5-NOT: OVERLOAD
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -2817,14 +2817,18 @@
Optional> ObjCSubsts = None);
 
 static std::string
-FormatFunctionParameter(const PrintingPolicy &Policy, const ParmVarDecl *Param,
-bool SuppressName = false, bool SuppressBlock = false,
+FormatFunctionParameter(const PrintingPolicy &Policy,
+const DeclaratorDecl *Param, bool SuppressName = false,
+bool SuppressBlock = false,
 Optional> ObjCSubsts = None) {
   // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
   // It would be better to pass in the param Type, which is usually available.
   // But this case is rare, so just pretend we fell back to int as elsewhere.
   if (!Param)
 return "int";
+  Decl::ObjCDeclQualifier ObjCQual = Decl::OBJC_TQ_None;
+  if (const auto *PVD = dyn_cast(Param))
+ObjCQual = PVD->getObjCDeclQualifier();
   bool ObjCMethodParam = isa(Param->getDeclContext());
   if (Param->getType()->isDependentType() ||
   !Param->getType()->isBlockPointerType()) {
@@ -2840,8 +2844,7 @@
   Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
 ObjCSubstitutionContext::Parameter);
 if (ObjCMethodParam) {
-  Result =
-  "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type);
+  Result = "(" + formatObjCParamQualifiers(ObjCQual, Type);
   Result += Type.getAsString(Policy) + ")";
   if (Param->getIdentifier() && !SuppressName)
 Result += Param->getIdentifier()->getName();
@@ -2878,8 +2881,7 @@
 
 if (ObjCMethodParam) {
   Result = Type.getAsString(Policy);
-  std::string Quals =
-  formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type);
+  std::string Quals = formatObjCParamQualifiers(ObjCQual, Type);

[PATCH] D116326: [CodeCompletion] Signature help for aggregate initialization.

2022-01-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 2 inline comments as done.
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/CodeComplete.cpp:1184
-  auto Name = Ident->getName();
-  if (!Name.empty())
-ParamNames.insert(Name.str());

kadircet wrote:
> we were never recording unnamed params before, now they'll be surfaced during 
> comment code completions. can you either keep dropping them here or on the 
> code completion generation side (~line 1997)
I don't think I've changed behavior here, if there's no name then the 
IdentifierInfo is nullptr



Comment at: clang/include/clang/Sema/CodeCompleteConsumer.h:1057
+: Kind(CK_Aggregate), AggregateType(Aggregate) {
+  assert(Aggregate != nullptr);
+}

kadircet wrote:
> we don't have assertions in other cases, why here? (i think we should have it 
> in other cases too, just wondering if there are any valid states where we 
> construct an overloadcandidate from nullptr)
I can't remember why I added it now!
I've added the others, tests still pass.



Comment at: clang/lib/Sema/CodeCompleteConsumer.cpp:522
+if (const auto *CRD = dyn_cast(AggregateType))
+  Count += CRD->getNumBases();
+return Count;

kadircet wrote:
> i think this is only valid for c++17 onwards `If the number of initializer 
> clauses exceeds the number of members and bases (since C++17) to initialize, 
> the program is ill-formed.` (same for param type/decl)
> 
> it gets even more complicated, since one doesn't have to nest initialization 
> of base class fields, e.g this is valid:
> ```
> struct X
> {
> int a;
> int b;
> };
> 
> struct Y : X
> {
> int c;
> };
> 
> Y y1{ {1,2}, 3};
> Y y2{ 1, 2, 3 }; // both of these set a=1, b=2, c=3
> ```
> i think this is only valid for c++17 onwards

We only get here for aggregate types, and pre-C++17 those are guaranteed to 
have no bases.

> one doesn't have to nest initialization of base class fields

Great catch, somehow I missed this in the spec. This makes things very 
complicated. Why on earth is this allowed?! (After some digging, compatibility 
with C99)

I can't see a reasonable way to support this. If it were just bases I'd drop 
support for them, but it applies to fields too.
The implementation difficulty is having to do full conversion-sequence checks 
for each element to tell whether it is a standalone element or the first in an 
implied nested list.

This elision is slightly discouraged (-Wmissing-braces in in -Wall) so I think 
it's OK to give results that are going to be a bit off if brace-elision is used.
If there are a lot of complaints we could try to detect this in future.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116326

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


[clang-tools-extra] 9e6f88b - [clangd] Respect .clang-tidy ExtraArgs (-Wfoo only) when producing diagnostics

2022-01-03 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-03T17:58:41+01:00
New Revision: 9e6f88b31a7f7957a850d3541ffa759f2993ffc1

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

LOG: [clangd] Respect .clang-tidy ExtraArgs (-Wfoo only) when producing 
diagnostics

This mechanism is used almost exclusively to enable extra warnings in clang-tidy
using ExtraArgs=-Wfoo, Checks="clang-diagnostic-foo".
Its presence is a strong signal that these flags are useful.

We choose not to actually emit them as clang-tidy diagnostics, but under their
"main" name - this ensures we show the same diagnostic in a consistent way.

We don't add the ExtraArgs to the compile command in general, but rather just
handle the -W flags, which is the common case and avoids unexpected
side-effects.
And we only do this for the main file parse, when producing diagnostics.

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

Added: 


Modified: 
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ParsedAST.cpp 
b/clang-tools-extra/clangd/ParsedAST.cpp
index 4b96725de4417..732c36813800f 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -246,6 +246,49 @@ class ReplayPreamble : private PPCallbacks {
   std::vector MainFileTokens;
 };
 
+// Find -W and -Wno- options in ExtraArgs and apply them to 
Diags.
+//
+// This is used to handle ExtraArgs in clang-tidy configuration.
+// We don't use clang's standard handling of this as we want slightly 
diff erent
+// behavior (e.g. we want to exclude these from -Wno-error).
+void applyWarningOptions(llvm::ArrayRef ExtraArgs,
+ DiagnosticsEngine &Diags) {
+  for (llvm::StringRef Group : ExtraArgs) {
+// Only handle args that are of the form -W[no-].
+// Other flags are possible but rare and deliberately out of scope.
+llvm::SmallVector Members;
+if (!Group.consume_front("-W") || Group.empty())
+  continue;
+bool Enable = !Group.consume_front("no-");
+if (Diags.getDiagnosticIDs()->getDiagnosticsInGroup(
+diag::Flavor::WarningOrError, Group, Members))
+  continue;
+
+// Upgrade (or downgrade) the severity of each diagnostic in the group.
+// If -Werror is on, newly added warnings will be treated as errors.
+// We don't want this, so keep track of them to fix afterwards.
+bool NeedsWerrorExclusion = false;
+for (diag::kind ID : Members) {
+  if (Enable) {
+if (Diags.getDiagnosticLevel(ID, SourceLocation()) <
+DiagnosticsEngine::Warning) {
+  Diags.setSeverity(ID, diag::Severity::Warning, SourceLocation());
+  if (Diags.getWarningsAsErrors())
+NeedsWerrorExclusion = true;
+}
+  } else {
+Diags.setSeverity(ID, diag::Severity::Ignored, SourceLocation());
+  }
+}
+if (NeedsWerrorExclusion) {
+  // FIXME: there's no API to suppress -Werror for single diagnostics.
+  // In some cases with sub-groups, we may end up erroneously
+  // downgrading diagnostics that were -Werror in the compile command.
+  Diags.setDiagnosticGroupWarningAsError(Group, false);
+}
+  }
+}
+
 } // namespace
 
 llvm::Optional
@@ -311,7 +354,32 @@ ParsedAST::build(llvm::StringRef Filename, const 
ParseInputs &Inputs,
 : "unknown error");
 return None;
   }
-  if (!PreserveDiags) {
+  tidy::ClangTidyOptions ClangTidyOpts;
+  if (PreserveDiags) {
+trace::Span Tracer("ClangTidyOpts");
+ClangTidyOpts = getTidyOptionsForFile(Inputs.ClangTidyProvider, Filename);
+dlog("ClangTidy configuration for file {0}: {1}", Filename,
+ tidy::configurationAsText(ClangTidyOpts));
+
+// If clang-tidy is configured to emit clang warnings, we should too.
+//
+// Such clang-tidy configuration consists of two parts:
+//   - ExtraArgs: ["-Wfoo"] causes clang to produce the warnings
+//   - Checks: "clang-diagnostic-foo" prevents clang-tidy filtering them 
out
+//
+// We treat these as clang warnings, so the Checks part is not relevant.
+// We must enable the warnings specified in ExtraArgs.
+//
+// We *don't* want to change the compile command directly. this can have
+// too many unexpected effects: breaking the command, interactions with
+// -- and -Werror, etc. Besides, we've already parsed the command.
+// Instead we parse the -W flags and handle them directly.
+auto &Diags = Clang->getDiagnostics();
+if (ClangTidyOpts.ExtraArgsBefore)
+  applyWarningOptions(*ClangTidyOpts.ExtraArgsBefore, Diags);
+if (ClangTidyOpts.ExtraArgs)
+  applyWarningOptions(*ClangTidyOpts.ExtraArgs, Diags);
+  } else {

[PATCH] D116147: [clangd] Respect .clang-tidy ExtraArgs (-Wfoo only) when producing diagnostics

2022-01-03 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rG9e6f88b31a7f: [clangd] Respect .clang-tidy ExtraArgs (-Wfoo 
only) when producing diagnostics (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D116147?vs=395858&id=397076#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116147

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -517,6 +517,80 @@
   DiagSeverity(DiagnosticsEngine::Error);
 }
 
+TidyProvider addClangArgs(std::vector ExtraArgs) {
+  return [ExtraArgs = std::move(ExtraArgs)](tidy::ClangTidyOptions &Opts,
+llvm::StringRef) {
+if (!Opts.ExtraArgs)
+  Opts.ExtraArgs.emplace();
+for (llvm::StringRef Arg : ExtraArgs)
+  Opts.ExtraArgs->emplace_back(Arg);
+  };
+}
+
+TEST(DiagnosticTest, ClangTidyEnablesClangWarning) {
+  Annotations Main(R"cpp( // error-ok
+static void [[foo]]() {}
+  )cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  // This is always emitted as a clang warning, not a clang-tidy diagnostic.
+  auto UnusedFooWarning =
+  AllOf(Diag(Main.range(), "unused function 'foo'"),
+DiagName("-Wunused-function"), DiagSource(Diag::Clang),
+DiagSeverity(DiagnosticsEngine::Warning));
+
+  // Check the -Wunused warning isn't initially on.
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+
+  // We enable warnings based on clang-tidy extra args.
+  TU.ClangTidyProvider = addClangArgs({"-Wunused"});
+  EXPECT_THAT(*TU.build().getDiagnostics(), ElementsAre(UnusedFooWarning));
+
+  // But we don't respect other args.
+  TU.ClangTidyProvider = addClangArgs({"-Wunused", "-Dfoo=bar"});
+  EXPECT_THAT(*TU.build().getDiagnostics(), ElementsAre(UnusedFooWarning))
+  << "Not unused function 'bar'!";
+
+  // -Werror doesn't apply to warnings enabled by clang-tidy extra args.
+  TU.ExtraArgs = {"-Werror"};
+  TU.ClangTidyProvider = addClangArgs({"-Wunused"});
+  EXPECT_THAT(*TU.build().getDiagnostics(),
+  ElementsAre(DiagSeverity(DiagnosticsEngine::Warning)));
+
+  // But clang-tidy extra args won't *downgrade* errors to warnings either.
+  TU.ExtraArgs = {"-Wunused", "-Werror"};
+  TU.ClangTidyProvider = addClangArgs({"-Wunused"});
+  EXPECT_THAT(*TU.build().getDiagnostics(),
+  ElementsAre(DiagSeverity(DiagnosticsEngine::Error)));
+
+  // FIXME: we're erroneously downgrading the whole group, this should be Error.
+  TU.ExtraArgs = {"-Wunused-function", "-Werror"};
+  TU.ClangTidyProvider = addClangArgs({"-Wunused"});
+  EXPECT_THAT(*TU.build().getDiagnostics(),
+  ElementsAre(DiagSeverity(DiagnosticsEngine::Warning)));
+
+  // This looks silly, but it's the typical result if a warning is enabled by a
+  // high-level .clang-tidy file and disabled by a low-level one.
+  TU.ExtraArgs = {};
+  TU.ClangTidyProvider = addClangArgs({"-Wunused", "-Wno-unused"});
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+
+  // Overriding only works in the proper order.
+  TU.ClangTidyProvider = addClangArgs({"-Wno-unused", "-Wunused"});
+  EXPECT_THAT(*TU.build().getDiagnostics(), SizeIs(1));
+
+  // More specific vs less-specific: match clang behavior
+  TU.ClangTidyProvider = addClangArgs({"-Wunused", "-Wno-unused-function"});
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+  TU.ClangTidyProvider = addClangArgs({"-Wunused-function", "-Wno-unused"});
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+
+  // We do allow clang-tidy config to disable warnings from the compile command.
+  // It's unclear this is ideal, but it's hard to avoid.
+  TU.ExtraArgs = {"-Wunused"};
+  TU.ClangTidyProvider = addClangArgs({"-Wno-unused"});
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+}
+
 TEST(DiagnosticTest, LongFixMessages) {
   // We limit the size of printed code.
   Annotations Source(R"cpp(
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -246,6 +246,49 @@
   std::vector MainFileTokens;
 };
 
+// Find -W and -Wno- options in ExtraArgs and apply them to Diags.
+//
+// This is used to handle ExtraArgs in clang-tidy configuration.
+// We don't use clang's standard handling of this as we want slightly different
+// behavior (e.g. we want to exclude these from -Wno-error).
+void applyWarningOptions(llvm::ArrayRef ExtraArgs,
+ DiagnosticsEngine &Diags) {
+  for (ll

[clang-tools-extra] fe68088 - [clangd] Helper for determining member insertion point.

2022-01-03 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-03T17:59:45+01:00
New Revision: fe68088d44f760c7d3d8ee6735d396d97cb55478

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

LOG: [clangd] Helper for determining member insertion point.

To be used in D116490 and D116385, and an upcoming patch to generate C++
constructors.

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

Added: 
clang-tools-extra/clangd/refactor/InsertionPoint.cpp
clang-tools-extra/clangd/refactor/InsertionPoint.h
clang-tools-extra/clangd/unittests/InsertionPointTests.cpp

Modified: 
clang-tools-extra/clangd/CMakeLists.txt
clang-tools-extra/clangd/unittests/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/clangd/CMakeLists.txt 
b/clang-tools-extra/clangd/CMakeLists.txt
index 056a3272ebd11..9c37cfe7b7001 100644
--- a/clang-tools-extra/clangd/CMakeLists.txt
+++ b/clang-tools-extra/clangd/CMakeLists.txt
@@ -131,6 +131,7 @@ add_clang_library(clangDaemon
   index/dex/PostingList.cpp
   index/dex/Trigram.cpp
 
+  refactor/InsertionPoint.cpp
   refactor/Rename.cpp
   refactor/Tweak.cpp
 

diff  --git a/clang-tools-extra/clangd/refactor/InsertionPoint.cpp 
b/clang-tools-extra/clangd/refactor/InsertionPoint.cpp
new file mode 100644
index 0..ce5f3a5a1d5fd
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/InsertionPoint.cpp
@@ -0,0 +1,157 @@
+//===--- InsertionPoint.cpp - Where should we add new code? 
---===//
+//
+// 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 "refactor/InsertionPoint.h"
+#include "support/Logger.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclObjC.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/Basic/SourceManager.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+// Choose the decl to insert before, according to an anchor.
+// Nullptr means insert at end of DC.
+// None means no valid place to insert.
+llvm::Optional insertionDecl(const DeclContext &DC,
+   const Anchor &A) {
+  bool LastMatched = false;
+  bool ReturnNext = false;
+  for (const auto *D : DC.decls()) {
+if (D->isImplicit())
+  continue;
+if (ReturnNext)
+  return D;
+
+const Decl *NonTemplate = D;
+if (auto *TD = llvm::dyn_cast(D))
+  NonTemplate = TD->getTemplatedDecl();
+bool Matches = A.Match(NonTemplate);
+dlog("{0} {1} {2}", Matches, D->getDeclKindName(), D);
+
+switch (A.Direction) {
+case Anchor::Above:
+  if (Matches && !LastMatched) {
+// Special case: if "above" matches an access specifier, we actually
+// want to insert below it!
+if (llvm::isa(D)) {
+  ReturnNext = true;
+  continue;
+}
+return D;
+  }
+  break;
+case Anchor::Below:
+  if (LastMatched && !Matches)
+return D;
+  break;
+}
+
+LastMatched = Matches;
+  }
+  if (ReturnNext || (LastMatched && A.Direction == Anchor::Below))
+return nullptr;
+  return llvm::None;
+}
+
+SourceLocation beginLoc(const Decl &D) {
+  auto Loc = D.getBeginLoc();
+  if (RawComment *Comment = D.getASTContext().getRawCommentForDeclNoCache(&D)) 
{
+auto CommentLoc = Comment->getBeginLoc();
+if (CommentLoc.isValid() && Loc.isValid() &&
+D.getASTContext().getSourceManager().isBeforeInTranslationUnit(
+CommentLoc, Loc))
+  Loc = CommentLoc;
+  }
+  return Loc;
+}
+
+bool any(const Decl *D) { return true; }
+
+SourceLocation endLoc(const DeclContext &DC) {
+  const Decl *D = llvm::cast(&DC);
+  if (auto *OCD = llvm::dyn_cast(D))
+return OCD->getAtEndRange().getBegin();
+  return D->getEndLoc();
+}
+
+AccessSpecifier getAccessAtEnd(const CXXRecordDecl &C) {
+  AccessSpecifier Spec = (C.getTagKind() == TTK_Class ? AS_private : 
AS_public);
+  for (const auto *D : C.decls())
+if (const auto *ASD = llvm::dyn_cast(D))
+  Spec = ASD->getAccess();
+  return Spec;
+}
+
+} // namespace
+
+SourceLocation insertionPoint(const DeclContext &DC,
+  llvm::ArrayRef Anchors) {
+  dlog("Looking for insertion point in {0}", DC.getDeclKindName());
+  for (const auto &A : Anchors) {
+dlog("  anchor ({0})", A.Direction == Anchor::Above ? "above" : "below");
+if (auto D = insertionDecl(DC, A)) {
+  dlog("  anchor matched before {0}", *D);
+  return *D ? beginLoc(**D) : endLoc(DC);
+}
+  }
+  dlog("no anchor matched");
+  return SourceLocation();
+}
+
+llvm::Expected
+insertDecl(llvm::St

[PATCH] D116502: [clangd] Helper for determining member insertion point.

2022-01-03 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rGfe68088d44f7: [clangd] Helper for determining member 
insertion point. (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116502

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/refactor/InsertionPoint.cpp
  clang-tools-extra/clangd/refactor/InsertionPoint.h
  clang-tools-extra/clangd/unittests/CMakeLists.txt
  clang-tools-extra/clangd/unittests/InsertionPointTests.cpp

Index: clang-tools-extra/clangd/unittests/InsertionPointTests.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/unittests/InsertionPointTests.cpp
@@ -0,0 +1,210 @@
+//===-- InsertionPointTess.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 "Annotations.h"
+#include "Protocol.h"
+#include "SourceCode.h"
+#include "TestTU.h"
+#include "TestWorkspace.h"
+#include "XRefs.h"
+#include "refactor/InsertionPoint.h"
+#include "clang/AST/DeclBase.h"
+#include "llvm/Testing/Support/Error.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+using llvm::HasValue;
+
+TEST(InsertionPointTests, Generic) {
+  Annotations Code(R"cpp(
+  namespace ns {
+$a^int a1;
+$b^// leading comment
+int b;
+$c^int c1; // trailing comment
+int c2;
+$a2^int a2;
+  $end^};
+  )cpp");
+
+  auto StartsWith =
+  [&](llvm::StringLiteral S) -> std::function {
+return [S](const Decl *D) {
+  if (const auto *ND = llvm::dyn_cast(D))
+return llvm::StringRef(ND->getNameAsString()).startswith(S);
+  return false;
+};
+  };
+
+  auto AST = TestTU::withCode(Code.code()).build();
+  auto &NS = cast(findDecl(AST, "ns"));
+
+  // Test single anchors.
+  auto Point = [&](llvm::StringLiteral Prefix, Anchor::Dir Direction) {
+auto Loc = insertionPoint(NS, {Anchor{StartsWith(Prefix), Direction}});
+return sourceLocToPosition(AST.getSourceManager(), Loc);
+  };
+  EXPECT_EQ(Point("a", Anchor::Above), Code.point("a"));
+  EXPECT_EQ(Point("a", Anchor::Below), Code.point("b"));
+  EXPECT_EQ(Point("b", Anchor::Above), Code.point("b"));
+  EXPECT_EQ(Point("b", Anchor::Below), Code.point("c"));
+  EXPECT_EQ(Point("c", Anchor::Above), Code.point("c"));
+  EXPECT_EQ(Point("c", Anchor::Below), Code.point("a2"));
+  EXPECT_EQ(Point("", Anchor::Above), Code.point("a"));
+  EXPECT_EQ(Point("", Anchor::Below), Code.point("end"));
+  EXPECT_EQ(Point("no_match", Anchor::Below), Position{});
+
+  // Test anchor chaining.
+  auto Chain = [&](llvm::StringLiteral P1, llvm::StringLiteral P2) {
+auto Loc = insertionPoint(NS, {Anchor{StartsWith(P1), Anchor::Above},
+   Anchor{StartsWith(P2), Anchor::Above}});
+return sourceLocToPosition(AST.getSourceManager(), Loc);
+  };
+  EXPECT_EQ(Chain("a", "b"), Code.point("a"));
+  EXPECT_EQ(Chain("b", "a"), Code.point("b"));
+  EXPECT_EQ(Chain("no_match", "a"), Code.point("a"));
+
+  // Test edit generation.
+  auto Edit = insertDecl("foo;", NS, {Anchor{StartsWith("a"), Anchor::Below}});
+  ASSERT_THAT_EXPECTED(Edit, llvm::Succeeded());
+  EXPECT_EQ(offsetToPosition(Code.code(), Edit->getOffset()), Code.point("b"));
+  EXPECT_EQ(Edit->getReplacementText(), "foo;");
+  // If no match, the edit is inserted at the end.
+  Edit = insertDecl("x;", NS, {Anchor{StartsWith("no_match"), Anchor::Below}});
+  ASSERT_THAT_EXPECTED(Edit, llvm::Succeeded());
+  EXPECT_EQ(offsetToPosition(Code.code(), Edit->getOffset()),
+Code.point("end"));
+}
+
+// For CXX, we should check:
+// - special handling for access specifiers
+// - unwrapping of template decls
+TEST(InsertionPointTests, CXX) {
+  Annotations Code(R"cpp(
+class C {
+public:
+  $Method^void pubMethod();
+  $Field^int PubField;
+
+$private^private:
+  $field^int PrivField;
+  $method^void privMethod();
+  template  void privTemplateMethod();
+$end^};
+  )cpp");
+
+  auto AST = TestTU::withCode(Code.code()).build();
+  const CXXRecordDecl &C = cast(findDecl(AST, "C"));
+
+  auto IsMethod = [](const Decl *D) { return llvm::isa(D); };
+  auto Any = [](const Decl *D) { return true; };
+
+  // Test single anchors.
+  auto Point = [&](Anchor A, AccessSpecifier Protection) {
+auto Loc = insertionPoint(C, {A}, Protection);
+return sourceLocToPosition(AST.getSourceManager(), Loc);
+  };
+  EXPECT_EQ(Point({IsMethod, Anchor::Above}, AS_public), Code.point("Method"));
+  EXPECT_EQ(Point({IsMethod,

[clang-tools-extra] 478863e - [clangd] Basic IncludeCleaner support for c/c++ standard library

2022-01-03 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-03T18:19:56+01:00
New Revision: 478863ef58c7f7314e0669d332a90d6e233d44fb

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

LOG: [clangd] Basic IncludeCleaner support for c/c++ standard library

There are some limitations here, so this is behind a flag for now (in addition
to the config setting for the overall feature).

- symbols without exactly one associated header aren't handled right
- no macro support
- referencing std::size_t usually doesn't leave any trace in the AST that the
  alias in std was used, so we associate with stddef.h instead of cstddef.
  (An AST issue not specific to stdlib, but much worse there)

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

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clangd/Headers.cpp 
b/clang-tools-extra/clangd/Headers.cpp
index 30cca7448be25..72da1be99283c 100644
--- a/clang-tools-extra/clangd/Headers.cpp
+++ b/clang-tools-extra/clangd/Headers.cpp
@@ -61,10 +61,19 @@ class IncludeStructure::RecordHeaders : public PPCallbacks,
   SM.getLineNumber(SM.getFileID(HashLoc), Inc.HashOffset) - 1;
   Inc.FileKind = FileKind;
   Inc.Directive = IncludeTok.getIdentifierInfo()->getPPKeywordID();
-  if (File)
-Inc.HeaderID = static_cast(Out->getOrCreateID(File));
   if (LastPragmaKeepInMainFileLine == Inc.HashLine)
 Inc.BehindPragmaKeep = true;
+  if (File) {
+IncludeStructure::HeaderID HID = Out->getOrCreateID(File);
+Inc.HeaderID = static_cast(HID);
+if (IsAngled)
+  if (auto StdlibHeader = stdlib::Header::named(Inc.Written)) {
+auto &IDs = Out->StdlibHeaders[*StdlibHeader];
+// Few physical files for one stdlib header name, linear scan is 
ok.
+if (!llvm::is_contained(IDs, HID))
+  IDs.push_back(HID);
+  }
+  }
 }
 
 // Record include graph (not just for main-file includes)
@@ -340,5 +349,155 @@ bool operator==(const Inclusion &LHS, const Inclusion 
&RHS) {
  std::tie(RHS.Directive, RHS.FileKind, RHS.HashOffset, RHS.HashLine,
   RHS.Resolved, RHS.Written);
 }
+
+namespace stdlib {
+static llvm::StringRef *HeaderNames;
+static std::pair *SymbolNames;
+static unsigned *SymbolHeaderIDs;
+static llvm::DenseMap *HeaderIDs;
+// Maps symbol name -> Symbol::ID, within a namespace.
+using NSSymbolMap = llvm::DenseMap;
+static llvm::DenseMap *NamespaceSymbols;
+
+static int initialize() {
+  unsigned SymCount = 0;
+#define SYMBOL(Name, NS, Header) ++SymCount;
+#include "CSymbolMap.inc"
+#include "StdSymbolMap.inc"
+#undef SYMBOL
+  SymbolNames = new std::remove_reference_t[SymCount];
+  SymbolHeaderIDs =
+  new std::remove_reference_t[SymCount];
+  NamespaceSymbols = new std::remove_reference_t;
+  HeaderIDs = new std::remove_reference_t;
+
+  auto AddNS = [&](llvm::StringRef NS) -> NSSymbolMap & {
+auto R = NamespaceSymbols->try_emplace(NS, nullptr);
+if (R.second)
+  R.first->second = new NSSymbolMap();
+return *R.first->second;
+  };
+
+  auto AddHeader = [&](llvm::StringRef Header) -> unsigned {
+return HeaderIDs->try_emplace(Header, HeaderIDs->size()).first->second;
+  };
+
+  auto Add = [&, SymIndex(0)](llvm::StringRef Name, llvm::StringRef NS,
+  llvm::StringRef HeaderName) mutable {
+if (NS == "None")
+  NS = "";
+
+SymbolNames[SymIndex] = {NS, Name};
+SymbolHeaderIDs[SymIndex] = AddHeader(HeaderName);
+
+NSSymbolMap &NSSymbols = AddNS(NS);
+NSSymbols.try_emplace(Name, SymIndex);
+
+++SymIndex;
+  };
+#define SYMBOL(Name, NS, Header) Add(#Name, #NS, #Header);
+#include "CSymbolMap.inc"
+#include "StdSymbolMap.inc"
+#undef SYMBOL
+
+  HeaderNames = new llvm::StringRef[HeaderIDs->size()];
+  for (const auto &E : *HeaderIDs)
+HeaderNames[E.second] = E.first;
+
+  return 0;
+}
+
+static void ensureInitialized() {
+  static int Dummy = initialize();
+  (void)Dummy;
+}
+
+llvm::Optional Header::named(llvm::StringRef Name) {
+  ensureInitialized();
+  auto It = HeaderIDs->find(Name);
+  if (It == HeaderIDs->end())
+return llvm::None;
+  return Header(It->second);
+}
+llvm::StringRef Header::name() const { return HeaderNames[ID]; }
+llvm::StringRef Symbol::scope() const { return SymbolNames[ID].first; }
+llvm::StringRef Symbol::name() const { return SymbolNames[ID].second; }
+llvm::Optional Symbol::named(l

[PATCH] D114077: [clangd] Basic IncludeCleaner support for c/c++ standard library

2022-01-03 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked 4 inline comments as done.
Closed by commit rG478863ef58c7: [clangd] Basic IncludeCleaner support for 
c/c++ standard library (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D114077?vs=396639&id=397082#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114077

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

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -8,7 +8,9 @@
 
 #include "Annotations.h"
 #include "IncludeCleaner.h"
+#include "SourceCode.h"
 #include "TestTU.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/Testing/Support/SupportHelpers.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -18,7 +20,9 @@
 namespace {
 
 using ::testing::ElementsAre;
+using ::testing::ElementsAreArray;
 using ::testing::IsEmpty;
+using ::testing::Pointee;
 using ::testing::UnorderedElementsAre;
 
 std::string guard(llvm::StringRef Code) {
@@ -211,7 +215,7 @@
 auto AST = TU.build();
 
 std::vector Points;
-for (const auto &Loc : findReferencedLocations(AST)) {
+for (const auto &Loc : findReferencedLocations(AST).User) {
   if (AST.getSourceManager().getBufferName(Loc).endswith(
   TU.HeaderFilename)) {
 Points.push_back(offsetToPosition(
@@ -225,6 +229,82 @@
   }
 }
 
+TEST(IncludeCleaner, Stdlib) {
+  // Smoke tests only for finding used symbols/headers.
+  // Details of Decl -> stdlib::Symbol -> stdlib::Headers mapping tested there.
+  auto TU = TestTU::withHeaderCode(R"cpp(
+namespace std { class error_code {}; }
+class error_code {};
+namespace nonstd { class error_code {}; }
+  )cpp");
+  struct {
+llvm::StringRef Code;
+std::vector Symbols;
+std::vector Headers;
+  } Tests[] = {
+  {"std::error_code x;", {"std::error_code"}, {""}},
+  {"error_code x;", {}, {}},
+  {"nonstd::error_code x;", {}, {}},
+  };
+
+  for (const auto &Test : Tests) {
+TU.Code = Test.Code.str();
+ParsedAST AST = TU.build();
+std::vector WantSyms;
+for (const auto &SymName : Test.Symbols) {
+  auto QName = splitQualifiedName(SymName);
+  auto Sym = stdlib::Symbol::named(QName.first, QName.second);
+  EXPECT_TRUE(Sym) << SymName;
+  WantSyms.push_back(*Sym);
+}
+std::vector WantHeaders;
+for (const auto &HeaderName : Test.Headers) {
+  auto Header = stdlib::Header::named(HeaderName);
+  EXPECT_TRUE(Header) << HeaderName;
+  WantHeaders.push_back(*Header);
+}
+
+ReferencedLocations Locs = findReferencedLocations(AST);
+EXPECT_THAT(Locs.Stdlib, ElementsAreArray(WantSyms));
+ReferencedFiles Files = findReferencedFiles(Locs, AST.getIncludeStructure(),
+AST.getSourceManager());
+EXPECT_THAT(Files.Stdlib, ElementsAreArray(WantHeaders));
+  }
+}
+
+MATCHER_P(WrittenInclusion, Written, "") {
+  if (arg.Written != Written)
+*result_listener << arg.Written;
+  return arg.Written == Written;
+}
+
+TEST(IncludeCleaner, StdlibUnused) {
+  setIncludeCleanerAnalyzesStdlib(true);
+  auto Cleanup =
+  llvm::make_scope_exit([] { setIncludeCleanerAnalyzesStdlib(false); });
+
+  auto TU = TestTU::withCode(R"cpp(
+#include 
+#include 
+std::list x;
+  )cpp");
+  // Layout of std library impl is not relevant.
+  TU.AdditionalFiles["bits"] = R"cpp(
+#pragma once
+namespace std {
+  template  class list {};
+  template  class queue {};
+}
+  )cpp";
+  TU.AdditionalFiles["list"] = "#include ";
+  TU.AdditionalFiles["queue"] = "#include ";
+  TU.ExtraArgs = {"-isystem", testRoot()};
+  auto AST = TU.build();
+
+  auto Unused = computeUnusedIncludes(AST);
+  EXPECT_THAT(Unused, ElementsAre(Pointee(WrittenInclusion("";
+}
+
 TEST(IncludeCleaner, GetUnusedHeaders) {
   llvm::StringLiteral MainFile = R"cpp(
 #include "a.h"
@@ -301,7 +381,7 @@
   auto ReferencedFiles =
   findReferencedFiles(findReferencedLocations(AST), Includes, SM);
   llvm::StringSet<> ReferencedFileNames;
-  for (FileID FID : ReferencedFiles)
+  for (FileID FID : ReferencedFiles.User)
 ReferencedFileNames.insert(
 SM.getPresumedLoc(SM.getLocForStartOfFile(FID)).getFilename());
   // Note we deduped the names as _number_ of s is uninteresting.
@@ -352,7 +432,7 @@
   AST.getIncludeStructure(), AST.getSourceManager()

[PATCH] D111100: enable plugins for clang-tidy

2022-01-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tools-extra/docs/clang-tidy/Contributing.rst:428
+of our new checks.
+
+.. code-block:: console

We should also document our expectations explicitly regarding things like ABI 
and API stability. e.g., remind users that there is none and so the plugin must 
be compiled against the version of clang-tidy that will be loading the plugin. 
(We should also make sure we're correct about that; I don't know if Clang 13 
and Clang 13.0.1 can share plugins or not.)

Another thing we should document is whether the plugins can or cannot use 
threads or TLS, or other details along those lines that developers need to be 
aware of.



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

vtjnash wrote:
> aaron.ballman wrote:
> > Shouldn't these functions be overloaded? We don't need it to be 
> > particularly functional, but the plugin should demonstrate that it works 
> > and can be run by clang-tidy (not just loaded and listed as a check).
> I figured that is guaranteed by the C++ linker, if it can successfully list 
> the check, so I didn't think it seemed essential to test for that also. I put 
> these here mostly just to help anyone copying the file to getting started 
> with adopting it to their use case.
I think it's important to demonstrate that the functionality works, and I think 
it's even more important to ensure that plugin support is maintained as new 
features are added to clang-tidy. "It links" is insufficient to tell us that.

One possible approach to this is to write and maintain a simple check as a 
plugin, then test it using the normal infrastructure (additional command line 
arg to load the plugin notwithstanding). We could either make it a functional 
check that users can optionally use (perhaps the reason it's a plugin is 
because it relies on a third-party library that may not always be available on 
all users' systems), or we could make it a toy check that only exists to test 
tidy features like plugins, plugin config options, etc.

The kinds of things I want to verify work are things like: does the plugin name 
get properly emitted as part of the diagnostics from the check? Are config 
options properly loaded for the plugin? Can a plugin alias a builtin check and 
provides a different set of config options?

We should also verify the tool gracefully handles a plugin that isn't valid 
(e.g., ask to load an arbitrary shared library as a plugin, ensure that tidy 
doesn't crash).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D00

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


[PATCH] D116541: [OpenMP] Introduce new flag to change offloading driver pipeline

2022-01-03 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, gregrodgers, JonChesterfield, ronlieb.
Herald added subscribers: ormris, dexonsmith, dang, guansong, hiraditya, 
yaxunl, mgorny.
jhuber6 requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, sstefan1.
Herald added projects: clang, LLVM.

This patch introduces the `-fopenmp-new-driver` option which instructs
the compiler to use a new driver scheme for producing offloading code.
In this scheme we create a complete offloading object file and then pass
it as input to the host compilation phase. This will allow us to embed
the object code in the backend phase.

[OpenMP] Add a flag for embedding a file into the module

This patch adds support for a flag `-fembed-offload-binary` to embed a
file as an ELF section in the output by placing it in a global variable.
This can be used to bundle offloading files with the host binary so it
can be accessed by the linker. The section is named using the
`-fembed-offload-section` option.

[OpenMP] Embed device files into the host IR

This patch adds support for embedding the device object files into the
host IR to create a fat binary. Each offloading file will be inserted
into a section with the following naming format
`.llvm.offloading..`.

[Clang] Introduce Clang Linker Wrapper Tool

This patch introduces a linker wrapper tool that allows us to preprocess
files before they are sent to the linker. This adds a dummy action and
job to the driver stage that builds the linker command as usual and then
replaces the command line with the wrapper tool.

[OpenMP] Add support for extracting device code in linker wrapper

This patchs add support for extracting device offloading code from the
linker's input files. If the file contains a section with the name
`.llvm.offloading..` it will be extracted to a new
temporary file to be linked. Addtionally, the host file containing it
will have the section stripped so it does not remain in the executable
once linked.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116541

Files:
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/CodeGen/BackendUtil.h
  clang/include/clang/Driver/Action.h
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Job.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/Driver/Action.cpp
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Clang.h
  clang/test/Driver/openmp-offload-gpu.c
  clang/test/Frontend/embed-object.ll
  clang/tools/CMakeLists.txt
  clang/tools/clang-linker-wrapper/CMakeLists.txt
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  llvm/include/llvm/Bitcode/BitcodeWriter.h
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp

Index: llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
===
--- llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -4971,3 +4971,42 @@
   llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
   NewUsed->setSection("llvm.metadata");
 }
+
+void llvm::EmbedObjectInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
+   StringRef SectionName) {
+  // Save llvm.compiler.used and remove it.
+  SmallVector UsedArray;
+  SmallVector UsedGlobals;
+  Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0);
+  GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
+  for (auto *GV : UsedGlobals) {
+if (!GV->getName().startswith("llvm.embedded.object"))
+  UsedArray.push_back(
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
+  }
+  if (Used)
+Used->eraseFromParent();
+
+  ArrayRef ModuleData = ArrayRef(
+  (const uint8_t *)Buf.getBufferStart(), Buf.getBufferSize());
+
+  // Embed the data in the 
+  llvm::Constant *ModuleConstant =
+  llvm::ConstantDataArray::get(M.getContext(), ModuleData);
+  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
+  M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
+  ModuleConstant, "llvm.embedded.object");
+  GV->setSection(SectionName);
+  // Set alignment to 1 to prevent padding between two contributions from input
+  // sections after linking.
+  GV->setAlignment(Align(1));
+  UsedArray.push_back(
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
+
+  // Recreate llvm.compiler.used.
+  ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
+  auto *NewUsed = new GlobalVariable(
+  M, ATy, false, llvm::GlobalValue::AppendingLinkage,
+  llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
+  NewUsed->setSection("llvm.metadata");
+}
Index: llvm/include/llvm/Bitcode/BitcodeWriter.h
=

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

2022-01-03 Thread Oleg Smolsky via Phabricator via cfe-commits
oleg.smolsky updated this revision to Diff 397086.
oleg.smolsky marked 2 inline comments as done.
oleg.smolsky added a comment.

Addressed review comments: explicit types and doc changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114995

Files:
  clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/modernize-use-default-member-init.rst
  
clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
@@ -45,6 +45,42 @@
   // CHECK-FIXES: int j{1};
 };
 
+struct PositiveNotDefaultInt {
+  PositiveNotDefaultInt(int) : i(7) {}
+  // CHECK-FIXES: PositiveNotDefaultInt(int)  {}
+  int i;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'i'
+  // CHECK-FIXES: int i{7};
+};
+
+// We cannot reconcile these initializers.
+struct TwoConstructors {
+TwoConstructors(int) : i(7) {}
+TwoConstructors(int, int) : i(8) {}
+int i;
+};
+
+struct PositiveNotDefaultOOLInt {
+  PositiveNotDefaultOOLInt(int);
+  int i;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'i'
+  // CHECK-FIXES: int i{7};
+};
+
+PositiveNotDefaultOOLInt::PositiveNotDefaultOOLInt(int) : i(7) {}
+// CHECK-FIXES: PositiveNotDefaultOOLInt::PositiveNotDefaultOOLInt(int)  {}
+
+struct PositiveNotDefaultOOLInt2 {
+  PositiveNotDefaultOOLInt2(int, int);
+  int i;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'i'
+  // CHECK-FIXES: int i{7};
+  int j;
+};
+
+PositiveNotDefaultOOLInt2::PositiveNotDefaultOOLInt2(int, int arg) : i(7), j(arg) {}
+// CHECK-FIXES: PositiveNotDefaultOOLInt2::PositiveNotDefaultOOLInt2(int, int arg) :  j(arg) {}
+
 struct PositiveUnaryMinusInt {
   PositiveUnaryMinusInt() : j(-1) {}
   // CHECK-FIXES: PositiveUnaryMinusInt()  {}
@@ -234,12 +270,6 @@
   int i : 5;
 };
 
-struct NegativeNotDefaultInt
-{
-  NegativeNotDefaultInt(int) : i(7) {}
-  int i;
-};
-
 struct NegativeDefaultArg
 {
   NegativeDefaultArg(int i = 4) : i(i) {}
Index: clang-tools-extra/docs/clang-tidy/checks/modernize-use-default-member-init.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/modernize-use-default-member-init.rst
+++ clang-tools-extra/docs/clang-tidy/checks/modernize-use-default-member-init.rst
@@ -3,7 +3,7 @@
 modernize-use-default-member-init
 =
 
-This check converts a default constructor's member initializers into the new
+This check converts constructors' member initializers into the new
 default member initializers in C++11. Other member initializers that match the
 default member initializer are removed. This can reduce repeated code or allow
 use of '= default'.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -73,6 +73,9 @@
 - Added support for `NOLINTBEGIN` ... `NOLINTEND` comments to suppress
   Clang-Tidy warnings over multiple lines.
 
+- Generalized the `modernize-use-default-member-init` check to handle non-default
+  constructors.
+
 New checks
 ^^
 
Index: clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -212,17 +212,14 @@
 InitBase);
 
   Finder->addMatcher(
-  cxxConstructorDecl(
-  isDefaultConstructor(),
-  forEachConstructorInitializer(
-  cxxCtorInitializer(
-  forField(unless(anyOf(getLangOpts().CPlusPlus20
-? unless(anything())
-: isBitField(),
-hasInClassInitializer(anything()),
-hasParent(recordDecl(isUnion()),
-  withInitializer(Init))
-  .bind("default"))),
+  cxxConstructorDecl(forEachConstructorInitializer(
+  cxxCtorInitializer(
+  forField(unless(anyOf(
+  getLangOpts().CPlusPlus20 ? unless(anything()) : isBitField(),
+  hasInClassInitializer(anything()),
+  hasParent(recordDecl(isUnion()),
+  withInitializer(Init))
+  .bind("default"

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

2022-01-03 Thread Oleg Smolsky via Phabricator via cfe-commits
oleg.smolsky added a comment.

Done with review changes.




Comment at: 
clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp:1
+
 //===--- UseDefaultMemberInitCheck.cpp - 
clang-tidy===//

aaron.ballman wrote:
> Spurious newline?
yep, removing it...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114995

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


[PATCH] D116541: [OpenMP] Introduce new flag to change offloading driver pipeline

2022-01-03 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 397089.
jhuber6 added a comment.

Updating to only contain this commit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116541

Files:
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/openmp-offload-gpu.c

Index: clang/test/Driver/openmp-offload-gpu.c
===
--- clang/test/Driver/openmp-offload-gpu.c
+++ clang/test/Driver/openmp-offload-gpu.c
@@ -343,3 +343,13 @@
 // RUN:   | FileCheck -check-prefix=SAVE_TEMPS_NAMES %s
 
 // SAVE_TEMPS_NAMES-NOT: "GNU::Linker"{{.*}}["[[SAVE_TEMPS_INPUT1:.*\.o]]", "[[SAVE_TEMPS_INPUT1]]"]
+
+// RUN:   %clang -### -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN:  -fopenmp-new-driver -no-canonical-prefixes -ccc-print-bindings %s -o openmp-offload-gpu 2>&1 \
+// RUN:   | FileCheck -check-prefix=NEW_DRIVER %s
+
+// NEW_DRIVER: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[HOST_INPUT:.+]]"], output: "[[HOST_BC:.+]]" 
+// NEW_DRIVER: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[DEVICE_INPUT:.+]]", "[[HOST_BC]]"], output: "[[DEVICE_ASM:.+]]"
+// NEW_DRIVER: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[DEVICE_ASM]]"], output: "[[DEVICE_OBJ:.+]]" 
+// NEW_DRIVER: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[HOST_BC]]", "[[DEVICE_OBJ]]"], output: "[[HOST_OBJ:.+]]" 
+// NEW_DRIVER: "x86_64-unknown-linux-gnu" - "[[LINKER:.+]]", inputs: ["[[HOST_OBJ]]"], output: "openmp-offload-gpu"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4338,6 +4338,7 @@
   bool IsHIP = JA.isOffloading(Action::OFK_HIP);
   bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
   bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
+  bool IsOpenMPHost = JA.isHostOffloading(Action::OFK_OpenMP);
   bool IsHeaderModulePrecompile = isa(JA);
   bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
  JA.isDeviceOffloading(Action::OFK_Host));
@@ -4358,6 +4359,7 @@
   InputInfoList ModuleHeaderInputs;
   const InputInfo *CudaDeviceInput = nullptr;
   const InputInfo *OpenMPDeviceInput = nullptr;
+  const InputInfo *OpenMPHostInput = nullptr;
   for (const InputInfo &I : Inputs) {
 if (&I == &Input) {
   // This is the primary input.
@@ -4374,6 +4376,8 @@
   CudaDeviceInput = &I;
 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
   OpenMPDeviceInput = &I;
+} else if (IsOpenMPHost && !OpenMPHostInput) {
+  OpenMPHostInput = &I;
 } else {
   llvm_unreachable("unexpectedly given multiple inputs");
 }
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -3788,6 +3788,11 @@
   // Builder to be used to build offloading actions.
   OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
 
+  // Offload kinds active for this compilation.
+  unsigned OffloadKinds = Action::OFK_None;
+  if (C.hasOffloadToolChain())
+OffloadKinds |= Action::OFK_OpenMP;
+
   // Construct the actions to perform.
   HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
   ActionList LinkerInputs;
@@ -3808,14 +3813,16 @@
 
 // Use the current host action in any of the offloading actions, if
 // required.
-if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
-  break;
+if (!Args.hasArg(options::OPT_fopenmp_new_driver))
+  if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
+break;
 
 for (phases::ID Phase : PL) {
 
   // Add any offload action the host action depends on.
-  Current = OffloadBuilder.addDeviceDependencesToHostAction(
-  Current, InputArg, Phase, PL.back(), FullPL);
+  if (!Args.hasArg(options::OPT_fopenmp_new_driver))
+Current = OffloadBuilder.addDeviceDependencesToHostAction(
+Current, InputArg, Phase, PL.back(), FullPL);
   if (!Current)
 break;
 
@@ -3855,6 +3862,11 @@
 break;
   }
 
+  // Try to build the offloading actions and add the result as a dependency
+  // to the host.
+  if (Args.hasArg(options::OPT_fopenmp_new_driver))
+Current = BuildOffloadingActions(C, Args, I, Current);
+
   // FIXME: Should we include any prior module file outputs as inputs of
   // later actions in the same command line?
 
@@ -3872,8 +3884,9 @@
 
   // Use the current host action in any of the offloading actions, if
   // required.
-  if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
-break;
+  if (!Args.hasArg(op

[PATCH] D116542: [OpenMP] Add a flag for embedding a file into the module

2022-01-03 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, gregrodgers, JonChesterfield, ronlieb.
Herald added subscribers: ormris, dexonsmith, dang, guansong, hiraditya, yaxunl.
jhuber6 requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, sstefan1.
Herald added projects: clang, LLVM.

This patch adds support for a flag `-fembed-offload-binary` to embed a
file as an ELF section in the output by placing it in a global variable.
This can be used to bundle offloading files with the host binary so it
can be accessed by the linker. The section is named using the
`-fembed-offload-section` option.

Depends on D116541 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116542

Files:
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/CodeGen/BackendUtil.h
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/test/Frontend/embed-object.ll
  llvm/include/llvm/Bitcode/BitcodeWriter.h
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp

Index: llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
===
--- llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -4971,3 +4971,42 @@
   llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
   NewUsed->setSection("llvm.metadata");
 }
+
+void llvm::EmbedObjectInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
+   StringRef SectionName) {
+  // Save llvm.compiler.used and remove it.
+  SmallVector UsedArray;
+  SmallVector UsedGlobals;
+  Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0);
+  GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
+  for (auto *GV : UsedGlobals) {
+if (!GV->getName().startswith("llvm.embedded.object"))
+  UsedArray.push_back(
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
+  }
+  if (Used)
+Used->eraseFromParent();
+
+  ArrayRef ModuleData = ArrayRef(
+  (const uint8_t *)Buf.getBufferStart(), Buf.getBufferSize());
+
+  // Embed the data in the 
+  llvm::Constant *ModuleConstant =
+  llvm::ConstantDataArray::get(M.getContext(), ModuleData);
+  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
+  M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
+  ModuleConstant, "llvm.embedded.object");
+  GV->setSection(SectionName);
+  // Set alignment to 1 to prevent padding between two contributions from input
+  // sections after linking.
+  GV->setAlignment(Align(1));
+  UsedArray.push_back(
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
+
+  // Recreate llvm.compiler.used.
+  ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
+  auto *NewUsed = new GlobalVariable(
+  M, ATy, false, llvm::GlobalValue::AppendingLinkage,
+  llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
+  NewUsed->setSection("llvm.metadata");
+}
Index: llvm/include/llvm/Bitcode/BitcodeWriter.h
===
--- llvm/include/llvm/Bitcode/BitcodeWriter.h
+++ llvm/include/llvm/Bitcode/BitcodeWriter.h
@@ -165,6 +165,11 @@
 bool EmbedCmdline,
 const std::vector &CmdArgs);
 
+  /// Embeds the memory buffer \p Buf into the module \p M as a global using the
+  /// section name \p SectionName.
+  void EmbedObjectInModule(Module &M, MemoryBufferRef Buf,
+   StringRef SectionName);
+
 } // end namespace llvm
 
 #endif // LLVM_BITCODE_BITCODEWRITER_H
Index: clang/test/Frontend/embed-object.ll
===
--- /dev/null
+++ clang/test/Frontend/embed-object.ll
@@ -0,0 +1,13 @@
+; RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm \
+; RUN:-fembed-offload-binary=%S/Inputs/empty.h -fembed-offload-section=section -x ir %s -o - \
+; RUN:| FileCheck %s -check-prefix=CHECK
+
+; CHECK: @llvm.embedded.object = private constant [0 x i8] zeroinitializer, section ".llvm.offloading.section", align 1
+; CHECK: @llvm.compiler.used = appending global [2 x i8*] [i8* @x, i8* getelementptr inbounds ([0 x i8], [0 x i8]* @llvm.embedded.object, i32 0, i32 0)], section "llvm.metadata"
+
+@x = private constant i8 1
+@llvm.compiler.used = appending global [1 x i8*] [i8* @x], section "llvm.metadata"
+
+define i32 @foo() {
+  ret i32 0
+}
Index: clang/lib/CodeGen/CodeGenAction.cpp
===
--- clang/lib/CodeGen/CodeGenAction.cpp
+++ clang/lib/CodeGen/CodeGenAction.cpp
@@ -1134,6 +1134,7 @@
 TheModule->setTargetTriple(TargetOpts.Triple);
   }
 
+  EmbedBinary(TheModule.get(), CodeGenOpts, Diagnostics);
   EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
 
   LLVMContex

[PATCH] D116543: [OpenMP] Embed device files into the host IR

2022-01-03 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, gregrodgers, JonChesterfield, ronlieb.
Herald added subscribers: guansong, yaxunl.
jhuber6 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

This patch adds support for embedding the device object files into the
host IR to create a fat binary. Each offloading file will be inserted
into a section with the following naming format
`.llvm.offloading..`.

Depends on D116542 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116543

Files:
  clang/lib/Driver/ToolChains/Clang.cpp


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4357,9 +4357,9 @@
   IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
 
   InputInfoList ModuleHeaderInputs;
+  InputInfoList OpenMPHostInputs;
   const InputInfo *CudaDeviceInput = nullptr;
   const InputInfo *OpenMPDeviceInput = nullptr;
-  const InputInfo *OpenMPHostInput = nullptr;
   for (const InputInfo &I : Inputs) {
 if (&I == &Input) {
   // This is the primary input.
@@ -4376,8 +4376,8 @@
   CudaDeviceInput = &I;
 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
   OpenMPDeviceInput = &I;
-} else if (IsOpenMPHost && !OpenMPHostInput) {
-  OpenMPHostInput = &I;
+} else if (IsOpenMPHost) {
+  OpenMPHostInputs.push_back(I);
 } else {
   llvm_unreachable("unexpectedly given multiple inputs");
 }
@@ -6870,6 +6870,32 @@
 }
   }
 
+  // Host-side OpenMP offloading recieves the device object files and embeds it
+  // in a named section including the associated target triple and 
architecture.
+  if (IsOpenMPHost && !OpenMPHostInputs.empty()) {
+SmallString<128> InputFiles("-fembed-offload-binary=");
+SmallString<128> InputSections("-fembed-offload-section=");
+
+auto InputFile = OpenMPHostInputs.begin();
+auto OpenMPTCs = C.getOffloadToolChains();
+for (auto TI = OpenMPTCs.first, TE = OpenMPTCs.second; TI != TE;
+ ++TI, ++InputFile) {
+  const ToolChain *TC = TI->second;
+  const ArgList &TCArgs = C.getArgsForToolChain(TC, "", 
Action::OFK_OpenMP);
+  InputSections += TC->getTripleString() + ".";
+  InputSections += TCArgs.getLastArgValue(options::OPT_march_EQ);
+  InputSections += ",";
+
+  InputFiles += 
C.getArgs().MakeArgString(TC->getInputFilename(*InputFile));
+  InputFiles += ",";
+}
+InputSections.pop_back();
+InputFiles.pop_back();
+
+CmdArgs.push_back(Args.MakeArgString(InputFiles.str()));
+CmdArgs.push_back(Args.MakeArgString(InputSections.str()));
+  }
+
   if (Triple.isAMDGPU()) {
 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
 


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4357,9 +4357,9 @@
   IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
 
   InputInfoList ModuleHeaderInputs;
+  InputInfoList OpenMPHostInputs;
   const InputInfo *CudaDeviceInput = nullptr;
   const InputInfo *OpenMPDeviceInput = nullptr;
-  const InputInfo *OpenMPHostInput = nullptr;
   for (const InputInfo &I : Inputs) {
 if (&I == &Input) {
   // This is the primary input.
@@ -4376,8 +4376,8 @@
   CudaDeviceInput = &I;
 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
   OpenMPDeviceInput = &I;
-} else if (IsOpenMPHost && !OpenMPHostInput) {
-  OpenMPHostInput = &I;
+} else if (IsOpenMPHost) {
+  OpenMPHostInputs.push_back(I);
 } else {
   llvm_unreachable("unexpectedly given multiple inputs");
 }
@@ -6870,6 +6870,32 @@
 }
   }
 
+  // Host-side OpenMP offloading recieves the device object files and embeds it
+  // in a named section including the associated target triple and architecture.
+  if (IsOpenMPHost && !OpenMPHostInputs.empty()) {
+SmallString<128> InputFiles("-fembed-offload-binary=");
+SmallString<128> InputSections("-fembed-offload-section=");
+
+auto InputFile = OpenMPHostInputs.begin();
+auto OpenMPTCs = C.getOffloadToolChains();
+for (auto TI = OpenMPTCs.first, TE = OpenMPTCs.second; TI != TE;
+ ++TI, ++InputFile) {
+  const ToolChain *TC = TI->second;
+  const ArgList &TCArgs = C.getArgsForToolChain(TC, "", Action::OFK_OpenMP);
+  InputSections += TC->getTripleString() + ".";
+  InputSections += TCArgs.getLastArgValue(options::OPT_march_EQ);
+  InputSections += ",";
+
+  InputFiles += C.getArgs().MakeArgString(TC->getInputFilename(*InputFile));
+  InputFiles += ",";
+}
+InputSections.pop_back();
+InputFiles.pop_back();
+
+CmdArgs.push_back(Args.MakeArgString(InputFiles.str()));
+CmdArgs.push_back(Args.Mak

[PATCH] D115716: [Analyzer][BugReporter] Replace the example bug report with the one used to generate PathDiagnostic

2022-01-03 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

First off, your patch is great, and I'm pretty sure we want it!

I remember working around here, and I either have never quite understood what 
makes `exampleReport` an example, or have long forgotten. Can we not just 
rename it to `chosenReport`, or simply `report`?




Comment at: clang/lib/StaticAnalyzer/Core/BugReporter.cpp:3068-3078
+  const BugReport *report = findReportInEquivalenceClass(EQ, bugReports);
   if (!report)
 return;
 
   // See whether we need to silence the checker/package.
   for (const std::string &CheckerOrPackage :
getAnalyzerOptions().SilencedCheckersAndPackages) {

Wouldn't it make more sense to create initialize (instead of resetting) 
`report` at the call to `generateDiagnosticForConsumerMap()`? This just looks a 
bit convoluted. We could turn everything up to that point into a 
[[https://llvm.org/docs/CodingStandards.html#turn-predicate-loops-into-predicate-functions
 | predicate function]].


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115716

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


[PATCH] D116492: [lld] Deprecate using llvm-config to detect llvm installation

2022-01-03 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added inline comments.



Comment at: clang/CMakeLists.txt:26
   "--src-root"
-  "--cmakedir")
+  "--cmakedir"
+  "--bindir"

I assume these are re-arranged to match what you're doing in lld. Is that 
correct?

Generally it is preferred to do this kind of non-functional restructuring in a 
separate commit from the commit with a functional change to make it easier to 
review the functional changes.

This patch as-is seems to have cleanup to clang, and a functional change for 
lld. Those should likely be two separate commits.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116492

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


[PATCH] D116544: [Clang] Introduce Clang Linker Wrapper Tool

2022-01-03 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, gregrodgers, JonChesterfield, ronlieb.
Herald added a subscriber: mgorny.
jhuber6 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

This patch introduces a linker wrapper tool that allows us to preprocess
files before they are sent to the linker. This adds a dummy action and
job to the driver stage that builds the linker command as usual and then
replaces the command line with the wrapper tool.

Depends on D116543 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116544

Files:
  clang/include/clang/Driver/Action.h
  clang/include/clang/Driver/Job.h
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/Action.cpp
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Clang.h
  clang/tools/CMakeLists.txt
  clang/tools/clang-linker-wrapper/CMakeLists.txt
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp

Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- /dev/null
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -0,0 +1,91 @@
+//===-- clang-linker-wrapper/ClangLinkerWrapper.cpp - wrapper over linker-===//
+//
+// 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/Basic/Version.h"
+#include "llvm/Object/Archive.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Errc.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/StringSaver.h"
+#include "llvm/Support/WithColor.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace llvm;
+
+static cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden);
+
+// Mark all our options with this category, everything else (except for -help)
+// will be hidden.
+static cl::OptionCategory
+ClangLinkerWrapperCategory("clang-linker-wrapper options");
+
+static cl::opt LinkerUserPath("linker-path",
+   cl::desc("Path of linker binary"),
+   cl::cat(ClangLinkerWrapperCategory));
+
+// Do not parse linker options
+static cl::list
+LinkerArgs(cl::Sink, cl::desc("..."));
+
+static Error runLinker(std::string LinkerPath,
+   SmallVectorImpl &Args) {
+  std::vector LinkerArgs;
+  LinkerArgs.push_back(LinkerPath);
+  for (auto &Arg : Args)
+LinkerArgs.push_back(Arg);
+
+  if (sys::ExecuteAndWait(LinkerPath, LinkerArgs))
+return createStringError(inconvertibleErrorCode(), "'linker' failed");
+  return Error::success();
+}
+
+static void PrintVersion(raw_ostream &OS) {
+  OS << clang::getClangToolFullVersion("clang-linker-wrapper") << '\n';
+}
+
+int main(int argc, const char **argv) {
+  sys::PrintStackTraceOnErrorSignal(argv[0]);
+  cl::SetVersionPrinter(PrintVersion);
+  cl::HideUnrelatedOptions(ClangLinkerWrapperCategory);
+  cl::ParseCommandLineOptions(
+  argc, argv,
+  "A wrapper utility over the host linker. It scans the input files for\n"
+  "sections that require additional processing prior to linking. The tool\n"
+  "will then transparently pass all arguments and input to the specified\n"
+  "host linker to create the final binary.\n");
+
+  if (Help) {
+cl::PrintHelpMessage();
+return EXIT_SUCCESS;
+  }
+
+  auto reportError = [argv](Error E) {
+logAllUnhandledErrors(std::move(E), WithColor::error(errs(), argv[0]));
+exit(EXIT_FAILURE);
+  };
+
+  // TODO: Scan input object files for offloading sections and extract them.
+  // TODO: Perform appropriate device linking action.
+  // TODO: Wrap device image in a host binary and pass it to the linker.
+  WithColor::warning(errs(), argv[0]) << "Offload linking not yet supported.\n";
+
+  SmallVector Argv;
+  for (const std::string &Arg : LinkerArgs)
+Argv.push_back(Arg);
+
+  if (Error Err = runLinker(LinkerUserPath, Argv))
+reportError(std::move(Err));
+
+  return EXIT_SUCCESS;
+}
Index: clang/tools/clang-linker-wrapper/CMakeLists.txt
===
--- /dev/null
+++ clang/tools/clang-linker-wrapper/CMakeLists.txt
@@ -0,0 +1,25 @@
+set(LLVM_LINK_COMPONENTS BitWriter Core Object Support)
+
+if(NOT CLANG_BUILT_STANDALONE)
+  set(tablegen_deps intrinsics_gen)
+endif()
+
+add_clang_executable(clang-linker-wrapper
+  ClangLinkerWrapper.cpp
+
+  DEPENDS
+ 

[PATCH] D116545: [OpenMP] Add support for extracting device code in linker wrapper

2022-01-03 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, gregrodgers, JonChesterfield, ronlieb.
Herald added subscribers: guansong, yaxunl, mgorny.
jhuber6 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

This patchs add support for extracting device offloading code from the
linker's input files. If the file contains a section with the name
`.llvm.offloading..` it will be extracted to a new
temporary file to be linked. Addtionally, the host file containing it
will have the section stripped so it does not remain in the executable
once linked.

Depends on D116544 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116545

Files:
  clang/tools/clang-linker-wrapper/CMakeLists.txt
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp

Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -5,23 +5,41 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===-===//
-///
+//
+// This tool works as a wrapper over a linking job. This tool is used to create
+// linked device images for offloading. It scans the linker's input for embedded
+// device offloading data stored in sections `.llvm.offloading..`
+// and extracts it as a temporary file. The extracted device files will then be
+// passed to a device linking job to create a final device image.
+//
 //===-===//
 
 #include "clang/Basic/Version.h"
+#include "llvm/BinaryFormat/Magic.h"
+#include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/IR/Constants.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IRReader/IRReader.h"
 #include "llvm/Object/Archive.h"
+#include "llvm/Object/ArchiveWriter.h"
+#include "llvm/Object/Binary.h"
+#include "llvm/Object/ObjectFile.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Errc.h"
+#include "llvm/Support/FileOutputBuffer.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/StringSaver.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
 using namespace llvm;
+using namespace llvm::object;
 
 static cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden);
 
@@ -30,16 +48,42 @@
 static cl::OptionCategory
 ClangLinkerWrapperCategory("clang-linker-wrapper options");
 
+static cl::opt StripSections(
+"strip-sections", cl::ZeroOrMore,
+cl::desc("Strip offloading sections from the host object file."),
+cl::init(true), cl::cat(ClangLinkerWrapperCategory));
+
 static cl::opt LinkerUserPath("linker-path",
cl::desc("Path of linker binary"),
cl::cat(ClangLinkerWrapperCategory));
 
-// Do not parse linker options
+// Do not parse linker options.
 static cl::list
 LinkerArgs(cl::Sink, cl::desc("..."));
 
-static Error runLinker(std::string LinkerPath,
-   SmallVectorImpl &Args) {
+/// Path of the current binary.
+static std::string LinkerExecutable;
+
+/// Magic section string that marks the existence of offloading data. The
+/// section string will be formatted as `.llvm.offloading..`.
+#define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading"
+
+struct DeviceFile {
+  DeviceFile(StringRef TheTriple, StringRef Arch, StringRef Filename)
+  : TheTriple(TheTriple), Arch(Arch), Filename(Filename) {}
+
+  const Triple TheTriple;
+  const std::string Arch;
+  const std::string Filename;
+};
+
+namespace {
+
+Expected>
+extractFromBuffer(std::unique_ptr Buffer,
+  SmallVectorImpl &DeviceFiles);
+
+Error runLinker(std::string &LinkerPath, SmallVectorImpl &Args) {
   std::vector LinkerArgs;
   LinkerArgs.push_back(LinkerPath);
   for (auto &Arg : Args)
@@ -50,11 +94,309 @@
   return Error::success();
 }
 
-static void PrintVersion(raw_ostream &OS) {
+void PrintVersion(raw_ostream &OS) {
   OS << clang::getClangToolFullVersion("clang-linker-wrapper") << '\n';
 }
 
+void removeFromCompilerUsed(Module &M, GlobalValue &Value) {
+  GlobalVariable *GV = M.getGlobalVariable("llvm.compiler.used");
+  Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
+  Constant *ValueToRemove =
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(&Value, Int8PtrTy);
+  SmallPtrSet InitAsSet;
+  SmallVector Init;
+  if (GV) {
+if (GV->hasInitializer()) {
+  auto *CA = cast(GV->getInitializer());
+  for (auto &Op : CA->operands()) {
+Constant *C = cast_or_null(Op);
+   

[PATCH] D116492: [lld] Deprecate using llvm-config to detect llvm installation

2022-01-03 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 added inline comments.



Comment at: clang/CMakeLists.txt:26
   "--src-root"
-  "--cmakedir")
+  "--cmakedir"
+  "--bindir"

beanz wrote:
> I assume these are re-arranged to match what you're doing in lld. Is that 
> correct?
> 
> Generally it is preferred to do this kind of non-functional restructuring in 
> a separate commit from the commit with a functional change to make it easier 
> to review the functional changes.
> 
> This patch as-is seems to have cleanup to clang, and a functional change for 
> lld. Those should likely be two separate commits.
Happy to split up.

The clang changes I wouldn't even say make it "better" per say, I am just 
reording things to put the stuff LLD also goes first for sake diffing the two. 
I thought that might look lke a noisy and pointless patch on its own, but I am 
happy to split it up if you still think it's a good idea.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116492

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


[PATCH] D116492: [lld] Deprecate using llvm-config to detect llvm installation

2022-01-03 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added inline comments.



Comment at: clang/CMakeLists.txt:26
   "--src-root"
-  "--cmakedir")
+  "--cmakedir"
+  "--bindir"

Ericson2314 wrote:
> beanz wrote:
> > I assume these are re-arranged to match what you're doing in lld. Is that 
> > correct?
> > 
> > Generally it is preferred to do this kind of non-functional restructuring 
> > in a separate commit from the commit with a functional change to make it 
> > easier to review the functional changes.
> > 
> > This patch as-is seems to have cleanup to clang, and a functional change 
> > for lld. Those should likely be two separate commits.
> Happy to split up.
> 
> The clang changes I wouldn't even say make it "better" per say, I am just 
> reording things to put the stuff LLD also goes first for sake diffing the 
> two. I thought that might look lke a noisy and pointless patch on its own, 
> but I am happy to split it up if you still think it's a good idea.
More smaller patches is generally the LLVM philosophy, so I do think it makes 
sense to split it up into an NFC patch for clang, and a separate change for lld.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116492

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


[PATCH] D114425: [clang] Add __builtin_bswap128

2022-01-03 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:2930
+  }
+  [[fallthrough]];
   case Builtin::BI__builtin_bswap16:

Quuxplusone wrote:
> Re clang-format's complaint: I would either move `[[fallthrough]];` inside 
> the curly braces, or (probably better) just eliminate the fallthrough by 
> either duplicating line 2934 or else doing
> ```
>   case Builtin::BI__builtin_bswap64:
>   case Builtin::BI__builtin_bswap128: {
> if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_bswap128 && 
> !Target.hasInt128Type())
>   CGM.ErrorUnsupported(E, "__builtin_bswap128");
> return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bswap));
>   }
> ```
I believe we are still using `LLVM_FALLTHROUGH` rather than `[[fallthrough]]`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114425

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


[PATCH] D116313: [MSVC] Silence -Wnon-virtual-dtor on DIA APIs

2022-01-03 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added a comment.
This revision is now accepted and ready to land.

lgtm


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116313

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


[PATCH] D115106: [clang-tidy] Fix `readability-static-accessed-through-instance` false negative for static methods

2022-01-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: sammccall, klimek, hokein.
aaron.ballman added a comment.

Adding some more reviewers, as this is starting to touch on AST matcher design 
more deeply and needs a wider audience.




Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:6017
+/// cxxMethodDecl(isStatic()) matches A::foo() but not A::bar()
+AST_MATCHER(CXXMethodDecl, isStatic) { return Node.isStatic(); }
+

simon.giesecke wrote:
> aaron.ballman wrote:
> > I would prefer we not expose this AST matcher as a public one. There's 
> > sufficient confusion around "as written in source" vs "computed" vs 
> > "linkage" in this area that I think we should be careful when introducing 
> > matchers around storage classes and storage durations. Then again, the 
> > water is already pretty muddy here, so maybe this ship sailed...
> > 
> > Other potential solutions to this issue would be to expose an AST matcher 
> > to traverse to the canonical decl or only matches the canonical decl, then 
> > we could use that to wrap the existing call to `isStaticStorageClass()`. 
> > (Of course, we could make this matcher local to just that source file, as 
> > well.)
> > 
> > Thoughts?
> I think if we have a `isStaticStorageClass` matcher, then we can also have 
> `isStatic` matcher.
> 
> But maybe we shouldn't have either of those in the public header, but maybe 
> add a different one as you suggested, under a suitable name with as little 
> ambiguity as possible.
> 
> And maybe keep the `isStaticStorageClass` matcher but rename it to reduce the 
> chance of misunderstanding?
> 
> Then, as mentioned in my original top-level comment, I can imagine that there 
> are more uses of the `isStaticStorageClass` matcher in clang-tidy rules (and 
> maybe elsewhere) that actually should use the new matcher.
My current thinking on this is that I'm not opposed to exposing the 
functionality, but I have Opinions about the names of how we expose these and 
what they model. There are quite a few ways to think about "is static" (with 
some overlap between them):

1) Was this declaration marked with the `static` keyword?
2) Does this declaration have static storage duration? 
http://eel.is/c++draft/basic.stc.static#def:storage_duration,static
3) Does this declaration have internal linkage? 
http://eel.is/c++draft/basic.link#3.1
4) Does this declaration have a static array extent? C2x 6.7.6.3p6
5) Does the definition a member function have access to a `this` pointer/does 
the definition of a data member contribute to the subobjects of the class? 
http://eel.is/c++draft/class.static
6) All of the above questions, but instead of specific to one declaration, is 
about all (re)declarations of the entity.

I don't think we want to cover #4 as part of this patch (that's more about 
types and less about declarations), and I think #6 is a general matcher 
question.

FWIW, we currently have matchers for:

`isStaticLocal`
`hasStaticStorageDuration`
`isStaticStorageClass`

So I don't think `isStatic` is viable -- it's just too ambiguous given all the 
many uses of the keyword and the existing set of matchers.

My intuition is that we might want a new kind of traversal matcher for matching 
over a set of redeclarations. e.g., `functionDecl(isStaticStorageClass())` vs 
`anyRedeclaration(functionDecl(isStaticStorageClass()))`:
```
static void func(); // #1
void func(); // #2
void func() {} // #3
```
where `functionDecl(isStaticStorageClass())` would match #1 and 
`anyRedeclaration(functionDecl(isStaticStorageClass))` would match #1, #2, and 
#3. I think if we had this sort of facility, we could probably make use of our 
existing matchers (perhaps with improved names) to achieve the same goal as 
you're going for, but I'm curious what other folks think as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115106

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


[PATCH] D116313: [MSVC] Silence -Wnon-virtual-dtor on DIA APIs

2022-01-03 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea added a comment.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116313

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


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

2022-01-03 Thread David Majnemer via Phabricator via cfe-commits
majnemer added a comment.

In D115456#3217595 , @momo5502 wrote:

> In D115456#3216811 , @majnemer 
> wrote:
>
>> This is looking great! Just a few more questions.
>>
>> What is the behavior with something like:
>>
>>   thread_local int x = 2;
>>   int f() {
>> return x;
>>   }
>>
>> I'm wondering if we need to move this logic 
>> 
>>  into the generic C++ ABI implementation.
>
> The MS compiler only emits the dynamic initializers for variables with 
> constructors/destructors, just like it is currently done here for the Itanium 
> ABI.
> I also thought about adopting that behaviour, but I think threre are 
> edge-cases when triggering dynamic TLS initialization even for constant 
> variables is useful.
> For example there might be custom TLS callbacks that can affect the value of 
> this variable.
>
> If desired, I can change it to match the behaviour of MS, but I thought it 
> could be beneficial to diverge in this case.

IMO, it is probably best to match behavior here within reason (ignoring bugs 
latent in MSVC) here. My thinking is that in the face of COMDATs, we cannot 
ensure which copy of an inline function will make its way to the binary and 
different link orders would provide different behavior.


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] D114425: [clang] Add __builtin_bswap128

2022-01-03 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:2930
+  }
+  [[fallthrough]];
   case Builtin::BI__builtin_bswap16:

craig.topper wrote:
> Quuxplusone wrote:
> > Re clang-format's complaint: I would either move `[[fallthrough]];` inside 
> > the curly braces, or (probably better) just eliminate the fallthrough by 
> > either duplicating line 2934 or else doing
> > ```
> >   case Builtin::BI__builtin_bswap64:
> >   case Builtin::BI__builtin_bswap128: {
> > if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_bswap128 && 
> > !Target.hasInt128Type())
> >   CGM.ErrorUnsupported(E, "__builtin_bswap128");
> > return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bswap));
> >   }
> > ```
> I believe we are still using `LLVM_FALLTHROUGH` rather than `[[fallthrough]]`
There's really no reason for the curly braces. There are no variables declared 
so you don't need a new scope. The code that it is being fallen into doesn't 
need them either.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114425

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


[PATCH] D116547: Revert "[amdgpu] Enable selection of `s_cselect_b64`."

2022-01-03 Thread David Salinas via Phabricator via cfe-commits
david-salinas created this revision.
Herald added subscribers: luke957, abrachet, ormris, foad, dang, jdoerfert, 
phosek, kerbowa, usaxena95, pengfei, s.egerton, asbirlea, mstorsjo, lebedev.ri, 
kadircet, rupprecht, arphaman, steven_wu, mgrang, simoncook, fedor.sergeev, 
hiraditya, krytarowski, arichardson, t-tye, tpr, dstuttard, yaxunl, mgorny, 
nhaehnle, jvesely, kzhuravl, emaste, arsenm, dschuff.
Herald added a reviewer: lebedev.ri.
Herald added a reviewer: jhenderson.
Herald added a project: lld-macho.
Herald added a reviewer: lld-macho.
david-salinas requested review of this revision.
Herald added subscribers: cfe-commits, llvm-commits, libcxx-commits, 
lldb-commits, Sanitizers, sstefan1, MaskRay, wdng.
Herald added a reviewer: jdoerfert.
Herald added projects: clang, Sanitizers, LLDB, libc++, LLVM, clang-tools-extra.
Herald added a reviewer: libc++.

This reverts commit 640beb38e7710b939b3cfb3f4c54accc694b1d30 
.

Change-Id: I179ce9595d31af5847fc5c29d66ae8c845dff0a8


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116547

Files:
  clang-tools-extra/clangd/unittests/TestScheme.h
  clang/lib/Driver/ToolChains/HIP.cpp
  clang/lib/Driver/ToolChains/HIP.h
  clang/test/CodeGen/Inputs/sanitizer-blacklist-vfsoverlay.yaml
  clang/test/CodeGen/catch-alignment-assumption-blacklist.c
  clang/test/CodeGen/catch-nullptr-and-nonzero-offset-blacklist.c
  clang/test/CodeGen/ubsan-blacklist.c
  clang/test/CodeGenCXX/cfi-blacklist.cpp
  clang/test/Driver/debug-var-experimental-switch.c
  clang/test/Sema/branch-protection-attr-err.c
  compiler-rt/cmake/Modules/CustomLibcxx/CMakeLists.txt
  compiler-rt/lib/sanitizer_common/sanitizer_persistent_allocator.h
  compiler-rt/lib/tsan/rtl/tsan_update_shadow_word.inc
  compiler-rt/test/fuzzer/EntropicScalePerExecTimeTest.cpp
  compiler-rt/test/fuzzer/entropic-scale-per-exec-time.test
  compiler-rt/test/memprof/TestCases/mem_info_cache_entries.cpp
  compiler-rt/test/memprof/TestCases/print_miss_rate.cpp
  compiler-rt/test/ubsan/TestCases/Pointer/alignment-assumption-ignorelist.cppp
  libcxx/cmake/caches/Generic-32bits.cmake
  libcxx/include/__memory/pointer_safety.h
  libcxx/test/libcxx/atomics/ext-int.verify.cpp
  libcxx/test/libcxx/atomics/libcpp-has-no-threads.compile.fail.cpp
  libcxx/test/libcxx/atomics/libcpp-has-no-threads.pass.cpp
  libcxx/test/std/algorithms/robust_against_adl.pass.cpp
  
libcxx/test/std/atomics/atomics.types.generic/trivially_copyable.compile.fail.cpp
  
libcxx/test/std/containers/sequences/vector/vector.modifiers/insert_iter_value.pass.cpp
  
libcxx/test/std/language.support/support.limits/support.limits.general/charconv.pass.cpp
  
libcxx/test/std/language.support/support.limits/support.limits.general/memory_resource.version.pass.cpp
  libcxx/test/std/numerics/c.math/abs.fail.cpp
  libcxx/test/std/strings/string.view/string.view.cons/deduct.pass.cpp
  
libcxx/test/std/utilities/any/any.nonmembers/any.cast/const_correctness.fail.cpp
  
libcxx/test/std/utilities/any/any.nonmembers/any.cast/not_copy_constructible.fail.cpp
  
libcxx/test/std/utilities/memory/util.dynamic.safety/declare_no_pointers.pass.cpp
  
libcxx/test/std/utilities/memory/util.dynamic.safety/declare_reachable.pass.cpp
  
libcxx/test/std/utilities/memory/util.dynamic.safety/get_pointer_safety.pass.cpp
  
libcxx/test/std/utilities/meta/meta.trans/meta.trans.other/result_of.deprecated.fail.cpp
  libcxx/test/support/coroutine_types.h
  libcxx/test/support/tracked_value.h
  libcxx/utils/google-benchmark/.clang-format
  libcxx/utils/google-benchmark/.github/.libcxx-setup.sh
  libcxx/utils/google-benchmark/.github/ISSUE_TEMPLATE/bug_report.md
  libcxx/utils/google-benchmark/.github/ISSUE_TEMPLATE/feature_request.md
  libcxx/utils/google-benchmark/.github/workflows/bazel.yml
  
libcxx/utils/google-benchmark/.github/workflows/build-and-test-perfcounters.yml
  libcxx/utils/google-benchmark/.github/workflows/build-and-test.yml
  libcxx/utils/google-benchmark/.github/workflows/pylint.yml
  libcxx/utils/google-benchmark/.github/workflows/sanitizer.yml
  libcxx/utils/google-benchmark/.github/workflows/test_bindings.yml
  libcxx/utils/google-benchmark/.gitignore
  libcxx/utils/google-benchmark/.travis.yml
  libcxx/utils/google-benchmark/.ycm_extra_conf.py
  libcxx/utils/google-benchmark/AUTHORS
  libcxx/utils/google-benchmark/BUILD.bazel
  libcxx/utils/google-benchmark/CMakeLists.txt
  libcxx/utils/google-benchmark/CONTRIBUTING.md
  libcxx/utils/google-benchmark/CONTRIBUTORS
  libcxx/utils/google-benchmark/LICENSE
  libcxx/utils/google-benchmark/README.md
  libcxx/utils/google-benchmark/WORKSPACE
  libcxx/utils/google-benchmark/_config.yml
  libcxx/utils/google-benchmark/appveyor.yml
  libcxx/utils/google-benchmark/bindings/python/BUILD
  libcxx/utils/google-benchmark/bindings/python/build_defs.bzl
  libcxx/utils/google-benchmark/bindings/python/google_benchmark/BUILD
  libcxx/utils/google-benchmark/bindings/python

[PATCH] D116548: [clang][cmake] Rearrange top-level CMakeLists.txt for D116492

2022-01-03 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 created this revision.
Ericson2314 added reviewers: beanz, tstellar.
Herald added a subscriber: mgorny.
Ericson2314 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

In that revision, I make LLD match Clang in deprecating `llvm-config`.
This patch isn't to worthwhile on its own --- there isn't a sense in
which the new order is "better" in isolation --- but by putting the
steps that LLD also neeeds to do first, I make the diff between LLD and
Clang's top-level `CMakeLists.txt` very legible.

Longer term I hope:

1. We can remove calling `llvm-config` altogether, and just go strait to 
finding the CMake config file. This is what Flang does, at least.
2. Hopefully the diffable part is smaller then --- i.e. there is less 
duplicated boilerplate.
3. Any duplicate boilerplate that remains can be factored out.

I didn't both trying to factor anything out in e.g. the top level common
CMake Utility modules because this deprecated-but-not-removed state is a
merely transitional.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116548

Files:
  clang/CMakeLists.txt

Index: clang/CMakeLists.txt
===
--- clang/CMakeLists.txt
+++ clang/CMakeLists.txt
@@ -2,7 +2,7 @@
 
 # If we are not building as a part of LLVM, build Clang as an
 # standalone project, using LLVM as an external library:
-if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR )
+if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
   project(Clang)
 
   set(CMAKE_CXX_STANDARD 14 CACHE STRING "C++ standard to conform to")
@@ -10,7 +10,7 @@
   set(CMAKE_CXX_EXTENSIONS NO)
 
   # Rely on llvm-config.
-  set(CONFIG_OUTPUT)
+  set(LLVM_CONFIG_OUTPUT)
   if(LLVM_CONFIG)
 set (LLVM_CONFIG_FOUND 1)
 message(STATUS "Found LLVM_CONFIG as ${LLVM_CONFIG}")
@@ -20,35 +20,36 @@
   automatically, but you can also use LLVM_DIR to specify \
   the path containing LLVMConfig.cmake.")
 set(CONFIG_COMMAND ${LLVM_CONFIG}
-  "--assertion-mode"
-  "--bindir"
-  "--libdir"
   "--includedir"
   "--prefix"
   "--src-root"
-  "--cmakedir")
+  "--cmakedir"
+  "--bindir"
+  "--libdir"
+  "--assertion-mode"
+  )
 execute_process(
   COMMAND ${CONFIG_COMMAND}
   RESULT_VARIABLE HAD_ERROR
-  OUTPUT_VARIABLE CONFIG_OUTPUT
+  OUTPUT_VARIABLE LLVM_CONFIG_OUTPUT
 )
 if(NOT HAD_ERROR)
   string(REGEX REPLACE
 "[ \t]*[\r\n]+[ \t]*" ";"
-CONFIG_OUTPUT ${CONFIG_OUTPUT})
+LLVM_CONFIG_OUTPUT ${LLVM_CONFIG_OUTPUT})
 else()
   string(REPLACE ";" " " CONFIG_COMMAND_STR "${CONFIG_COMMAND}")
   message(STATUS "${CONFIG_COMMAND_STR}")
   message(FATAL_ERROR "llvm-config failed with status ${HAD_ERROR}")
 endif()
 
-list(GET CONFIG_OUTPUT 0 ENABLE_ASSERTIONS)
-list(GET CONFIG_OUTPUT 1 TOOLS_BINARY_DIR)
-list(GET CONFIG_OUTPUT 2 LIBRARY_DIR)
-list(GET CONFIG_OUTPUT 3 INCLUDE_DIR)
-list(GET CONFIG_OUTPUT 4 LLVM_OBJ_ROOT)
-list(GET CONFIG_OUTPUT 5 MAIN_SRC_DIR)
-list(GET CONFIG_OUTPUT 6 LLVM_CONFIG_CMAKE_DIR)
+list(GET LLVM_CONFIG_OUTPUT 0 MAIN_INCLUDE_DIR)
+list(GET LLVM_CONFIG_OUTPUT 1 LLVM_OBJ_ROOT)
+list(GET LLVM_CONFIG_OUTPUT 2 MAIN_SRC_DIR)
+list(GET LLVM_CONFIG_OUTPUT 3 LLVM_CONFIG_CMAKE_DIR)
+list(GET LLVM_CONFIG_OUTPUT 4 TOOLS_BINARY_DIR)
+list(GET LLVM_CONFIG_OUTPUT 5 LIBRARY_DIR)
+list(GET LLVM_CONFIG_OUTPUT 6 ENABLE_ASSERTIONS)
 
 # Normalize LLVM_CMAKE_DIR. --cmakedir might contain backslashes.
 # CMake assumes slashes as PATH.
@@ -71,17 +72,17 @@
   if (NOT LLVM_CONFIG_FOUND)
 # Pull values from LLVMConfig.cmake.  We can drop this once the llvm-config
 # path is removed.
+set(MAIN_INCLUDE_DIR ${LLVM_INCLUDE_DIR})
+set(LLVM_OBJ_DIR ${LLVM_BINARY_DIR})
 set(TOOLS_BINARY_DIR ${LLVM_TOOLS_BINARY_DIR})
 set(LIBRARY_DIR ${LLVM_LIBRARY_DIR})
-set(INCLUDE_DIR ${LLVM_INCLUDE_DIR})
-set(LLVM_OBJ_DIR ${LLVM_BINARY_DIR})
   endif()
 
-  set(LLVM_TOOLS_BINARY_DIR ${TOOLS_BINARY_DIR} CACHE PATH "Path to llvm/bin")
-  set(LLVM_LIBRARY_DIR ${LIBRARY_DIR} CACHE PATH "Path to llvm/lib")
-  set(LLVM_MAIN_INCLUDE_DIR ${INCLUDE_DIR} CACHE PATH "Path to llvm/include")
+  set(LLVM_MAIN_INCLUDE_DIR ${MAIN_INCLUDE_DIR} CACHE PATH "Path to llvm/include")
   set(LLVM_BINARY_DIR ${LLVM_OBJ_ROOT} CACHE PATH "Path to LLVM build tree")
   set(LLVM_MAIN_SRC_DIR ${MAIN_SRC_DIR} CACHE PATH "Path to LLVM source tree")
+  set(LLVM_TOOLS_BINARY_DIR ${TOOLS_BINARY_DIR} CACHE PATH "Path to llvm/bin")
+  set(LLVM_LIBRARY_DIR ${LIBRARY_DIR} CACHE PATH "Path to llvm/lib")
 
   find_program(LLVM_TABLEGEN_EXE "llvm-tblgen" ${LLVM_TOOLS_BINARY_DIR}
 NO_DEFAULT_PATH)
@@ -184,11 +185,12 @@
 endif()
   endif()
 
-  set( CLANG_BUILT_STANDALONE 1 )
+  set(CLANG_BUILT_STANDALONE TRUE)
+
   set(BACKEND_PACKAGE_STRING "LLVM ${LLVM_PACKAGE_VERSI

[PATCH] D116492: [lld] Deprecate using llvm-config to detect llvm installation

2022-01-03 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 updated this revision to Diff 397100.
Ericson2314 added a comment.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Split out Clang changes into separate commit


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116492

Files:
  lld/CMakeLists.txt

Index: lld/CMakeLists.txt
===
--- lld/CMakeLists.txt
+++ lld/CMakeLists.txt
@@ -1,58 +1,77 @@
+cmake_minimum_required(VERSION 3.13.4)
+
 include(GNUInstallDirs)
 
-# Check if lld is built as a standalone project.
+# If we are not building as a part of LLVM, build LLD as an
+# standalone project, using LLVM as an external library:
 if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
   project(lld)
-  cmake_minimum_required(VERSION 3.13.4)
 
   set(CMAKE_INCLUDE_CURRENT_DIR ON)
-  set(LLD_BUILT_STANDALONE TRUE)
 
-  find_program(LLVM_CONFIG_PATH "llvm-config" DOC "Path to llvm-config binary")
-  if(NOT LLVM_CONFIG_PATH)
-message(FATAL_ERROR "llvm-config not found: specify LLVM_CONFIG_PATH")
-  endif()
+  # Rely on llvm-config.
+  set(LLVM_CONFIG_OUTPUT)
+  if(LLVM_CONFIG)
+set (LLVM_CONFIG_FOUND 1)
+message(STATUS "Found LLVM_CONFIG as ${LLVM_CONFIG}")
+message(DEPRECATION "Using llvm-config to detect the LLVM installation is \
+  deprecated.  The installed cmake files should be used \
+  instead.  CMake should be able to detect your LLVM install \
+  automatically, but you can also use LLVM_DIR to specify \
+  the path containing LLVMConfig.cmake.")
+set(CONFIG_COMMAND ${LLVM_CONFIG}
+  "--includedir"
+  "--prefix"
+  "--src-root"
+  "--cmakedir"
+  )
+execute_process(
+  COMMAND ${CONFIG_COMMAND}
+  RESULT_VARIABLE HAD_ERROR
+  OUTPUT_VARIABLE LLVM_CONFIG_OUTPUT
+)
+if(NOT HAD_ERROR)
+  string(REGEX REPLACE
+"[ \t]*[\r\n]+[ \t]*" ";"
+LLVM_CONFIG_OUTPUT ${LLVM_CONFIG_OUTPUT})
+else()
+  string(REPLACE ";" " " CONFIG_COMMAND_STR "${CONFIG_COMMAND}")
+  message(STATUS "${CONFIG_COMMAND_STR}")
+  message(FATAL_ERROR "llvm-config failed with status ${HAD_ERROR}")
+endif()
+
+list(GET LLVM_CONFIG_OUTPUT 0 MAIN_INCLUDE_DIR)
+list(GET LLVM_CONFIG_OUTPUT 1 LLVM_OBJ_ROOT)
+list(GET LLVM_CONFIG_OUTPUT 2 MAIN_SRC_DIR)
+list(GET LLVM_CONFIG_OUTPUT 3 LLVM_CONFIG_CMAKE_DIR)
 
-  execute_process(COMMAND "${LLVM_CONFIG_PATH}"
-  "--obj-root"
-  "--includedir"
-  "--cmakedir"
-  "--src-root"
-  RESULT_VARIABLE HAD_ERROR
-  OUTPUT_VARIABLE LLVM_CONFIG_OUTPUT
-  OUTPUT_STRIP_TRAILING_WHITESPACE)
-  if(HAD_ERROR)
-message(FATAL_ERROR "llvm-config failed with status ${HAD_ERROR}")
+# Normalize LLVM_CMAKE_DIR. --cmakedir might contain backslashes.
+# CMake assumes slashes as PATH.
+file(TO_CMAKE_PATH ${LLVM_CONFIG_CMAKE_DIR} LLVM_CMAKE_DIR)
   endif()
 
-  string(REGEX REPLACE "[ \t]*[\r\n]+[ \t]*" ";" LLVM_CONFIG_OUTPUT "${LLVM_CONFIG_OUTPUT}")
+  find_package(LLVM REQUIRED HINTS "${LLVM_CMAKE_DIR}")
+  list(APPEND CMAKE_MODULE_PATH ${LLVM_DIR})
 
-  list(GET LLVM_CONFIG_OUTPUT 0 OBJ_ROOT)
-  list(GET LLVM_CONFIG_OUTPUT 1 MAIN_INCLUDE_DIR)
-  list(GET LLVM_CONFIG_OUTPUT 2 LLVM_CMAKE_DIR)
-  list(GET LLVM_CONFIG_OUTPUT 3 MAIN_SRC_DIR)
+  # We can't check LLVM_CONFIG here, because find_package(LLVM ...) also sets
+  # LLVM_CONFIG.
+  if (NOT LLVM_CONFIG_FOUND)
+# Pull values from LLVMConfig.cmake.  We can drop this once the llvm-config
+# path is removed.
+set(MAIN_INCLUDE_DIR ${LLVM_INCLUDE_DIR})
+set(LLVM_OBJ_DIR ${LLVM_BINARY_DIR})
+  endif()
 
-  set(LLVM_OBJ_ROOT ${OBJ_ROOT} CACHE PATH "path to LLVM build tree")
-  set(LLVM_MAIN_INCLUDE_DIR ${MAIN_INCLUDE_DIR} CACHE PATH "path to llvm/include")
+  set(LLVM_MAIN_INCLUDE_DIR ${MAIN_INCLUDE_DIR} CACHE PATH "Path to llvm/include")
+  set(LLVM_BINARY_DIR ${LLVM_OBJ_ROOT} CACHE PATH "Path to LLVM build tree")
   set(LLVM_MAIN_SRC_DIR ${MAIN_SRC_DIR} CACHE PATH "Path to LLVM source tree")
 
-  file(TO_CMAKE_PATH "${LLVM_OBJ_ROOT}" LLVM_BINARY_DIR)
-  file(TO_CMAKE_PATH "${LLVM_CMAKE_DIR}" LLVM_CMAKE_DIR)
-
-  if(NOT EXISTS "${LLVM_CMAKE_DIR}/LLVMConfig.cmake")
-message(FATAL_ERROR "LLVMConfig.cmake not found")
-  endif()
-  include("${LLVM_CMAKE_DIR}/LLVMConfig.cmake")
-
-  list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}")
+  find_program(LLVM_TABLEGEN_EXE "llvm-tblgen" ${LLVM_TOOLS_BINARY_DIR}
+NO_DEFAULT_PATH)
 
-  set(PACKAGE_VERSION "${LLVM_PACKAGE_VERSION}")
-  include_directories("${LLVM_BINARY_DIR}/include" ${LLVM_INCLUDE_DIRS})
-  link_directories(${LLVM_LIBRARY_DIRS})
-
-  set(LLVM_LIBRARY_OUTPUT_INTDIR ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/lib${LLVM_LIBDIR_SUFFIX})
+  # They are used as destination of target gen

[PATCH] D116492: [lld] Deprecate using llvm-config to detect llvm installation

2022-01-03 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 marked 2 inline comments as done.
Ericson2314 added inline comments.



Comment at: clang/CMakeLists.txt:26
   "--src-root"
-  "--cmakedir")
+  "--cmakedir"
+  "--bindir"

beanz wrote:
> Ericson2314 wrote:
> > beanz wrote:
> > > I assume these are re-arranged to match what you're doing in lld. Is that 
> > > correct?
> > > 
> > > Generally it is preferred to do this kind of non-functional restructuring 
> > > in a separate commit from the commit with a functional change to make it 
> > > easier to review the functional changes.
> > > 
> > > This patch as-is seems to have cleanup to clang, and a functional change 
> > > for lld. Those should likely be two separate commits.
> > Happy to split up.
> > 
> > The clang changes I wouldn't even say make it "better" per say, I am just 
> > reording things to put the stuff LLD also goes first for sake diffing the 
> > two. I thought that might look lke a noisy and pointless patch on its own, 
> > but I am happy to split it up if you still think it's a good idea.
> More smaller patches is generally the LLVM philosophy, so I do think it makes 
> sense to split it up into an NFC patch for clang, and a separate change for 
> lld.
Sure. Done in D116492.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116492

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


[PATCH] D114425: [clang] Add __builtin_bswap128

2022-01-03 Thread David Majnemer via Phabricator via cfe-commits
majnemer added a comment.

In D114425#3217478 , @Quuxplusone 
wrote:

> In D114425#3216802 , @majnemer 
> wrote:
>
>> OOC, how hard would it be to generalize this builtin a little? It is nice 
>> that we have builtins like `__builtin_add_overflow` which do the right thing 
>> regardless of their input.
>>
>> It seems like it would be nice if we started to expose more intrinsics which 
>> did the right thing regardless of operand width; another bonus is that it 
>> composes well with language features like `_BitInt`.
>
> IMHO such builtins are nice iff the programmer can be 100% sure that the 
> compiler will interpret them the same way as a human reader. 
> `__builtin_add_overflow` is easy because its first two arguments are 
> "mathematical integers" (where integer promotion doesn't matter) and its 
> third argument is a pointer (where integer promotion can't happen). So you 
> can really throw any combination of types at it, and it'll do "the right 
> thing" https://godbolt.org/z/sa7b894oa (although I admit I was surprised that 
> this worked).
> For a hypothetical `__builtin_bswap`, you would probably need a similar 
> pointer-based interface like
>
>   short s16 = 0xFEDC;
>   __builtin_bswap(&s16);  // hypothetically
>   assert(s16 == 0xDCFE);
>   
>   assert(__builtin_bswap16(s16) == 0xDCFE);
>   assert(__builtin_bswap32(s16) == 0xDCFE);  // the problem to solve: s16 
> eagerly promotes to int, which changes the result
>
> The downside is that the pointer-based interface is less ergonomic than 
> today's value-based signatures, and probably worse codegen at `-O0` (because 
> the programmer has to materialize the operand into a named variable, and then 
> the compiler won't remove that variable because you might want to debug it). 
> The upside (as you said) is that a generic builtin could work with `_ExtInt` 
> types and so on.

I think one way of side stepping that problem would be to say that 
`__builtin_bswap` only works with unsigned types.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114425

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


[PATCH] D116492: [lld] Deprecate using llvm-config to detect llvm installation

2022-01-03 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 marked an inline comment as done.
Ericson2314 added inline comments.



Comment at: clang/CMakeLists.txt:26
   "--src-root"
-  "--cmakedir")
+  "--cmakedir"
+  "--bindir"

Ericson2314 wrote:
> beanz wrote:
> > Ericson2314 wrote:
> > > beanz wrote:
> > > > I assume these are re-arranged to match what you're doing in lld. Is 
> > > > that correct?
> > > > 
> > > > Generally it is preferred to do this kind of non-functional 
> > > > restructuring in a separate commit from the commit with a functional 
> > > > change to make it easier to review the functional changes.
> > > > 
> > > > This patch as-is seems to have cleanup to clang, and a functional 
> > > > change for lld. Those should likely be two separate commits.
> > > Happy to split up.
> > > 
> > > The clang changes I wouldn't even say make it "better" per say, I am just 
> > > reording things to put the stuff LLD also goes first for sake diffing the 
> > > two. I thought that might look lke a noisy and pointless patch on its 
> > > own, but I am happy to split it up if you still think it's a good idea.
> > More smaller patches is generally the LLVM philosophy, so I do think it 
> > makes sense to split it up into an NFC patch for clang, and a separate 
> > change for lld.
> Sure. Done in D116492.
Oops, that's this one! I meant D116548.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116492

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


  1   2   3   >