[clang] 5fc6213 - Revert change to clang/test/CodeGen/arm_acle.c

2022-07-19 Thread Nicolai Hähnle via cfe-commits

Author: Nicolai Hähnle
Date: 2022-07-19T09:11:23+02:00
New Revision: 5fc62135511069086e88f846f9bac2eb40b01e94

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

LOG: Revert change to clang/test/CodeGen/arm_acle.c

For some reason, update_cc_test_checks.py produced a failing test.

Partial revert of 301011fa6078b4f16bd3fc6158d9c6fddad7e118

Added: 


Modified: 
clang/test/CodeGen/arm_acle.c

Removed: 




diff  --git a/clang/test/CodeGen/arm_acle.c b/clang/test/CodeGen/arm_acle.c
index 9a731742e946..7fbaf36aec3d 100644
--- a/clang/test/CodeGen/arm_acle.c
+++ b/clang/test/CodeGen/arm_acle.c
@@ -56,12 +56,12 @@ void test_isb(void) {
 /* 8.4 Hints */
 // AArch32-LABEL: @test_yield(
 // AArch32-NEXT:  entry:
-// AArch32-NEXT:call void @llvm.arm.hint(i32 1) #[[ATTR1:[0-9]+]]
+// AArch32-NEXT:call void @llvm.arm.hint(i32 1) [[ATTR1:#.*]]
 // AArch32-NEXT:ret void
 //
 // AArch64-LABEL: @test_yield(
 // AArch64-NEXT:  entry:
-// AArch64-NEXT:call void @llvm.aarch64.hint(i32 1) #[[ATTR3:[0-9]+]]
+// AArch64-NEXT:call void @llvm.aarch64.hint(i32 1) [[ATTR3:#.*]]
 // AArch64-NEXT:ret void
 //
 void test_yield(void) {
@@ -70,12 +70,12 @@ void test_yield(void) {
 
 // AArch32-LABEL: @test_wfe(
 // AArch32-NEXT:  entry:
-// AArch32-NEXT:call void @llvm.arm.hint(i32 2) #[[ATTR1]]
+// AArch32-NEXT:call void @llvm.arm.hint(i32 2) [[ATTR1]]
 // AArch32-NEXT:ret void
 //
 // AArch64-LABEL: @test_wfe(
 // AArch64-NEXT:  entry:
-// AArch64-NEXT:call void @llvm.aarch64.hint(i32 2) #[[ATTR3]]
+// AArch64-NEXT:call void @llvm.aarch64.hint(i32 2) [[ATTR3]]
 // AArch64-NEXT:ret void
 //
 void test_wfe(void) {
@@ -84,12 +84,12 @@ void test_wfe(void) {
 
 // AArch32-LABEL: @test_wfi(
 // AArch32-NEXT:  entry:
-// AArch32-NEXT:call void @llvm.arm.hint(i32 3) #[[ATTR1]]
+// AArch32-NEXT:call void @llvm.arm.hint(i32 3) [[ATTR1]]
 // AArch32-NEXT:ret void
 //
 // AArch64-LABEL: @test_wfi(
 // AArch64-NEXT:  entry:
-// AArch64-NEXT:call void @llvm.aarch64.hint(i32 3) #[[ATTR3]]
+// AArch64-NEXT:call void @llvm.aarch64.hint(i32 3) [[ATTR3]]
 // AArch64-NEXT:ret void
 //
 void test_wfi(void) {
@@ -98,12 +98,12 @@ void test_wfi(void) {
 
 // AArch32-LABEL: @test_sev(
 // AArch32-NEXT:  entry:
-// AArch32-NEXT:call void @llvm.arm.hint(i32 4) #[[ATTR1]]
+// AArch32-NEXT:call void @llvm.arm.hint(i32 4) [[ATTR1]]
 // AArch32-NEXT:ret void
 //
 // AArch64-LABEL: @test_sev(
 // AArch64-NEXT:  entry:
-// AArch64-NEXT:call void @llvm.aarch64.hint(i32 4) #[[ATTR3]]
+// AArch64-NEXT:call void @llvm.aarch64.hint(i32 4) [[ATTR3]]
 // AArch64-NEXT:ret void
 //
 void test_sev(void) {
@@ -112,12 +112,12 @@ void test_sev(void) {
 
 // AArch32-LABEL: @test_sevl(
 // AArch32-NEXT:  entry:
-// AArch32-NEXT:call void @llvm.arm.hint(i32 5) #[[ATTR1]]
+// AArch32-NEXT:call void @llvm.arm.hint(i32 5) [[ATTR1]]
 // AArch32-NEXT:ret void
 //
 // AArch64-LABEL: @test_sevl(
 // AArch64-NEXT:  entry:
-// AArch64-NEXT:call void @llvm.aarch64.hint(i32 5) #[[ATTR3]]
+// AArch64-NEXT:call void @llvm.aarch64.hint(i32 5) [[ATTR3]]
 // AArch64-NEXT:ret void
 //
 void test_sevl(void) {
@@ -141,10 +141,10 @@ void test_dbg(void) {
 // AArch32-NEXT:[[TMP0:%.*]] = bitcast i8* [[P:%.*]] to i32*
 // AArch32-NEXT:br label [[DO_BODY_I:%.*]]
 // AArch32:   do.body.i:
-// AArch32-NEXT:[[LDREX_I:%.*]] = call i32 @llvm.arm.ldrex.p0i32(i32* 
elementtype(i32) [[TMP0]]) #[[ATTR1]]
-// AArch32-NEXT:[[STREX_I:%.*]] = call i32 @llvm.arm.strex.p0i32(i32 
[[X:%.*]], i32* elementtype(i32) [[TMP0]]) #[[ATTR1]]
+// AArch32-NEXT:[[LDREX_I:%.*]] = call i32 @llvm.arm.ldrex.p0i32(i32* 
elementtype(i32) [[TMP0]]) [[ATTR1]]
+// AArch32-NEXT:[[STREX_I:%.*]] = call i32 @llvm.arm.strex.p0i32(i32 
[[X:%.*]], i32* elementtype(i32) [[TMP0]]) [[ATTR1]]
 // AArch32-NEXT:[[TOBOOL_I:%.*]] = icmp ne i32 [[STREX_I]], 0
-// AArch32-NEXT:br i1 [[TOBOOL_I]], label [[DO_BODY_I]], label 
[[__SWP_EXIT:%.*]], !llvm.loop [[LOOP7:![0-9]+]]
+// AArch32-NEXT:br i1 [[TOBOOL_I]], label [[DO_BODY_I]], label 
[[__SWP_EXIT:%.*]], [[LOOP3:!llvm.loop !.*]]
 // AArch32:   __swp.exit:
 // AArch32-NEXT:ret void
 //
@@ -153,12 +153,12 @@ void test_dbg(void) {
 // AArch64-NEXT:[[TMP0:%.*]] = bitcast i8* [[P:%.*]] to i32*
 // AArch64-NEXT:br label [[DO_BODY_I:%.*]]
 // AArch64:   do.body.i:
-// AArch64-NEXT:[[LDXR_I:%.*]] = call i64 @llvm.aarch64.ldxr.p0i32(i32* 
elementtype(i32) [[TMP0]]) #[[ATTR3]]
+// AArch64-NEXT:[[LDXR_I:%.*]] = call i64 @llvm.aarch64.ldxr.p0i32(i32* 
elementtype(i32) [[TMP0]]) [[ATTR3]]
 // AArch64-NEXT:[[TMP1:%.*]] = trunc i64 [[LDXR_I]] to i32
 // AArch64-NEXT:[[TMP2:%.*]] = zext i32 [[X:%.*]] to

[PATCH] D129573: [clang] add a diagnostic note 'while loop outside functions' at global scope

2022-07-19 Thread YingChi Long via Phabricator via cfe-commits
inclyc updated this revision to Diff 445712.

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

https://reviews.llvm.org/D129573

Files:
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/Parse/ParseDecl.cpp
  clang/test/Parser/while-loop-outside-function.c
  clang/test/Parser/while-loop-outside-function.cpp

Index: clang/test/Parser/while-loop-outside-function.cpp
===
--- /dev/null
+++ clang/test/Parser/while-loop-outside-function.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+while(true) {}; // expected-error {{while loop outside of a function}}
+
+// without semicolon
+while(true) {} // expected-error {{while loop outside of a function}}
+
+while(true)  // expected-error {{while loop outside of a function}}
+{
+// some statements
+int some_var = 3;
+some_var += 2;
+}
+
+do { // expected-error {{expected unqualified-id}}
+int some_var = 1;
+some_var += 3;
+} 
+while(true); // expected-error {{while loop outside of a function}}
+
+void someFunction() {
+while(true) {};
+}
+
+class SomeClass {
+public:
+while(true) {} // expected-error {{expected member name or ';' after declaration specifiers}}
+void some_fn() {
+while(true) {}
+}
+};
Index: clang/test/Parser/while-loop-outside-function.c
===
--- /dev/null
+++ clang/test/Parser/while-loop-outside-function.c
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+// basic
+while(1) {}; // expected-error {{while loop outside of a function}}
+
+
+// location?
+while(1) // expected-error {{while loop outside of a function}}
+{};
+
+// empty statement without semicolon
+while(1) // expected-error {{while loop outside of a function}}
+{}
+
+// some statements
+while(1)  // expected-error {{while loop outside of a function}}
+{
+int some_var = 0;
+}
+
+// recovery
+void some_fn();
+
+void some_fn() {
+while(1) {};
+}
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -6344,23 +6344,27 @@
diag::err_expected_member_name_or_semi)
   << (D.getDeclSpec().isEmpty() ? SourceRange()
 : D.getDeclSpec().getSourceRange());
-} else if (getLangOpts().CPlusPlus) {
-  if (Tok.isOneOf(tok::period, tok::arrow))
-Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
-  else {
-SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
-if (Tok.isAtStartOfLine() && Loc.isValid())
-  Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
-  << getLangOpts().CPlusPlus;
-else
-  Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
-   diag::err_expected_unqualified_id)
-  << getLangOpts().CPlusPlus;
-  }
 } else {
-  Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
-   diag::err_expected_either)
-  << tok::identifier << tok::l_paren;
+  if (Tok.getKind() == tok::TokenKind::kw_while) {
+Diag(Tok, diag::err_while_loop_outside_of_a_function);
+  } else if (getLangOpts().CPlusPlus) {
+if (Tok.isOneOf(tok::period, tok::arrow))
+  Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
+else {
+  SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
+  if (Tok.isAtStartOfLine() && Loc.isValid())
+Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
+<< getLangOpts().CPlusPlus;
+  else
+Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
+ diag::err_expected_unqualified_id)
+<< getLangOpts().CPlusPlus;
+}
+  } else {
+Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
+ diag::err_expected_either)
+<< tok::identifier << tok::l_paren;
+  }
 }
 D.SetIdentifier(nullptr, Tok.getLocation());
 D.setInvalidType(true);
Index: clang/include/clang/Basic/DiagnosticParseKinds.td
===
--- clang/include/clang/Basic/DiagnosticParseKinds.td
+++ clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -538,6 +538,8 @@
   "cannot use %select{dot|arrow}0 operator on a type">;
 def err_expected_unqualified_id : Error<
   "expected %select{identifier|unqualified-id}0">;
+def err_while_loop_outside_of_a_function : Error<
+  "while loop outside of a function">; 
 def err_brackets_go_after_unqualified_id : Error<
   "brackets are not allowed here; to declare an array, "
   "place the brackets after the %select{identifier|name}0">;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mai

[PATCH] D129222: [pseudo] Implement a guard to determine function declarator.

2022-07-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 445714.
hokein marked 3 inline comments as done.
hokein added a comment.

restore the previous and simplified function-declarator test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129222

Files:
  clang-tools-extra/pseudo/lib/cxx/CXX.cpp
  clang-tools-extra/pseudo/lib/cxx/cxx.bnf
  clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
  clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
  clang-tools-extra/pseudo/test/cxx/recovery-func-parameters.cpp
  clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
  clang-tools-extra/pseudo/test/glr.cpp

Index: clang-tools-extra/pseudo/test/glr.cpp
===
--- clang-tools-extra/pseudo/test/glr.cpp
+++ clang-tools-extra/pseudo/test/glr.cpp
@@ -1,4 +1,4 @@
-// RUN: clang-pseudo -grammar=%cxx-bnf-file -source=%s --print-forest -print-statistics | FileCheck %s
+// RUN: clang-pseudo -grammar=cxx -source=%s --print-forest -print-statistics | FileCheck %s
 
 void foo() {
   T* a; // a multiply expression or a pointer declaration?
Index: clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
===
--- clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
+++ clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
@@ -3,7 +3,7 @@
 // CHECK:  translation-unit~simple-declaration
 // CHECK-NEXT: ├─decl-specifier-seq~AUTO := tok[0]
 // CHECK-NEXT: ├─init-declarator-list~init-declarator
-// CHECK-NEXT: │ ├─declarator~IDENTIFIER := tok[1]
+// CHECK-NEXT: │ ├─non-function-declarator~IDENTIFIER := tok[1]
 // CHECK-NEXT: │ └─initializer~brace-or-equal-initializer
 // CHECK-NEXT: │   ├─= := tok[2]
 // CHECK-NEXT: │   └─initializer-clause~braced-init-list
Index: clang-tools-extra/pseudo/test/cxx/recovery-func-parameters.cpp
===
--- clang-tools-extra/pseudo/test/cxx/recovery-func-parameters.cpp
+++ clang-tools-extra/pseudo/test/cxx/recovery-func-parameters.cpp
@@ -1,8 +1,8 @@
 // RUN: clang-pseudo -grammar=cxx -source=%s --print-forest | FileCheck %s
 void foo(complete garbage???) {}
-// CHECK:  translation-unit~function-definition := decl-specifier-seq declarator function-body
+// CHECK:  translation-unit~function-definition := decl-specifier-seq function-declarator function-body
 // CHECK-NEXT: ├─decl-specifier-seq~VOID := tok[0]
-// CHECK-NEXT: ├─declarator~noptr-declarator := noptr-declarator parameters-and-qualifiers
+// CHECK-NEXT: ├─function-declarator~noptr-declarator := noptr-declarator parameters-and-qualifiers
 // CHECK-NEXT: │ ├─noptr-declarator~IDENTIFIER := tok[1]
 // CHECK-NEXT: │ └─parameters-and-qualifiers := ( parameter-declaration-clause [recover=Brackets] )
 // CHECK-NEXT: │   ├─( := tok[2]
Index: clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
===
--- clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
+++ clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
@@ -1,11 +1,9 @@
 // The standard grammar allows an function-body to use any declarator, including
 // a non-function declarator. This creates an ambiguity where a
 // simple-declaration is misparsed as a function-definition.
-// FIXME: eliminate this false parse.
-// XFAIL: *
 
 // RUN: clang-pseudo -grammar=cxx -source=%s --print-forest | FileCheck %s
 void (*s)(){};
 // CHECK-NOT:  function-definition
-// CHECK:  init-declarator := declarator initializer
+// CHECK:  init-declarator := non-function-declarator initializer
 // CHECK-NOT:  function-definition
Index: clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
===
--- clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
+++ clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
@@ -1,11 +1,9 @@
 // The standard grammar allows an init-list with any declarator, including
 // a function declarator. This creates an ambiguity where a function-definition
 // is misparsed as a simple-declaration.
-// FIXME: eliminate this false parse.
-// XFAIL: *
 
 // RUN: clang-pseudo -grammar=cxx -source=%s --print-forest | FileCheck %s
 void s(){};
 // CHECK-NOT:  simple-declaration
-// CHECK:  function-definition := decl-specifier-seq declarator
-// function-body CHECK-NOT:  simple-declaration
+// CHECK:  function-definition := decl-specifier-seq function-declarator function-body
+// CHECK-NOT:  simple-declaration
Index: clang-tools-extra/pseudo/lib/cxx/cxx.bnf
===
--- clang-tools-extra/pseudo/lib/cxx/cxx.bnf
+++ clang-tools-extra/pseudo/lib/cxx/cxx.bnf
@@ -332,7 +332,7 @@
 block-declaration := static_assert-decla

[clang-tools-extra] d489b38 - [pseudo] Implement a guard to determine function declarator.

2022-07-19 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-07-19T09:44:45+02:00
New Revision: d489b3807f096584175c321ce7f20e9dcd49b1da

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

LOG: [pseudo] Implement a guard to determine function declarator.

This eliminates some simple-declaration/function-definition false
parses.

- implement a function to determine whether a declarator ForestNode is a
  function declarator;
- extend the standard declarator to two guarded function-declarator and
  non-function-declarator nonterminals;

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

Added: 


Modified: 
clang-tools-extra/pseudo/lib/cxx/CXX.cpp
clang-tools-extra/pseudo/lib/cxx/cxx.bnf
clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
clang-tools-extra/pseudo/test/cxx/recovery-func-parameters.cpp
clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
clang-tools-extra/pseudo/test/glr.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/lib/cxx/CXX.cpp 
b/clang-tools-extra/pseudo/lib/cxx/CXX.cpp
index 9a03422153f06..d6c056a25e365 100644
--- a/clang-tools-extra/pseudo/lib/cxx/CXX.cpp
+++ b/clang-tools-extra/pseudo/lib/cxx/CXX.cpp
@@ -46,6 +46,66 @@ bool guardExport(llvm::ArrayRef RHS,
   return Tokens.tokens()[RHS.front()->startTokenIndex()].text() == "export";
 }
 
+bool isFunctionDeclarator(const ForestNode *Declarator) {
+  assert(Declarator->symbol() == (SymbolID)(cxx::Symbol::declarator));
+  bool IsFunction = false;
+  using cxx::Rule;
+  while (true) {
+// not well-formed code, return the best guess.
+if (Declarator->kind() != ForestNode::Sequence)
+  return IsFunction;
+
+switch ((cxx::Rule)Declarator->rule()) {
+case Rule::noptr_declarator_0declarator_id: // reached the bottom
+  return IsFunction;
+// *X is a nonfunction (unless X is a function).
+case Rule::ptr_declarator_0ptr_operator_1ptr_declarator:
+  Declarator = Declarator->elements()[1];
+  IsFunction = false;
+  continue;
+// X() is a function (unless X is a pointer or similar).
+case Rule::
+
declarator_0noptr_declarator_1parameters_and_qualifiers_2trailing_return_type:
+case Rule::noptr_declarator_0noptr_declarator_1parameters_and_qualifiers:
+  Declarator = Declarator->elements()[0];
+  IsFunction = true;
+  continue;
+// X[] is an array (unless X is a pointer or function).
+case Rule::
+
noptr_declarator_0noptr_declarator_1l_square_2constant_expression_3r_square:
+case Rule::noptr_declarator_0noptr_declarator_1l_square_2r_square:
+  Declarator = Declarator->elements()[0];
+  IsFunction = false;
+  continue;
+// (X) is whatever X is.
+case Rule::noptr_declarator_0l_paren_1ptr_declarator_2r_paren:
+  Declarator = Declarator->elements()[1];
+  continue;
+case Rule::ptr_declarator_0noptr_declarator:
+case Rule::declarator_0ptr_declarator:
+  Declarator = Declarator->elements()[0];
+  continue;
+
+default:
+  assert(false && "unhandled declarator for IsFunction");
+  return IsFunction;
+}
+  }
+  llvm_unreachable("unreachable");
+}
+bool guardFunction(llvm::ArrayRef RHS,
+   const TokenStream &Tokens) {
+  assert(RHS.size() == 1 &&
+ RHS.front()->symbol() == (SymbolID)(cxx::Symbol::declarator));
+  return isFunctionDeclarator(RHS.front());
+}
+bool guardNonFunction(llvm::ArrayRef RHS,
+  const TokenStream &Tokens) {
+  assert(RHS.size() == 1 &&
+ RHS.front()->symbol() == (SymbolID)(cxx::Symbol::declarator));
+  return !isFunctionDeclarator(RHS.front());
+}
+
 llvm::DenseMap buildGuards() {
   return {
   {(ExtensionID)Extension::Override, guardOverride},
@@ -53,6 +113,8 @@ llvm::DenseMap buildGuards() {
   {(ExtensionID)Extension::Import, guardImport},
   {(ExtensionID)Extension::Export, guardExport},
   {(ExtensionID)Extension::Module, guardModule},
+  {(ExtensionID)Extension::FunctionDeclarator, guardFunction},
+  {(ExtensionID)Extension::NonFunctionDeclarator, guardNonFunction},
   };
 }
 

diff  --git a/clang-tools-extra/pseudo/lib/cxx/cxx.bnf 
b/clang-tools-extra/pseudo/lib/cxx/cxx.bnf
index 08384af9d9399..4e434b1e037cc 100644
--- a/clang-tools-extra/pseudo/lib/cxx/cxx.bnf
+++ b/clang-tools-extra/pseudo/lib/cxx/cxx.bnf
@@ -332,7 +332,7 @@ block-declaration := using-directive
 block-declaration := static_assert-declaration
 block-declaration := alias-declaration
 block-declaration := opaque-enum-declaration
-nodeclspec-function-declaration := declarator ;
+nodeclspec-function-declaration := function-declarator ;
 alias-declaration := USING IDENTIFIER = defining-type-id ;
 simple-declaration := decl-specifier-seq init-

[PATCH] D129222: [pseudo] Implement a guard to determine function declarator.

2022-07-19 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd489b3807f09: [pseudo] Implement a guard to determine 
function declarator. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129222

Files:
  clang-tools-extra/pseudo/lib/cxx/CXX.cpp
  clang-tools-extra/pseudo/lib/cxx/cxx.bnf
  clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
  clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
  clang-tools-extra/pseudo/test/cxx/recovery-func-parameters.cpp
  clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
  clang-tools-extra/pseudo/test/glr.cpp

Index: clang-tools-extra/pseudo/test/glr.cpp
===
--- clang-tools-extra/pseudo/test/glr.cpp
+++ clang-tools-extra/pseudo/test/glr.cpp
@@ -1,4 +1,4 @@
-// RUN: clang-pseudo -grammar=%cxx-bnf-file -source=%s --print-forest -print-statistics | FileCheck %s
+// RUN: clang-pseudo -grammar=cxx -source=%s --print-forest -print-statistics | FileCheck %s
 
 void foo() {
   T* a; // a multiply expression or a pointer declaration?
Index: clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
===
--- clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
+++ clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
@@ -3,7 +3,7 @@
 // CHECK:  translation-unit~simple-declaration
 // CHECK-NEXT: ├─decl-specifier-seq~AUTO := tok[0]
 // CHECK-NEXT: ├─init-declarator-list~init-declarator
-// CHECK-NEXT: │ ├─declarator~IDENTIFIER := tok[1]
+// CHECK-NEXT: │ ├─non-function-declarator~IDENTIFIER := tok[1]
 // CHECK-NEXT: │ └─initializer~brace-or-equal-initializer
 // CHECK-NEXT: │   ├─= := tok[2]
 // CHECK-NEXT: │   └─initializer-clause~braced-init-list
Index: clang-tools-extra/pseudo/test/cxx/recovery-func-parameters.cpp
===
--- clang-tools-extra/pseudo/test/cxx/recovery-func-parameters.cpp
+++ clang-tools-extra/pseudo/test/cxx/recovery-func-parameters.cpp
@@ -1,8 +1,8 @@
 // RUN: clang-pseudo -grammar=cxx -source=%s --print-forest | FileCheck %s
 void foo(complete garbage???) {}
-// CHECK:  translation-unit~function-definition := decl-specifier-seq declarator function-body
+// CHECK:  translation-unit~function-definition := decl-specifier-seq function-declarator function-body
 // CHECK-NEXT: ├─decl-specifier-seq~VOID := tok[0]
-// CHECK-NEXT: ├─declarator~noptr-declarator := noptr-declarator parameters-and-qualifiers
+// CHECK-NEXT: ├─function-declarator~noptr-declarator := noptr-declarator parameters-and-qualifiers
 // CHECK-NEXT: │ ├─noptr-declarator~IDENTIFIER := tok[1]
 // CHECK-NEXT: │ └─parameters-and-qualifiers := ( parameter-declaration-clause [recover=Brackets] )
 // CHECK-NEXT: │   ├─( := tok[2]
Index: clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
===
--- clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
+++ clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
@@ -1,11 +1,9 @@
 // The standard grammar allows an function-body to use any declarator, including
 // a non-function declarator. This creates an ambiguity where a
 // simple-declaration is misparsed as a function-definition.
-// FIXME: eliminate this false parse.
-// XFAIL: *
 
 // RUN: clang-pseudo -grammar=cxx -source=%s --print-forest | FileCheck %s
 void (*s)(){};
 // CHECK-NOT:  function-definition
-// CHECK:  init-declarator := declarator initializer
+// CHECK:  init-declarator := non-function-declarator initializer
 // CHECK-NOT:  function-definition
Index: clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
===
--- clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
+++ clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
@@ -1,11 +1,9 @@
 // The standard grammar allows an init-list with any declarator, including
 // a function declarator. This creates an ambiguity where a function-definition
 // is misparsed as a simple-declaration.
-// FIXME: eliminate this false parse.
-// XFAIL: *
 
 // RUN: clang-pseudo -grammar=cxx -source=%s --print-forest | FileCheck %s
 void s(){};
 // CHECK-NOT:  simple-declaration
-// CHECK:  function-definition := decl-specifier-seq declarator
-// function-body CHECK-NOT:  simple-declaration
+// CHECK:  function-definition := decl-specifier-seq function-declarator function-body
+// CHECK-NOT:  simple-declaration
Index: clang-tools-extra/pseudo/lib/cxx/cxx.bnf
===
--- clang-tools-extra/pseudo/lib/cxx/cxx.bnf
+++ clang-tools-extra/pseudo/lib/

[clang] 4bb19de - [X86] Add 64 bit implement for __SSC_MARK

2022-07-19 Thread Xiang1 Zhang via cfe-commits

Author: Xiang1 Zhang
Date: 2022-07-19T16:13:41+08:00
New Revision: 4bb19de4b6cbe56636a1e7cd9c53aae3dcf4d4b0

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

LOG: [X86] Add 64 bit implement for __SSC_MARK

Reviewed By: craig.topper, pengfei.wang, jinsong
Differential Revision: https://reviews.llvm.org/D129826

Added: 


Modified: 
clang/lib/Headers/x86gprintrin.h
clang/test/CodeGen/X86/x86-ssc-mark.c

Removed: 




diff  --git a/clang/lib/Headers/x86gprintrin.h 
b/clang/lib/Headers/x86gprintrin.h
index 01e741f1eb611..2c2fbb97c9ac8 100644
--- a/clang/lib/Headers/x86gprintrin.h
+++ b/clang/lib/Headers/x86gprintrin.h
@@ -25,11 +25,29 @@
 #include 
 #endif
 
-#define __SSC_MARK(Tag)
\
-  __asm__ __volatile__("mov {%%ebx, %%eax|eax, ebx}; "  \
-   "mov {%0, %%ebx|ebx, %0}; "  \
+#if defined(__i386__)
+#define __FULLBX "ebx"
+#define __TMPGPR "eax"
+#else
+// When in 64-bit target, the 32-bit operands generate a 32-bit result,
+// zero-extended to a 64-bit result in the destination general-purpose,
+// It means "mov x %ebx" will clobber the higher 32 bits of rbx, so we
+// should preserve the 64-bit register rbx.
+#define __FULLBX "rbx"
+#define __TMPGPR "rax"
+#endif
+
+#define __MOVEGPR(__r1, __r2) "mov {%%"__r1 ", %%"__r2 "|"__r2 ", "__r1"};"
+
+#define __SAVE_GPRBX __MOVEGPR(__FULLBX, __TMPGPR)
+#define __RESTORE_GPRBX __MOVEGPR(__TMPGPR, __FULLBX)
+
+#define __SSC_MARK(__Tag)  
\
+  __asm__ __volatile__( __SAVE_GPRBX   
\
+   "mov {%0, %%ebx|ebx, %0}; " 
\
".byte 0x64, 0x67, 0x90; "  
\
-   "mov {%%eax, %%ebx|ebx, eax};" ::"i"(Tag)\
-   : "%eax");
+__RESTORE_GPRBX
\
+   ::"i"(__Tag)
\
+   :  __TMPGPR );
 
 #endif /* __X86GPRINTRIN_H */

diff  --git a/clang/test/CodeGen/X86/x86-ssc-mark.c 
b/clang/test/CodeGen/X86/x86-ssc-mark.c
index bcfee4fb3b0c5..0eb86c7c15b9a 100644
--- a/clang/test/CodeGen/X86/x86-ssc-mark.c
+++ b/clang/test/CodeGen/X86/x86-ssc-mark.c
@@ -1,20 +1,29 @@
 // REQUIRES: x86-registered-target
-// RUN: %clang_cc1 %s -triple=x86_64-unknown-unknown -S -ffreestanding -o - | 
FileCheck %s
-// RUN: %clang_cc1 %s -triple=i386-unknown-unknown -S -ffreestanding -o - | 
FileCheck %s
+// RUN: %clang_cc1 %s -triple=i386-unknown-unknown -S -ffreestanding -o - | 
FileCheck %s --check-prefix=X86
+// RUN: %clang_cc1 %s -triple=x86_64-unknown-unknown -S -ffreestanding -o - | 
FileCheck %s --check-prefix=X64
 
 #include 
 
 // The ebx may be use for base pointer, we need to restore it in time.
 void ssc_mark(void) {
-// CHECK-LABEL: ssc_mark
-// CHECK: #APP
-// CHECK: movl%ebx, %eax
-// CHECK: movl$0, %ebx
-// CHECK: .byte   100
-// CHECK: .byte   103
-// CHECK: .byte   144
-// CHECK: movl%eax, %ebx
-// CHECK: #NO_APP
+// X86-LABEL: ssc_mark
+// X86: #APP
+// X86: movl%ebx, %eax
+// X86: movl$9, %ebx
+// X86: .byte   100
+// X86: .byte   103
+// X86: .byte   144
+// X86: movl%eax, %ebx
+// X86: #NO_APP
 
-  __SSC_MARK(0x0);
+// X64-LABEL: ssc_mark
+// X64: #APP
+// X64: movq%rbx, %rax
+// X64: movl$9, %ebx
+// X64: .byte   100
+// X64: .byte   103
+// X64: .byte   144
+// X64: movq%rax, %rbx
+// X64: #NO_APP
+  __SSC_MARK(0x9);
 }



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


[PATCH] D129826: [X86] [BugFix] Add 64 bit implement for __SSC_MARK

2022-07-19 Thread Xiang Zhang 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 rG4bb19de4b6cb: [X86] Add 64 bit implement for __SSC_MARK 
(authored by xiangzhangllvm).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129826

Files:
  clang/lib/Headers/x86gprintrin.h
  clang/test/CodeGen/X86/x86-ssc-mark.c


Index: clang/test/CodeGen/X86/x86-ssc-mark.c
===
--- clang/test/CodeGen/X86/x86-ssc-mark.c
+++ clang/test/CodeGen/X86/x86-ssc-mark.c
@@ -1,20 +1,29 @@
 // REQUIRES: x86-registered-target
-// RUN: %clang_cc1 %s -triple=x86_64-unknown-unknown -S -ffreestanding -o - | 
FileCheck %s
-// RUN: %clang_cc1 %s -triple=i386-unknown-unknown -S -ffreestanding -o - | 
FileCheck %s
+// RUN: %clang_cc1 %s -triple=i386-unknown-unknown -S -ffreestanding -o - | 
FileCheck %s --check-prefix=X86
+// RUN: %clang_cc1 %s -triple=x86_64-unknown-unknown -S -ffreestanding -o - | 
FileCheck %s --check-prefix=X64
 
 #include 
 
 // The ebx may be use for base pointer, we need to restore it in time.
 void ssc_mark(void) {
-// CHECK-LABEL: ssc_mark
-// CHECK: #APP
-// CHECK: movl%ebx, %eax
-// CHECK: movl$0, %ebx
-// CHECK: .byte   100
-// CHECK: .byte   103
-// CHECK: .byte   144
-// CHECK: movl%eax, %ebx
-// CHECK: #NO_APP
+// X86-LABEL: ssc_mark
+// X86: #APP
+// X86: movl%ebx, %eax
+// X86: movl$9, %ebx
+// X86: .byte   100
+// X86: .byte   103
+// X86: .byte   144
+// X86: movl%eax, %ebx
+// X86: #NO_APP
 
-  __SSC_MARK(0x0);
+// X64-LABEL: ssc_mark
+// X64: #APP
+// X64: movq%rbx, %rax
+// X64: movl$9, %ebx
+// X64: .byte   100
+// X64: .byte   103
+// X64: .byte   144
+// X64: movq%rax, %rbx
+// X64: #NO_APP
+  __SSC_MARK(0x9);
 }
Index: clang/lib/Headers/x86gprintrin.h
===
--- clang/lib/Headers/x86gprintrin.h
+++ clang/lib/Headers/x86gprintrin.h
@@ -25,11 +25,29 @@
 #include 
 #endif
 
-#define __SSC_MARK(Tag)
\
-  __asm__ __volatile__("mov {%%ebx, %%eax|eax, ebx}; "  \
-   "mov {%0, %%ebx|ebx, %0}; "  \
+#if defined(__i386__)
+#define __FULLBX "ebx"
+#define __TMPGPR "eax"
+#else
+// When in 64-bit target, the 32-bit operands generate a 32-bit result,
+// zero-extended to a 64-bit result in the destination general-purpose,
+// It means "mov x %ebx" will clobber the higher 32 bits of rbx, so we
+// should preserve the 64-bit register rbx.
+#define __FULLBX "rbx"
+#define __TMPGPR "rax"
+#endif
+
+#define __MOVEGPR(__r1, __r2) "mov {%%"__r1 ", %%"__r2 "|"__r2 ", "__r1"};"
+
+#define __SAVE_GPRBX __MOVEGPR(__FULLBX, __TMPGPR)
+#define __RESTORE_GPRBX __MOVEGPR(__TMPGPR, __FULLBX)
+
+#define __SSC_MARK(__Tag)  
\
+  __asm__ __volatile__( __SAVE_GPRBX   
\
+   "mov {%0, %%ebx|ebx, %0}; " 
\
".byte 0x64, 0x67, 0x90; "  
\
-   "mov {%%eax, %%ebx|ebx, eax};" ::"i"(Tag)\
-   : "%eax");
+__RESTORE_GPRBX
\
+   ::"i"(__Tag)
\
+   :  __TMPGPR );
 
 #endif /* __X86GPRINTRIN_H */


Index: clang/test/CodeGen/X86/x86-ssc-mark.c
===
--- clang/test/CodeGen/X86/x86-ssc-mark.c
+++ clang/test/CodeGen/X86/x86-ssc-mark.c
@@ -1,20 +1,29 @@
 // REQUIRES: x86-registered-target
-// RUN: %clang_cc1 %s -triple=x86_64-unknown-unknown -S -ffreestanding -o - | FileCheck %s
-// RUN: %clang_cc1 %s -triple=i386-unknown-unknown -S -ffreestanding -o - | FileCheck %s
+// RUN: %clang_cc1 %s -triple=i386-unknown-unknown -S -ffreestanding -o - | FileCheck %s --check-prefix=X86
+// RUN: %clang_cc1 %s -triple=x86_64-unknown-unknown -S -ffreestanding -o - | FileCheck %s --check-prefix=X64
 
 #include 
 
 // The ebx may be use for base pointer, we need to restore it in time.
 void ssc_mark(void) {
-// CHECK-LABEL: ssc_mark
-// CHECK: #APP
-// CHECK: movl%ebx, %eax
-// CHECK: movl$0, %ebx
-// CHECK: .byte   100
-// CHECK: .byte   103
-// CHECK: .byte   144
-// CHECK: movl%eax, %ebx
-// CHECK: #NO_APP
+// X86-LABEL: ssc_mark
+// X86: #APP
+// X86: movl%ebx, %eax
+// X86: movl$9, %ebx
+// X86: .byte   100
+// X86: .byte   103
+// X86: .byte   144
+// X86: movl%eax, %ebx
+// X86: #NO_APP
 
-  __SSC_MARK(0x0);
+// X64-LABEL: ssc_mark
+// X64: #APP
+// X64: movq%rbx, %rax
+// X64: movl$9, %ebx
+// X

[PATCH] D130041: [clangd] Add decl/def support to SymbolDetails

2022-07-19 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

thanks, this LG per symboldetails change but as discussed offline i think we 
actually need a new request or a capability to indicate this (and having a new 
request is just easier for both clients and clangd) otherwise it can't be 
reliably used by clients.

in addition to that let's move the objcmethod related changes to its own patch 
since it's addressing a different issue.




Comment at: clang-tools-extra/clangd/AST.cpp:174
   auto L = D.getLocation();
+  // Use the start of the first selector fragment instead of the -/+ location.
+  if (const auto *MD = dyn_cast(&D))

can we do this in a separate change? as it has wider implications



Comment at: clang-tools-extra/clangd/Protocol.h:1097
+
+  llvm::Optional declarationRange;
+

ah getting absolute paths .. alright i guess we need to make this one optional, 
sorry for the noise on this one :/



Comment at: clang-tools-extra/clangd/XRefs.cpp:86
   return RD->getDefinition();
+  if (const auto *MD = dyn_cast(D))
+if (MD->isThisDeclarationADefinition())

again let's move this into a separate change



Comment at: clang-tools-extra/clangd/XRefs.cpp:1528
   }
-
+  auto MainFilePath =
+  getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM);

let's just pass the TUPath from ClangdServer into the request. (we should do 
the same for `locateSymbolAt`, but on a separate change)



Comment at: clang-tools-extra/clangd/XRefs.cpp:1557
+AST.getASTContext(), nameLocation(*Def, SM), *MainFilePath);
+  const NamedDecl *Decl = getPreferredDecl(D);
+  NewSymbol.declarationRange = makeLocation(

let's do this cannonicalization in the beginning of the loop, i.e:
```
for (const NamedDecl *D : getDeclAtPosition(AST, *CurLoc, Relations)) {
  D = getPreferredDecl(D);
  
}
```



Comment at: clang-tools-extra/clangd/test/symbol-info.test:4
 ---
 
{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///simple.cpp","languageId":"cpp","version":1,"text":"void
 foo(); int main() { foo(); }\n"}}}
 ---

can you also introduce the definition?



Comment at: clang-tools-extra/clangd/unittests/SymbolInfoTests.cpp:24
+  std::string Name;
+
+  std::string Container;

nit: drop the empty lines in between these fields



Comment at: clang-tools-extra/clangd/unittests/SymbolInfoTests.cpp:29
+
+  const char *DeclMarker = nullptr;
+  const char *DefMarker = nullptr;

since you're always calling these `decl` or `def`, you can instead check 
whether the annotation has any range named `def`/`decl` and expect those 
accordingly rather than mentioning them one extra time inside the testcases. 
i.e:

case:

```
void $def[[foo]]() {}
  int bar() {
fo^o();
  }
```

check:
```
Annotations Test(Case);
SymbolDetails Expected;
auto Def = Test.ranges("def");
auto Decl = Test.ranges("decl");
if (!Def.empty()) {
  Expected.decl = Expected.def = makelocation ...
} else if (!Decl.empty()) {
  Expected.decl = makelocation ...
}
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130041

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


[PATCH] D130063: [Driver] Enable sanitizers on FreeBSD AArch64

2022-07-19 Thread Andrew Turner via Phabricator via cfe-commits
andrew created this revision.
andrew added reviewers: Sanitizers, emaste, dim, arichardson.
Herald added a subscriber: kristof.beyls.
Herald added a project: All.
andrew requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

These sanitizers have been ported and tested to work on AArch64.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130063

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


Index: clang/lib/Driver/ToolChains/FreeBSD.cpp
===
--- clang/lib/Driver/ToolChains/FreeBSD.cpp
+++ clang/lib/Driver/ToolChains/FreeBSD.cpp
@@ -487,12 +487,14 @@
   Res |= SanitizerKind::PointerCompare;
   Res |= SanitizerKind::PointerSubtract;
   Res |= SanitizerKind::Vptr;
-  if (IsX86_64 || IsMIPS64) {
+  if (IsAArch64 || IsX86_64 || IsMIPS64) {
 Res |= SanitizerKind::Leak;
 Res |= SanitizerKind::Thread;
   }
   if (IsX86 || IsX86_64) {
 Res |= SanitizerKind::Function;
+  }
+  if (IsAArch64 || IsX86 || IsX86_64) {
 Res |= SanitizerKind::SafeStack;
 Res |= SanitizerKind::Fuzzer;
 Res |= SanitizerKind::FuzzerNoLink;
@@ -500,8 +502,6 @@
   if (IsAArch64 || IsX86_64) {
 Res |= SanitizerKind::KernelAddress;
 Res |= SanitizerKind::KernelMemory;
-  }
-  if (IsX86_64) {
 Res |= SanitizerKind::Memory;
   }
   return Res;


Index: clang/lib/Driver/ToolChains/FreeBSD.cpp
===
--- clang/lib/Driver/ToolChains/FreeBSD.cpp
+++ clang/lib/Driver/ToolChains/FreeBSD.cpp
@@ -487,12 +487,14 @@
   Res |= SanitizerKind::PointerCompare;
   Res |= SanitizerKind::PointerSubtract;
   Res |= SanitizerKind::Vptr;
-  if (IsX86_64 || IsMIPS64) {
+  if (IsAArch64 || IsX86_64 || IsMIPS64) {
 Res |= SanitizerKind::Leak;
 Res |= SanitizerKind::Thread;
   }
   if (IsX86 || IsX86_64) {
 Res |= SanitizerKind::Function;
+  }
+  if (IsAArch64 || IsX86 || IsX86_64) {
 Res |= SanitizerKind::SafeStack;
 Res |= SanitizerKind::Fuzzer;
 Res |= SanitizerKind::FuzzerNoLink;
@@ -500,8 +502,6 @@
   if (IsAArch64 || IsX86_64) {
 Res |= SanitizerKind::KernelAddress;
 Res |= SanitizerKind::KernelMemory;
-  }
-  if (IsX86_64) {
 Res |= SanitizerKind::Memory;
   }
   return Res;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D129748: [Modules] Disable preferred_name attribute in C++20 Modules

2022-07-19 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

In D129748#3660684 , @aaron.ballman 
wrote:

> The argument type is `TypeArgument`, not `TypdefType`. The guts of the 
> reading code for the preferred name attribute *should* be:

Oh, My bad. I didn't mention it in the above response. In 
https://github.com/llvm/llvm-project/blob/469044cfd355d34573643a57b5d2a78a9c341327/clang/lib/Sema/SemaDeclAttr.cpp#L1427-L1456,
 we could find that the type of `PreferredName` must be a type def type to a 
record type.

> I'm still not quite seeing that this only impacts one attribute. I *think* 
> this would happen for the others listed if the attribute argument was 
> similarly a typedef as with your example using `preferred_name`.

After experimenting the all day, I can't say the similar problem won't 
definitely happen to other attributes if they using a typedef as the attribute 
argument.

---

Here is the story of my experiment. The readers could skip this if not 
interested. `IBOutletCollection` is an Objective-C attributes. And the type 
argument of `TypeTagForDatatype` is required to be integral type: 
https://releases.llvm.org/9.0.0/tools/clang/docs/AttributeReference.html#type-tag-for-datatype.
  So let's see about `gsl::Owner` and `gsl::Pointer`. They are symmetric so 
let's see `gsl::Owner`.

First, I tried to following example, which replace [[gsl::Owner]] with 
`preferred_name`:

  template
  class basic_string_view;
  
  typedef basic_string_view string_view;
  
  template
  class
  [[gsl::Owner(string_view)]]
  basic_string_view {
  public:
  basic_string_view() 
  {
  }
  };
  
  inline basic_string_view foo()
  {
return basic_string_view();
  }

Then it don't meet the ODR violation problem. The reason is in the following 
AST:

  |-ClassTemplateDecl 0x7914038  col:7 
basic_string_view
  | |-TemplateTypeParmDecl 0x7913ec0  col:16 class depth 0 
index 0 _CharT
  | |-CXXRecordDecl 0x7913f88  col:7 class basic_string_view
  | | `-OwnerAttr 0x7914670  string_view
  | `-ClassTemplateSpecializationDecl 0x7914240  line:10:1 
class basic_string_view definition
  |   |-DefinitionData pass_in_registers empty standard_layout 
trivially_copyable has_user_declared_ctor can_const_default_init
  |   | |-DefaultConstructor exists non_trivial user_provided 
defaulted_is_constexpr
  |   | |-CopyConstructor simple trivial has_const_param 
implicit_has_const_param
  |   | |-MoveConstructor exists simple trivial
  |   | |-CopyAssignment simple trivial has_const_param needs_implicit 
implicit_has_const_param
  |   | |-MoveAssignment exists simple trivial needs_implicit
  |   | `-Destructor simple irrelevant trivial constexpr
  |   |-TemplateArgument type 'char'
  |   | `-BuiltinType 0x78c7e50 'char'
  |   |-OwnerAttr 0x7914b98  string_view
  |   |-CXXRecordDecl 0x7914c68  col:1 implicit class 
basic_string_view
  |   |-AccessSpecDecl 0x7914d18  col:1 public
  |   |-CXXConstructorDecl 0x7933d20  line:12:5 used 
basic_string_view 'void ()'
  |   | `-CompoundStmt 0x7914978 
  |   |-CXXConstructorDecl 0x7933ed0  col:1 implicit constexpr 
basic_string_view 'void (const basic_string_view &)' inline default 
trivial noexcept-unevaluated 0x7933ed0
  |   | `-ParmVarDecl 0x7933ff0  col:1 'const basic_string_view &'
  |   |-CXXConstructorDecl 0x79340a0  col:1 implicit constexpr 
basic_string_view 'void (basic_string_view &&)' inline default trivial 
noexcept-unevaluated 0x79340a0
  |   | `-ParmVarDecl 0x79341c0  col:1 'basic_string_view &&'
  |   `-CXXDestructorDecl 0x79343a0  col:1 implicit referenced constexpr 
~basic_string_view 'void () noexcept' inline default trivial
  |-TypedefDecl 0x79143e8  col:33 referenced string_view 
'basic_string_view':'basic_string_view'
  | `-TemplateSpecializationType 0x7914360 'basic_string_view' sugar 
basic_string_view
  |   |-TemplateArgument type 'char'
  |   | `-BuiltinType 0x78c7e50 'char'
  |   `-RecordType 0x7914340 'basic_string_view'
  | `-ClassTemplateSpecialization 0x7914240 'basic_string_view'
  |-ClassTemplateDecl 0x79145b0 prev 0x7914038  line:10:1 
basic_string_view
  | |-TemplateTypeParmDecl 0x7914448  col:16 class depth 0 
index 0 _CharT
  | |-CXXRecordDecl 0x7914518 prev 0x7913f88  line:10:1 
class basic_string_view definition
  | | |-DefinitionData empty standard_layout trivially_copyable 
has_user_declared_ctor can_const_default_init
  | | | |-DefaultConstructor exists non_trivial user_provided 
defaulted_is_constexpr
  | | | |-CopyConstructor simple trivial has_const_param needs_implicit 
implicit_has_const_param
  | | | |-MoveConstructor exists simple trivial needs_implicit
  | | | |-CopyAssignment simple trivial has_const_param needs_implicit 
implicit_has_const_param
  | | | |-MoveAssignment exists simple trivial needs_implicit
  | | | `-Destructor simple irrelevant trivial constexpr needs_implicit
  | | |-OwnerAttr 0x79146d0  string_view
  | | |-CXXRecordDecl 0x7914738  col:1 implicit referenced 
class basic_string_view
  | | |-AccessSpe

[PATCH] D109977: LLVM Driver Multicall tool

2022-07-19 Thread Michał Górny via Phabricator via cfe-commits
mgorny added a comment.

> Personally I really wish that the build system issue can be fixed in the 
> upcoming 15.0.0 release and encourage distributions to use it to decrease 
> executable sizes.

Me too, not because of multicall but because right now it's impossible to even 
build clang with multicall disabled. It's a complete 100% blocker for us.

In D109977#3661581 , @abrachet wrote:

> When running just `cmake ../clang -G Ninja` did you delete CMakeCache.txt?

I'm pretty sure I did.

> If you didn't then perhaps something from the full command you gave stayed 
> around and caused the error. I suspect then I will need the full command you 
> have supplied above including gentoo_common_config.cmake. Likely I will not 
> need gentoo_toolchain.cmake

I'm going to start by trying against with today's main, maybe (hopefully) 
something changed. I just hoped I wouldn't have to spend the time I don't 
really have on this but I guess I have no other option :-(.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109977

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


[PATCH] D129982: [clang-format][NFC] Refactor RequiresDoesNotChangeParsingOfTheRest

2022-07-19 Thread Owen Pan via Phabricator via cfe-commits
owenpan updated this revision to Diff 445725.
owenpan added a comment.

Uploaded the correct diff.


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

https://reviews.llvm.org/D129982

Files:
  clang/unittests/Format/TokenAnnotatorTest.cpp

Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -549,323 +549,171 @@
 }
 
 TEST_F(TokenAnnotatorTest, RequiresDoesNotChangeParsingOfTheRest) {
-  auto NumberOfAdditionalRequiresClauseTokens = 5u;
-  auto NumberOfTokensBeforeRequires = 5u;
-
-  auto BaseTokens = annotate("template\n"
- "T Pi = 3.14;");
-  auto ConstrainedTokens = annotate("template\n"
-"  requires Foo\n"
-"T Pi = 3.14;");
-
-  auto NumberOfBaseTokens = 11u;
-
-  ASSERT_EQ(BaseTokens.size(), NumberOfBaseTokens) << BaseTokens;
-  ASSERT_EQ(ConstrainedTokens.size(),
-NumberOfBaseTokens + NumberOfAdditionalRequiresClauseTokens)
-  << ConstrainedTokens;
-
-  for (auto I = 0u; I < NumberOfBaseTokens; ++I) {
-if (I < NumberOfTokensBeforeRequires) {
-  EXPECT_EQ(*BaseTokens[I], *ConstrainedTokens[I]) << I;
-} else {
-  EXPECT_EQ(*BaseTokens[I],
-*ConstrainedTokens[I + NumberOfAdditionalRequiresClauseTokens])
-  << I;
+  const char *BaseCode = nullptr;
+  const char *ConstrainedCode = nullptr;
+  auto BaseTokenCount = 0u;
+  auto RequiresTokenCount = 0u;
+  auto PrefixTokenCount = 0u;
+
+  auto TestRequires = [&](int Line) {
+const auto BaseTokens = annotate(BaseCode);
+const auto ConstrainedTokens = annotate(ConstrainedCode);
+
+#define LINE " (Line " << Line << ')'
+
+ASSERT_EQ(BaseTokens.size(), BaseTokenCount) << BaseTokens << LINE;
+ASSERT_EQ(ConstrainedTokens.size(), BaseTokenCount + RequiresTokenCount)
+<< LINE;
+
+for (auto I = 0u; I < BaseTokenCount; ++I) {
+  EXPECT_EQ(
+  *BaseTokens[I],
+  *ConstrainedTokens[I < PrefixTokenCount ? I : I + RequiresTokenCount])
+  << I << LINE;
 }
-  }
 
-  BaseTokens = annotate("template\n"
-"struct Bar;");
-  ConstrainedTokens = annotate("template\n"
-   "  requires Foo\n"
-   "struct Bar;");
-  NumberOfBaseTokens = 9u;
-
-  ASSERT_EQ(BaseTokens.size(), NumberOfBaseTokens) << BaseTokens;
-  ASSERT_EQ(ConstrainedTokens.size(),
-NumberOfBaseTokens + NumberOfAdditionalRequiresClauseTokens)
-  << ConstrainedTokens;
-
-  for (auto I = 0u; I < NumberOfBaseTokens; ++I) {
-if (I < NumberOfTokensBeforeRequires) {
-  EXPECT_EQ(*BaseTokens[I], *ConstrainedTokens[I]) << I;
-} else {
-  EXPECT_EQ(*BaseTokens[I],
-*ConstrainedTokens[I + NumberOfAdditionalRequiresClauseTokens])
-  << I;
-}
-  }
-
-  BaseTokens = annotate("template\n"
-"struct Bar {"
-"  T foo();\n"
-"  T bar();\n"
-"};");
-  ConstrainedTokens = annotate("template\n"
-   "  requires Foo\n"
-   "struct Bar {"
-   "  T foo();\n"
-   "  T bar();\n"
-   "};");
-  NumberOfBaseTokens = 21u;
-
-  ASSERT_EQ(BaseTokens.size(), NumberOfBaseTokens) << BaseTokens;
-  ASSERT_EQ(ConstrainedTokens.size(),
-NumberOfBaseTokens + NumberOfAdditionalRequiresClauseTokens)
-  << ConstrainedTokens;
-
-  for (auto I = 0u; I < NumberOfBaseTokens; ++I) {
-if (I < NumberOfTokensBeforeRequires) {
-  EXPECT_EQ(*BaseTokens[I], *ConstrainedTokens[I]) << I;
-} else {
-  EXPECT_EQ(*BaseTokens[I],
-*ConstrainedTokens[I + NumberOfAdditionalRequiresClauseTokens])
-  << I;
-}
-  }
-
-  BaseTokens = annotate("template\n"
-"Bar(T) -> Bar;");
-  ConstrainedTokens = annotate("template\n"
-   "  requires Foo\n"
-   "Bar(T) -> Bar;");
-  NumberOfBaseTokens = 16u;
-
-  ASSERT_EQ(BaseTokens.size(), NumberOfBaseTokens) << BaseTokens;
-  ASSERT_EQ(ConstrainedTokens.size(),
-NumberOfBaseTokens + NumberOfAdditionalRequiresClauseTokens)
-  << ConstrainedTokens;
-
-  for (auto I = 0u; I < NumberOfBaseTokens; ++I) {
-if (I < NumberOfTokensBeforeRequires) {
-  EXPECT_EQ(*BaseTokens[I], *ConstrainedTokens[I]) << I;
-} else {
-  EXPECT_EQ(*BaseTokens[I],
-*ConstrainedTokens[I + NumberOfAdditionalRequiresClauseTokens])
-  << I;
-}
-  }
-
-  BaseTokens = annotate("template\n"
-"T foo();");
-  ConstrainedTokens = annotate("template\n"
-   "  requires Foo\n"

[PATCH] D130065: [X86] Use Min behavior for cf-protection-{return,branch}/ibt-seal module flags

2022-07-19 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay created this revision.
MaskRay added reviewers: craig.topper, joaomoreira, pengfei, xiangzhangllvm.
Herald added subscribers: jsji, StephenFan.
Herald added a project: All.
MaskRay requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

These features require that all object files are compiled with the support. When
the feature is disabled for an object file, the merge behavior should treat the
file having a value of 0 (see D129911 ).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130065

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/X86/x86-cf-protection.c


Index: clang/test/CodeGen/X86/x86-cf-protection.c
===
--- clang/test/CodeGen/X86/x86-cf-protection.c
+++ clang/test/CodeGen/X86/x86-cf-protection.c
@@ -8,7 +8,7 @@
 // RETURN: #define __CET__ 2
 // BRANCH: #define __CET__ 1
 // FULL: #define __CET__ 3
-// CFPROT: "cf-protection-branch", i32 1
-// IBTSEAL: "ibt-seal", i32 1
+// CFPROT: !{i32 8, !"cf-protection-branch", i32 1}
+// IBTSEAL: !{i32 8, !"ibt-seal", i32 1}
 // NOIBTSEAL-NOT: "ibt-seal", i32 1
 void foo() {}
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -743,19 +743,19 @@
   if (CodeGenOpts.CFProtectionReturn &&
   Target.checkCFProtectionReturnSupported(getDiags())) {
 // Indicate that we want to instrument return control flow protection.
-getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
+getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return",
   1);
   }
 
   if (CodeGenOpts.CFProtectionBranch &&
   Target.checkCFProtectionBranchSupported(getDiags())) {
 // Indicate that we want to instrument branch control flow protection.
-getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
+getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch",
   1);
   }
 
   if (CodeGenOpts.IBTSeal)
-getModule().addModuleFlag(llvm::Module::Override, "ibt-seal", 1);
+getModule().addModuleFlag(llvm::Module::Min, "ibt-seal", 1);
 
   if (CodeGenOpts.FunctionReturnThunks)
 getModule().addModuleFlag(llvm::Module::Override, 
"function_return_thunk_extern", 1);


Index: clang/test/CodeGen/X86/x86-cf-protection.c
===
--- clang/test/CodeGen/X86/x86-cf-protection.c
+++ clang/test/CodeGen/X86/x86-cf-protection.c
@@ -8,7 +8,7 @@
 // RETURN: #define __CET__ 2
 // BRANCH: #define __CET__ 1
 // FULL: #define __CET__ 3
-// CFPROT: "cf-protection-branch", i32 1
-// IBTSEAL: "ibt-seal", i32 1
+// CFPROT: !{i32 8, !"cf-protection-branch", i32 1}
+// IBTSEAL: !{i32 8, !"ibt-seal", i32 1}
 // NOIBTSEAL-NOT: "ibt-seal", i32 1
 void foo() {}
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -743,19 +743,19 @@
   if (CodeGenOpts.CFProtectionReturn &&
   Target.checkCFProtectionReturnSupported(getDiags())) {
 // Indicate that we want to instrument return control flow protection.
-getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
+getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return",
   1);
   }
 
   if (CodeGenOpts.CFProtectionBranch &&
   Target.checkCFProtectionBranchSupported(getDiags())) {
 // Indicate that we want to instrument branch control flow protection.
-getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
+getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch",
   1);
   }
 
   if (CodeGenOpts.IBTSeal)
-getModule().addModuleFlag(llvm::Module::Override, "ibt-seal", 1);
+getModule().addModuleFlag(llvm::Module::Min, "ibt-seal", 1);
 
   if (CodeGenOpts.FunctionReturnThunks)
 getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D130063: [Driver] Enable sanitizers on FreeBSD AArch64

2022-07-19 Thread Dimitry Andric via Phabricator via cfe-commits
dim accepted this revision.
dim added a comment.
This revision is now accepted and ready to land.

LGTM, are there any tests that need to be enabled explicitly?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130063

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


[PATCH] D130066: [pseudo] Key guards by RuleID, add guards to literals (and 0).

2022-07-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: hokein.
Herald added a project: All.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, alextsao1999.
Herald added a project: clang-tools-extra.

After this, NUMERIC_CONSTANT and strings should parse only one way.

There are 8 types of literals, and 24 valid (literal, TokenKind) pairs.
This means adding 8 new named guards (or 24, if we want to assert the token).

It seems fairly clear to me at this point that the guard names are unneccesary
indirection: the guards are in fact coupled to the rule signature.

(Also add the zero guard I forgot in the previous patch.)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130066

Files:
  clang-tools-extra/pseudo/gen/Main.cpp
  clang-tools-extra/pseudo/include/clang-pseudo/Language.h
  clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/lib/cxx/CXX.cpp
  clang-tools-extra/pseudo/lib/cxx/cxx.bnf
  clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
  clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp
  clang-tools-extra/pseudo/test/cxx/literals.cpp
  clang-tools-extra/pseudo/test/cxx/mixed-designator.cpp
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp
  clang-tools-extra/pseudo/unittests/GLRTest.cpp
  clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Index: clang-tools-extra/pseudo/unittests/GrammarTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GrammarTest.cpp
+++ clang-tools-extra/pseudo/unittests/GrammarTest.cpp
@@ -102,16 +102,11 @@
 TEST_F(GrammarTest, Annotation) {
   build(R"bnf(
 _ := x
-
-x := y [guard=value]
-y := IDENTIFIER [guard=final]
-
+x := IDENTIFIER [guard]
   )bnf");
-  ASSERT_TRUE(Diags.empty());
-  EXPECT_EQ(G.lookupRule(ruleFor("_")).Guard, 0);
-  EXPECT_GT(G.lookupRule(ruleFor("x")).Guard, 0);
-  EXPECT_GT(G.lookupRule(ruleFor("y")).Guard, 0);
-  EXPECT_NE(G.lookupRule(ruleFor("x")).Guard, G.lookupRule(ruleFor("y")).Guard);
+  ASSERT_THAT(Diags, IsEmpty());
+  EXPECT_FALSE(G.lookupRule(ruleFor("_")).Guarded);
+  EXPECT_TRUE(G.lookupRule(ruleFor("x")).Guarded);
 }
 
 TEST_F(GrammarTest, MangleName) {
Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -631,10 +631,10 @@
   build(R"bnf(
 _ := start
 
-start := IDENTIFIER [guard=TestOnly]
+start := IDENTIFIER [guard]
   )bnf");
   TestLang.Guards.try_emplace(
-  extensionID("TestOnly"),
+  ruleFor("start"),
   [&](llvm::ArrayRef RHS, const TokenStream &Tokens) {
 assert(RHS.size() == 1 &&
RHS.front()->symbol() == tokenSymbol(clang::tok::identifier));
@@ -647,7 +647,7 @@
   const TokenStream &Succeeded = cook(lex(Input, LOptions), LOptions);
   EXPECT_EQ(glrParse({Succeeded, Arena, GSStack}, id("start"), TestLang)
 .dumpRecursive(TestLang.G),
-"[  0, end) start := IDENTIFIER [guard=TestOnly]\n"
+"[  0, end) start := IDENTIFIER [guard]\n"
 "[  0, end) └─IDENTIFIER := tok[0]\n");
 
   Input = "notest";
Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -45,6 +45,8 @@
 desc("Strip directives and select conditional sections"));
 static opt PrintStatistics("print-statistics", desc("Print GLR parser statistics"));
 static opt PrintForest("print-forest", desc("Print parse forest"));
+static opt ForestAbbrev("forest-abbrev", desc("Abbreviate parse forest"),
+  init(true));
 static opt StartSymbol("start-symbol",
 desc("specify the start symbol to parse"),
 init("translation-unit"));
@@ -148,7 +150,7 @@
 glrParse(clang::pseudo::ParseParams{*ParseableStream, Arena, GSS},
  *StartSymID, Lang);
 if (PrintForest)
-  llvm::outs() << Root.dumpRecursive(Lang.G, /*Abbreviated=*/true);
+  llvm::outs() << Root.dumpRecursive(Lang.G, /*Abbreviated=*/ForestAbbrev);
 
 if (PrintStatistics) {
   llvm::outs() << "Forest bytes: " << Arena.bytes()
Index: clang-tools-extra/pseudo/test/cxx/mixed-designator.cpp
===
--- clang-tools-extra/pseudo/test/cxx/mixed-designator.cpp
+++ clang-tools-extra/pseudo/test/cxx/mixed-designator.cpp
@@ -5,16 +5,16 @@
 // CHECK-NEXT: ├─{ := tok[3]
 // CHECK-NEXT: ├─initializer-list
 // CHECK-NEXT: │ ├─initializer-list
-// CHECK-NEXT: │ │ ├─initializer-list~literal
-// CHECK:  │ │ ├─, := tok[5]
+// CHECK-NEXT: │ │ ├─initi

[PATCH] D130063: [Driver] Enable sanitizers on FreeBSD AArch64

2022-07-19 Thread Andrew Turner via Phabricator via cfe-commits
andrew added a comment.

No tests, but D125883 , D125758 
, and D125873 
 need to be committed first.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130063

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


[PATCH] D109977: LLVM Driver Multicall tool

2022-07-19 Thread Michał Górny via Phabricator via cfe-commits
mgorny added a comment.

Hmm, I have another idea. Do you have individual LLVM static (or shared) 
libraries installed? On Gentoo we install only the dylib and a few unavoidable 
static libs:

  /usr/lib/llvm/15/lib64/libRemarks.so
  /usr/lib/llvm/15/lib64/libRemarks.so.15git
  /usr/lib/llvm/15/lib64/libLLVM-15git.so
  /usr/lib/llvm/15/lib64/libLLVM.so
  /usr/lib/llvm/15/lib64/libLLVM-15.0.0git.so
  /usr/lib/llvm/15/lib64/libLTO.so
  /usr/lib/llvm/15/lib64/libLTO.so.15git
  /usr/lib/llvm/15/lib64/libLLVMTableGen.a
  /usr/lib/llvm/15/lib64/libLLVMSupport.a
  /usr/lib/llvm/15/lib64/libLLVMDemangle.a

On my end, I'm going to check if installing full set of static libs changes 
anything.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109977

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


[PATCH] D130066: [pseudo] Key guards by RuleID, add guards to literals (and 0).

2022-07-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 445760.
sammccall added a comment.

reorder a bit


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130066

Files:
  clang-tools-extra/pseudo/gen/Main.cpp
  clang-tools-extra/pseudo/include/clang-pseudo/Language.h
  clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/lib/cxx/CXX.cpp
  clang-tools-extra/pseudo/lib/cxx/cxx.bnf
  clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
  clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp
  clang-tools-extra/pseudo/test/cxx/literals.cpp
  clang-tools-extra/pseudo/test/cxx/mixed-designator.cpp
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp
  clang-tools-extra/pseudo/unittests/GLRTest.cpp
  clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Index: clang-tools-extra/pseudo/unittests/GrammarTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GrammarTest.cpp
+++ clang-tools-extra/pseudo/unittests/GrammarTest.cpp
@@ -102,16 +102,11 @@
 TEST_F(GrammarTest, Annotation) {
   build(R"bnf(
 _ := x
-
-x := y [guard=value]
-y := IDENTIFIER [guard=final]
-
+x := IDENTIFIER [guard]
   )bnf");
-  ASSERT_TRUE(Diags.empty());
-  EXPECT_EQ(G.lookupRule(ruleFor("_")).Guard, 0);
-  EXPECT_GT(G.lookupRule(ruleFor("x")).Guard, 0);
-  EXPECT_GT(G.lookupRule(ruleFor("y")).Guard, 0);
-  EXPECT_NE(G.lookupRule(ruleFor("x")).Guard, G.lookupRule(ruleFor("y")).Guard);
+  ASSERT_THAT(Diags, IsEmpty());
+  EXPECT_FALSE(G.lookupRule(ruleFor("_")).Guarded);
+  EXPECT_TRUE(G.lookupRule(ruleFor("x")).Guarded);
 }
 
 TEST_F(GrammarTest, MangleName) {
Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -631,10 +631,10 @@
   build(R"bnf(
 _ := start
 
-start := IDENTIFIER [guard=TestOnly]
+start := IDENTIFIER [guard]
   )bnf");
   TestLang.Guards.try_emplace(
-  extensionID("TestOnly"),
+  ruleFor("start"),
   [&](llvm::ArrayRef RHS, const TokenStream &Tokens) {
 assert(RHS.size() == 1 &&
RHS.front()->symbol() == tokenSymbol(clang::tok::identifier));
@@ -647,7 +647,7 @@
   const TokenStream &Succeeded = cook(lex(Input, LOptions), LOptions);
   EXPECT_EQ(glrParse({Succeeded, Arena, GSStack}, id("start"), TestLang)
 .dumpRecursive(TestLang.G),
-"[  0, end) start := IDENTIFIER [guard=TestOnly]\n"
+"[  0, end) start := IDENTIFIER [guard]\n"
 "[  0, end) └─IDENTIFIER := tok[0]\n");
 
   Input = "notest";
Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -45,6 +45,8 @@
 desc("Strip directives and select conditional sections"));
 static opt PrintStatistics("print-statistics", desc("Print GLR parser statistics"));
 static opt PrintForest("print-forest", desc("Print parse forest"));
+static opt ForestAbbrev("forest-abbrev", desc("Abbreviate parse forest"),
+  init(true));
 static opt StartSymbol("start-symbol",
 desc("specify the start symbol to parse"),
 init("translation-unit"));
@@ -148,7 +150,7 @@
 glrParse(clang::pseudo::ParseParams{*ParseableStream, Arena, GSS},
  *StartSymID, Lang);
 if (PrintForest)
-  llvm::outs() << Root.dumpRecursive(Lang.G, /*Abbreviated=*/true);
+  llvm::outs() << Root.dumpRecursive(Lang.G, /*Abbreviated=*/ForestAbbrev);
 
 if (PrintStatistics) {
   llvm::outs() << "Forest bytes: " << Arena.bytes()
Index: clang-tools-extra/pseudo/test/cxx/mixed-designator.cpp
===
--- clang-tools-extra/pseudo/test/cxx/mixed-designator.cpp
+++ clang-tools-extra/pseudo/test/cxx/mixed-designator.cpp
@@ -5,16 +5,16 @@
 // CHECK-NEXT: ├─{ := tok[3]
 // CHECK-NEXT: ├─initializer-list
 // CHECK-NEXT: │ ├─initializer-list
-// CHECK-NEXT: │ │ ├─initializer-list~literal
-// CHECK:  │ │ ├─, := tok[5]
+// CHECK-NEXT: │ │ ├─initializer-list~NUMERIC_CONSTANT
+// CHECK-NEXT: │ │ ├─, := tok[5]
 // CHECK-NEXT: │ │ └─initializer-list-item
 // CHECK-NEXT: │ │   ├─designator
 // CHECK-NEXT: │ │   │ ├─. := tok[6]
 // CHECK-NEXT: │ │   │ └─IDENTIFIER := tok[7]
 // CHECK-NEXT: │ │   └─brace-or-equal-initializer
 // CHECK-NEXT: │ │ ├─= := tok[8]
-// CHECK-NEXT: │ │ └─initializer-clause~literal
-// CHECK:  │ ├─, := tok[10]
+// CHECK-NEXT: │ │ └â

[PATCH] D126189: [C++20][Modules] Build module static initializers per P1874R1.

2022-07-19 Thread H. Vetinari via Phabricator via cfe-commits
h-vetinari added a comment.

Is it realistic for this to land before LLVM 15 branches? Would be great!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126189

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


[PATCH] D129573: [clang] add a diagnostic note 'while loop outside functions' at global scope

2022-07-19 Thread YingChi Long via Phabricator via cfe-commits
inclyc updated this revision to Diff 445771.

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

https://reviews.llvm.org/D129573

Files:
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/Parse/ParseDecl.cpp
  clang/test/Parser/while-loop-outside-function.c
  clang/test/Parser/while-loop-outside-function.cpp

Index: clang/test/Parser/while-loop-outside-function.cpp
===
--- /dev/null
+++ clang/test/Parser/while-loop-outside-function.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+while(true) {}; // expected-error {{while loop outside of a function}}
+
+// without semicolon
+while(true) {} // expected-error {{while loop outside of a function}}
+
+while(true)  // expected-error {{while loop outside of a function}}
+{
+// some statements
+int some_var = 3;
+some_var += 2;
+}
+
+do { // expected-error {{expected unqualified-id}}
+int some_var = 1;
+some_var += 3;
+} 
+while(true); // expected-error {{while loop outside of a function}}
+
+void someFunction() {
+while(true) {};
+}
+
+class SomeClass {
+public:
+while(true) {} // expected-error {{expected member name or ';' after declaration specifiers}}
+void some_fn() {
+while(true) {}
+}
+};
Index: clang/test/Parser/while-loop-outside-function.c
===
--- /dev/null
+++ clang/test/Parser/while-loop-outside-function.c
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+// basic
+while(1) {}; // expected-error {{while loop outside of a function}}
+
+
+// location?
+while(1) // expected-error {{while loop outside of a function}}
+{};
+
+// empty statement without semicolon
+while(1) // expected-error {{while loop outside of a function}}
+{}
+
+// some statements
+while(1)  // expected-error {{while loop outside of a function}}
+{
+int some_var = 0;
+}
+
+// recovery
+void some_fn();
+
+void some_fn() {
+while(1) {};
+}
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -6344,23 +6344,27 @@
diag::err_expected_member_name_or_semi)
   << (D.getDeclSpec().isEmpty() ? SourceRange()
 : D.getDeclSpec().getSourceRange());
-} else if (getLangOpts().CPlusPlus) {
-  if (Tok.isOneOf(tok::period, tok::arrow))
-Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
-  else {
-SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
-if (Tok.isAtStartOfLine() && Loc.isValid())
-  Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
-  << getLangOpts().CPlusPlus;
-else
-  Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
-   diag::err_expected_unqualified_id)
-  << getLangOpts().CPlusPlus;
-  }
 } else {
-  Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
-   diag::err_expected_either)
-  << tok::identifier << tok::l_paren;
+  if (Tok.getKind() == tok::TokenKind::kw_while) {
+Diag(Tok, diag::err_while_loop_outside_of_a_function);
+  } else if (getLangOpts().CPlusPlus) {
+if (Tok.isOneOf(tok::period, tok::arrow))
+  Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
+else {
+  SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
+  if (Tok.isAtStartOfLine() && Loc.isValid())
+Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
+<< getLangOpts().CPlusPlus;
+  else
+Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
+ diag::err_expected_unqualified_id)
+<< getLangOpts().CPlusPlus;
+}
+  } else {
+Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
+ diag::err_expected_either)
+<< tok::identifier << tok::l_paren;
+  }
 }
 D.SetIdentifier(nullptr, Tok.getLocation());
 D.setInvalidType(true);
Index: clang/include/clang/Basic/DiagnosticParseKinds.td
===
--- clang/include/clang/Basic/DiagnosticParseKinds.td
+++ clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -538,6 +538,8 @@
   "cannot use %select{dot|arrow}0 operator on a type">;
 def err_expected_unqualified_id : Error<
   "expected %select{identifier|unqualified-id}0">;
+def err_while_loop_outside_of_a_function : Error<
+  "while loop outside of a function">; 
 def err_brackets_go_after_unqualified_id : Error<
   "brackets are not allowed here; to declare an array, "
   "place the brackets after the %select{identifier|name}0">;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mai

[PATCH] D109977: LLVM Driver Multicall tool

2022-07-19 Thread Michał Górny via Phabricator via cfe-commits
mgorny added a comment.

Unfortunately, that doesn't seem to be it. I think at this point it would be 
easier for both of us if I tried to figure it out myself on Gentoo rather than 
trying to make it reproducible elsewhere. If you want, you could try grabbing 
e.g. a Gentoo stage3 image (e.g. via Docker or systemd-nspawn) and trying 
`ACCEPT_KEYWORDS=** emerge -v clang:15` there but I suppose you'd have to 
figure out some Gentoo basics anyway (and then you'd realize it's the best 
distro in the world and waste years of your life developing it :-P).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109977

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


[PATCH] D126189: [C++20][Modules] Build module static initializers per P1874R1.

2022-07-19 Thread Iain Sandoe via Phabricator via cfe-commits
iains added a comment.

In D126189#3662123 , @h-vetinari 
wrote:

> Is it realistic for this to land before LLVM 15 branches? Would be great!

that is the intention - I just got side-tracked with trying to replicate the 
test fails that got the commit reverted.  AFAICT it's OK now, and i plan to 
re-land it soon.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126189

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


[PATCH] D130055: Clang extensions yolo, woot & kaboom

2022-07-19 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a subscriber: balazske.
Szelethus added a comment.

Yeah, I'm afraid no fun is allowed on this block. On another note, `kaboom` is 
interesting, shouldn't we assume all functions to be `kaboom` unless proven to 
be `woot`?

@balazske's work on checking the return value of certain function calls is 
related to this as well!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130055

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


[PATCH] D122234: [clang] Link libbitint for large division of _BitInt

2022-07-19 Thread Matthias Gehre via Phabricator via cfe-commits
mgehre-amd abandoned this revision.
mgehre-amd added a comment.

Instead of linking to libbitint, I instead created a backend pass to transform 
div/rem instructions: https://reviews.llvm.org/D130076


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122234

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


[PATCH] D130078: [flang][nfc] Rename `AddOtherOptions` as `ForwardOptions`

2022-07-19 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski created this revision.
awarzynski added a reviewer: tarunprabhu.
Herald added a reviewer: sscalpone.
Herald added a project: All.
awarzynski requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

The updated name better reflects what this hook is intended for.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130078

Files:
  clang/lib/Driver/ToolChains/Flang.cpp
  clang/lib/Driver/ToolChains/Flang.h


Index: clang/lib/Driver/ToolChains/Flang.h
===
--- clang/lib/Driver/ToolChains/Flang.h
+++ clang/lib/Driver/ToolChains/Flang.h
@@ -39,13 +39,13 @@
   /// \param [out] CmdArgs The list of output command arguments
   void AddPreprocessingOptions(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs) const;
-  /// Extract other compilation options from the driver arguments and add them
-  /// to the command arguments.
+
+  /// This method will effectively copy options from \a Args into \a CmdArgs.
   ///
   /// \param [in] Args The list of input driver arguments
   /// \param [out] CmdArgs The list of output command arguments
-  void AddOtherOptions(const llvm::opt::ArgList &Args,
-   llvm::opt::ArgStringList &CmdArgs) const;
+  void ForwardOptions(const llvm::opt::ArgList &Args,
+  llvm::opt::ArgStringList &CmdArgs) const;
 
 public:
   Flang(const ToolChain &TC);
Index: clang/lib/Driver/ToolChains/Flang.cpp
===
--- clang/lib/Driver/ToolChains/Flang.cpp
+++ clang/lib/Driver/ToolChains/Flang.cpp
@@ -51,7 +51,7 @@
options::OPT_I, options::OPT_cpp, options::OPT_nocpp});
 }
 
-void Flang::AddOtherOptions(const ArgList &Args, ArgStringList &CmdArgs) const 
{
+void Flang::ForwardOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
   Args.AddAllArgs(CmdArgs,
   {options::OPT_module_dir, options::OPT_fdebug_module_writer,
options::OPT_fintrinsic_modules_path, options::OPT_pedantic,
@@ -117,8 +117,8 @@
   if (D.getDiags().getDiagnosticOptions().ShowColors)
 CmdArgs.push_back("-fcolor-diagnostics");
 
-  // Add other compile options
-  AddOtherOptions(Args, CmdArgs);
+  // Handle options which are simply forwarded to -fc1.
+  ForwardOptions(Args, CmdArgs);
 
   // Forward -Xflang arguments to -fc1
   Args.AddAllArgValues(CmdArgs, options::OPT_Xflang);


Index: clang/lib/Driver/ToolChains/Flang.h
===
--- clang/lib/Driver/ToolChains/Flang.h
+++ clang/lib/Driver/ToolChains/Flang.h
@@ -39,13 +39,13 @@
   /// \param [out] CmdArgs The list of output command arguments
   void AddPreprocessingOptions(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs) const;
-  /// Extract other compilation options from the driver arguments and add them
-  /// to the command arguments.
+
+  /// This method will effectively copy options from \a Args into \a CmdArgs.
   ///
   /// \param [in] Args The list of input driver arguments
   /// \param [out] CmdArgs The list of output command arguments
-  void AddOtherOptions(const llvm::opt::ArgList &Args,
-   llvm::opt::ArgStringList &CmdArgs) const;
+  void ForwardOptions(const llvm::opt::ArgList &Args,
+  llvm::opt::ArgStringList &CmdArgs) const;
 
 public:
   Flang(const ToolChain &TC);
Index: clang/lib/Driver/ToolChains/Flang.cpp
===
--- clang/lib/Driver/ToolChains/Flang.cpp
+++ clang/lib/Driver/ToolChains/Flang.cpp
@@ -51,7 +51,7 @@
options::OPT_I, options::OPT_cpp, options::OPT_nocpp});
 }
 
-void Flang::AddOtherOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
+void Flang::ForwardOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
   Args.AddAllArgs(CmdArgs,
   {options::OPT_module_dir, options::OPT_fdebug_module_writer,
options::OPT_fintrinsic_modules_path, options::OPT_pedantic,
@@ -117,8 +117,8 @@
   if (D.getDiags().getDiagnosticOptions().ShowColors)
 CmdArgs.push_back("-fcolor-diagnostics");
 
-  // Add other compile options
-  AddOtherOptions(Args, CmdArgs);
+  // Handle options which are simply forwarded to -fc1.
+  ForwardOptions(Args, CmdArgs);
 
   // Forward -Xflang arguments to -fc1
   Args.AddAllArgValues(CmdArgs, options::OPT_Xflang);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D130081: Add foldings for multi-line comment.

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

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130081

Files:
  clang-tools-extra/clangd/SemanticSelection.cpp
  clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
@@ -335,6 +335,26 @@
   ]]}   \
 ]]};
   )cpp",
+  R"cpp(
+int a;
+[[/* Multi 
+line
+comment */]]
+
+int b;
+[[/* Multi 
+  * line
+  *  comment 
+  */]]
+
+int c;
+[[// A comment 
+// expanding more than
+
+// one
+
+// line.]]
+  )cpp",
   };
   for (const char *Test : Tests) {
 auto T = Annotations(Test);
Index: clang-tools-extra/clangd/SemanticSelection.cpp
===
--- clang-tools-extra/clangd/SemanticSelection.cpp
+++ clang-tools-extra/clangd/SemanticSelection.cpp
@@ -179,10 +179,10 @@
 // Related issue: https://github.com/clangd/clangd/issues/310
 llvm::Expected>
 getFoldingRanges(const std::string &Code) {
-  auto OrigStream = clang::pseudo::lex(Code, clang::pseudo::genericLangOpts());
+  auto OrigStream = pseudo::lex(Code, clang::pseudo::genericLangOpts());
 
-  auto DirectiveStructure = clang::pseudo::DirectiveTree::parse(OrigStream);
-  clang::pseudo::chooseConditionalBranches(DirectiveStructure, OrigStream);
+  auto DirectiveStructure = pseudo::DirectiveTree::parse(OrigStream);
+  pseudo::chooseConditionalBranches(DirectiveStructure, OrigStream);
 
   // FIXME: Provide ranges in the disabled-PP regions as well.
   auto Preprocessed = DirectiveStructure.stripDirectives(OrigStream);
@@ -191,26 +191,49 @@
   pseudo::pairBrackets(ParseableStream);
 
   std::vector Result;
-  for (const auto &Tok : ParseableStream.tokens()) {
+  auto ToFoldingRange = [](Position Start, Position End, std::string Kind) {
+FoldingRange FR;
+FR.startLine = Start.line;
+FR.startCharacter = Start.character;
+FR.endLine = End.line;
+FR.endCharacter = End.character;
+FR.kind = Kind;
+return FR;
+  };
+  auto OriginalToken = [&](const pseudo::Token &T) {
+return OrigStream.tokens()[T.OriginalIndex];
+  };
+  auto StartOffset = [&](const pseudo::Token &T) {
+return OriginalToken(T).text().data() - Code.data();
+  };
+  auto Tokens = ParseableStream.tokens();
+  // Brackets.
+  for (const auto &Tok : Tokens) {
 if (auto *Paired = Tok.pair()) {
   // Process only token at the start of the range. Avoid ranges on a single
   // line.
   if (Tok.Line < Paired->Line) {
-Position Start = offsetToPosition(
-Code,
-OrigStream.tokens()[Tok.OriginalIndex].text().data() - Code.data());
-Position End = offsetToPosition(
-Code, OrigStream.tokens()[Paired->OriginalIndex].text().data() -
-  Code.data());
-FoldingRange FR;
-FR.startLine = Start.line;
-FR.startCharacter = Start.character + 1;
-FR.endLine = End.line;
-FR.endCharacter = End.character;
-Result.push_back(FR);
+Position Start = offsetToPosition(Code, 1 + StartOffset(Tok));
+Position End = offsetToPosition(Code, StartOffset(*Paired));
+Result.push_back(ToFoldingRange(Start, End, "region"));
   }
 }
   }
+  // Multi-line comments.
+  for (const auto *T = Tokens.begin(); T != Tokens.end();) {
+if (T->Kind != tok::comment) {
+  T++;
+  continue;
+}
+Position Start = offsetToPosition(Code, StartOffset(*T));
+Position End;
+while (T->Kind == tok::comment && T != Tokens.end()) {
+  End = offsetToPosition(Code, StartOffset(*T) + OriginalToken(*T).Length);
+  T++;
+}
+if (Start.line < End.line)
+  Result.push_back(ToFoldingRange(Start, End, "comment"));
+  }
   return Result;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D127293: [clang-tidy] Ignore other members in a union if any member of it is initialized in cppcoreguidelines-pro-type-member-init

2022-07-19 Thread gehry via Phabricator via cfe-commits
Sockke updated this revision to Diff 445792.
Sockke added a comment.

Added test cases where there is a struct with an anonymous union and another 
field that does need an initializer.


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

https://reviews.llvm.org/D127293

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
@@ -552,3 +552,30 @@
   int A;
   // CHECK-FIXES-NOT: int A{};
 };
+
+struct S1 {
+  S1() {}
+  union {
+int a = 0;
+int b;
+  };
+};
+
+struct S2 {
+  S2() : a{} {}
+  union {
+int a;
+int b;
+  };
+};
+
+struct S3 {
+  S3() {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these fields: A [cppcoreguidelines-pro-type-member-init]
+  int A;
+  // CHECK-FIXES: int A{};
+  union {
+int B;
+int C = 0;
+  };
+};
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -201,6 +201,11 @@
   Fixed an issue when there was already an initializer in the constructor and
   the check would try to create another initializer for the same member.
 
+- Fixed a false positive in :doc:`cppcoreguidelines-pro-type-member-init
+  ` when warnings
+  would be emitted for uninitialized members of an anonymous union despite
+  there being an initializer for one of the other members.
+
 - Fixed a false positive in :doc:`cppcoreguidelines-virtual-class-destructor
   ` involving
   ``final`` classes. The check will not diagnose classes marked ``final``, since
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
@@ -61,6 +61,17 @@
   }
 }
 
+void removeFieldInitialized(const FieldDecl *M,
+SmallPtrSetImpl &FieldDecls) {
+  const RecordDecl *R = M->getParent();
+  if (R && R->isUnion()) {
+// Erase all members in a union if any member of it is initialized.
+for (const auto *F : R->fields())
+  FieldDecls.erase(F);
+  } else
+FieldDecls.erase(M);
+}
+
 void removeFieldsInitializedInBody(
 const Stmt &Stmt, ASTContext &Context,
 SmallPtrSetImpl &FieldDecls) {
@@ -70,7 +81,7 @@
 hasLHS(memberExpr(member(fieldDecl().bind("fieldDecl")),
 Stmt, Context);
   for (const auto &Match : Matches)
-FieldDecls.erase(Match.getNodeAs("fieldDecl"));
+removeFieldInitialized(Match.getNodeAs("fieldDecl"), FieldDecls);
 }
 
 StringRef getName(const FieldDecl *Field) { return Field->getName(); }
@@ -418,13 +429,20 @@
 
   // Gather all fields (direct and indirect) that need to be initialized.
   SmallPtrSet FieldsToInit;
-  forEachField(ClassDecl, ClassDecl.fields(), [&](const FieldDecl *F) {
+  bool AnyMemberHasInitPerUnion = false;
+  forEachFieldWithFilter(ClassDecl, ClassDecl.fields(),
+ AnyMemberHasInitPerUnion, [&](const FieldDecl *F) {
 if (IgnoreArrays && F->getType()->isArrayType())
   return;
+if (F->hasInClassInitializer() && F->getParent()->isUnion()) {
+  AnyMemberHasInitPerUnion = true;
+  removeFieldInitialized(F, FieldsToInit);
+}
 if (!F->hasInClassInitializer() &&
 utils::type_traits::isTriviallyDefaultConstructible(F->getType(),
 Context) &&
-!isEmpty(Context, F->getType()) && !F->isUnnamedBitfield())
+!isEmpty(Context, F->getType()) && !F->isUnnamedBitfield() &&
+!AnyMemberHasInitPerUnion)
   FieldsToInit.insert(F);
   });
   if (FieldsToInit.empty())
@@ -437,7 +455,7 @@
   if (Init->isAnyMemberInitializer() && Init->isWritten()) {
 if (IsUnion)
   return; // We can only initialize one member of a union.
-FieldsToInit.erase(Init->getAnyMember());
+removeFieldInitialized(Init->getAnyMember(), FieldsToInit);
   }
 }
 removeFieldsInitializedInBody(*Ctor->getBody(), Context, FieldsToInit);
@@ -478,7 +496,7 @@
   // Collect all fields but only suggest a fix for the first member of unions,
   // as initializing more than one union member is an error.
   SmallPtrSet FieldsToFix;
-  bool AnyMemberHasInitPerUnion = false;
+  AnyMemberHasInitPerUnion = false;
   forEachFieldWithFilter(Clas

[PATCH] D130004: [pseudo] Add `clang-pseudo -html-forest=`, an HTML forest browser

2022-07-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Super cool! Can't wait to use it.

The code looks good, just nits (feel free to ignore)




Comment at: clang-tools-extra/pseudo/tool/CMakeLists.txt:29
+add_custom_target(clang-pseudo-resources DEPENDS HTMLForestResources.inc)
+add_dependencies(clang-pseudo clang-pseudo-resources)

This likely introduces some pain. (An alternative is to inline the content of 
`.js`, `.css`, `html` in the cpp directly, but it is awkward).

Would be nice to prepare an internal BUILD file change when landing (if you 
don't have time, I'm happy to help with it).



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.cpp:64
+  void write() {
+Out << "\n\n\nHTMLForest\n";
+Out << "" << HTMLForest_js << "\n";

nit: it is clearer to use use `llvm::formatv`

```
llvm::formatv(R"html(
...
)html", js, css, forest_json, code, html);.
```



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.cpp:115
+  llvm::DenseMap Index;
+  std::vector> Queue;
+  auto AssignID = [&](const ForestNode* N, Token::Index End) -> unsigned {

I'd suggest renaming to `Array` and adding comment for the `Index` (it is the 
index in the `Queue`), `Queue` leaves an impression to me that we will do some 
pop_back.



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.cpp:170
+
+// We only accept the derived stream here. Would it be useful or confusing
+// to allow the original stream instead?

Having derived stream is fine to me at the moment, particularly useful for 
debugging.

But as a regular user, I would prefer to see the original token stream (the 
derived stream is confusing, as a regular user doesn't know how pseudoparser 
work inside).



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.css:50
+}
+#i_kind {
+  float: right;

nit: just an idea we could use different background color for different forest 
node kind.



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.css:63
+
+#tree {
+  flex-grow: 0;

nit: can we make the tree and code view resizable?  so that I can adjust the 
width of tree/code view.



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.css:82
+.tree-node.terminal .name { font-family: monospace; }
+.tree-node.ambiguous > header .name { color: #803; font-weight: bold; }
+

nit: we could also add some style (possibly red indicating the error) for 
opaque node.



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.html:1
+
+

I think it might be better to move these `.html, .css, .js` files to a separate 
directory  `tool/resources` rather than `tool`.



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.html:13
+  
+
+  

nit: maybe name it `i_context_stack`, I had no idea what does the `context` 
mean until I read the actual implementation. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130004

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


[PATCH] D130078: [flang][nfc] Rename `AddOtherOptions` as `ForwardOptions`

2022-07-19 Thread Tarun Prabhu via Phabricator via cfe-commits
tarunprabhu accepted this revision.
tarunprabhu 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/D130078/new/

https://reviews.llvm.org/D130078

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


[PATCH] D130058: [Clang] Diagnose ill-formed constant expression when setting a non fixed enum to a value outside the range of the enumeration values

2022-07-19 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticASTKinds.td:370
+def note_constexpr_unscoped_enum_out_of_range : Note<
+  "store of value outside of the range of unscoped enum, valid values %0 to 
%1">;
 def err_experimental_clang_interp_failed : Error<

This is a bit awkwardly phrased to me... though I don't have a better idea.  
Perhaps take another run, or get Aaron to look at it?



Comment at: clang/lib/AST/ExprConstant.cpp:13512
 
+if (Info.Ctx.getLangOpts().CPlusPlus20)
+  if (const EnumType *ET = dyn_cast(DestType)) {

Why the check for C++20?  This is UB as a Defect Report, which applies to all 
versions of C++.



Comment at: clang/lib/AST/ExprConstant.cpp:13533
+
+  if (NumNegativeBits) {
+unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);

So my reading of 'within the range of the enumeration values' is different 
here.  Given:

`enum F { -4, 4};`, the valid values for assignment I would say are -4, -3, -2, 
-1, 0, 1, 2, 3, 4.  This error seems to be a bit more permissive here by making 
sure it is represent-able by the number of bits required to represent the enum.





Comment at: clang/test/SemaCXX/constant-expression-cxx2a.cpp:1477
+
+enum E { e1=-4, e2=4};
+void testValueInRangeOfEnumerationValues() {

Theres likely quite a few more tests that need to be done.  We should have one 
where it validates against a fixed underlying type, AND probably a pair of ones 
to check against scoped enums.  

I wouldn't expect a scoped enum to diagnose, but a test to make sure we're 
checking the right thing is likely valuable. 


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

https://reviews.llvm.org/D130058

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


[PATCH] D129855: [clang][PowerPC] Set lld as clang's default linker for PowerPC Linux

2022-07-19 Thread Quinn Pham via Phabricator via cfe-commits
quinnp added a comment.

In D129855#3657006 , @MaskRay wrote:

> This is not right as using `ld.lld` as the default linker isn't the majority 
> case. If you want to change the default for your distribution, set 
> `-DCLANG_DEFAULT_LINKER=lld`.
> (Alternatively, you can have a `ld` symlink pointing to `lld`.)

Hi @MaskRay! Do you mean I should abandon this change or find a way to set the 
CMake variable `CLANG_DEFAULT_LINKER` to `lld` as default when building for 
PowerPC Linux? I wasn't able to find any examples of people setting CMake 
variables for specific distributions.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129855

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


[PATCH] D130081: Add foldings for multi-line comment.

2022-07-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/SemanticSelection.cpp:176
 
 // FIXME(kirillbobyrev): Collect comments, PP conditional regions, includes and
 // other code regions (e.g. public/private/protected sections of classes,

nit: update the fixme, comment is supported now.



Comment at: clang-tools-extra/clangd/SemanticSelection.cpp:231
+while (T->Kind == tok::comment && T != Tokens.end()) {
+  End = offsetToPosition(Code, StartOffset(*T) + OriginalToken(*T).Length);
+  T++;

we can save some cost if we first get the final End comment, and calculate the 
offset from it.



Comment at: clang-tools-extra/clangd/SemanticSelection.cpp:235
+if (Start.line < End.line)
+  Result.push_back(ToFoldingRange(Start, End, "comment"));
+  }

since LSP defines 3 kinds (`region`, `comment`, `import`), I'd suggest defining 
these string literals in the `Protocol.h`, rather than using the magic string 
here. 



Comment at: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp:351
+int c;
+[[// A comment 
+// expanding more than

For this case, my personal preference would be to have 3 different foldings, 
rather than a union one.

If you think about cases like below, it makes more sense to have individual 
folding per comment.

```
/* comment 1
*/

/* comment 2
*/
```

```
/* comment 1
*/

// comment 2
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130081

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


[PATCH] D130011: Use pseudoparser-based folding ranges in ClangdServer.

2022-07-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

The change looks good to me.

> as discussed offline i don't see much value in having an extra flag to choose 
> between ast-based and pseudo-based implementation, as the pseudo-based one is 
> a super-set of the ast-based implementation. hence it shouldn't be regressing 
> change in any way, therefore i am in favor of just using the pseudo based 
> implementation inside clangdserver at all times (this is already hidden 
> behind a flag ATM).

+1

> independent of that, branch cut is next tuesday. so i'd rather not land it 
> until the cut happens (existing implementation is also crashing, but it's the 
> devil we know and it would be nice to not introduce new failures).

What the main concern here? This feature is hidden under a flag which is off by 
default (and I don't think any user would turn it because the syntax-tree 
implementation is crashy), it should not affect any users, so it seems fine to 
land it even before the branch cut.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130011

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


[PATCH] D130055: Clang extensions yolo, woot & kaboom

2022-07-19 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added a comment.

In D130055#3662206 , @Szelethus wrote:

> On another note, `kaboom` is interesting, shouldn't we assume all functions 
> to be `kaboom` unless proven to be `woot`?

I won’t claim to have spent a whole lot of time thinking on this. The idea came 
to me yesterday and I just wrote it up. My thought process was this:

The existing analysis errs to the side of not diagnosing anything it isn’t sure 
is an issue, so by default operations are ignored. Ignored operations are 
important in some use cases where initialization might be more than one call, 
like a builder pattern. They could instead be their own annotation, I propose 
‘schroedinger’.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130055

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


[PATCH] D129748: [Modules] Disable preferred_name attribute in C++20 Modules

2022-07-19 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

I'll note that I don't "like" the idea, so much as I see this patch as an 
'improvement' to unblock efforts with additional value, though not much of one. 
 I suspect as Aaron does that there is a significant problem that needs fixing 
here with how our serialization works, and that we should be putting effort 
into fixing that.

As far as THIS patch, I would be OK with 'holding my nose' and accepting it 
short-term so we can get Module-ized versions of the STL into clang-15, but 
only if someone was still actively working ot figure out our serialization 
problem, and only if Tom/Aaron are OK holding their nose as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129748

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


[PATCH] D130058: [Clang] Diagnose ill-formed constant expression when setting a non fixed enum to a value outside the range of the enumeration values

2022-07-19 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:13533
+
+  if (NumNegativeBits) {
+unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);

erichkeane wrote:
> So my reading of 'within the range of the enumeration values' is different 
> here.  Given:
> 
> `enum F { -4, 4};`, the valid values for assignment I would say are -4, -3, 
> -2, -1, 0, 1, 2, 3, 4.  This error seems to be a bit more permissive here by 
> making sure it is represent-able by the number of bits required to represent 
> the enum.
> 
> 
Aaron pointed out off-line that I'm incorrect in what 'range of enumeration 
values' means, and that the values comes from 
https://eel.is/c++draft/dcl.enum#8.sentence-2.

So the logic here needs to be to find the smallest integer (regardless of the 
power-of-2-ness of its bit-size) that can represent all of the values 
(including a 1 bit value for empty I think?), and diagnose based on that.



Comment at: clang/test/SemaCXX/constant-expression-cxx2a.cpp:1477
+
+enum E { e1=-4, e2=4};
+void testValueInRangeOfEnumerationValues() {

erichkeane wrote:
> Theres likely quite a few more tests that need to be done.  We should have 
> one where it validates against a fixed underlying type, AND probably a pair 
> of ones to check against scoped enums.  
> 
> I wouldn't expect a scoped enum to diagnose, but a test to make sure we're 
> checking the right thing is likely valuable. 
Another good test is the empty-enum case.


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

https://reviews.llvm.org/D130058

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


[PATCH] D129014: rewording static_assert to more generic static assertion

2022-07-19 Thread Muhammad Usman Shahid via Phabricator via cfe-commits
Codesbyusman added a comment.

*ERR_CLOSED:  This revision has already been
closed*

@Shivam Gupta https://reviews.llvm.org/D129014>+public+5e9f0937aab6a...@reviews.llvm.org> can
not update the patch. it seems it is closed.

F23843528: image003.png 

F23843527: image001.png 

F23843526: image002.png 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129014

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


[PATCH] D130089: update-test-checks: safely handle tests with #if's

2022-07-19 Thread Nicolai Hähnle via Phabricator via cfe-commits
nhaehnle created this revision.
nhaehnle added reviewers: MaskRay, arsenm, aemerson, arichardson.
Herald added subscribers: StephenFan, kristof.beyls.
Herald added a project: All.
nhaehnle requested review of this revision.
Herald added subscribers: cfe-commits, wdng.
Herald added projects: clang, LLVM.

There is at least one Clang test (clang/test/CodeGen/arm_acle.c) which
has functions guarded by #if's that cause those functions to be compiled
only for a subset of RUN lines.

This results in a case where one RUN line has a body for the function
and another doesn't. Treat this case as a conflict for any prefixes that
the two RUN lines have in common.

This change exposed a bug where functions with '$' in the name weren't
properly recognized in ARM assembly (despite there being a test case
that was supposed to catch the problem!). This bug is fixed as well.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130089

Files:
  clang/test/utils/update_cc_test_checks/Inputs/ifdef.c
  clang/test/utils/update_cc_test_checks/Inputs/ifdef.c.expected
  clang/test/utils/update_cc_test_checks/ifdef.test
  
llvm/test/tools/UpdateTestChecks/update_llc_test_checks/Inputs/arm_function_name.ll
  
llvm/test/tools/UpdateTestChecks/update_llc_test_checks/Inputs/arm_function_name.ll.expected
  llvm/utils/UpdateTestChecks/asm.py
  llvm/utils/UpdateTestChecks/common.py
  llvm/utils/update_analyze_test_checks.py
  llvm/utils/update_cc_test_checks.py
  llvm/utils/update_llc_test_checks.py
  llvm/utils/update_test_checks.py

Index: llvm/utils/update_test_checks.py
===
--- llvm/utils/update_test_checks.py
+++ llvm/utils/update_test_checks.py
@@ -120,6 +120,7 @@
verbose=ti.args.verbose)
   builder.process_run_line(common.OPT_FUNCTION_RE, common.scrub_body,
   raw_tool_output, prefixes, False)
+  builder.processed_prefixes(prefixes)
 
 func_dict = builder.finish_and_get_func_dict()
 is_in_function = False
Index: llvm/utils/update_llc_test_checks.py
===
--- llvm/utils/update_llc_test_checks.py
+++ llvm/utils/update_llc_test_checks.py
@@ -137,6 +137,7 @@
 
   scrubber, function_re = output_type.get_run_handler(triple)
   builder.process_run_line(function_re, scrubber, raw_tool_output, prefixes, True)
+  builder.processed_prefixes(prefixes)
 
 func_dict = builder.finish_and_get_func_dict()
 global_vars_seen_dict = {}
Index: llvm/utils/update_cc_test_checks.py
===
--- llvm/utils/update_cc_test_checks.py
+++ llvm/utils/update_cc_test_checks.py
@@ -214,6 +214,7 @@
 builder.process_run_line(
 common.OPT_FUNCTION_RE, common.scrub_body, raw_tool_output,
 prefixes, False)
+builder.processed_prefixes(prefixes)
   else:
 print('The clang command line should include -emit-llvm as asm tests '
   'are discouraged in Clang testsuite.', file=sys.stderr)
Index: llvm/utils/update_analyze_test_checks.py
===
--- llvm/utils/update_analyze_test_checks.py
+++ llvm/utils/update_analyze_test_checks.py
@@ -124,6 +124,8 @@
 common.warn('Don\'t know how to deal with this output')
 continue
 
+  builder.processed_prefixes(prefixes)
+
 func_dict = builder.finish_and_get_func_dict()
 is_in_function = False
 is_in_function_start = False
Index: llvm/utils/UpdateTestChecks/common.py
===
--- llvm/utils/UpdateTestChecks/common.py
+++ llvm/utils/UpdateTestChecks/common.py
@@ -496,6 +496,7 @@
 self._func_dict = {}
 self._func_order = {}
 self._global_var_dict = {}
+self._processed_prefixes = set()
 for tuple in run_list:
   for prefix in tuple[0]:
 self._func_dict.update({prefix:dict()})
@@ -584,30 +585,43 @@
scrubbed_body)
 
 if func in self._func_dict[prefix]:
-  if (self._func_dict[prefix][func] is None or
-  str(self._func_dict[prefix][func]) != scrubbed_body or
-  self._func_dict[prefix][func].args_and_sig != args_and_sig or
-  self._func_dict[prefix][func].attrs != attrs):
-if (self._func_dict[prefix][func] is not None and
-self._func_dict[prefix][func].is_same_except_arg_names(
+  if (self._func_dict[prefix][func] is not None and
+  (str(self._func_dict[prefix][func]) != scrubbed_body or
+   self._func_dict[prefix][func].args_and_sig != args_and_sig or
+   self._func_dict[prefix][func].attrs != attrs)):
+if self._func_dict[prefix][func].is_same_except_arg_names(
 scrubbed_extra,
 args_and_sig,
 attrs,
-is

[PATCH] D128927: [libc++] Always build c++experimental.a

2022-07-19 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

The weird part here is that you're configuring libc++, but you are building 
neither the static nor the shared library. I don't understand why you do that, 
and that may hide some other more fundamental issue in your setup. Anyways, I 
think the issue should be resolved by 1d0f79558ca47f50119fb38c62ff5afd3160d260 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128927

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


[clang] 7300a65 - [libc++] Re-apply "Always build c++experimental.a""

2022-07-19 Thread Louis Dionne via cfe-commits

Author: Louis Dionne
Date: 2022-07-19T10:44:19-04:00
New Revision: 7300a651f5f3b43f9fa3a2d9927322b0e061fcb2

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

LOG: [libc++] Re-apply "Always build c++experimental.a""

This re-applies bb939931a1ad, which had been reverted by 09cebfb978de
because it broke Chromium. The issues seen by Chromium should be
addressed by 1d0f79558ca4.

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

Added: 


Modified: 
clang/cmake/caches/Fuchsia-stage2.cmake
clang/cmake/caches/Fuchsia.cmake
compiler-rt/cmake/Modules/AddCompilerRT.cmake
libcxx/CMakeLists.txt
libcxx/appveyor.yml
libcxx/cmake/caches/AIX.cmake
libcxx/cmake/caches/Apple.cmake
libcxx/cmake/caches/Generic-no-experimental.cmake
libcxx/docs/BuildingLibcxx.rst
libcxx/docs/UsingLibcxx.rst
libcxx/src/CMakeLists.txt
libcxx/test/CMakeLists.txt

libcxx/test/libcxx/experimental/memory/memory.resource.global/global_memory_resource_lifetime.pass.cpp

libcxx/test/libcxx/experimental/memory/memory.resource.global/new_delete_resource_lifetime.pass.cpp

libcxx/test/std/experimental/memory/memory.polymorphic.allocator.class/memory.polymorphic.allocator.mem/construct_pair.pass.cpp

libcxx/test/std/experimental/memory/memory.polymorphic.allocator.class/memory.polymorphic.allocator.mem/construct_piecewise_pair_evil.pass.cpp

libcxx/test/std/experimental/memory/memory.polymorphic.allocator.class/memory.polymorphic.allocator.mem/destroy.pass.cpp

libcxx/test/std/experimental/memory/memory.polymorphic.allocator.class/memory.polymorphic.allocator.mem/resource.pass.cpp

libcxx/test/std/experimental/memory/memory.polymorphic.allocator.class/memory.polymorphic.allocator.mem/select_on_container_copy_construction.pass.cpp

libcxx/test/std/experimental/memory/memory.resource.aliases/header_deque_synop.pass.cpp

libcxx/test/std/experimental/memory/memory.resource.aliases/header_forward_list_synop.pass.cpp

libcxx/test/std/experimental/memory/memory.resource.aliases/header_list_synop.pass.cpp

libcxx/test/std/experimental/memory/memory.resource.aliases/header_map_synop.pass.cpp

libcxx/test/std/experimental/memory/memory.resource.aliases/header_regex_synop.pass.cpp

libcxx/test/std/experimental/memory/memory.resource.aliases/header_set_synop.pass.cpp

libcxx/test/std/experimental/memory/memory.resource.aliases/header_string_synop.pass.cpp

libcxx/test/std/experimental/memory/memory.resource.aliases/header_unordered_map_synop.pass.cpp

libcxx/test/std/experimental/memory/memory.resource.aliases/header_unordered_set_synop.pass.cpp

libcxx/test/std/experimental/memory/memory.resource.aliases/header_vector_synop.pass.cpp

libcxx/test/std/experimental/memory/memory.resource.global/new_delete_resource.pass.cpp

libcxx/test/std/experimental/memory/memory.resource.global/null_memory_resource.pass.cpp
libcxx/utils/ci/run-buildbot
libcxx/utils/libcxx/test/params.py

Removed: 




diff  --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index 13d47d16508df..566df27c1d1cc 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -80,7 +80,6 @@ if(WIN32)
   set(RUNTIMES_${target}_CMAKE_SYSTEM_NAME Windows CACHE STRING "")
   set(RUNTIMES_${target}_CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "")
   set(RUNTIMES_${target}_LIBCXX_ABI_VERSION 2 CACHE STRING "")
-  set(RUNTIMES_${target}_LIBCXX_ENABLE_EXPERIMENTAL_LIBRARY OFF CACHE BOOL "")
   set(RUNTIMES_${target}_LIBCXX_ENABLE_FILESYSTEM OFF CACHE BOOL "")
   set(RUNTIMES_${target}_LIBCXX_ENABLE_ABI_LINKER_SCRIPT OFF CACHE BOOL "")
   set(RUNTIMES_${target}_LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")

diff  --git a/clang/cmake/caches/Fuchsia.cmake 
b/clang/cmake/caches/Fuchsia.cmake
index 83232b776ad9e..73ef571507179 100644
--- a/clang/cmake/caches/Fuchsia.cmake
+++ b/clang/cmake/caches/Fuchsia.cmake
@@ -51,7 +51,6 @@ endif()
 
 if(WIN32)
   set(LIBCXX_ABI_VERSION 2 CACHE STRING "")
-  set(LIBCXX_ENABLE_EXPERIMENTAL_LIBRARY OFF CACHE BOOL "")
   set(LIBCXX_ENABLE_FILESYSTEM OFF CACHE BOOL "")
   set(LIBCXX_ENABLE_ABI_LINKER_SCRIPT OFF CACHE BOOL "")
   set(LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")

diff  --git a/compiler-rt/cmake/Modules/AddCompilerRT.cmake 
b/compiler-rt/cmake/Modules/AddCompilerRT.cmake
index b7eb04327bb1d..00bb892be595a 100644
--- a/compiler-rt/cmake/Modules/AddCompilerRT.cmake
+++ b/compiler-rt/cmake/Modules/AddCompilerRT.cmake
@@ -685,7 +685,6 @@ macro(add_custom_libcxx name prefix)
-DLIBCXXABI_HERMETIC_STATIC_LIBRARY=ON
-DLIBCXXABI_INCLUDE_TESTS=OFF
-DLIBCXX_CXX_ABI=libcxxabi
-   -DLIBCXX_ENABLE

[PATCH] D128927: [libc++] Always build c++experimental.a

2022-07-19 Thread Louis Dionne via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7300a651f5f3: [libc++] Re-apply "Always build 
c++experimental.a"" (authored by ldionne).

Changed prior to commit:
  https://reviews.llvm.org/D128927?vs=443344&id=445822#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128927

Files:
  clang/cmake/caches/Fuchsia-stage2.cmake
  clang/cmake/caches/Fuchsia.cmake
  compiler-rt/cmake/Modules/AddCompilerRT.cmake
  libcxx/CMakeLists.txt
  libcxx/appveyor.yml
  libcxx/cmake/caches/AIX.cmake
  libcxx/cmake/caches/Apple.cmake
  libcxx/cmake/caches/Generic-no-experimental.cmake
  libcxx/docs/BuildingLibcxx.rst
  libcxx/docs/UsingLibcxx.rst
  libcxx/src/CMakeLists.txt
  libcxx/test/CMakeLists.txt
  
libcxx/test/libcxx/experimental/memory/memory.resource.global/global_memory_resource_lifetime.pass.cpp
  
libcxx/test/libcxx/experimental/memory/memory.resource.global/new_delete_resource_lifetime.pass.cpp
  
libcxx/test/std/experimental/memory/memory.polymorphic.allocator.class/memory.polymorphic.allocator.mem/construct_pair.pass.cpp
  
libcxx/test/std/experimental/memory/memory.polymorphic.allocator.class/memory.polymorphic.allocator.mem/construct_piecewise_pair_evil.pass.cpp
  
libcxx/test/std/experimental/memory/memory.polymorphic.allocator.class/memory.polymorphic.allocator.mem/destroy.pass.cpp
  
libcxx/test/std/experimental/memory/memory.polymorphic.allocator.class/memory.polymorphic.allocator.mem/resource.pass.cpp
  
libcxx/test/std/experimental/memory/memory.polymorphic.allocator.class/memory.polymorphic.allocator.mem/select_on_container_copy_construction.pass.cpp
  
libcxx/test/std/experimental/memory/memory.resource.aliases/header_deque_synop.pass.cpp
  
libcxx/test/std/experimental/memory/memory.resource.aliases/header_forward_list_synop.pass.cpp
  
libcxx/test/std/experimental/memory/memory.resource.aliases/header_list_synop.pass.cpp
  
libcxx/test/std/experimental/memory/memory.resource.aliases/header_map_synop.pass.cpp
  
libcxx/test/std/experimental/memory/memory.resource.aliases/header_regex_synop.pass.cpp
  
libcxx/test/std/experimental/memory/memory.resource.aliases/header_set_synop.pass.cpp
  
libcxx/test/std/experimental/memory/memory.resource.aliases/header_string_synop.pass.cpp
  
libcxx/test/std/experimental/memory/memory.resource.aliases/header_unordered_map_synop.pass.cpp
  
libcxx/test/std/experimental/memory/memory.resource.aliases/header_unordered_set_synop.pass.cpp
  
libcxx/test/std/experimental/memory/memory.resource.aliases/header_vector_synop.pass.cpp
  
libcxx/test/std/experimental/memory/memory.resource.global/new_delete_resource.pass.cpp
  
libcxx/test/std/experimental/memory/memory.resource.global/null_memory_resource.pass.cpp
  libcxx/utils/ci/run-buildbot
  libcxx/utils/libcxx/test/params.py

Index: libcxx/utils/libcxx/test/params.py
===
--- libcxx/utils/libcxx/test/params.py
+++ libcxx/utils/libcxx/test/params.py
@@ -159,15 +159,19 @@
 ])),
 
   Parameter(name='enable_experimental', choices=[True, False], type=bool, default=True,
-help="Whether to enable tests for experimental C++ libraries (typically Library Fundamentals TSes).",
+help="Whether to enable tests for experimental C++ Library features.",
 actions=lambda experimental: [] if not experimental else [
-  AddFeature('c++experimental'),
   # When linking in MSVC mode via the Clang driver, a -l
   # maps to .lib, so we need to use -llibc++experimental here
   # to make it link against the static libc++experimental.lib.
   # We can't check for the feature 'msvc' in available_features
   # as those features are added after processing parameters.
-  PrependLinkFlag(lambda config: '-llibc++experimental' if _isMSVC(config) else '-lc++experimental')
+  #
+  # TODO: Switch to using the appropriate experimental compiler flag once
+  #   all compilers we support implement that flag.
+  AddFeature('c++experimental'),
+  PrependLinkFlag(lambda cfg: '-llibc++experimental' if _isMSVC(cfg) else '-lc++experimental'),
+  AddCompileFlag('-D_LIBCPP_ENABLE_EXPERIMENTAL'),
 ]),
 
   Parameter(name='long_tests', choices=[True, False], type=bool, default=True,
Index: libcxx/utils/ci/run-buildbot
===
--- libcxx/utils/ci/run-buildbot
+++ libcxx/utils/ci/run-buildbot
@@ -105,7 +105,6 @@
 # -D_LIBCPP_HAS_NO_INT128 (both when building the library itself and
 # when building tests) to allow enabling filesystem for running tests,
 # even if it uses a non-permanent ABI.
-
 generate-cmake-base \
   -DLLVM_ENABLE_RUNTIMES="libcxx" \
   -DCMAKE_C_COMPILER=cl

[PATCH] D130029: [analyzer][NFC] Use `SValVisitor` instead of explicit helper functions

2022-07-19 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

Thanks! LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130029

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


[PATCH] D130091: [clang][analyzer] Added partial wide character support to CStringChecker

2022-07-19 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: steakhal, manas, ASDenysPetrov, martong, gamesh411, 
dkrupp, donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, 
baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a reviewer: NoQ.
Herald added a project: All.
balazske requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Support for functions wmemcpy, wcslen, wcsnlen is added to the checker.
Documentation and tests are updated and extended with the new functions.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130091

Files:
  clang/docs/analyzer/checkers.rst
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/test/Analysis/cstring.c

Index: clang/test/Analysis/cstring.c
===
--- /dev/null
+++ clang/test/Analysis/cstring.c
@@ -0,0 +1,126 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=unix.cstring \
+// RUN:-analyzer-checker=alpha.unix.cstring \
+// RUN:-analyzer-checker=debug.ExprInspection \
+// RUN:-w -verify %s
+
+typedef __SIZE_TYPE__ size_t;
+typedef __WCHAR_TYPE__ wchar_t;
+void *memcpy(void *dest, const void *src,
+ size_t count);
+wchar_t *wmemcpy(wchar_t *restrict dest, const wchar_t *restrict src,
+ size_t count);
+size_t strlen(const char *s);
+size_t wcslen(const wchar_t *s);
+size_t strnlen(const char *s, size_t maxlen);
+size_t wcsnlen(const wchar_t *s, size_t maxlen);
+
+static const char str[] = "Hello world";
+static const wchar_t w_str[] = L"Hello world";
+
+extern void clang_analyzer_eval(int);
+
+void test_sizeof(void) {
+  char buffer[32];
+  memcpy(buffer, str, sizeof(str));
+  memcpy(buffer, str, sizeof(str) + 1); // expected-warning {{Memory copy function accesses out-of-bound array element [alpha.unix.cstring.OutOfBounds]}}
+}
+
+void w_test_sizeof(void) {
+  wchar_t w_buffer[32];
+  wmemcpy(w_buffer, w_str, sizeof(w_str) / sizeof(w_str[0]));
+  wmemcpy(w_buffer, w_str, (sizeof(w_str) / sizeof(w_str[0])) + 1); // expected-warning {{Memory copy function accesses out-of-bound array element}}
+}
+
+void test_strlen(void) {
+  char buffer[32];
+  // FIXME: This should work with 'str' instead of 'str1'
+  const char str1[] = "Hello world";
+  memcpy(buffer, str1, strlen(str1) + 1);
+  memcpy(buffer, str1, strlen(str1) + 2); // expected-warning {{Memory copy function accesses out-of-bound array element}}
+}
+
+void w_test_wcslen(void) {
+  wchar_t w_buffer[32];
+  // FIXME: This should work with 'w_str' instead of 'w_str1'
+  const wchar_t w_str1[] = L"Hello world";
+  wmemcpy(w_buffer, w_str1, wcslen(w_str1) + 1);
+  wmemcpy(w_buffer, w_str1, wcslen(w_str1) + 2); // expected-warning {{Memory copy function accesses out-of-bound array element}}
+}
+
+void test_strnlen(void) {
+  const char str1[] = "0123456789";
+  const char str2[] = "";
+  clang_analyzer_eval(strnlen(str1, 1) == 1); // expected-warning {{TRUE}}
+  clang_analyzer_eval(strnlen(str1, 100) == 10); // expected-warning {{TRUE}}
+  clang_analyzer_eval(strnlen(str2, 10) == 0); // expected-warning {{TRUE}}
+}
+
+void w_test_wcsnlen(void) {
+  const wchar_t str1[] = L"0123456789";
+  const wchar_t str2[] = L"";
+  clang_analyzer_eval(wcsnlen(str1, 1) == 1); // expected-warning {{TRUE}}
+  clang_analyzer_eval(wcsnlen(str1, 100) == 10); // expected-warning {{TRUE}}
+  clang_analyzer_eval(wcsnlen(str2, 10) == 0); // expected-warning {{TRUE}}
+}
+
+void test_strlen_with_zero(void) {
+  char buffer[32];
+  const char str1[] = "Hello\0world";
+  clang_analyzer_eval(strlen(str1) == 11); // expected-warning {{TRUE}}
+}
+
+void test_dst_overflow(void) {
+  char buffer[] = "Helloworld";
+  memcpy(buffer, str, sizeof(str)); // expected-warning {{Memory copy function overflows the destination buffer [alpha.unix.cstring.OutOfBounds]}}
+}
+
+void w_test_dst_overflow(void) {
+  wchar_t buffer[] = L"Helloworld";
+  wmemcpy(buffer, w_str, sizeof(w_str) / sizeof(w_str[0])); // expected-warning {{Memory copy function overflows the destination buffer}}
+}
+
+void test_dst_offset(void) {
+  char buffer[] = "Hello world";
+  memcpy(buffer + 1, str, sizeof(str)); // expected-warning {{Memory copy function overflows the destination buffer}}
+}
+
+void w_test_dst_offset(void) {
+  wchar_t buffer[] = L"Hello world";
+  wmemcpy(buffer + 1, w_str, sizeof(w_str) / sizeof(w_str[0])); // expected-warning {{Memory copy function overflows the destination buffer}}
+}
+
+int test_strlen_null() {
+  return strlen(0); // expected-warning {{Null pointer passed as 1st argument to string length function [unix.cstring.NullArg]}}
+}
+
+int test_wcslen_null() {
+  return wcslen(0); // expected-warning {{Null pointer passed as 1st argument to string length function}}
+}
+
+int test_strnlen_null() {
+  return strnlen(0, 10); // expected-warning {{Null pointer passed as 1st argument to string le

[PATCH] D129401: [libLTO] Set data-sections by default in libLTO for ELF and XCOFF.

2022-07-19 Thread Quinn Pham via Phabricator via cfe-commits
quinnp updated this revision to Diff 445835.
quinnp marked an inline comment as done.
quinnp added a comment.

Fixing test case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129401

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/test/Driver/gold-lto-sections.c
  clang/test/Driver/lto-data-sections.c
  llvm/lib/LTO/LTOCodeGenerator.cpp
  llvm/test/LTO/PowerPC/data-sections-aix.ll
  llvm/test/LTO/PowerPC/data-sections-linux.ll

Index: llvm/test/LTO/PowerPC/data-sections-linux.ll
===
--- /dev/null
+++ llvm/test/LTO/PowerPC/data-sections-linux.ll
@@ -0,0 +1,26 @@
+; RUN: rm -rf %t
+; RUN: mkdir %t
+; RUN: llvm-as %s -o %t/bc.bc
+; RUN: llvm-lto -exported-symbol var -O0 %t/bc.bc -o %t/default.o
+; RUN: llvm-lto -exported-symbol var -O0 --data-sections=true %t/bc.bc -o \
+; RUN:   %t/data-sections.o
+; RUN: llvm-lto -exported-symbol var -O0 --data-sections=false %t/bc.bc -o \
+; RUN:   %t/no-data-sections.o
+; RUN: obj2yaml %t/default.o | FileCheck --match-full-lines %s
+; RUN: obj2yaml %t/data-sections.o | FileCheck --match-full-lines %s
+; RUN: obj2yaml %t/no-data-sections.o | FileCheck --match-full-lines \
+; RUN:   --check-prefix CHECK-NO-DATA-SECTIONS %s
+
+target triple = "powerpc64le-unknown-linux-gnu"
+
+@var = global i32 0
+
+; CHECK:   Symbols:
+; CHECK: - Name:var
+; CHECK-NEXT:  Type:STT_OBJECT
+; CHECK-NEXT:  Section: .bss.var
+
+; CHECK-NO-DATA-SECTIONS:  Symbols:
+; CHECK-NO-DATA-SECTIONS:- Name:var
+; CHECK-NO-DATA-SECTIONS-NEXT: Type:STT_OBJECT
+; CHECK-NO-DATA-SECTIONS-NEXT: Section: .bss
Index: llvm/test/LTO/PowerPC/data-sections-aix.ll
===
--- /dev/null
+++ llvm/test/LTO/PowerPC/data-sections-aix.ll
@@ -0,0 +1,22 @@
+; RUN: rm -rf %t
+; RUN: mkdir %t
+; RUN: llvm-as %s -o %t/bc.bc
+; RUN: llvm-lto -exported-symbol var -O0 %t/bc.bc -o %t/default.o
+; RUN: llvm-lto -exported-symbol var -O0 --data-sections=true %t/bc.bc -o \
+; RUN:   %t/data-sections.o
+; RUN: llvm-lto -exported-symbol var -O0 --data-sections=false %t/bc.bc -o \
+; RUN:   %t/no-data-sections.o
+; RUN: obj2yaml %t/default.o | FileCheck --match-full-lines %s
+; RUN: obj2yaml %t/data-sections.o | FileCheck --match-full-lines %s
+; RUN: obj2yaml %t/no-data-sections.o | FileCheck --match-full-lines \
+; RUN:   --check-prefix CHECK-NO-DATA-SECTIONS %s
+
+target triple = "powerpc-ibm-aix7.2.0.0"
+
+@var = global i32 0
+
+; CHECK:  Symbols:
+; CHECK-NOT:- Name: .data
+
+; CHECK-NO-DATA-SECTIONS: Symbols:
+; CHECK-NO-DATA-SECTIONS:   - Name: .data
Index: llvm/lib/LTO/LTOCodeGenerator.cpp
===
--- llvm/lib/LTO/LTOCodeGenerator.cpp
+++ llvm/lib/LTO/LTOCodeGenerator.cpp
@@ -19,6 +19,7 @@
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/CommandFlags.h"
 #include "llvm/CodeGen/ParallelCG.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/Config/config.h"
@@ -344,6 +345,14 @@
   Config.CPU = "cyclone";
   }
 
+  // If data-sections is not explicitly set or unset, set data-sections by
+  // default for ELF and XCOFF to match the behaviour of lld and gold plugin.
+  llvm::Triple::ObjectFormatType ObjectFormat = Triple.getObjectFormat();
+  if (!codegen::getExplicitDataSections() &&
+  (ObjectFormat == llvm::Triple::ObjectFormatType::ELF ||
+   ObjectFormat == llvm::Triple::ObjectFormatType::XCOFF))
+Config.Options.DataSections = true;
+
   TargetMach = createTargetMachine();
   assert(TargetMach && "Unable to create target machine");
 
Index: clang/test/Driver/lto-data-sections.c
===
--- /dev/null
+++ clang/test/Driver/lto-data-sections.c
@@ -0,0 +1,10 @@
+// RUN: touch %t.o
+// RUN: %clang %t.o -### -flto 2>&1 | FileCheck %s
+// RUN: %clang %t.o -### -flto 2>&1 -fdata-sections | FileCheck %s \
+// RUN:   --check-prefix=CHECK-DATA-SECTIONS
+// RUN: %clang %t.o -### -flto 2>&1 -fno-data-sections | FileCheck %s \
+// RUN:   --check-prefix=CHECK-NO-DATA-SECTIONS
+
+// CHECK-NOT: "-plugin-opt=-data-sections"
+// CHECK-DATA-SECTIONS: "-plugin-opt=-data-sections=1"
+// CHECK-NO-DATA-SECTIONS: "-plugin-opt=-data-sections=0"
Index: clang/test/Driver/gold-lto-sections.c
===
--- clang/test/Driver/gold-lto-sections.c
+++ clang/test/Driver/gold-lto-sections.c
@@ -5,4 +5,4 @@
 // RUN: -ffunction-sections -fdata-sections \
 // RUN: | FileCheck %s
 // CHECK: "-plugin-opt=-function-sections"
-// CHECK: "-plugin-opt=-data-sections"
+// CHECK: "-plugin-o

[PATCH] D129401: [libLTO] Set data-sections by default in libLTO for ELF and XCOFF.

2022-07-19 Thread Quinn Pham via Phabricator via cfe-commits
quinnp added a comment.

> If this is for the legacy LTO interface, please state so.  `lld/*/LTO.cpp` 
> sets `c.Options.DataSections = true;` to enable data sections by default.

Hey @MaskRay, I'm not sure what is considered the legacy LTO interface, but 
this change is to make the `libLTO` codegen match the behaviour of `LTO` used 
through `lld` and `gold plugin`. Both `lld` and `gold plugin` turn on 
`data-sections` for `LTO` by default:

- as you mentioned `lld/*/LTO.cpp` sets `c.Options.DataSections = true;` by 
default.
- and `llvm/tools/gold/gold-plugin.cpp` sets `Conf.Options.DataSections = 
SplitSections;` provided that the user did not explicitly set/unset 
`data-sections` where `SplitSections` is `true` unless `gold plugin` is doing a 
relocatable link.

@hubert.reinterpretcast please correct me if I am wrong about why this change 
is needed.




Comment at: llvm/lib/LTO/LTOCodeGenerator.cpp:351
+  llvm::Triple::ObjectFormatType ObjectFormat = Triple.getObjectFormat();
+  if (!codegen::getExplicitDataSections() &&
+  (ObjectFormat == llvm::Triple::ObjectFormatType::ELF ||

hubert.reinterpretcast wrote:
> w2yehia wrote:
> > quinnp wrote:
> > > w2yehia wrote:
> > > > any reason we do this for ELF and XCOFF only?
> > > I don't think there is a particular reason that we do this for ELF and 
> > > XCOFF only. We needed this fixed for `AIX` (`XCOFF`) and wanted to change 
> > > `Linux` (`ELF`) to match the behaviour of `lld`/`gold` at the same time. 
> > > I'm not sure what other file formats need for this so I did not include 
> > > them.
> > > 
> > > @hubert.reinterpretcast might have a better answer for this.
> > I don't know either about the other formats, was just wondering.
> > I think it's safe to do it for the file formats that we know are currently 
> > different between libLTO and lld/gold. The proposed change is an 
> > improvement with minimal risk.
> I agree with @w2yehia that we should change the data-sections to "on" by 
> default in libLTO for the other file formats where one of lld/the gold plugin 
> sets it to "on".
@hubert.reinterpretcast I think that if we want to change `data-sections` to 
"on" by default for any file format which  `lld` or `gold plugin` set 
data-sections to "on", we would set `data-sections` to "on" for all file 
formats. This is because `gold plugin` does not check the file format when it 
is setting `data-sections`. You can see where `gold plugin` sets 
`data-sections` here: 
https://github.com/llvm/llvm-project/blob/main/llvm/tools/gold/gold-plugin.cpp#L893

Do you suggest that we remove the checks for file format when setting 
`data-sections` in `libLTO`? ie. change the `if` statement to this:
```
if (!codegen::getExplicitDataSections())
  Config.Options.DataSections = true;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129401

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


[PATCH] D109977: LLVM Driver Multicall tool

2022-07-19 Thread Michał Górny via Phabricator via cfe-commits
mgorny added a comment.

Ok, I think the key to reproducing it is `-DLLVM_LINK_LLVM_DYLIB=ON`. We pass 
that while building LLVM, so it gets passed on to clang but I suppose passing 
it to clang build might be sufficient to reproduce the problem.

The actual problem is that you're passing `${USE_SHARED}` to `llvm_config()` 
(in `add_llvm_executable`) before it's defined. Moving the definition earlier 
fixed this error but uncovers another problem:

  CMake Error at cmake/modules/AddClang.cmake:188 (target_link_libraries):
The keyword signature for target_link_libraries has already been used with
the target "obj.clang".  All uses of target_link_libraries with a target
must be either all-keyword or all-plain.
  
The uses of the keyword signature are here:
  
 * /usr/lib/llvm/15/lib64/cmake/llvm/LLVM-Config.cmake:92 
(target_link_libraries)
  
  Call Stack (most recent call first):
tools/driver/CMakeLists.txt:37 (clang_target_link_libraries)

Now, if you move `USE_SHARED` definition using the following patch:

  diff --git a/llvm/cmake/modules/AddLLVM.cmake 
b/llvm/cmake/modules/AddLLVM.cmake
  index 8e1385e90b82..c37c1c3aa59d 100644
  --- a/llvm/cmake/modules/AddLLVM.cmake
  +++ b/llvm/cmake/modules/AddLLVM.cmake
  @@ -890,6 +890,10 @@ macro(add_llvm_executable name)
   set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
 endif()
   
  +  if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
  +set(USE_SHARED USE_SHARED)
  +  endif()
  +
 if (ARG_GENERATE_DRIVER)
   string(REPLACE "-" "_" TOOL_NAME ${name})
   foreach(path ${CMAKE_MODULE_PATH})
  @@ -964,10 +968,6 @@ macro(add_llvm_executable name)
   add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
 endif(LLVM_EXPORTED_SYMBOL_FILE)
   
  -  if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
  -set(USE_SHARED USE_SHARED)
  -  endif()
  -
 set(EXCLUDE_FROM_ALL OFF)
 set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} 
LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
 llvm_config( ${name} ${USE_SHARED} ${LLVM_LINK_COMPONENTS} )

you should be able to reproduce the latter error using a regular in-tree build, 
e.g.:

  cmake ../llvm -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo 
-DLLVM_ENABLE_PROJECTS='llvm;clang' -DLLVM_BUILD_LLVM_DYLIB=ON 
-DLLVM_LINK_LLVM_DYLIB=ON


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109977

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


[PATCH] D129401: [libLTO] Set data-sections by default in libLTO for ELF and XCOFF.

2022-07-19 Thread Quinn Pham via Phabricator via cfe-commits
quinnp updated this revision to Diff 445839.
quinnp added a comment.

Modifying a test to fix check lines.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129401

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/test/Driver/gold-lto-sections.c
  clang/test/Driver/lto-data-sections.c
  llvm/lib/LTO/LTOCodeGenerator.cpp
  llvm/test/LTO/PowerPC/data-sections-aix.ll
  llvm/test/LTO/PowerPC/data-sections-linux.ll

Index: llvm/test/LTO/PowerPC/data-sections-linux.ll
===
--- /dev/null
+++ llvm/test/LTO/PowerPC/data-sections-linux.ll
@@ -0,0 +1,26 @@
+; RUN: rm -rf %t
+; RUN: mkdir %t
+; RUN: llvm-as %s -o %t/bc.bc
+; RUN: llvm-lto -exported-symbol var -O0 %t/bc.bc -o %t/default.o
+; RUN: llvm-lto -exported-symbol var -O0 --data-sections=true %t/bc.bc -o \
+; RUN:   %t/data-sections.o
+; RUN: llvm-lto -exported-symbol var -O0 --data-sections=false %t/bc.bc -o \
+; RUN:   %t/no-data-sections.o
+; RUN: obj2yaml %t/default.o | FileCheck --match-full-lines %s
+; RUN: obj2yaml %t/data-sections.o | FileCheck --match-full-lines %s
+; RUN: obj2yaml %t/no-data-sections.o | FileCheck --match-full-lines \
+; RUN:   --check-prefix CHECK-NO-DATA-SECTIONS %s
+
+target triple = "powerpc64le-unknown-linux-gnu"
+
+@var = global i32 0
+
+; CHECK:   Symbols:
+; CHECK: - Name:var
+; CHECK-NEXT:  Type:STT_OBJECT
+; CHECK-NEXT:  Section: .bss.var
+
+; CHECK-NO-DATA-SECTIONS:  Symbols:
+; CHECK-NO-DATA-SECTIONS:- Name:var
+; CHECK-NO-DATA-SECTIONS-NEXT: Type:STT_OBJECT
+; CHECK-NO-DATA-SECTIONS-NEXT: Section: .bss
Index: llvm/test/LTO/PowerPC/data-sections-aix.ll
===
--- /dev/null
+++ llvm/test/LTO/PowerPC/data-sections-aix.ll
@@ -0,0 +1,22 @@
+; RUN: rm -rf %t
+; RUN: mkdir %t
+; RUN: llvm-as %s -o %t/bc.bc
+; RUN: llvm-lto -exported-symbol var -O0 %t/bc.bc -o %t/default.o
+; RUN: llvm-lto -exported-symbol var -O0 --data-sections=true %t/bc.bc -o \
+; RUN:   %t/data-sections.o
+; RUN: llvm-lto -exported-symbol var -O0 --data-sections=false %t/bc.bc -o \
+; RUN:   %t/no-data-sections.o
+; RUN: obj2yaml %t/default.o | FileCheck --match-full-lines %s
+; RUN: obj2yaml %t/data-sections.o | FileCheck --match-full-lines %s
+; RUN: obj2yaml %t/no-data-sections.o | FileCheck --match-full-lines \
+; RUN:   --check-prefix CHECK-NO-DATA-SECTIONS %s
+
+target triple = "powerpc-ibm-aix7.2.0.0"
+
+@var = global i32 0
+
+; CHECK:  Symbols:
+; CHECK-NOT:- Name: .data
+
+; CHECK-NO-DATA-SECTIONS: Symbols:
+; CHECK-NO-DATA-SECTIONS:   - Name: .data
Index: llvm/lib/LTO/LTOCodeGenerator.cpp
===
--- llvm/lib/LTO/LTOCodeGenerator.cpp
+++ llvm/lib/LTO/LTOCodeGenerator.cpp
@@ -19,6 +19,7 @@
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/CommandFlags.h"
 #include "llvm/CodeGen/ParallelCG.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/Config/config.h"
@@ -344,6 +345,14 @@
   Config.CPU = "cyclone";
   }
 
+  // If data-sections is not explicitly set or unset, set data-sections by
+  // default for ELF and XCOFF to match the behaviour of lld and gold plugin.
+  llvm::Triple::ObjectFormatType ObjectFormat = Triple.getObjectFormat();
+  if (!codegen::getExplicitDataSections() &&
+  (ObjectFormat == llvm::Triple::ObjectFormatType::ELF ||
+   ObjectFormat == llvm::Triple::ObjectFormatType::XCOFF))
+Config.Options.DataSections = true;
+
   TargetMach = createTargetMachine();
   assert(TargetMach && "Unable to create target machine");
 
Index: clang/test/Driver/lto-data-sections.c
===
--- /dev/null
+++ clang/test/Driver/lto-data-sections.c
@@ -0,0 +1,11 @@
+// RUN: touch %t.o
+// RUN: %clang %t.o -### -flto 2>&1 | FileCheck %s
+// RUN: %clang %t.o -### -flto 2>&1 -fdata-sections | FileCheck %s \
+// RUN:   --check-prefix=CHECK-DATA-SECTIONS
+// RUN: %clang %t.o -### -flto 2>&1 -fno-data-sections | FileCheck %s \
+// RUN:   --check-prefix=CHECK-NO-DATA-SECTIONS
+
+// CHECK-NOT: "-plugin-opt=-data-sections=1"
+// CHECK-NOT: "-plugin-opt=-data-sections=0"
+// CHECK-DATA-SECTIONS: "-plugin-opt=-data-sections=1"
+// CHECK-NO-DATA-SECTIONS: "-plugin-opt=-data-sections=0"
Index: clang/test/Driver/gold-lto-sections.c
===
--- clang/test/Driver/gold-lto-sections.c
+++ clang/test/Driver/gold-lto-sections.c
@@ -5,4 +5,4 @@
 // RUN: -ffunction-sections -fdata-sections \
 // RUN: | FileCheck %s
 // CHECK: "-plugin-opt=-function-sections"
-// CHECK: "-plugin-opt=-data-secti

[PATCH] D130095: [clangd] Improve XRefs support for ObjCMethodDecl

2022-07-19 Thread David Goldman via Phabricator via cfe-commits
dgoldman created this revision.
dgoldman added a reviewer: kadircet.
Herald added subscribers: usaxena95, arphaman.
Herald added a project: All.
dgoldman requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

- Correct nameLocation to point to the first selector fragment instead of the - 
or +

- getDefinition now searches through the proper impl decls to find the 
definition of the ObjCMethodDecl if one exists


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130095

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/AST.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -957,6 +957,46 @@
 Fo^o * getFoo() {
   return 0;
 }
+  )objc",
+
+  R"objc(// Method decl and definition for ObjC class.
+@interface Cat
+- (void)$decl[[meow]];
+@end
+@implementation Cat
+- (void)$def[[meow]] {}
+@end
+void makeNoise(Cat *kitty) {
+  [kitty me^ow];
+}
+  )objc",
+
+  R"objc(// Method decl and definition for ObjC category.
+@interface Dog
+@end
+@interface Dog (Play)
+- (void)$decl[[runAround]];
+@end
+@implementation Dog (Play)
+- (void)$def[[runAround]] {}
+@end
+void play(Dog *dog) {
+  [dog run^Around];
+}
+  )objc",
+
+  R"objc(// Method decl and definition for ObjC class extension.
+@interface Dog
+@end
+@interface Dog ()
+- (void)$decl[[howl]];
+@end
+@implementation Dog
+- (void)$def[[howl]] {}
+@end
+void play(Dog *dog) {
+  [dog ho^wl];
+}
   )objc"};
   for (const char *Test : Tests) {
 Annotations T(Test);
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -83,32 +83,19 @@
   if (const auto *CTD = dyn_cast(D))
 if (const auto *RD = CTD->getTemplatedDecl())
   return RD->getDefinition();
-  // Objective-C classes can have three types of declarations:
-  //
-  // - forward declaration: @class MyClass;
-  // - true declaration (interface definition): @interface MyClass ... @end
-  // - true definition (implementation): @implementation MyClass ... @end
-  //
-  // Objective-C categories are extensions are on classes:
-  //
-  // - declaration: @interface MyClass (Ext) ... @end
-  // - definition: @implementation MyClass (Ext) ... @end
-  //
-  // With one special case, a class extension, which is normally used to keep
-  // some declarations internal to a file without exposing them in a header.
-  //
-  // - class extension declaration: @interface MyClass () ... @end
-  // - which really links to class definition: @implementation MyClass ... @end
-  if (const auto *ID = dyn_cast(D))
-return ID->getImplementation();
-  if (const auto *CD = dyn_cast(D)) {
-if (CD->IsClassExtension()) {
-  if (const auto *ID = CD->getClassInterface())
-return ID->getImplementation();
+  if (const auto *MD = dyn_cast(D)) {
+if (MD->isThisDeclarationADefinition())
+  return MD;
+auto *DeclCtx = cast(MD->getDeclContext());
+if (DeclCtx->isInvalidDecl())
   return nullptr;
-}
-return CD->getImplementation();
+
+if (const auto *CD = dyn_cast(DeclCtx))
+  if (const auto *Impl = getCorrespondingObjCImpl(CD))
+return Impl->getMethod(MD->getSelector(), MD->isInstanceMethod());
   }
+  if (const auto *CD = dyn_cast(D))
+return getCorrespondingObjCImpl(CD);
   // Only a single declaration is allowed.
   if (isa(D) || isa(D) ||
   isa(D)) // except cases above
Index: clang-tools-extra/clangd/AST.h
===
--- clang-tools-extra/clangd/AST.h
+++ clang-tools-extra/clangd/AST.h
@@ -93,6 +93,30 @@
 SymbolID getSymbolID(const llvm::StringRef MacroName, const MacroInfo *MI,
  const SourceManager &SM);
 
+/// Return the corresponding implementation/definition for the given ObjC
+/// container if it has one, otherwise, return nullptr.
+///
+/// Objective-C classes can have three types of declarations:
+///
+/// - forward declaration: @class MyClass;
+/// - true declaration (interface definition): @interface MyClass ... @end
+/// - true definition (implementation): @implementation MyClass ... @end
+///
+/// Objective-C categories are extensions are on classes:
+///
+/// - declaration: @interface MyClass (Ext) ... @end
+/// - definition: @implementation MyClass (Ext) ... 

[clang] a62868a - [libclang][ObjC] Inherit availability attribute from containing decls or

2022-07-19 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2022-07-19T09:17:39-07:00
New Revision: a62868aaeaac1c6464a3acbc90209458e4594338

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

LOG: [libclang][ObjC] Inherit availability attribute from containing decls or
interface decls

This patch teaches getCursorPlatformAvailabilityForDecl to look for
availability attributes on the containing decls or interface decls if
the current decl doesn't have any availability attributes.

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

Added: 
clang/test/Index/availability.mm

Modified: 
clang/tools/libclang/CIndex.cpp

Removed: 




diff  --git a/clang/test/Index/availability.mm 
b/clang/test/Index/availability.mm
new file mode 100644
index ..7c76a86d77d0
--- /dev/null
+++ b/clang/test/Index/availability.mm
@@ -0,0 +1,79 @@
+__attribute__((availability(macosx, introduced = 8.0)))
+@interface C {
+  int i0;
+  int i1 __attribute__((availability(macosx, introduced = 9.0)));
+}
+@property int p0;
+@property int p1 __attribute__((availability(macosx, introduced=9.0)));
+- (void)m0;
+- (void)m1 __attribute__((availability(macosx, introduced = 9.0)));
+@end
+
+@implementation C
+- (void)m0 {
+}
+- (void)m1 {
+}
+@end
+
+__attribute__((availability(macosx, introduced = 10.0)))
+@interface C(Cat)
+@property int p2;
+@property int p3 __attribute__((availability(macosx, introduced=11.0)));
+- (void)m2;
+- (void)m3 __attribute__((availability(macosx, introduced = 11.0)));
+@end
+
+@implementation C(Cat)
+- (void)m2 {
+}
+- (void)m3 {
+}
+@end
+
+__attribute__((availability(macosx, introduced = 10.0)))
+@protocol P
+@property int p4;
+@property int p5 __attribute__((availability(macosx, introduced=11.0)));
+- (void)m4;
+- (void)m5 __attribute__((availability(macosx, introduced = 11.0)));
+@end
+
+@interface C(Cat2)
+@end
+
+@implementation C(Cat2)
+@end
+
+// RUN: c-index-test -test-print-type --std=c++11 %s | FileCheck %s
+
+// CHECK: ObjCInterfaceDecl=C:2:12  (macos, introduced=8.0)
+// CHECK: ObjCIvarDecl=i0:3:7 (Definition)  (macos, introduced=8.0)
+// CHECK: ObjCIvarDecl=i1:4:7 (Definition)  (macos, introduced=9.0)
+// CHECK: ObjCPropertyDecl=p0:6:15  (macos, introduced=8.0)
+// CHECK: ObjCPropertyDecl=p1:7:15  (macos, introduced=9.0)
+// CHECK: ObjCInstanceMethodDecl=m0:8:9  (macos, introduced=8.0)
+// CHECK: ObjCInstanceMethodDecl=m1:9:9  (macos, introduced=9.0)
+
+// CHECK: ObjCImplementationDecl=C:12:17 (Definition)  (macos, introduced=8.0)
+// CHECK: ObjCInstanceMethodDecl=m0:13:9 (Definition)  (macos, introduced=8.0)
+// CHECK: ObjCInstanceMethodDecl=m1:15:9 (Definition)  (macos, introduced=9.0)
+
+// CHECK: ObjCCategoryDecl=Cat:20:12  (macos, introduced=10.0)
+// CHECK: ObjCPropertyDecl=p2:21:15  (macos, introduced=10.0)
+// CHECK: ObjCPropertyDecl=p3:22:15  (macos, introduced=11.0)
+// CHECK: ObjCInstanceMethodDecl=m2:23:9  (macos, introduced=10.0)
+// CHECK: ObjCInstanceMethodDecl=m3:24:9  (macos, introduced=11.0)
+
+// CHECK: ObjCCategoryImplDecl=Cat:27:17 (Definition)  (macos, introduced=10.0)
+// CHECK: ObjCInstanceMethodDecl=m2:28:9 (Definition)  (macos, introduced=10.0)
+// CHECK: ObjCInstanceMethodDecl=m3:30:9 (Definition)  (macos, introduced=11.0)
+
+// CHECK: ObjCProtocolDecl=P:35:11 (Definition)  (macos, introduced=10.0)
+// CHECK: ObjCPropertyDecl=p4:36:15  (macos, introduced=10.0)
+// CHECK: ObjCPropertyDecl=p5:37:15  (macos, introduced=11.0)
+// CHECK: ObjCInstanceMethodDecl=m4:38:9  (macos, introduced=10.0)
+// CHECK: ObjCInstanceMethodDecl=m5:39:9  (macos, introduced=11.0)
+
+// CHECK: ObjCCategoryDecl=Cat2:42:12  (macos, introduced=8.0)
+// CHECK: ObjCCategoryImplDecl=Cat2:45:17 (Definition)  (macos, introduced=8.0)

diff  --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index 420ee25d1df7..776761db2b1c 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -8258,8 +8258,35 @@ static void getCursorPlatformAvailabilityForDecl(
   deprecated_message, always_unavailable, unavailable_message,
   AvailabilityAttrs);
 
-  if (AvailabilityAttrs.empty())
+  // If no availability attributes are found, inherit the attribute from the
+  // containing decl or the class or category interface decl.
+  if (AvailabilityAttrs.empty()) {
+const ObjCContainerDecl *CD = nullptr;
+const DeclContext *DC = D->getDeclContext();
+
+if (auto *IMD = dyn_cast(D))
+  CD = IMD->getClassInterface();
+else if (auto *CatD = dyn_cast(D))
+  CD = CatD->getClassInterface();
+else if (auto *IMD = dyn_cast(D))
+  CD = IMD->getCategoryDecl();
+else if (auto *ID = dyn_cast(DC))
+  CD = ID;
+else if (auto *CatD = dyn_cast(DC))
+  CD = CatD;
+else if (auto *IMD = dyn_cast(DC))
+  CD = IMD->getCl

[PATCH] D129886: [clang] Add -fdiagnostics-format=sarif option for future SARIF output

2022-07-19 Thread Abraham Corea Diaz via Phabricator via cfe-commits
abrahamcd updated this revision to Diff 445845.
abrahamcd marked 5 inline comments as done.
abrahamcd edited the summary of this revision.
abrahamcd added a comment.

Update test file to check for warning and address other minor comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129886

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/TextDiagnostic.cpp
  clang/test/Driver/fdiagnostics-format-sarif.cpp


Index: clang/test/Driver/fdiagnostics-format-sarif.cpp
===
--- /dev/null
+++ clang/test/Driver/fdiagnostics-format-sarif.cpp
@@ -0,0 +1,2 @@
+// RUN: %clang -fsyntax-only -fdiagnostics-format=sarif %s -### 2>&1 | 
FileCheck %s --check-prefix=WARN
+// WARN: warning: diagnostic formatting in SARIF mode is currently unstable 
[-Wsarif-format-unstable]
Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -815,6 +815,7 @@
 
   emitFilename(PLoc.getFilename(), Loc.getManager());
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
 if (DiagOpts->ShowLine)
   OS << ':' << LineNo;
@@ -837,6 +838,7 @@
   OS << ColNo;
 }
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
   case DiagnosticOptions::Vi:OS << ':';break;
   case DiagnosticOptions::MSVC:
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4006,6 +4006,9 @@
   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
 CmdArgs.push_back("-fdiagnostics-format");
 CmdArgs.push_back(A->getValue());
+if (StringRef(A->getValue()) == "sarif") {
+  D.Diag(diag::warn_drv_sarif_format_unstable);
+}
   }
 
   if (const Arg *A = Args.getLastArg(
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -5580,8 +5580,8 @@
 
 def fdiagnostics_format : Separate<["-"], "fdiagnostics-format">,
   HelpText<"Change diagnostic formatting to match IDE and command line tools">,
-  Values<"clang,msvc,vi">,
-  NormalizedValuesScope<"DiagnosticOptions">, NormalizedValues<["Clang", 
"MSVC", "Vi"]>,
+  Values<"clang,msvc,vi,sarif">,
+  NormalizedValuesScope<"DiagnosticOptions">, NormalizedValues<["Clang", 
"MSVC", "Vi", "SARIF"]>,
   MarshallingInfoEnum, "Clang">;
 def fdiagnostics_show_category : Separate<["-"], "fdiagnostics-show-category">,
   HelpText<"Print diagnostic category">,
Index: clang/include/clang/Basic/DiagnosticOptions.h
===
--- clang/include/clang/Basic/DiagnosticOptions.h
+++ clang/include/clang/Basic/DiagnosticOptions.h
@@ -74,7 +74,7 @@
   friend class CompilerInvocation;
 
 public:
-  enum TextDiagnosticFormat { Clang, MSVC, Vi };
+  enum TextDiagnosticFormat { Clang, MSVC, Vi, SARIF };
 
   // Default values.
   enum {
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -678,4 +678,8 @@
 def err_drv_invalid_empty_dxil_validator_version : Error<
   "invalid validator version : %0\n"
   "If validator major version is 0, minor version must also be 0.">;
+
+def warn_drv_sarif_format_unstable : Warning<
+  "diagnostic formatting in SARIF mode is currently unstable">,
+  InGroup>;
 }


Index: clang/test/Driver/fdiagnostics-format-sarif.cpp
===
--- /dev/null
+++ clang/test/Driver/fdiagnostics-format-sarif.cpp
@@ -0,0 +1,2 @@
+// RUN: %clang -fsyntax-only -fdiagnostics-format=sarif %s -### 2>&1 | FileCheck %s --check-prefix=WARN
+// WARN: warning: diagnostic formatting in SARIF mode is currently unstable [-Wsarif-format-unstable]
Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -815,6 +815,7 @@
 
   emitFilename(PLoc.getFilename(), Loc.getManager());
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
 if (DiagOpts->ShowLine)
   OS << ':' << LineNo;
@@ -837,6 +838,7 @@
   OS << ColNo;
 }
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOp

[PATCH] D129504: [libclang][ObjC] Inherit availability attribute from containing decls or interface decls

2022-07-19 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa62868aaeaac: [libclang][ObjC] Inherit availability 
attribute from containing decls or (authored by ahatanak).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129504

Files:
  clang/test/Index/availability.mm
  clang/tools/libclang/CIndex.cpp

Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -8258,8 +8258,35 @@
   deprecated_message, always_unavailable, unavailable_message,
   AvailabilityAttrs);
 
-  if (AvailabilityAttrs.empty())
+  // If no availability attributes are found, inherit the attribute from the
+  // containing decl or the class or category interface decl.
+  if (AvailabilityAttrs.empty()) {
+const ObjCContainerDecl *CD = nullptr;
+const DeclContext *DC = D->getDeclContext();
+
+if (auto *IMD = dyn_cast(D))
+  CD = IMD->getClassInterface();
+else if (auto *CatD = dyn_cast(D))
+  CD = CatD->getClassInterface();
+else if (auto *IMD = dyn_cast(D))
+  CD = IMD->getCategoryDecl();
+else if (auto *ID = dyn_cast(DC))
+  CD = ID;
+else if (auto *CatD = dyn_cast(DC))
+  CD = CatD;
+else if (auto *IMD = dyn_cast(DC))
+  CD = IMD->getClassInterface();
+else if (auto *IMD = dyn_cast(DC))
+  CD = IMD->getCategoryDecl();
+else if (auto *PD = dyn_cast(DC))
+  CD = PD;
+
+if (CD)
+  getCursorPlatformAvailabilityForDecl(
+  CD, always_deprecated, deprecated_message, always_unavailable,
+  unavailable_message, AvailabilityAttrs);
 return;
+  }
 
   llvm::sort(
   AvailabilityAttrs, [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
Index: clang/test/Index/availability.mm
===
--- /dev/null
+++ clang/test/Index/availability.mm
@@ -0,0 +1,79 @@
+__attribute__((availability(macosx, introduced = 8.0)))
+@interface C {
+  int i0;
+  int i1 __attribute__((availability(macosx, introduced = 9.0)));
+}
+@property int p0;
+@property int p1 __attribute__((availability(macosx, introduced=9.0)));
+- (void)m0;
+- (void)m1 __attribute__((availability(macosx, introduced = 9.0)));
+@end
+
+@implementation C
+- (void)m0 {
+}
+- (void)m1 {
+}
+@end
+
+__attribute__((availability(macosx, introduced = 10.0)))
+@interface C(Cat)
+@property int p2;
+@property int p3 __attribute__((availability(macosx, introduced=11.0)));
+- (void)m2;
+- (void)m3 __attribute__((availability(macosx, introduced = 11.0)));
+@end
+
+@implementation C(Cat)
+- (void)m2 {
+}
+- (void)m3 {
+}
+@end
+
+__attribute__((availability(macosx, introduced = 10.0)))
+@protocol P
+@property int p4;
+@property int p5 __attribute__((availability(macosx, introduced=11.0)));
+- (void)m4;
+- (void)m5 __attribute__((availability(macosx, introduced = 11.0)));
+@end
+
+@interface C(Cat2)
+@end
+
+@implementation C(Cat2)
+@end
+
+// RUN: c-index-test -test-print-type --std=c++11 %s | FileCheck %s
+
+// CHECK: ObjCInterfaceDecl=C:2:12  (macos, introduced=8.0)
+// CHECK: ObjCIvarDecl=i0:3:7 (Definition)  (macos, introduced=8.0)
+// CHECK: ObjCIvarDecl=i1:4:7 (Definition)  (macos, introduced=9.0)
+// CHECK: ObjCPropertyDecl=p0:6:15  (macos, introduced=8.0)
+// CHECK: ObjCPropertyDecl=p1:7:15  (macos, introduced=9.0)
+// CHECK: ObjCInstanceMethodDecl=m0:8:9  (macos, introduced=8.0)
+// CHECK: ObjCInstanceMethodDecl=m1:9:9  (macos, introduced=9.0)
+
+// CHECK: ObjCImplementationDecl=C:12:17 (Definition)  (macos, introduced=8.0)
+// CHECK: ObjCInstanceMethodDecl=m0:13:9 (Definition)  (macos, introduced=8.0)
+// CHECK: ObjCInstanceMethodDecl=m1:15:9 (Definition)  (macos, introduced=9.0)
+
+// CHECK: ObjCCategoryDecl=Cat:20:12  (macos, introduced=10.0)
+// CHECK: ObjCPropertyDecl=p2:21:15  (macos, introduced=10.0)
+// CHECK: ObjCPropertyDecl=p3:22:15  (macos, introduced=11.0)
+// CHECK: ObjCInstanceMethodDecl=m2:23:9  (macos, introduced=10.0)
+// CHECK: ObjCInstanceMethodDecl=m3:24:9  (macos, introduced=11.0)
+
+// CHECK: ObjCCategoryImplDecl=Cat:27:17 (Definition)  (macos, introduced=10.0)
+// CHECK: ObjCInstanceMethodDecl=m2:28:9 (Definition)  (macos, introduced=10.0)
+// CHECK: ObjCInstanceMethodDecl=m3:30:9 (Definition)  (macos, introduced=11.0)
+
+// CHECK: ObjCProtocolDecl=P:35:11 (Definition)  (macos, introduced=10.0)
+// CHECK: ObjCPropertyDecl=p4:36:15  (macos, introduced=10.0)
+// CHECK: ObjCPropertyDecl=p5:37:15  (macos, introduced=11.0)
+// CHECK: ObjCInstanceMethodDecl=m4:38:9  (macos, introduced=10.0)
+// CHECK: ObjCInstanceMethodDecl=m5:39:9  (macos, introduced=11.0)
+
+// CHECK: ObjCCategoryDecl=Cat2:42:12  (macos, introduced=8.0)
+// CHECK: ObjCCategoryImplDecl=Cat2:45:17 (Definition)  (macos, introduced=8.0)
___
cfe-commits mailing list
c

[PATCH] D128750: [c++20] Implement P2113R0: Changes to the Partial Ordering of Constrained Functions

2022-07-19 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson added a comment.

In D128750#3661576 , @ychen wrote:

> ...
> There is *no* way to reorder the template parameters list again (to get two 
> or more reordering) and the resulted template still works, because of the 
> *positionally correspond* requirement. If this reasoning is sound, I think 
> the current approach of deducing order to compare constraints for rewritten 
> candidates is correct. I wouldn't say I'm 100% confident. But it still makes 
> sense to me at this moment.

I'm not sure I follow your reasoning here. I agree we can't reorder the 
function parameters, but in your example with T/U/V we have 3 template 
parameters that we could reorder in 6 different ways. According to how I read 
6.2.1.2 we'd need to check there's only one way to order them equivalently, 
which (I think) reduces to every template parameter appears only once.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128750

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


[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: JonChesterfield, yaxunl, saiislam, arsenm, 
carlo.bertolli, MaskRay, jdoerfert, tianshilei1992.
Herald added subscribers: kosarev, StephenFan, t-tye, tpr, dstuttard, jvesely, 
kzhuravl.
Herald added a project: All.
jhuber6 requested review of this revision.
Herald added subscribers: cfe-commits, wdng.
Herald added a project: clang.

The AMDGPU library uses several control constants to change code paths
for the math functions and intrinsics. These are normally included using
several individual bitcode libraries at link time. However, this is
problematic because it requires us to know the AMDGPU architecture at
link time which should not be strictly necessary. This patch adds new
code that emits the constants that would normally be included by the
bitcode libraries. This removes around six libraries we would otherwise
need to include and now we can link these libraries in unconditionally
like we do with libdevice.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130096

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  clang/lib/CodeGen/TargetInfo.h
  clang/test/CodeGen/amdgcn-occl-constants.c

Index: clang/test/CodeGen/amdgcn-occl-constants.c
===
--- /dev/null
+++ clang/test/CodeGen/amdgcn-occl-constants.c
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -target-cpu gfx90a -S -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -target-cpu gfx90a -fgpu-fast-relaxed-math \
+// RUN:   -S -emit-llvm -o - %s | FileCheck %s --check-prefix=FAST
+
+void foo() {}
+
+// CHECK: @__oclc_daz_opt = weak_odr hidden local_unnamed_addr addrspace(4) constant i8 0, align 1
+// CHECK: @__oclc_wavefrontsize64 = weak_odr hidden local_unnamed_addr addrspace(4) constant i8 1, align 1
+// CHECK: @__oclc_finite_only_opt = weak_odr hidden local_unnamed_addr addrspace(4) constant i8 0, align 1
+// CHECK: @__oclc_unsafe_math_opt = weak_odr hidden local_unnamed_addr addrspace(4) constant i8 0, align 1
+// CHECK: @__oclc_correctly_rounded_sqrt32 = weak_odr hidden local_unnamed_addr addrspace(4) constant i8 1, align 1
+// CHECK: @__oclc_ISA_version = weak_odr hidden local_unnamed_addr addrspace(4) constant i32 9010, align 4
+// CHECK: @__oclc_ABI_version = weak_odr hidden local_unnamed_addr addrspace(4) constant i32 400, align 4
+
+// FAST: @__oclc_daz_opt = weak_odr hidden local_unnamed_addr addrspace(4) constant i8 0, align 1
+// FAST: @__oclc_wavefrontsize64 = weak_odr hidden local_unnamed_addr addrspace(4) constant i8 1, align 1
+// FAST: @__oclc_finite_only_opt = weak_odr hidden local_unnamed_addr addrspace(4) constant i8 1, align 1
+// FAST: @__oclc_unsafe_math_opt = weak_odr hidden local_unnamed_addr addrspace(4) constant i8 1, align 1
+// FAST: @__oclc_correctly_rounded_sqrt32 = weak_odr hidden local_unnamed_addr addrspace(4) constant i8 1, align 1
+// FAST: @__oclc_ISA_version = weak_odr hidden local_unnamed_addr addrspace(4) constant i32 9010, align 4
+// FAST: @__oclc_ABI_version = weak_odr hidden local_unnamed_addr addrspace(4) constant i32 400, align 4
Index: clang/lib/CodeGen/TargetInfo.h
===
--- clang/lib/CodeGen/TargetInfo.h
+++ clang/lib/CodeGen/TargetInfo.h
@@ -63,6 +63,9 @@
   CodeGen::CodeGenModule &CGM,
   const llvm::MapVector &MangledDeclNames) const {}
 
+  /// Provides a convenient hook to handle extra target-specific globals.
+  virtual void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const {}
+
   /// Any further codegen related checks that need to be done on a function call
   /// in a target specific manner.
   virtual void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -34,6 +34,7 @@
 #include "llvm/IR/IntrinsicsS390.h"
 #include "llvm/IR/Type.h"
 #include "llvm/Support/MathExtras.h"
+#include "llvm/Support/TargetParser.h"
 #include "llvm/Support/raw_ostream.h"
 #include  // std::sort
 
@@ -9307,6 +9308,8 @@
   void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F,
  CodeGenModule &CGM) const;
 
+  void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const override;
+
   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &M) const override;
   unsigned getOpenCLKernelCallingConv() const override;
@@ -9422,6 +9425,61 @@
   }
 }
 
+void AMDGPUTargetCodeGenInfo::emitTargetGlobals(
+CodeGen::CodeGenModule &CGM) const {
+  if (!CGM.getTriple().isAMDGCN())
+return;
+  StringRef CPU = CGM.getTarget().getTargetOpts().CPU;
+  // Chec

[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

Let me know if I should move this code somewhere else, or if there are 
problems. One change I made is that the constant is `weak_odr` and `hidden` 
instead of `linkonce_odr` and `protected`. This is so this constant is alive 
until link time, AMDGPU pretty much always uses LTO so these should be 
optimized out when we internalize symbols. I'm assuming we don't need 
`protected` visibility as these shouldn't be read from another executable (e.g. 
the host).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D129016: [PowerPC] implemented @llvm.ppc.kill.canary to corrupt stack guard

2022-07-19 Thread Paul Scoropan via Phabricator via cfe-commits
pscoro updated this revision to Diff 445853.
pscoro added a comment.

formatted comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129016

Files:
  llvm/lib/Target/PowerPC/PPCISelLowering.cpp


Index: llvm/lib/Target/PowerPC/PPCISelLowering.cpp
===
--- llvm/lib/Target/PowerPC/PPCISelLowering.cpp
+++ llvm/lib/Target/PowerPC/PPCISelLowering.cpp
@@ -10699,12 +10699,12 @@
 MachineFunction &MF = DAG.getMachineFunction();
 const Module *M = MF.getMMI().getModule();
 
-/* If SafeStack or !StackProtector, kill_canary not supported */
+// If SafeStack or !StackProtector, kill_canary is not supported.
 if (MF.getFunction().hasFnAttribute(Attribute::SafeStack) ||
 !MF.getFunction().hasStackProtectorFnAttr()) {
   DAG.ReplaceAllUsesOfValueWith(
   SDValue(Op.getNode(), 0),
-  Op->getOperand(0)); // prepare node for deletion
+  Op->getOperand(0));
   break;
 }
 
@@ -10713,44 +10713,39 @@
 SDValue Load;
 SDValue Store;
 
-const uint64_t XORWord =
-0x; // XORing with 0b111...111 will never
-// result in the original word
+// The new stored canary word should never be the same as the canary word
+// before corruption, so we XOR the canary word with all 1 bits.
+const uint64_t XORWord = 0x; 
 
-if (useLoadStackGuardNode()) { // linux uses LOAD_STACK_GUARD node instead
-   // of having a canary word global value
+// Linux uses LOAD_STACK_GUARD node instead of a canary global value.
+if (useLoadStackGuardNode()) {
   MachineSDNode *LSG =
   DAG.getMachineNode(PPC::LOAD_STACK_GUARD, DL, VT, Op->getOperand(0));
   Load = SDValue(LSG, 0);
 
-  /* frame index used to determine stack guard location if
-   * LOAD_STACK_GUARD is used */
+  // Frame index used to determine stack guard location if 
+  // LOAD_STACK_GUARD is used.
   MachineFrameInfo &MFI = MF.getFrameInfo();
-  int SPI = MFI.getStackProtectorIndex(); // should return -1
+  int SPI = MFI.getStackProtectorIndex();
   PPCFunctionInfo *FuncInfo = MF.getInfo();
   SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), VT);
 
-  // XOR canary word and store back
   Store = DAG.getStore(
   Op->getOperand(0), DL,
   DAG.getNode(ISD::XOR, DL, VT, Load, DAG.getConstant(XORWord, DL, 
VT)),
-  DAG.getNode( // add frame index, stack protector index, return node
-   // result
-  ISD::ADD, DL, VT, FIN, DAG.getConstant(SPI, DL, VT)),
+  DAG.getNode(ISD::ADD, DL, VT, FIN, DAG.getConstant(SPI, DL, VT)),
   MachinePointerInfo());
 
-} else if (Value *GV =
-   getSDagStackGuard(*M)) { // on aix, load from global value
+} else if (Value *GV = getSDagStackGuard(*M)) {
+  // AIX load from global value.
   VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
 GV->getType(), true);
   SDValue CanaryLoc =
   DAG.getGlobalAddress(dyn_cast(GV), DL, VT);
 
-  // Load from global value
   Load = DAG.getLoad(VT, DL, Op->getOperand(0), CanaryLoc,
  MachinePointerInfo());
 
-  // XOR canary word and store back
   Store = DAG.getStore(
   Op->getOperand(0), DL,
   DAG.getNode(ISD::XOR, DL, VT, Load, DAG.getConstant(XORWord, DL, 
VT)),


Index: llvm/lib/Target/PowerPC/PPCISelLowering.cpp
===
--- llvm/lib/Target/PowerPC/PPCISelLowering.cpp
+++ llvm/lib/Target/PowerPC/PPCISelLowering.cpp
@@ -10699,12 +10699,12 @@
 MachineFunction &MF = DAG.getMachineFunction();
 const Module *M = MF.getMMI().getModule();
 
-/* If SafeStack or !StackProtector, kill_canary not supported */
+// If SafeStack or !StackProtector, kill_canary is not supported.
 if (MF.getFunction().hasFnAttribute(Attribute::SafeStack) ||
 !MF.getFunction().hasStackProtectorFnAttr()) {
   DAG.ReplaceAllUsesOfValueWith(
   SDValue(Op.getNode(), 0),
-  Op->getOperand(0)); // prepare node for deletion
+  Op->getOperand(0));
   break;
 }
 
@@ -10713,44 +10713,39 @@
 SDValue Load;
 SDValue Store;
 
-const uint64_t XORWord =
-0x; // XORing with 0b111...111 will never
-// result in the original word
+// The new stored canary word should never be the same as the canary word
+// before corruption, so we XOR the canary word with all 1 bits.
+const uint64_t XORWord = 0x; 
 
-if (useLoadStackGuardNode()) { // linux uses LOAD_STACK_GUARD node instead
- 

[PATCH] D129048: Rewording the "static_assert" to static assertion

2022-07-19 Thread Shivam Gupta via Phabricator via cfe-commits
xgupta added a comment.

In D129048#3662634 , @Codesbyusman 
wrote:

> the libcxx updates but not tested. working on them

I just run the check-cxx on local system. It seems to pass all testcases after 
applying the current patch.

Testing Time: 2147.75s

  Unsupported  :  307
  Passed   : 7184
  Expectedly Failed:   41


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129048

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


[PATCH] D121141: [Clang] Add `-fexperimental-library` flag to enable unstable and experimental features: follow-up fixes

2022-07-19 Thread Louis Dionne via Phabricator via cfe-commits
ldionne marked 12 inline comments as done.
ldionne added a comment.

In D121141#3658946 , @phosek wrote:

> That's correct, I implemented the support for `-stdlib=libc++` on MSVC 
> targets in D101479 , but that change caused 
> a number of build failures including the compiler-rt due to 
> `_HAS_EXCEPTIONS=0` so relanding that change is blocked on D103947 
> .

Awesome, thanks both for the additional context. I'll try to take a look at 
D103947  soon. In the meantime, I'll mark the 
test as `XFAIL` on Windows just to unblock this patch, because it absolutely 
needs to land for LLVM 15.




Comment at: clang/lib/Driver/ToolChain.cpp:1016
 CmdArgs.push_back("-lc++");
+if (Args.hasArg(options::OPT_fexperimental_library))
+  CmdArgs.push_back("-lc++experimental");

MaskRay wrote:
> ldionne wrote:
> > MaskRay wrote:
> > > There may be an archive ordering problem. 
> > I'm not sure I follow -- what problem are you concerned about?
> https://lld.llvm.org/ELF/warn_backrefs.html 
> 
> When these -l options are used to link archives (.a), they should be added in 
> a dependency order.
> 
> -lc++experimental presumably uses symbols from -lc++abi and must precede 
> -lc++abi.
> -lc++abi uses symbols from -lunwind and must precede -lunwind.
> 
> For macOS and Windows, the order usually doesn't matter.
Got it, thanks. In this case, however, we're only linking against libc++, not 
libc++abi. So presumably there isn't any potential issue here? However, I agree 
that the other places where I had `-lc++experimental` after `-lc++abi` are a 
problem, and I am fixing those.



Comment at: clang/test/Driver/experimental-library-flag.cpp:6
+// -fexperimental-library must be passed to CC1
+// CHECK: -fexperimental-library
+

MaskRay wrote:
> Suggest testing `-lc++` as well
IMO this is not the right place to test this -- this should only be testing 
stuff that is specific to `-fexperimental-library`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121141

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


[PATCH] D121141: [Clang] Add `-fexperimental-library` flag to enable unstable and experimental features: follow-up fixes

2022-07-19 Thread Louis Dionne via Phabricator via cfe-commits
ldionne updated this revision to Diff 445859.
ldionne marked 2 inline comments as done.
ldionne added a comment.

Address most review feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121141

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/include/clang/Basic/Features.def
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/AIX.cpp
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/CloudABI.cpp
  clang/lib/Driver/ToolChains/CrossWindows.cpp
  clang/lib/Driver/ToolChains/Darwin.cpp
  clang/lib/Driver/ToolChains/FreeBSD.cpp
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/lib/Driver/ToolChains/Hexagon.cpp
  clang/lib/Driver/ToolChains/MipsLinux.cpp
  clang/lib/Driver/ToolChains/NaCl.cpp
  clang/lib/Driver/ToolChains/OpenBSD.cpp
  clang/lib/Driver/ToolChains/VEToolchain.cpp
  clang/lib/Driver/ToolChains/WebAssembly.cpp
  clang/test/Driver/experimental-library-flag.cpp
  clang/test/Driver/unstable-flag.cpp
  clang/test/Lexer/has_feature_cxx_unstable.cpp
  clang/test/Lexer/has_feature_experimental_library.cpp

Index: clang/test/Lexer/has_feature_experimental_library.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_experimental_library.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -E -fexperimental-library %s -o - | FileCheck --check-prefix=CHECK-EXPERIMENTAL %s
+// RUN: %clang_cc1 -E %s -o - | FileCheck --check-prefix=CHECK-NO-EXPERIMENTAL %s
+
+#if __has_feature(experimental_library)
+int has_experimental_library();
+#else
+int has_no_experimental_library();
+#endif
+// CHECK-EXPERIMENTAL: int has_experimental_library();
+// CHECK-NO-EXPERIMENTAL: int has_no_experimental_library();
Index: clang/test/Lexer/has_feature_cxx_unstable.cpp
===
--- clang/test/Lexer/has_feature_cxx_unstable.cpp
+++ /dev/null
@@ -1,10 +0,0 @@
-// RUN: %clang_cc1 -funstable -E %s -o - | FileCheck --check-prefix=CHECK-UNSTABLE %s
-// RUN: %clang_cc1 -E %s -o - | FileCheck --check-prefix=CHECK-NO-UNSTABLE %s
-
-#if __has_feature(cxx_unstable)
-int has_cxx_unstable();
-#else
-int has_no_cxx_unstable();
-#endif
-// CHECK-UNSTABLE: int has_cxx_unstable();
-// CHECK-NO-UNSTABLE: int has_no_cxx_unstable();
Index: clang/test/Driver/unstable-flag.cpp
===
--- clang/test/Driver/unstable-flag.cpp
+++ /dev/null
@@ -1,5 +0,0 @@
-// RUN: %clang -funstable -### %s 2>&1 | FileCheck %s
-
-// CHECK: -funstable
-// CHECK: -fcoroutines-ts
-// CHECK: -fmodules-ts
Index: clang/test/Driver/experimental-library-flag.cpp
===
--- /dev/null
+++ clang/test/Driver/experimental-library-flag.cpp
@@ -0,0 +1,15 @@
+// On Windows, -stdlib=libc++ is currently ignored, so -lc++experimental is not added.
+// Once -stdlib=libc++ works on Windows, this XFAIL can be removed.
+// XFAIL: windows
+
+// RUN: %clangxx -fexperimental-library -stdlib=libc++ -### %s 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-LIBCXX %s
+// RUN: %clangxx -fexperimental-library -stdlib=libstdc++ -### %s 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-LIBSTDCXX %s
+// RUN: %clangxx -fexperimental-library -stdlib=libc++ -nostdlib++ -### %s 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-NOSTDLIB %s
+
+// -fexperimental-library must be passed to CC1.
+// CHECK: -fexperimental-library
+
+// Depending on the stdlib in use, we should (or not) pass -lc++experimental.
+// CHECK-LIBCXX: -lc++experimental
+// CHECK-LIBSTDCXX-NOT: -lc++experimental
+// CHECK-NOSTDLIB-NOT: -lc++experimental
Index: clang/lib/Driver/ToolChains/WebAssembly.cpp
===
--- clang/lib/Driver/ToolChains/WebAssembly.cpp
+++ clang/lib/Driver/ToolChains/WebAssembly.cpp
@@ -444,6 +444,8 @@
   switch (GetCXXStdlibType(Args)) {
   case ToolChain::CST_Libcxx:
 CmdArgs.push_back("-lc++");
+if (Args.hasArg(options::OPT_fexperimental_library))
+  CmdArgs.push_back("-lc++experimental");
 CmdArgs.push_back("-lc++abi");
 break;
   case ToolChain::CST_Libstdcxx:
Index: clang/lib/Driver/ToolChains/VEToolchain.cpp
===
--- clang/lib/Driver/ToolChains/VEToolchain.cpp
+++ clang/lib/Driver/ToolChains/VEToolchain.cpp
@@ -141,6 +141,8 @@
   tools::addArchSpecificRPath(*this, Args, CmdArgs);
 
   CmdArgs.push_back("-lc++");
+  if (Args.hasArg(options::OPT_fexperimental_library))
+CmdArgs.push_back("-lc++experimental");
   CmdArgs.push_back("-lc++abi");
   CmdArgs.push_back("-lunwind");
   // libc++ requires -lpthread under glibc environment
Index: clang/lib/Driver/ToolChains/OpenBSD.cpp
==

[PATCH] D129048: Rewording the "static_assert" to static assertion

2022-07-19 Thread Muhammad Usman Shahid via Phabricator via cfe-commits
Codesbyusman added a comment.

In D129048#3662972 , @xgupta wrote:

> In D129048#3662634 , @Codesbyusman 
> wrote:
>
>> the libcxx updates but not tested. working on them
>
> I just run the check-cxx on local system. It seems to pass all testcases 
> after applying the current patch.
>
> Testing Time: 2147.75s
>
>   Unsupported  :  307
>   Passed   : 7184
>   Expectedly Failed:   41

Thanks @xgupta


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129048

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


[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a reviewer: b-sumner.
JonChesterfield added a comment.

Tagging Brian as the code owner of rocm device libs - emitting these in clang 
would simplify that library.

Currently clang reads these commandline flags and conditionally links in 
bitcode files to introduce these symbols. There's existing command line flags 
for controlling which files are linked. I think this patch should probably use 
the existing flags to choose which values to set and delete the existing 
handling.

As written I think this is a no op, in that the libraries will currently be 
linked anyway and override the symbols clang has injected


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

I've thought that directly emitting these constants would be better. This will 
also make it so you can't try to continue using llvm-link for these libraries, 
which is a plus since it doesn't have the same necessary attribute propagation 
clang does when linking these


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D129886: [clang] Add -fdiagnostics-format=sarif option for future SARIF output

2022-07-19 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb accepted this revision.
cjdb added a comment.
This revision is now accepted and ready to land.

Thanks for working on this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129886

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


[PATCH] D112621: [analyzer][solver] Introduce reasoning for not equal to operator

2022-07-19 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D112621#3660256 , @manas wrote:

> Considering @ASDenysPetrov 's example of `LHS = [1, 2] U [8, 9]` and `RHS = 
> [5, 6]`, I constructed a test case as following:
>
> `(((u1 >= 1 && u1 <= 2) || (u1 >= 8 && u1 <= 9)) && u2 >= 5 && u2 <= 6)`
>
> but I can see that the analyzer is bifurcating paths at the OR operator. 
> Essentially, there are two diverged paths:
>
> 1. `1 <= u1 && u1 <= 2 && 5 <= u2 && u2 <= 6`
>
> 2. `8 <= u1 && u1 <= 9 && 5 <= u2 && u2 <= 6`
>
> Separately, they hit `VisitBinaryOperator` and in both cases, we get 
> `TRUE` for `(u1 != u2)`.
>
> Is there any other way to formulate the expression so that it constructs `LHS 
> = [1, 2] U [8, 9]` and doesn't bifurcate?

@manas, constrain into `[8, 9]` first and then pop out each intermediate 
element. This should work:

  void clang_analyzer_eval(bool);
  
  template 
  void clang_analyzer_value(T x);
  
  extern void abort() __attribute__((__noreturn__));
  #define assert(expr) ((expr) ? (void)(0) : abort())
  
  void testDisequalityRules(unsigned int u1, unsigned int u2, unsigned int u3,
int s1, int s2, int s3, unsigned char uch,
signed char sch, short ssh, unsigned short ush) {
  assert(1 <= u1 && u1 <= 9);
  assert(u1 != 3);
  assert(u1 != 4);
  assert(u1 != 5);
  assert(u1 != 6);
  assert(u1 != 7);
  clang_analyzer_value(u1);  // expected-warning{{32u:{ [1, 2], [8, 9] 
}}}
  assert(5 <= u2 && u2 <= 6);
  clang_analyzer_value(u2);  // expected-warning{{32u:{ [5, 6] }}}
  
  clang_analyzer_eval(u1 != u2); // expected-warning{{TRUE}}
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112621

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


[PATCH] D129873: [clang-offload-bundler] Library-ize ClangOffloadBundler

2022-07-19 Thread Jacob Lambert via Phabricator via cfe-commits
lamb-j updated this revision to Diff 445863.
lamb-j added a comment.

Moving classes into clang namespace, more specific name for config class


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129873

Files:
  clang/include/clang/Driver/OffloadBundler.h
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/OffloadBundler.cpp
  clang/tools/clang-offload-bundler/CMakeLists.txt
  clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp

Index: clang/tools/clang-offload-bundler/CMakeLists.txt
===
--- clang/tools/clang-offload-bundler/CMakeLists.txt
+++ clang/tools/clang-offload-bundler/CMakeLists.txt
@@ -2,15 +2,16 @@
 
 add_clang_tool(clang-offload-bundler
   ClangOffloadBundler.cpp
-  
+
   DEPENDS
   intrinsics_gen
   )
 
 set(CLANG_OFFLOAD_BUNDLER_LIB_DEPS
   clangBasic
+  clangDriver
   )
-  
+
 add_dependencies(clang clang-offload-bundler)
 
 clang_target_link_libraries(clang-offload-bundler
Index: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
===
--- clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
+++ clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
@@ -7,15 +7,14 @@
 //===--===//
 ///
 /// \file
-/// This file implements a clang-offload-bundler that bundles different
-/// files that relate with the same source code but different targets into a
-/// single one. Also the implements the opposite functionality, i.e. unbundle
-/// files previous created by this tool.
+/// This file implements a stand-alone clang-offload-bundler tool using the
+/// OffloadBundler API.
 ///
 //===--===//
 
 #include "clang/Basic/Cuda.h"
 #include "clang/Basic/Version.h"
+#include "clang/Driver/OffloadBundler.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
@@ -55,38 +54,45 @@
 
 using namespace llvm;
 using namespace llvm::object;
+using namespace clang;
 
-static cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden);
+static void PrintVersion(raw_ostream &OS) {
+  OS << clang::getClangToolFullVersion("clang-offload-bundler") << '\n';
+}
+
+int main(int argc, const char **argv) {
+
+  cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden);
 
-// Mark all our options with this category, everything else (except for -version
-// and -help) will be hidden.
-static cl::OptionCategory
+  // Mark all our options with this category, everything else (except for
+  // -version and -help) will be hidden.
+  cl::OptionCategory
 ClangOffloadBundlerCategory("clang-offload-bundler options");
-static cl::list
-InputFileNames("input",
+  cl::list
+InputFileNames("input", cl::ZeroOrMore,
cl::desc("Input file."
 " Can be specified multiple times "
 "for multiple input files."),
cl::cat(ClangOffloadBundlerCategory));
-static cl::list
-InputFileNamesDeprecatedOpt("inputs", cl::CommaSeparated,
+  cl::list
+InputFileNamesDeprecatedOpt("inputs", cl::CommaSeparated, cl::ZeroOrMore,
 cl::desc("[,...] (deprecated)"),
 cl::cat(ClangOffloadBundlerCategory));
-static cl::list
-OutputFileNames("output",
+  cl::list
+OutputFileNames("output", cl::ZeroOrMore,
 cl::desc("Output file."
  " Can be specified multiple times "
  "for multiple output files."),
 cl::cat(ClangOffloadBundlerCategory));
-static cl::list
-OutputFileNamesDeprecatedOpt("outputs", cl::CommaSeparated,
+  cl::list
+OutputFileNamesDeprecatedOpt("outputs", cl::CommaSeparated, cl::ZeroOrMore,
  cl::desc("[,...] (deprecated)"),
  cl::cat(ClangOffloadBundlerCategory));
-static cl::list
+  cl::list
 TargetNames("targets", cl::CommaSeparated,
 cl::desc("[-,...]"),
 cl::cat(ClangOffloadBundlerCategory));
-static cl::opt
+  cl::opt
 FilesType("type", cl::Required,
   cl::desc("Type of the files to be bundled/unbundled.\n"
"Current supported types are:\n"
@@ -102,1265 +108,34 @@
"  gch - precompiled-header\n"
"  ast - clang AST file"),
   cl::cat(ClangOffloadBundlerCategory));
-static cl::opt
+  cl::opt
 Unbundle("unbundle",
  cl::desc("Unbundle bundled file into several output files.\n"),
  cl::init(false), cl::cat(ClangOffloadBundlerCategory));
-
-static cl::opt
+  cl::opt
 ListBundleIDs("list", cl::desc("List bundle IDs in the bundled file.\n"),
   

[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D130096#3663010 , @JonChesterfield 
wrote:

> Tagging Brian as the code owner of rocm device libs - emitting these in clang 
> would simplify that library.
>
> Currently clang reads these commandline flags and conditionally links in 
> bitcode files to introduce these symbols. There's existing command line flags 
> for controlling which files are linked. I think this patch should probably 
> use the existing flags to choose which values to set and delete the existing 
> handling.
>
> As written I think this is a no op, in that the libraries will currently be 
> linked anyway and override the symbols clang has injected

Yeah, I wasn't sure if I should do some scan to check if we actually need 
these. Basically just check if any function declarations start with `__ocml`. 
But that might untenable in the future as we try to move to a generic math 
library that doesn't eagerly emit target specific declarations in clang.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/lib/CodeGen/TargetInfo.cpp:9456
+llvm::ConstantInt::get(Type, Value), Name, nullptr,
+llvm::GlobalValue::ThreadLocalMode::NotThreadLocal, 4);
+GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Local);

Should use the address space enum



Comment at: clang/lib/CodeGen/TargetInfo.cpp:9463
+  // TODO: Add flags to toggle these as-needed.
+  bool DenormAtZero = !((Features & llvm::AMDGPU::FEATURE_FAST_FMA_F32) &&
+(Features & llvm::AMDGPU::FEATURE_FAST_DENORMAL_F32));

Typo At


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

A safer bet is to use the current control flow that links in specific bitcode 
files, but create the global directly instead of linking in the file. That'll 
give us zero semantic change and a clang that ignores those bitcode files if 
present.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D129536: [CUDA][FIX] Make shfl[_sync] for unsigned long long non-recursive

2022-07-19 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert updated this revision to Diff 445864.
jdoerfert added a comment.

Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129536

Files:
  clang/lib/Headers/__clang_cuda_intrinsics.h
  clang/test/CodeGenCUDA/shuffle_long_long.cu

Index: clang/test/CodeGenCUDA/shuffle_long_long.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDA/shuffle_long_long.cu
@@ -0,0 +1,64 @@
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang_cc1 -triple nvptx64-nvidia-cuda -fcuda-is-device -emit-llvm %s -o - | FileCheck %s --check-prefix=NO_SYNC
+// RUN: %clang_cc1 -triple nvptx64-nvidia-cuda -fcuda-is-device -emit-llvm -target-feature +ptx70 -DSYNC -DCUDA_VERSION=9000 %s -o - | FileCheck %s --check-prefix=SYNC
+
+#include "Inputs/cuda.h"
+
+#undef __CUDA_ARCH__
+#define __CUDA_ARCH__ 300
+
+__device__ void *memcpy(void *dest, const void *src, size_t n);
+
+#define warpSize 32
+#include "__clang_cuda_intrinsics.h"
+
+__device__ void use(unsigned long long, long long);
+
+// Test function, 4 shfl calls.
+// NO_SYNC: define{{.*}} @_Z14test_long_longv
+// NO_SYNC: call noundef i64 @_Z6__shflyii(
+// NO_SYNC: call noundef i64 @_Z6__shflxii(
+
+// SYNC: define{{.*}} @_Z14test_long_longv
+// SYNC:call noundef i64 @_Z11__shfl_syncjyii(
+// SYNC:call noundef i64 @_Z11__shfl_syncjxii(
+
+// unsigned long long -> long long
+// NO_SYNC: define{{.*}} @_Z6__shflyii
+// NO_SYNC: call noundef i64 @_Z6__shflxii(
+
+// long long -> int + int
+// NO_SYNC: define{{.*}} @_Z6__shflxii
+// NO_SYNC: call noundef i32 @_Z6__shfliii(
+// NO_SYNC: call noundef i32 @_Z6__shfliii(
+
+// NO_SYNC: define{{.*}} @_Z6__shfliii
+// NO_SYNC:   call i32 @llvm.nvvm.shfl.idx.i32
+
+// unsigned long long -> long long
+// SYNC: _Z11__shfl_syncjyii
+// SYNC: call noundef i64 @_Z11__shfl_syncjxii(
+
+// long long -> int + int
+// SYNC: define{{.*}} @_Z11__shfl_syncjxii
+// SYNC: call noundef i32 @_Z11__shfl_syncjiii(
+// SYNC: call noundef i32 @_Z11__shfl_syncjiii(
+
+// SYNC: define{{.*}} @_Z11__shfl_syncjiii
+// SYNC:  call i32 @llvm.nvvm.shfl.sync.idx.i32
+
+__device__ void test_long_long() {
+  unsigned long long ull = 13;
+  long long ll = 17;
+#ifndef SYNC
+  ull = __shfl(ull, 7, 32);
+  ll = __shfl(ll, 7, 32);
+  use(ull, ll);
+#else
+  ull = __shfl_sync(0x11, ull, 7, 32);
+  ll = __shfl_sync(0x11, ll, 7, 32);
+  use(ull, ll);
+#endif
+}
+
Index: clang/lib/Headers/__clang_cuda_intrinsics.h
===
--- clang/lib/Headers/__clang_cuda_intrinsics.h
+++ clang/lib/Headers/__clang_cuda_intrinsics.h
@@ -45,7 +45,7 @@
 _Static_assert(sizeof(__val) == sizeof(__Bits));   \
 _Static_assert(sizeof(__Bits) == 2 * sizeof(int)); \
 __Bits __tmp;  \
-memcpy(&__tmp, &__val, sizeof(__val));\
+memcpy(&__tmp, &__val, sizeof(__val)); \
 __tmp.__a = ::__FnName(__tmp.__a, __offset, __width);  \
 __tmp.__b = ::__FnName(__tmp.__b, __offset, __width);  \
 long long __ret;   \
@@ -71,8 +71,8 @@
   }\
   inline __device__ unsigned long long __FnName(   \
   unsigned long long __val, __Type __offset, int __width = warpSize) { \
-return static_cast(::__FnName( \
-static_cast(__val), __offset, __width));   \
+return static_cast(\
+::__FnName(static_cast(__val), __offset, __width)); \
   }\
   inline __device__ double __FnName(double __val, __Type __offset, \
 int __width = warpSize) {  \
@@ -139,8 +139,8 @@
   inline __device__ unsigned long long __FnName(   \
   unsigned int __mask, unsigned long long __val, __Type __offset,  \
   int __width = warpSize) {\
-return static_cast(::__FnName( \
-__mask, static_cast(__val), __offset, __width));   \
+return static_cast(\
+::__FnName(__mask, static_cast(__val), __offset, __width)); \
   }\
   inline __device__ long __FnName(unsigned int __mask, long __val, \
   __Type __offset, int __width = warpSize) {   \
@@ -234,8 +234,8 @@
   return __nvvm_m

[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D130096#3663062 , @JonChesterfield 
wrote:

> A safer bet is to use the current control flow that links in specific bitcode 
> files, but create the global directly instead of linking in the file. That'll 
> give us zero semantic change and a clang that ignores those bitcode files if 
> present.

Do we expect those libraries to be linked per-TU via `-mlink-builtin-bitcode`? 
The usage I see passes them to `lld` directly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D129873: [clang-offload-bundler] Library-ize ClangOffloadBundler

2022-07-19 Thread Jacob Lambert via Phabricator via cfe-commits
lamb-j updated this revision to Diff 445865.
lamb-j added a comment.

Bug fix


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129873

Files:
  clang/include/clang/Driver/OffloadBundler.h
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/OffloadBundler.cpp
  clang/tools/clang-offload-bundler/CMakeLists.txt
  clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp

Index: clang/tools/clang-offload-bundler/CMakeLists.txt
===
--- clang/tools/clang-offload-bundler/CMakeLists.txt
+++ clang/tools/clang-offload-bundler/CMakeLists.txt
@@ -2,15 +2,16 @@
 
 add_clang_tool(clang-offload-bundler
   ClangOffloadBundler.cpp
-  
+
   DEPENDS
   intrinsics_gen
   )
 
 set(CLANG_OFFLOAD_BUNDLER_LIB_DEPS
   clangBasic
+  clangDriver
   )
-  
+
 add_dependencies(clang clang-offload-bundler)
 
 clang_target_link_libraries(clang-offload-bundler
Index: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
===
--- clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
+++ clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
@@ -7,15 +7,14 @@
 //===--===//
 ///
 /// \file
-/// This file implements a clang-offload-bundler that bundles different
-/// files that relate with the same source code but different targets into a
-/// single one. Also the implements the opposite functionality, i.e. unbundle
-/// files previous created by this tool.
+/// This file implements a stand-alone clang-offload-bundler tool using the
+/// OffloadBundler API.
 ///
 //===--===//
 
 #include "clang/Basic/Cuda.h"
 #include "clang/Basic/Version.h"
+#include "clang/Driver/OffloadBundler.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
@@ -55,38 +54,45 @@
 
 using namespace llvm;
 using namespace llvm::object;
+using namespace clang;
 
-static cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden);
+static void PrintVersion(raw_ostream &OS) {
+  OS << clang::getClangToolFullVersion("clang-offload-bundler") << '\n';
+}
+
+int main(int argc, const char **argv) {
+
+  cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden);
 
-// Mark all our options with this category, everything else (except for -version
-// and -help) will be hidden.
-static cl::OptionCategory
+  // Mark all our options with this category, everything else (except for
+  // -version and -help) will be hidden.
+  cl::OptionCategory
 ClangOffloadBundlerCategory("clang-offload-bundler options");
-static cl::list
-InputFileNames("input",
+  cl::list
+InputFileNames("input", cl::ZeroOrMore,
cl::desc("Input file."
 " Can be specified multiple times "
 "for multiple input files."),
cl::cat(ClangOffloadBundlerCategory));
-static cl::list
-InputFileNamesDeprecatedOpt("inputs", cl::CommaSeparated,
+  cl::list
+InputFileNamesDeprecatedOpt("inputs", cl::CommaSeparated, cl::ZeroOrMore,
 cl::desc("[,...] (deprecated)"),
 cl::cat(ClangOffloadBundlerCategory));
-static cl::list
-OutputFileNames("output",
+  cl::list
+OutputFileNames("output", cl::ZeroOrMore,
 cl::desc("Output file."
  " Can be specified multiple times "
  "for multiple output files."),
 cl::cat(ClangOffloadBundlerCategory));
-static cl::list
-OutputFileNamesDeprecatedOpt("outputs", cl::CommaSeparated,
+  cl::list
+OutputFileNamesDeprecatedOpt("outputs", cl::CommaSeparated, cl::ZeroOrMore,
  cl::desc("[,...] (deprecated)"),
  cl::cat(ClangOffloadBundlerCategory));
-static cl::list
+  cl::list
 TargetNames("targets", cl::CommaSeparated,
 cl::desc("[-,...]"),
 cl::cat(ClangOffloadBundlerCategory));
-static cl::opt
+  cl::opt
 FilesType("type", cl::Required,
   cl::desc("Type of the files to be bundled/unbundled.\n"
"Current supported types are:\n"
@@ -102,1265 +108,34 @@
"  gch - precompiled-header\n"
"  ast - clang AST file"),
   cl::cat(ClangOffloadBundlerCategory));
-static cl::opt
+  cl::opt
 Unbundle("unbundle",
  cl::desc("Unbundle bundled file into several output files.\n"),
  cl::init(false), cl::cat(ClangOffloadBundlerCategory));
-
-static cl::opt
+  cl::opt
 ListBundleIDs("list", cl::desc("List bundle IDs in the bundled file.\n"),
   cl::init(false), cl::cat(ClangOffloadBundlerCateg

[PATCH] D129864: [Flang] Generate documentation for compiler flags

2022-07-19 Thread Dylan Fleming via Phabricator via cfe-commits
DylanFleming-arm updated this revision to Diff 445872.
DylanFleming-arm added a comment.

Edited summary to be more clear.

I've also changed the format of the if(!included) as you suggested (and did the 
same for the call to isGroupIncluded)

I also added the assert you asked for, and then since there's an if statement 
checking for the opposite condition, I removed that as it's now unreachable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129864

Files:
  clang/utils/TableGen/ClangOptionDocEmitter.cpp
  flang/docs/CMakeLists.txt
  flang/docs/index.md
  flang/include/flang/FlangOptionsDocs.td

Index: flang/include/flang/FlangOptionsDocs.td
===
--- /dev/null
+++ flang/include/flang/FlangOptionsDocs.td
@@ -0,0 +1,35 @@
+//==--- FlangOptionDocs.td - Option documentation -===//
+//
+// 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
+//
+//===--===//
+
+def GlobalDocumentation {
+  code Intro =[{..
+  ---
+  NOTE: This file is automatically generated by running clang-tblgen
+  -gen-opt-docs. Do not edit this file by hand!!
+  ---
+
+=
+Flang command line argument reference
+=
+.. contents::
+   :local:
+
+Introduction
+
+
+}];
+
+  string Program = "flang";
+
+  list ExcludedFlags = [];
+  list IncludedFlags = ["FlangOption"];
+
+}
+
+
+include "../../../clang/include/clang/Driver/Options.td"
Index: flang/docs/index.md
===
--- flang/docs/index.md
+++ flang/docs/index.md
@@ -45,6 +45,7 @@
DoConcurrent
Extensions
FIRLangRef
+   FlangCommandLineReference
FlangDriver
FortranIR
FortranLLVMTestSuite
Index: flang/docs/CMakeLists.txt
===
--- flang/docs/CMakeLists.txt
+++ flang/docs/CMakeLists.txt
@@ -91,6 +91,16 @@
 endif()
 endif()
 
+function (gen_rst_file_from_td output_file td_option source docs_target)
+  if (NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${source}")
+message(FATAL_ERROR "Cannot find source file: ${source} in ${CMAKE_CURRENT_SOURCE_DIR}")
+  endif()
+  get_filename_component(TABLEGEN_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/${source}" DIRECTORY)
+  list(APPEND LLVM_TABLEGEN_FLAGS "-I${TABLEGEN_INCLUDE_DIR}")
+  clang_tablegen(Source/${output_file} ${td_option} SOURCE ${source} TARGET "gen-${output_file}")
+  add_dependencies(${docs_target} "gen-${output_file}")
+endfunction()
+
 if (LLVM_ENABLE_SPHINX)
   include(AddSphinxTarget)
   if (SPHINX_FOUND)
@@ -114,6 +124,7 @@
   COMMAND "${Python3_EXECUTABLE}"
   ARGS ${CMAKE_CURRENT_BINARY_DIR}/Source/FIR/CreateFIRLangRef.py)
 
+  gen_rst_file_from_td(FlangCommandLineReference.rst -gen-opt-docs ../include/flang/FlangOptionsDocs.td docs-flang-html)
 endif()
 if (${SPHINX_OUTPUT_MAN})
   add_sphinx_target(man flang)
Index: clang/utils/TableGen/ClangOptionDocEmitter.cpp
===
--- clang/utils/TableGen/ClangOptionDocEmitter.cpp
+++ clang/utils/TableGen/ClangOptionDocEmitter.cpp
@@ -168,6 +168,29 @@
   return false;
 }
 
+bool isIncluded(const Record *OptionOrGroup, const Record *DocInfo) {
+  assert(DocInfo->getValue("IncludedFlags") && "Missing includeFlags");
+  for (StringRef Inclusion : DocInfo->getValueAsListOfStrings("IncludedFlags"))
+if (hasFlag(OptionOrGroup, Inclusion))
+  return true;
+  return false;
+}
+
+bool isGroupIncluded(const DocumentedGroup &Group, const Record *DocInfo) {
+  if (isIncluded(Group.Group, DocInfo))
+return true;
+  for (auto &O : Group.Options)
+if (isIncluded(O.Option, DocInfo))
+  return true;
+  for (auto &G : Group.Groups) {
+if (isIncluded(G.Group, DocInfo))
+  return true;
+if (isGroupIncluded(G, DocInfo))
+  return true;
+  }
+  return false;
+}
+
 bool isExcluded(const Record *OptionOrGroup, const Record *DocInfo) {
   // FIXME: Provide a flag to specify the set of exclusions.
   for (StringRef Exclusion : DocInfo->getValueAsListOfStrings("ExcludedFlags"))
@@ -304,6 +327,8 @@
 raw_ostream &OS) {
   if (isExcluded(Option.Option, DocInfo))
 return;
+  if (DocInfo->getValue("IncludedFlags") && !isIncluded(Option.Option, DocInfo))
+return;
   if (Option.Option->getValueAsDef("Kind")->getName() == "KIND_UNKNOWN" ||
   Option.Option->getValueAsDef("Kind")->getName() == "KIND_INPUT")
 return;
@@ -379,6 +404,9 @@
   if

[PATCH] D125418: [Arm64EC 6/?] Implement C/C++ mangling for Arm64EC function definitions.

2022-07-19 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:5128
+// to the function itself; it points to a stub for the compiler.
+// FIXME: We also need to emit an entry thunk.
+SmallString<256> MangledName;

bcl5980 wrote:
> A headache thing here.
> We need to get the function definition with triple x64 to define entry thunk. 
> For now the function definition here is aarch64 version.
> For example the case in Microsoft doc "Understanding Arm64EC ABI and assembly 
> code":
> 
> ```
> struct SC {
> char a;
> char b;
> char c;
> };
> int fB(int a, double b, int i1, int i2, int i3);
> int fC(int a, struct SC c, int i1, int i2, int i3);
> int fA(int a, double b, struct SC c, int i1, int i2, int i3) {
> return fB(a, b, i1, i2, i3) + fC(a, c, i1, i2, i3);
> }
> ```
> 
> x64 version IR for fA is:
> ```
> define dso_local i32 @fA(i32 noundef %a, double noundef %b, ptr nocapture 
> noundef readonly %c, i32 noundef %i1, i32 noundef %i2, i32 noundef %i3) 
> local_unnamed_addr #0 { ... }
> ```
> aarch64 version IR for fA is:
> 
> ```
> define dso_local i32 @"#fA"(i32 noundef %a, double noundef %b, i64 %c.coerce, 
> i32 noundef %i1, i32 noundef %i2, i32 noundef %i3) #0 {...}
> ```
> Arm64 will allow any size structure to be assigned to a register directly. 
> x64 only allows sizes 1, 2, 4 and 8. 
> Entry thunk follow x64 version function type. But we only have aarch64 
> version function type.
> 
> I think the best way to do is create a x64 version codeGenModule and use the 
> x64 CGM to generate the function type for entry thunk. But it is hard for me 
> to do here. I tried a little but a lot of issues happen.
> 
> One other way is only modify `AArch64ABIInfo::classifyArgumentType`, copy the 
> x64 code into the function and add a flag to determine which version will the 
> function use. It is easier but I'm not sure it is the only difference between 
> x64 and aarch64. Maybe the classify return also need to do this. And it is 
> not a clean way I think.
Oh, that's annoying... I hadn't considered the case of a struct of size 3/5/6/7.

Like I noted on D126811, attaching thunks to calls is tricky if we try to do it 
from clang.

Computing the right IR type shouldn't be that hard by itself; we can call into 
call lowering code in TargetInfo without modifying much else.  (We just need a 
bit to tell the TargetInfo to redirect the call, like D125419.  Use an entry 
point like CodeGenTypes::arrangeCall.)  You don't need to mess with the type 
system or anything like that.

The problem is correctly representing the lowered call in IR; we really don't 
want to do lowering early because it will block optimizations.  I considered 
using an operand bundle; we can probably make that work, but it's complicated, 
and probably disables some optimizations.

I think the best thing we can do here is add an IR attribute to mark arguments 
which are passed directly on AArch64, but need to be passed indirectly for the 
x64 ABI.  Then AArch64Arm64ECCallLowering can check for the attribute and 
modify its behavior.  This isn't really clean in the sense that it's specific 
to the x64/aarch64 pair of calling conventions, but I think the alternative is 
worse.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125418

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


[PATCH] D130095: [clangd] Improve XRefs support for ObjCMethodDecl

2022-07-19 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 445873.
dgoldman added a comment.

Run clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130095

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/AST.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -957,6 +957,46 @@
 Fo^o * getFoo() {
   return 0;
 }
+  )objc",
+
+  R"objc(// Method decl and definition for ObjC class.
+@interface Cat
+- (void)$decl[[meow]];
+@end
+@implementation Cat
+- (void)$def[[meow]] {}
+@end
+void makeNoise(Cat *kitty) {
+  [kitty me^ow];
+}
+  )objc",
+
+  R"objc(// Method decl and definition for ObjC category.
+@interface Dog
+@end
+@interface Dog (Play)
+- (void)$decl[[runAround]];
+@end
+@implementation Dog (Play)
+- (void)$def[[runAround]] {}
+@end
+void play(Dog *dog) {
+  [dog run^Around];
+}
+  )objc",
+
+  R"objc(// Method decl and definition for ObjC class extension.
+@interface Dog
+@end
+@interface Dog ()
+- (void)$decl[[howl]];
+@end
+@implementation Dog
+- (void)$def[[howl]] {}
+@end
+void play(Dog *dog) {
+  [dog ho^wl];
+}
   )objc"};
   for (const char *Test : Tests) {
 Annotations T(Test);
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -83,32 +83,19 @@
   if (const auto *CTD = dyn_cast(D))
 if (const auto *RD = CTD->getTemplatedDecl())
   return RD->getDefinition();
-  // Objective-C classes can have three types of declarations:
-  //
-  // - forward declaration: @class MyClass;
-  // - true declaration (interface definition): @interface MyClass ... @end
-  // - true definition (implementation): @implementation MyClass ... @end
-  //
-  // Objective-C categories are extensions are on classes:
-  //
-  // - declaration: @interface MyClass (Ext) ... @end
-  // - definition: @implementation MyClass (Ext) ... @end
-  //
-  // With one special case, a class extension, which is normally used to keep
-  // some declarations internal to a file without exposing them in a header.
-  //
-  // - class extension declaration: @interface MyClass () ... @end
-  // - which really links to class definition: @implementation MyClass ... @end
-  if (const auto *ID = dyn_cast(D))
-return ID->getImplementation();
-  if (const auto *CD = dyn_cast(D)) {
-if (CD->IsClassExtension()) {
-  if (const auto *ID = CD->getClassInterface())
-return ID->getImplementation();
+  if (const auto *MD = dyn_cast(D)) {
+if (MD->isThisDeclarationADefinition())
+  return MD;
+auto *DeclCtx = cast(MD->getDeclContext());
+if (DeclCtx->isInvalidDecl())
   return nullptr;
-}
-return CD->getImplementation();
+
+if (const auto *CD = dyn_cast(DeclCtx))
+  if (const auto *Impl = getCorrespondingObjCImpl(CD))
+return Impl->getMethod(MD->getSelector(), MD->isInstanceMethod());
   }
+  if (const auto *CD = dyn_cast(D))
+return getCorrespondingObjCImpl(CD);
   // Only a single declaration is allowed.
   if (isa(D) || isa(D) ||
   isa(D)) // except cases above
Index: clang-tools-extra/clangd/AST.h
===
--- clang-tools-extra/clangd/AST.h
+++ clang-tools-extra/clangd/AST.h
@@ -93,6 +93,30 @@
 SymbolID getSymbolID(const llvm::StringRef MacroName, const MacroInfo *MI,
  const SourceManager &SM);
 
+/// Return the corresponding implementation/definition for the given ObjC
+/// container if it has one, otherwise, return nullptr.
+///
+/// Objective-C classes can have three types of declarations:
+///
+/// - forward declaration: @class MyClass;
+/// - true declaration (interface definition): @interface MyClass ... @end
+/// - true definition (implementation): @implementation MyClass ... @end
+///
+/// Objective-C categories are extensions are on classes:
+///
+/// - declaration: @interface MyClass (Ext) ... @end
+/// - definition: @implementation MyClass (Ext) ... @end
+///
+/// With one special case, a class extension, which is normally used to keep
+/// some declarations internal to a file without exposing them in a header.
+///
+/// - class extension declaration: @interface MyClass () ... @end
+/// - which really links to class definition: @implementation MyClass ... @end
+///
+/// For Objective-C p

[PATCH] D128750: [c++20] Implement P2113R0: Changes to the Partial Ordering of Constrained Functions

2022-07-19 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added a comment.

In D128750#3662898 , @royjacobson 
wrote:

> but in your example with T/U/V we have 3 template parameters that we could 
> reorder in 6 different ways.

But, any reordering of the 6 that does not have consecutive U and V  is not 
valid. Because in the other template, T/U is consecutive and used by X in 
that order. I don't think it is allowed to change the template parameter 
references in the function parameters.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128750

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


[PATCH] D130055: Clang extensions yolo, woot & kaboom

2022-07-19 Thread Jan Korous via Phabricator via cfe-commits
jkorous added a comment.

Hi Chris! This is a very interesting idea!

I do have couple thoughts - mostly that this could lead to something great and 
I would love it to apply to as many relevant cases as possible.

It looks like there is a possibility that a free function, static method or a 
method of another class (a `friend`?) should be `woot` for a specific 
pointer/reference parameter.

  struct Foo {int a};
  void init_Foo(Foo& f) { f.a = 42; }

In the same spirit as the above I think that `kaboom` should be applicable to 
functions in general.

BTW - if we generalize `woot` and `kaboom` - won't we get support for built-in 
types as a side-effect and won't that give us C support as a side-effect?

Last but not least - it would be really interesting to have the ability to 
check and diagnose improper use of these attributes.
One specific scenario that seems interesting to me is the ability to verify 
also absence of an attribute. (That could in-turn potentially unlock more 
aggressive analysis at call-sites.)
Example:

  struct Bar {
int a, b;
Bar() : a(0) { } // <--- warning: constructor should be [[yolo]]
  };

...and if we had that - would might potentially even collapse `woot` and 
!`yolo` together?
I can imagine that some parts of C++ would be tricky - e. g. templates so not 
sure how far could this idea be stretched.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130055

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


[PATCH] D130055: Clang extensions yolo, woot & kaboom

2022-07-19 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added a comment.

In D130055#3663164 , @jkorous wrote:

> It looks like there is a possibility that a free function, static method or a 
> method of another class (a `friend`?) should be `woot` for a specific 
> pointer/reference parameter.

Oh! That's a fascinating idea I hadn't considered. As implemented I only 
applied the `woot`-iness of a function to it's `this` parameter.

> In the same spirit as the above I think that `kaboom` should be applicable to 
> functions in general.

I'd have to double check, but I'm pretty sure non-member functions get treated 
as `Use` in the analysis today, so they _should_ implicitly be `kaboom`.

> BTW - if we generalize `woot` and `kaboom` - won't we get support for 
> built-in types as a side-effect and won't that give us C support as a 
> side-effect?

I think generally we have support for built-in types through this analysis 
already. This just piggybacks off the existing support.

> Last but not least - it would be really interesting to have the ability to 
> check and diagnose improper use of these attributes.

This would be super cool!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130055

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


[PATCH] D128465: [llvm] add zstd to `llvm::compression` namespace

2022-07-19 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan accepted this revision.
leonardchan added a comment.

LGTM tested on mac on my end


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128465

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


[PATCH] D128465: [llvm] add zstd to `llvm::compression` namespace

2022-07-19 Thread Cole Kissane 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 rGe939bf67e340: [llvm] add zstd to `llvm::compression` 
namespace (authored by ckissane).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128465

Files:
  llvm/CMakeLists.txt
  llvm/cmake/config-ix.cmake
  llvm/cmake/modules/LLVMConfig.cmake.in
  llvm/include/llvm/Config/llvm-config.h.cmake
  llvm/include/llvm/Support/Compression.h
  llvm/lib/Support/CMakeLists.txt
  llvm/lib/Support/Compression.cpp
  llvm/test/lit.site.cfg.py.in
  llvm/unittests/Support/CompressionTest.cpp
  utils/bazel/llvm_configs/llvm-config.h.cmake

Index: utils/bazel/llvm_configs/llvm-config.h.cmake
===
--- utils/bazel/llvm_configs/llvm-config.h.cmake
+++ utils/bazel/llvm_configs/llvm-config.h.cmake
@@ -95,6 +95,9 @@
 /* Define if zlib compression is available */
 #cmakedefine01 LLVM_ENABLE_ZLIB
 
+/* Define if zstd compression is available */
+#cmakedefine01 LLVM_ENABLE_ZSTD
+
 /* Define if LLVM was built with a dependency to the libtensorflow dynamic library */
 #cmakedefine LLVM_HAVE_TF_API
 
Index: llvm/unittests/Support/CompressionTest.cpp
===
--- llvm/unittests/Support/CompressionTest.cpp
+++ llvm/unittests/Support/CompressionTest.cpp
@@ -61,4 +61,42 @@
 }
 #endif
 
+#if LLVM_ENABLE_ZSTD
+static void testZstdCompression(StringRef Input, int Level) {
+  SmallVector Compressed;
+  SmallVector Uncompressed;
+  zstd::compress(arrayRefFromStringRef(Input), Compressed, Level);
+
+  // Check that uncompressed buffer is the same as original.
+  Error E = zstd::uncompress(Compressed, Uncompressed, Input.size());
+  consumeError(std::move(E));
+
+  EXPECT_EQ(Input, toStringRef(Uncompressed));
+  if (Input.size() > 0) {
+// Uncompression fails if expected length is too short.
+E = zstd::uncompress(Compressed, Uncompressed, Input.size() - 1);
+EXPECT_EQ("Destination buffer is too small", llvm::toString(std::move(E)));
+  }
+}
+
+TEST(CompressionTest, Zstd) {
+  testZstdCompression("", zstd::DefaultCompression);
+
+  testZstdCompression("hello, world!", zstd::NoCompression);
+  testZstdCompression("hello, world!", zstd::BestSizeCompression);
+  testZstdCompression("hello, world!", zstd::BestSpeedCompression);
+  testZstdCompression("hello, world!", zstd::DefaultCompression);
+
+  const size_t kSize = 1024;
+  char BinaryData[kSize];
+  for (size_t i = 0; i < kSize; ++i)
+BinaryData[i] = i & 255;
+  StringRef BinaryDataStr(BinaryData, kSize);
+
+  testZstdCompression(BinaryDataStr, zstd::NoCompression);
+  testZstdCompression(BinaryDataStr, zstd::BestSizeCompression);
+  testZstdCompression(BinaryDataStr, zstd::BestSpeedCompression);
+  testZstdCompression(BinaryDataStr, zstd::DefaultCompression);
+}
+#endif
 }
Index: llvm/test/lit.site.cfg.py.in
===
--- llvm/test/lit.site.cfg.py.in
+++ llvm/test/lit.site.cfg.py.in
@@ -37,6 +37,7 @@
 config.llvm_use_intel_jitevents = @LLVM_USE_INTEL_JITEVENTS@
 config.llvm_use_sanitizer = "@LLVM_USE_SANITIZER@"
 config.have_zlib = @LLVM_ENABLE_ZLIB@
+config.have_zstd = @LLVM_ENABLE_ZSTD@
 config.have_libxar = @LLVM_HAVE_LIBXAR@
 config.have_libxml2 = @LLVM_ENABLE_LIBXML2@
 config.have_curl = @LLVM_ENABLE_CURL@
Index: llvm/lib/Support/Compression.cpp
===
--- llvm/lib/Support/Compression.cpp
+++ llvm/lib/Support/Compression.cpp
@@ -20,6 +20,9 @@
 #if LLVM_ENABLE_ZLIB
 #include 
 #endif
+#if LLVM_ENABLE_ZSTD
+#include 
+#endif
 
 using namespace llvm;
 using namespace llvm::compression;
@@ -100,3 +103,65 @@
   llvm_unreachable("zlib::uncompress is unavailable");
 }
 #endif
+
+#if LLVM_ENABLE_ZSTD
+
+bool zstd::isAvailable() { return true; }
+
+void zstd::compress(ArrayRef Input,
+SmallVectorImpl &CompressedBuffer, int Level) {
+  unsigned long CompressedBufferSize = ::ZSTD_compressBound(Input.size());
+  CompressedBuffer.resize_for_overwrite(CompressedBufferSize);
+  unsigned long CompressedSize =
+  ::ZSTD_compress((char *)CompressedBuffer.data(), CompressedBufferSize,
+  (const char *)Input.data(), Input.size(), Level);
+  if (ZSTD_isError(CompressedSize))
+report_bad_alloc_error("Allocation failed");
+  // Tell MemorySanitizer that zstd output buffer is fully initialized.
+  // This avoids a false report when running LLVM with uninstrumented ZLib.
+  __msan_unpoison(CompressedBuffer.data(), CompressedSize);
+  if (CompressedSize < CompressedBuffer.size())
+CompressedBuffer.truncate(CompressedSize);
+}
+
+Error zstd::uncompress(ArrayRef Input, uint8_t *UncompressedBuffer,
+   size_t &UncompressedSize) {
+  const size_t Res =
+  ::ZSTD_decom

[PATCH] D130004: [pseudo] Add `clang-pseudo -html-forest=`, an HTML forest browser

2022-07-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 7 inline comments as done.
sammccall added a comment.

Thanks for the review!




Comment at: clang-tools-extra/pseudo/tool/CMakeLists.txt:29
+add_custom_target(clang-pseudo-resources DEPENDS HTMLForestResources.inc)
+add_dependencies(clang-pseudo clang-pseudo-resources)

hokein wrote:
> This likely introduces some pain. (An alternative is to inline the content of 
> `.js`, `.css`, `html` in the cpp directly, but it is awkward).
> 
> Would be nice to prepare an internal BUILD file change when landing (if you 
> don't have time, I'm happy to help with it).
> This likely introduces some pain. (An alternative is to inline the content of 
> `.js`, `.css`, `html` in the cpp directly, but it is awkward).
Yeah, I think this is unreasonably difficult to edit, unfortunately - no editor 
understands JS/CSS/html inside string literals. (We can probably get away with 
the HTML, but the JS is a significant amount of code)

(In fact had a second mode where the resources were read from disk without a 
recompile, which was faster while working on it, but I don't think it's 
necessary - inotifywait loop is enough)
 
> Would be nice to prepare an internal BUILD file change when landing (if you 
> don't have time, I'm happy to help with it).
Good point, I'll prepare that.



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.cpp:64
+  void write() {
+Out << "\n\n\nHTMLForest\n";
+Out << "" << HTMLForest_js << "\n";

hokein wrote:
> nit: it is clearer to use use `llvm::formatv`
> 
> ```
> llvm::formatv(R"html(
> ...
> )html", js, css, forest_json, code, html);.
> ```
I guess, but:
 - a long formatv string means it's hard to spot which {n} corresponds to which 
arg
 - we still have to break up the formatv for writeForestJSON() etc, which 
doesn't seem like a natural place to break.

Added a small tag(name, block) function instead which I think makes the 
structure easier to follow (basically the clang-formatted code shows the HTML 
structure)



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.cpp:115
+  llvm::DenseMap Index;
+  std::vector> Queue;
+  auto AssignID = [&](const ForestNode* N, Token::Index End) -> unsigned {

hokein wrote:
> I'd suggest renaming to `Array` and adding comment for the `Index` (it is the 
> index in the `Queue`), `Queue` leaves an impression to me that we will do 
> some pop_back.
I agree about Queue.
`Array` is confusing as this isn't actually either a C++ array or a 
`json::Array`.
Chose `Sequence` to emphasize that it's the order we're establishing.



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.cpp:170
+
+// We only accept the derived stream here. Would it be useful or confusing
+// to allow the original stream instead?

hokein wrote:
> Having derived stream is fine to me at the moment, particularly useful for 
> debugging.
> 
> But as a regular user, I would prefer to see the original token stream (the 
> derived stream is confusing, as a regular user doesn't know how pseudoparser 
> work inside).
Yeah, I think we'll want this later changed to FIXME.
We will have to assume some invariants to get it (i.e. that the derived tokens 
are basically a same-order subset of the original ones).
Not sure if "regular users" will ever see this tool :-) I'm not sure it extends 
well to forests, we may want something else.



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.css:50
+}
+#i_kind {
+  float: right;

hokein wrote:
> nit: just an idea we could use different background color for different 
> forest node kind.
Done, and made the colors of the nodes in the tree match.
I like it, hope it's not too rainbow-y



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.css:63
+
+#tree {
+  flex-grow: 0;

hokein wrote:
> nit: can we make the tree and code view resizable?  so that I can adjust the 
> width of tree/code view.
`resize: horizontal` seems to do the trick



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.html:1
+
+

hokein wrote:
> I think it might be better to move these `.html, .css, .js` files to a 
> separate directory  `tool/resources` rather than `tool`.
the tool/ directory is ~empty or I would... happy to add some more structure if 
it gets at all crowded



Comment at: clang-tools-extra/pseudo/tool/HTMLForest.html:13
+  
+
+  

hokein wrote:
> nit: maybe name it `i_context_stack`, I had no idea what does the `context` 
> mean until I read the actual implementation. 
Renamed to `i_ancestors` which seems explicit without being long


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130004

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.

[PATCH] D130004: [pseudo] Add `clang-pseudo -html-forest=`, an HTML forest browser

2022-07-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 445884.
sammccall marked 6 inline comments as done.
sammccall added a comment.

review changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130004

Files:
  clang-tools-extra/pseudo/test/html-forest.c
  clang-tools-extra/pseudo/tool/CMakeLists.txt
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp
  clang-tools-extra/pseudo/tool/HTMLForest.cpp
  clang-tools-extra/pseudo/tool/HTMLForest.css
  clang-tools-extra/pseudo/tool/HTMLForest.html
  clang-tools-extra/pseudo/tool/HTMLForest.js
  clang-tools-extra/pseudo/tool/bundle_resources.py

Index: clang-tools-extra/pseudo/tool/bundle_resources.py
===
--- /dev/null
+++ clang-tools-extra/pseudo/tool/bundle_resources.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python3
+# Simple bundler of files into string constants.
+#
+# Usage: bundle_resources.py foo.inc a.js b.css ...
+# Produces foo.inc containing:
+#   const char a_js[] = "...";
+#   const char b_css[] = "...";
+import sys
+
+outfile = sys.argv[1]
+infiles = sys.argv[2:]
+
+with open(outfile, 'w') as out:
+  for filename in infiles:
+varname = filename.replace('.', '_')
+out.write("const char " + varname + "[] = \n");
+# MSVC limits each chunk of string to 2k.
+# Not quite enough for the JS file, so split by lines.
+# The overall limit is 64k, which ought to be enough for anyone.
+for line in open(filename).read().split('\n'):
+  out.write('  R"x(' + line + ')x" "\\n"\n' )
+out.write('  ;\n');
Index: clang-tools-extra/pseudo/tool/HTMLForest.js
===
--- /dev/null
+++ clang-tools-extra/pseudo/tool/HTMLForest.js
@@ -0,0 +1,285 @@
+// The global map of forest node index => NodeView.
+views = [];
+// NodeView is a visible forest node.
+// It has an entry in the navigation tree, and a span in the code itself.
+// Each NodeView is associated with a forest node, but not all nodes have views:
+// - nodes not reachable though current ambiguity selection
+// - trivial "wrapping" sequence nodes are abbreviated away
+class NodeView {
+  // Builds a node representing forest[index], or its target if it is a wrapper.
+  // Registers the node in the global map.
+  static make(index, parent, abbrev) {
+var node = forest[index];
+if (node.kind == 'sequence' && node.children.length == 1 && forest[node.children[0]].kind != 'ambiguous') {
+  abbrev ||= [];
+  abbrev.push(index);
+  return NodeView.make(node.children[0], parent, abbrev);
+}
+return views[index] = new NodeView(index, parent, node, abbrev);
+  }
+
+  constructor(index, parent, node, abbrev) {
+this.abbrev = abbrev || [];
+this.parent = parent;
+this.children = (node.kind == 'ambiguous' ? [node.selected] : node.children || []).map((c) => NodeView.make(c, this));
+this.index = index;
+this.node = node;
+views[index] = this;
+
+this.span = this.buildSpan();
+this.tree = this.buildTree();
+  }
+
+  // Replaces the token sequence in #code with a .
+  buildSpan() {
+var elt = document.createElement('span');
+elt.dataset['index'] = this.index;
+elt.classList.add("node");
+elt.classList.add("selectable-node");
+elt.classList.add(this.node.kind);
+
+var begin = null, end = null;
+if (this.children.length != 0) {
+  begin = this.children[0].span;
+  end = this.children[this.children.length-1].span.nextSibling;
+} else if (this.node.kind == 'terminal') {
+  begin = document.getElementById(this.node.token);
+  end = begin.nextSibling;
+} else if (this.node.kind == 'opaque') {
+  begin = document.getElementById(this.node.firstToken);
+  end = (this.node.lastToken == null) ? begin :
+  document.getElementById(this.node.lastToken).nextSibling;
+}
+var parent = begin.parentNode;
+splice(begin, end, elt);
+parent.insertBefore(elt, end);
+return elt;
+  }
+
+  // Returns a (detached)  suitable for use in #tree.
+  buildTree() {
+var elt = document.createElement('li');
+elt.dataset['index'] = this.index;
+elt.classList.add('tree-node');
+elt.classList.add('selectable-node');
+elt.classList.add(this.node.kind);
+var header = document.createElement('header');
+elt.appendChild(header);
+
+if (this.abbrev.length > 0) {
+  var abbrev = document.createElement('span');
+  abbrev.classList.add('abbrev');
+  abbrev.innerText = forest[this.abbrev[0]].symbol;
+  header.appendChild(abbrev);
+}
+var name = document.createElement('span');
+name.classList.add('name');
+name.innerText = this.node.symbol;
+header.appendChild(name);
+
+if (this.children.length != 0) {
+  var sublist = document.createElement('ul');
+  this.children.forEach((c) => sublist.appendChild(c.tree));
+  elt.appendChild(sublist);
+

[PATCH] D112621: [analyzer][solver] Introduce reasoning for not equal to operator

2022-07-19 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

In D112621#3660256 , @manas wrote:

> Is there any other way to formulate the expression so that it constructs `LHS 
> = [1, 2] U [8, 9]` and doesn't bifurcate?

Try this `u1 > 0 && u1 < 10 && u1 != 3 && u1 != 4 && u1 != 5 && u1 != 6 && u1 
!= 7 && u2 > 4 && u2 < 7`. This is a bit verbose but it will avoid bifurcating.




Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1624-1626
+  if (LHS.isEmpty() || RHS.isEmpty()) {
+return RangeFactory.getEmptySet();
+  }

Syntax: We usually don't use braces for single-line statements.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1630-1631
+
+  RangeSet CastedLHS = RangeFactory.castTo(LHS, ResultType);
+  RangeSet CastedRHS = RangeFactory.castTo(RHS, ResultType);
+

And again. This is incorrect to cast your `un/signeds` to `bool`.
First, `castTo` currently does not support this operation correctly AFAIR (My 
fault. I'll add the support later). And thus, I've no idea why your tests pass.
Second, you will get from e.g. `u32[1,9]`  -  `bool[1,1]` and from `i32[42, 
45]` - `bool[1,1]`. Then `bool[1,1]` would be equal to `bool[1,1]`, but it 
shouldn't in terms of `u/i32`.

Here you should emulate the behavior of C++ abstract machine, hence cast both 
to the biggest type or unsigned one.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1633-1636
+  if (CastedLHS == RangeFactory.getEmptySet() ||
+  CastedRHS == RangeFactory.getEmptySet()) {
+return infer(T);
+  }

`castTo` won't produce you empty RangeSets unless the originals were already 
empty, but we checked for this previously.  So, you don't need this check.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1415-1416
+
+  Range CoarseLHS = fillGaps(LHS);
+  Range CoarseRHS = fillGaps(RHS);
+

manas wrote:
> ASDenysPetrov wrote:
> > Avoid filling the gaps, because it's completely possible to compare all the 
> > ranges.
> > E.g. //LHS //`[1,2]U[8,9]`  and  //RHS //`[5,6]` are not equal.
> > And you don't need to fiil the gap in LHS, because it will lead you to a 
> > wrong answer, like `[1,9] != [5,6]` => **UNKNOWN** instead of **TRUE**.
> If we don't fill gaps, then we will be making this method O(n) instead of 
> O(1) as of now. As I see it, filling RHS (and not filling LHS), it can 
> iterate over all ranges in LHS, and check each range's intersection with 
> CoarseRHS.
> 
> Before, I do this, I just wanted to point out the unreachability of concrete 
> cases to this method. I have tried to explain this below.
Here I'd rather get a correct result and wait a bit then contra-versa.



Comment at: clang/test/Analysis/constant-folding.c:289
+
+  // Check when RHS is in between two Ranges in LHS
+  if (((u1 >= 1 && u1 <= 2) || (u1 >= 8 && u1 <= 9)) &&

manas wrote:
> @ASDenysPetrov I have used your example, but I realized that the path 
> bifurcates and sizeof `LHS` RangeSet is always 1 inside 
> `VisitBinaryOperator`.
Just do as I advised in the main comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112621

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


[PATCH] D109977: LLVM Driver Multicall tool

2022-07-19 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D109977#3662859 , @mgorny wrote:

> Ok, I think the key to reproducing it is `-DLLVM_LINK_LLVM_DYLIB=ON`. We pass 
> that while building LLVM, so it gets passed on to clang but I suppose passing 
> it to clang build might be sufficient to reproduce the problem.
> ...



  cmake -Sllvm -B/tmp/out/play -G Ninja -DCMAKE_BUILD_TYPE=Release 
-DLLVM_ENABLE_PROJECTS='llvm;clang' -DLLVM_BUILD_LLVM_DYLIB=ON 
-DLLVM_LINK_LLVM_DYLIB=ON
  ninja -C /tmp/out/play all

works on my Debian testing machine at main (without any patch).

---

If I enable `-DLLVM_TOOL_LLVM_DRIVER_BUILD=on`, there is an incompatibility due 
to some `cl::opt` options registered more than once.
This is a classical error. I think at this point 
`-DLLVM_TOOL_LLVM_DRIVER_BUILD=on` users are not supposed to use 
-DLLVM_BUILD_LLVM_DYLIB=ON,
but it'll be useful to fix this to get more size reduction.

  % ninja -C /tmp/out/play bin/llvm
  % /tmp/out/play/bin/llvm clang --help
  : CommandLine Error: Option 'arm-implicit-it' registered more than once!
  LLVM ERROR: inconsistency in registered CommandLine options
  [1]160970 IOT instruction  /tmp/out/play/bin/llvm clang --help


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109977

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


[PATCH] D128955: [WPD] Use new llvm.public.type.test intrinsic for potentially publicly visible classes

2022-07-19 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson added a comment.

Thanks for implementing this!

In D71913 , I also modified this code, which 
might need something similar: 
https://github.com/llvm/llvm-project/blob/59afc4038b1096bc6fea7b322091f6e5e2dc0b38/clang/lib/CodeGen/ItaniumCXXABI.cpp#L707-L713




Comment at: clang/test/CodeGenCXX/thinlto-distributed-type-metadata.cpp:22
 // OPT-NOT: @llvm.type.test
-// OPT-NOT: call void @llvm.assume
 // We should have only one @llvm.assume call, the one that was expanded

Why remove this one here and below?



Comment at: clang/test/CodeGenCXX/type-metadata.cpp:148
+  // CFI-TT-MS: [[P:%[^ ]*]] = call i1 @llvm.type.test(i8* [[VT:%[^ ]*]], 
metadata !"?AUA@@")
+  // VTABLE-TT-MS: [[P:%[^ ]*]] = call i1 @llvm.type.test(i8* [[VT:%[^ ]*]], 
metadata !"?AUA@@")
   // TC-ITANIUM: [[PAIR:%[^ ]*]] = call { i8*, i1 } 
@llvm.type.checked.load(i8* {{%[^ ]*}}, i32 0, metadata !"_ZTS1A")

It's a little confusing to distinguish the results by prefixing them as "CFI" 
or "VTABLE". Afaict the behavior is determined by whether -fvisibility=hidden 
has been passed in all cases for Itanium.

And MS is always hidden from what I see here? So in that case no need to split 
the expected results into two copies.



Comment at: lld/test/ELF/lto/update_public_type_test.ll:1
+; REQUIRES: x86
+

Add comments about what is being tested. Also good to test via llvm-lto2 which 
has a similar -whole-program-visibility option, rather than just via lld here. 
See for example llvm/test/ThinLTO/X86/devirt_vcall_vis_public.ll.



Comment at: llvm/lib/LTO/LTOBackend.cpp:595
 
+  updatePublicTypeTestCalls(Mod, Conf.HasWholeProgramVisibility);
+

aeubanks wrote:
> I'm not sure where the best place to put these is
I don't think that this will work for distributed ThinLTO, where the ThinLTO 
Backends are run via clang, which isn't going to have this config variable set 
(since it is set only during LTO linking). I think something may need to be 
recorded in the index as a flag there at thin link / indexing time that can be 
checked here.

It would then be nice to consolidate this handling into WPD itself, e.g. at the 
start of DevirtModule::run, but unfortunately we won't have a summary index for 
pure regular LTO WPD so I don't think that would work. So in here is ok but I 
would do it early to handle some of the early return cases.

(Please add a distributed ThinLTO test too)



Comment at: llvm/lib/Transforms/IPO/LowerTypeTests.cpp:1849
+  dropTypeTests(M, *TypeTestFunc);
+Function *PublicTypeTestFunc =
+M.getFunction(Intrinsic::getName(Intrinsic::public_type_test));

Shouldn't we have converted all of these by now?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128955

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


[PATCH] D130081: Add foldings for multi-line comment.

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

Addressed comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130081

Files:
  clang-tools-extra/clangd/Protocol.cpp
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/SemanticSelection.cpp
  clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
@@ -335,6 +335,27 @@
   ]]}   \
 ]]};
   )cpp",
+  R"cpp(
+[[/* Multi 
+  * line
+  *  comment 
+  */]]
+  )cpp",
+  R"cpp(
+[[// Multiple continuous comments
+// are
+
+// collapsed
+
+// into one.]]
+
+int a;
+[[/* comment 1
+*/
+
+/* comment 1
+*/]]
+  )cpp",
   };
   for (const char *Test : Tests) {
 auto T = Annotations(Test);
Index: clang-tools-extra/clangd/SemanticSelection.cpp
===
--- clang-tools-extra/clangd/SemanticSelection.cpp
+++ clang-tools-extra/clangd/SemanticSelection.cpp
@@ -173,16 +173,16 @@
   return collectFoldingRanges(SyntaxTree, TM);
 }
 
-// FIXME(kirillbobyrev): Collect comments, PP conditional regions, includes and
-// other code regions (e.g. public/private/protected sections of classes,
-// control flow statement bodies).
+// FIXME( usaxena95): Collect PP conditional regions, includes and other code
+// regions (e.g. public/private/protected sections of classes, control flow
+// statement bodies).
 // Related issue: https://github.com/clangd/clangd/issues/310
 llvm::Expected>
 getFoldingRanges(const std::string &Code) {
-  auto OrigStream = clang::pseudo::lex(Code, clang::pseudo::genericLangOpts());
+  auto OrigStream = pseudo::lex(Code, clang::pseudo::genericLangOpts());
 
-  auto DirectiveStructure = clang::pseudo::DirectiveTree::parse(OrigStream);
-  clang::pseudo::chooseConditionalBranches(DirectiveStructure, OrigStream);
+  auto DirectiveStructure = pseudo::DirectiveTree::parse(OrigStream);
+  pseudo::chooseConditionalBranches(DirectiveStructure, OrigStream);
 
   // FIXME: Provide ranges in the disabled-PP regions as well.
   auto Preprocessed = DirectiveStructure.stripDirectives(OrigStream);
@@ -191,26 +191,53 @@
   pseudo::pairBrackets(ParseableStream);
 
   std::vector Result;
-  for (const auto &Tok : ParseableStream.tokens()) {
+  auto ToFoldingRange = [](Position Start, Position End,
+   FoldingRangeKind Kind) {
+FoldingRange FR;
+FR.startLine = Start.line;
+FR.startCharacter = Start.character;
+FR.endLine = End.line;
+FR.endCharacter = End.character;
+FR.kind = Kind;
+return FR;
+  };
+  auto OriginalToken = [&](const pseudo::Token &T) {
+return OrigStream.tokens()[T.OriginalIndex];
+  };
+  auto StartOffset = [&](const pseudo::Token &T) {
+return OriginalToken(T).text().data() - Code.data();
+  };
+  auto Tokens = ParseableStream.tokens();
+  // Brackets.
+  for (const auto &Tok : Tokens) {
 if (auto *Paired = Tok.pair()) {
   // Process only token at the start of the range. Avoid ranges on a single
   // line.
   if (Tok.Line < Paired->Line) {
-Position Start = offsetToPosition(
-Code,
-OrigStream.tokens()[Tok.OriginalIndex].text().data() - Code.data());
-Position End = offsetToPosition(
-Code, OrigStream.tokens()[Paired->OriginalIndex].text().data() -
-  Code.data());
-FoldingRange FR;
-FR.startLine = Start.line;
-FR.startCharacter = Start.character + 1;
-FR.endLine = End.line;
-FR.endCharacter = End.character;
-Result.push_back(FR);
+Position Start = offsetToPosition(Code, 1 + StartOffset(Tok));
+Position End = offsetToPosition(Code, StartOffset(*Paired));
+Result.push_back(ToFoldingRange(Start, End, FoldingRangeKind::region));
   }
 }
   }
+  // Multi-line comments.
+  for (const auto *T = Tokens.begin(); T != Tokens.end();) {
+if (T->Kind != tok::comment) {
+  T++;
+  continue;
+}
+Position Start = offsetToPosition(Code, StartOffset(*T));
+const pseudo::Token *LastComment = T;
+while (T != Tokens.end() && T->Kind == tok::comment &&
+   LastComment->Line == T->Line + 1) {
+  LastComment = T;
+  T++;
+}
+Position End = offsetToPosition(
+Code, StartOffset(*LastComment) + OriginalToken(*LastComment).Length);
+if (Start.line < End.line)
+  Result.push_back(ToFoldingRange(Start, End, FoldingRangeKind::comment));
+  }
   return Result;

[PATCH] D130081: Add foldings for multi-line comment.

2022-07-19 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 added inline comments.



Comment at: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp:351
+int c;
+[[// A comment 
+// expanding more than

hokein wrote:
> For this case, my personal preference would be to have 3 different foldings, 
> rather than a union one.
> 
> If you think about cases like below, it makes more sense to have individual 
> folding per comment.
> 
> ```
> /* comment 1
> */
> 
> /* comment 2
> */
> ```
> 
> ```
> /* comment 1
> */
> 
> // comment 2
> ```
In the cases mentioned, I think these comments would be about the same context. 
If I want to fold (possibly long) comments with interleaved new lines, I would 
be interested in folding all the related comments to look at the code clearly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130081

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


[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

There is no constant propagation for globals with weak linage, right? 
Otherwise, it won't work. My concern is that there may be optimization passes 
which do not respect the weak linkage and uses the incorrect default value for 
OpenCL or HIP. Therefore I am not very confident to enable this for OpenCL or 
HIP unless these variables have the correct value based on the compilation 
options.




Comment at: clang/lib/CodeGen/TargetInfo.cpp:9480
+  AddGlobal("__oclc_ISA_version", Minor + Major * 1000, 32);
+  AddGlobal("__oclc_ABI_version", 400, 32);
+}

should be determined by the code object version option.



Comment at: clang/test/CodeGen/amdgcn-occl-constants.c:8
+// CHECK: @__oclc_daz_opt = weak_odr hidden local_unnamed_addr addrspace(4) 
constant i8 0, align 1
+// CHECK: @__oclc_wavefrontsize64 = weak_odr hidden local_unnamed_addr 
addrspace(4) constant i8 1, align 1
+// CHECK: @__oclc_finite_only_opt = weak_odr hidden local_unnamed_addr 
addrspace(4) constant i8 0, align 1

need a check for __oclc_wavefrontsize64=0 for gfx1030


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D129886: [clang] Add -fdiagnostics-format=sarif option for future SARIF output

2022-07-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:4009-4011
+if (StringRef(A->getValue()) == "sarif") {
+  D.Diag(diag::warn_drv_sarif_format_unstable);
+}

Do we want to be kind to people who spell it SARIF (given that it's an acronym, 
some folks may spell it that way reflexively)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129886

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


[PATCH] D130081: Add foldings for multi-line comment.

2022-07-19 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 445893.
usaxena95 added a comment.

Do not fill Kind in JSON when it is unspecified.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130081

Files:
  clang-tools-extra/clangd/Protocol.cpp
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/SemanticSelection.cpp
  clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
@@ -335,6 +335,27 @@
   ]]}   \
 ]]};
   )cpp",
+  R"cpp(
+[[/* Multi 
+  * line
+  *  comment 
+  */]]
+  )cpp",
+  R"cpp(
+[[// Multiple continuous comments
+// are
+
+// collapsed
+
+// into one.]]
+
+int a;
+[[/* comment 1
+*/
+
+/* comment 1
+*/]]
+  )cpp",
   };
   for (const char *Test : Tests) {
 auto T = Annotations(Test);
Index: clang-tools-extra/clangd/SemanticSelection.cpp
===
--- clang-tools-extra/clangd/SemanticSelection.cpp
+++ clang-tools-extra/clangd/SemanticSelection.cpp
@@ -173,16 +173,16 @@
   return collectFoldingRanges(SyntaxTree, TM);
 }
 
-// FIXME(kirillbobyrev): Collect comments, PP conditional regions, includes and
-// other code regions (e.g. public/private/protected sections of classes,
-// control flow statement bodies).
+// FIXME( usaxena95): Collect PP conditional regions, includes and other code
+// regions (e.g. public/private/protected sections of classes, control flow
+// statement bodies).
 // Related issue: https://github.com/clangd/clangd/issues/310
 llvm::Expected>
 getFoldingRanges(const std::string &Code) {
-  auto OrigStream = clang::pseudo::lex(Code, clang::pseudo::genericLangOpts());
+  auto OrigStream = pseudo::lex(Code, clang::pseudo::genericLangOpts());
 
-  auto DirectiveStructure = clang::pseudo::DirectiveTree::parse(OrigStream);
-  clang::pseudo::chooseConditionalBranches(DirectiveStructure, OrigStream);
+  auto DirectiveStructure = pseudo::DirectiveTree::parse(OrigStream);
+  pseudo::chooseConditionalBranches(DirectiveStructure, OrigStream);
 
   // FIXME: Provide ranges in the disabled-PP regions as well.
   auto Preprocessed = DirectiveStructure.stripDirectives(OrigStream);
@@ -191,26 +191,53 @@
   pseudo::pairBrackets(ParseableStream);
 
   std::vector Result;
-  for (const auto &Tok : ParseableStream.tokens()) {
+  auto ToFoldingRange = [](Position Start, Position End,
+   FoldingRangeKind Kind) {
+FoldingRange FR;
+FR.startLine = Start.line;
+FR.startCharacter = Start.character;
+FR.endLine = End.line;
+FR.endCharacter = End.character;
+FR.kind = Kind;
+return FR;
+  };
+  auto OriginalToken = [&](const pseudo::Token &T) {
+return OrigStream.tokens()[T.OriginalIndex];
+  };
+  auto StartOffset = [&](const pseudo::Token &T) {
+return OriginalToken(T).text().data() - Code.data();
+  };
+  auto Tokens = ParseableStream.tokens();
+  // Brackets.
+  for (const auto &Tok : Tokens) {
 if (auto *Paired = Tok.pair()) {
   // Process only token at the start of the range. Avoid ranges on a single
   // line.
   if (Tok.Line < Paired->Line) {
-Position Start = offsetToPosition(
-Code,
-OrigStream.tokens()[Tok.OriginalIndex].text().data() - Code.data());
-Position End = offsetToPosition(
-Code, OrigStream.tokens()[Paired->OriginalIndex].text().data() -
-  Code.data());
-FoldingRange FR;
-FR.startLine = Start.line;
-FR.startCharacter = Start.character + 1;
-FR.endLine = End.line;
-FR.endCharacter = End.character;
-Result.push_back(FR);
+Position Start = offsetToPosition(Code, 1 + StartOffset(Tok));
+Position End = offsetToPosition(Code, StartOffset(*Paired));
+Result.push_back(ToFoldingRange(Start, End, FoldingRangeKind::region));
   }
 }
   }
+  // Multi-line comments.
+  for (const auto *T = Tokens.begin(); T != Tokens.end();) {
+if (T->Kind != tok::comment) {
+  T++;
+  continue;
+}
+Position Start = offsetToPosition(Code, StartOffset(*T));
+const pseudo::Token *LastComment = T;
+while (T != Tokens.end() && T->Kind == tok::comment &&
+   LastComment->Line == T->Line + 1) {
+  LastComment = T;
+  T++;
+}
+Position End = offsetToPosition(
+Code, StartOffset(*LastComment) + OriginalToken(*LastComment).Length);
+if (Start.line < End.line)
+  Result.push_back(ToFoldingRange(Start, End, FoldingRangeKind::comment));
+  }
   return Result;
 }
 
Index: cl

[PATCH] D129886: [clang] Add -fdiagnostics-format=sarif option for future SARIF output

2022-07-19 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:4009-4011
+if (StringRef(A->getValue()) == "sarif") {
+  D.Diag(diag::warn_drv_sarif_format_unstable);
+}

aaron.ballman wrote:
> Do we want to be kind to people who spell it SARIF (given that it's an 
> acronym, some folks may spell it that way reflexively)?
tbh I think it's worth accepting both `sarif` and `SARIF`, if we can.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129886

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


[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 marked an inline comment as done.
jhuber6 added a comment.

In D130096#3663295 , @yaxunl wrote:

> There is no constant propagation for globals with weak linage, right? 
> Otherwise, it won't work. My concern is that there may be optimization passes 
> which do not respect the weak linkage and uses the incorrect default value 
> for OpenCL or HIP. Therefore I am not very confident to enable this for 
> OpenCL or HIP unless these variables have the correct value based on the 
> compilation options.

Yes, the problem is that `linkonce_odr` can be removed and as-such isn't usable 
for linking libraries late like we want to. You are correct that `weak_odr` 
normally cannot be propagated as another TU could potentially change it, but if 
we're linking this via LTO like AMDGPU does it should always be internalized in 
the linker. The OpenMP runtime has a similar `weak_odr` variable that gets 
internalized when we do LTO so it should apply here as well. Although my 
assumption is that AMDGPU always feeds bitcode directly to either `lld` or 
`clang-linker-wrapper` without invoking `llc` manually, I may be wrong there.




Comment at: clang/lib/CodeGen/TargetInfo.cpp:9480
+  AddGlobal("__oclc_ISA_version", Minor + Major * 1000, 32);
+  AddGlobal("__oclc_ABI_version", 400, 32);
+}

yaxunl wrote:
> should be determined by the code object version option.
Yes I wasn't sure about this one. Could you elaborate where we derive that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D130058: [Clang] Diagnose ill-formed constant expression when setting a non fixed enum to a value outside the range of the enumeration values

2022-07-19 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added a comment.

Note I took my range generation code from `CGExpr.cpp` function 
`getRangeForType(...)` I was considering perhaps making the code common, maybe 
this could be a helper in `EnumDecl`? Does that makes sense?




Comment at: clang/lib/AST/ExprConstant.cpp:13512
 
+if (Info.Ctx.getLangOpts().CPlusPlus20)
+  if (const EnumType *ET = dyn_cast(DestType)) {

erichkeane wrote:
> Why the check for C++20?  This is UB as a Defect Report, which applies to all 
> versions of C++.
I did not realized we apply defects back, I can remove the C++20 check.



Comment at: clang/lib/AST/ExprConstant.cpp:13533
+
+  if (NumNegativeBits) {
+unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);

erichkeane wrote:
> erichkeane wrote:
> > So my reading of 'within the range of the enumeration values' is different 
> > here.  Given:
> > 
> > `enum F { -4, 4};`, the valid values for assignment I would say are -4, -3, 
> > -2, -1, 0, 1, 2, 3, 4.  This error seems to be a bit more permissive here 
> > by making sure it is represent-able by the number of bits required to 
> > represent the enum.
> > 
> > 
> Aaron pointed out off-line that I'm incorrect in what 'range of enumeration 
> values' means, and that the values comes from 
> https://eel.is/c++draft/dcl.enum#8.sentence-2.
> 
> So the logic here needs to be to find the smallest integer (regardless of the 
> power-of-2-ness of its bit-size) that can represent all of the values 
> (including a 1 bit value for empty I think?), and diagnose based on that.
So I used ubsan to validate my checks e.g. https://godbolt.org/z/1j43465K7 but 
perhaps ubsan is getting it wrong as well?



Comment at: clang/test/SemaCXX/constant-expression-cxx2a.cpp:1477
+
+enum E { e1=-4, e2=4};
+void testValueInRangeOfEnumerationValues() {

erichkeane wrote:
> erichkeane wrote:
> > Theres likely quite a few more tests that need to be done.  We should have 
> > one where it validates against a fixed underlying type, AND probably a pair 
> > of ones to check against scoped enums.  
> > 
> > I wouldn't expect a scoped enum to diagnose, but a test to make sure we're 
> > checking the right thing is likely valuable. 
> Another good test is the empty-enum case.
Good point on the tests, yes we should not diagnose on a scoped enum.


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

https://reviews.llvm.org/D130058

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


[PATCH] D130058: [Clang] Diagnose ill-formed constant expression when setting a non fixed enum to a value outside the range of the enumeration values

2022-07-19 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:13527
+  llvm::APInt Min;
+  llvm::APInt End;
+

Why "End" instead of max?



Comment at: clang/lib/AST/ExprConstant.cpp:13533
+
+  if (NumNegativeBits) {
+unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);

shafik wrote:
> erichkeane wrote:
> > erichkeane wrote:
> > > So my reading of 'within the range of the enumeration values' is 
> > > different here.  Given:
> > > 
> > > `enum F { -4, 4};`, the valid values for assignment I would say are -4, 
> > > -3, -2, -1, 0, 1, 2, 3, 4.  This error seems to be a bit more permissive 
> > > here by making sure it is represent-able by the number of bits required 
> > > to represent the enum.
> > > 
> > > 
> > Aaron pointed out off-line that I'm incorrect in what 'range of enumeration 
> > values' means, and that the values comes from 
> > https://eel.is/c++draft/dcl.enum#8.sentence-2.
> > 
> > So the logic here needs to be to find the smallest integer (regardless of 
> > the power-of-2-ness of its bit-size) that can represent all of the values 
> > (including a 1 bit value for empty I think?), and diagnose based on that.
> So I used ubsan to validate my checks e.g. https://godbolt.org/z/1j43465K7 
> but perhaps ubsan is getting it wrong as well?
Playing with that link, I THINK this is right?  I couldn't get it to be the 
'wrong' message there. It DID take a while to figure out what is going on here.

I DO like the idea of abstracting this into some sort of `InRangeOfValues` 
thing on EnumDecl so that UBSan and this can share it.


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

https://reviews.llvm.org/D130058

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


[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D130096#3663295 , @yaxunl wrote:

> There is no constant propagation for globals with weak linage, right? 
> Otherwise, it won't work. My concern is that there may be optimization passes 
> which do not respect the weak linkage and uses the incorrect default value 
> for OpenCL or HIP. Therefore I am not very confident to enable this for 
> OpenCL or HIP unless these variables have the correct value based on the 
> compilation options.

Instead of `weak_odr` we could probably use add this to compiler used instead 
if that's an issue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

In D130096#3663398 , @jhuber6 wrote:

> In D130096#3663295 , @yaxunl wrote:
>
>> There is no constant propagation for globals with weak linage, right? 
>> Otherwise, it won't work. My concern is that there may be optimization 
>> passes which do not respect the weak linkage and uses the incorrect default 
>> value for OpenCL or HIP. Therefore I am not very confident to enable this 
>> for OpenCL or HIP unless these variables have the correct value based on the 
>> compilation options.
>
> Instead of `weak_odr` we could probably use add this to compiler used instead 
> if that's an issue.

the libraries get internalized as-is. Why does this need to be weak_odr?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D130108: git-clang-format: format index not worktree when using --staged

2022-07-19 Thread Mészáros Gergely via Phabricator via cfe-commits
Maetveis created this revision.
Maetveis added a project: clang-format.
Herald added a subscriber: arphaman.
Herald added a project: All.
Maetveis requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

When --staged (or --cached) use the index for formatting as well, not just for 
the line numbers
to format.
Without this change git-clang-format gets the changed line numbers based on the 
index, but then
formats these lines on the working tree version of the file.
This is a problem when the working tree and index differ. One common case would 
be 
(and is the motivation behind this patch) when applying the suggested changes 
`git-clang-format --staged`,
then forgetting to add the applied changes. When `git-clang-format --staged 
--diff` is used in a
pre-commit hook in this scenario, then the hook would allow committing the 
improperly formatted changes,
as the file is correctly formatted in the work tree.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130108

Files:
  clang/tools/clang-format/git-clang-format

Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -184,8 +184,12 @@
  binary=opts.binary,
  style=opts.style)
   else:
-old_tree = create_tree_from_workdir(changed_lines)
+if opts.staged:
+  old_tree = create_tree_from_index(changed_lines)
+else:
+  old_tree = create_tree_from_workdir(changed_lines)
 new_tree = run_clang_format_and_save_to_tree(changed_lines,
+ revision="" if opts.staged else None,
  binary=opts.binary,
  style=opts.style)
   if opts.verbose >= 1:
@@ -393,12 +397,27 @@
   Returns the object ID (SHA-1) of the created tree."""
   return create_tree(filenames, '--stdin')
 
+def create_tree_from_index(filenames):
+  # Copy the environment, because the files have to be read from the original index
+  env = os.environ.copy()
+  def index_contents_generator():
+for filename in filenames:
+  git_ls_files_cmd = ['git', 'ls-files', '--stage', '-z', '--', filename]
+  git_ls_files = subprocess.Popen(git_ls_files_cmd, env=env, stdin=subprocess.PIPE,
+  stdout=subprocess.PIPE)
+  stdout = git_ls_files.communicate()[0]
+  yield convert_string(stdout.split(b'\0')[0])
+  return create_tree(index_contents_generator(), '--index-info')
+
 
 def run_clang_format_and_save_to_tree(changed_lines, revision=None,
   binary='clang-format', style=None):
   """Run clang-format on each file and save the result to a git tree.
 
   Returns the object ID (SHA-1) of the created tree."""
+  # Copy the environment when formatting the files in the index, because the files
+  # have to be read from the original index
+  env = os.environ.copy() if revision == '' else None
   def iteritems(container):
   try:
   return container.iteritems() # Python 2
@@ -406,11 +425,14 @@
   return container.items() # Python 3
   def index_info_generator():
 for filename, line_ranges in iteritems(changed_lines):
-  if revision:
-git_metadata_cmd = ['git', 'ls-tree',
-'%s:%s' % (revision, os.path.dirname(filename)),
-os.path.basename(filename)]
-git_metadata = subprocess.Popen(git_metadata_cmd, stdin=subprocess.PIPE,
+  if revision is not None:
+if len(revision) > 0:
+  git_metadata_cmd = ['git', 'ls-tree'
+  '%s:%s' % (revision, os.path.dirname(filename)),
+  os.path.basename(filename)]
+else:
+  git_metadata_cmd = ['git', 'ls-files', '--stage', '--', filename]
+git_metadata = subprocess.Popen(git_metadata_cmd, env=env, stdin=subprocess.PIPE,
 stdout=subprocess.PIPE)
 stdout = git_metadata.communicate()[0]
 mode = oct(int(stdout.split()[0], 8))
@@ -422,7 +444,8 @@
   blob_id = clang_format_to_blob(filename, line_ranges,
  revision=revision,
  binary=binary,
- style=style)
+ style=style,
+ env=env)
   yield '%s %s\t%s' % (mode, blob_id, filename)
   return create_tree(index_info_generator(), '--index-info')
 
@@ -448,11 +471,12 @@
 
 
 def clang_format_to_blob(filename, line_ranges, revision=None,
- binary='clang-format', style=None):
+ binary='clang-format', style=None, env=Non

[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D130096#3663411 , @arsenm wrote:

> In D130096#3663398 , @jhuber6 wrote:
>
>> In D130096#3663295 , @yaxunl wrote:
>>
>>> There is no constant propagation for globals with weak linage, right? 
>>> Otherwise, it won't work. My concern is that there may be optimization 
>>> passes which do not respect the weak linkage and uses the incorrect default 
>>> value for OpenCL or HIP. Therefore I am not very confident to enable this 
>>> for OpenCL or HIP unless these variables have the correct value based on 
>>> the compilation options.
>>
>> Instead of `weak_odr` we could probably use add this to compiler used 
>> instead if that's an issue.
>
> the libraries get internalized as-is. Why does this need to be weak_odr?

It depends where we want to do the linking. For my purposes I'd like to be able 
to link in these libraries at link time. This allows us to link in target 
specific libraries as-needed so we can make generated code more generic until 
linking or the backend. The problem with `linkonce_odr` is that it does not 
need to emit a symbol, so it will usually be optimized out by clang. E.g. the 
following won't work because these generated globals will be optimized out 
completely before we have any library to use them.

  clang amdgpu.c -c -O3
  clang amdgpu.o 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D121141: [Clang] Add `-fexperimental-library` flag to enable unstable and experimental features: follow-up fixes

2022-07-19 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

Windows seems to have been "fixed" (a band-aid really), and the Linux failure 
seems unrelated, so I'll ship this now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121141

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


[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-07-19 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D130096#3663062 , @JonChesterfield 
wrote:

> A safer bet is to use the current control flow that links in specific bitcode 
> files, but create the global directly instead of linking in the file. That'll 
> give us zero semantic change and a clang that ignores those bitcode files if 
> present.

I think I understand what you're saying better now. We should instead have this 
controlled as a flag via `clang` that the driver will add. This will just tell 
us to trigger some backend utility to emit the same code. I can look into doing 
that, will make it easier to just have the clang driver state that we should 
emit this for HIP / OpenMP unless `nogpulib` is passed for example.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[clang] ca495e3 - [clang] Add a new flag -fexperimental-library to enable experimental library features

2022-07-19 Thread Louis Dionne via cfe-commits

Author: Louis Dionne
Date: 2022-07-19T15:04:58-04:00
New Revision: ca495e36c1b4d4b8be47c9140647e6e934913cba

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

LOG: [clang] Add a new flag -fexperimental-library to enable experimental 
library features

Based on the discussion at [1], this patch adds a Clang flag called
-fexperimental-library that controls whether experimental library
features are provided in libc++. In essence, it links against the
experimental static archive provided by libc++ and defines a feature
that can be picked up by libc++ to enable experimental features.

This ensures that users don't start depending on experimental
(and hence unstable) features unknowingly.

[1]: 
https://discourse.llvm.org/t/rfc-a-compiler-flag-to-enable-experimental-unstable-language-and-library-features

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

Added: 
clang/test/Driver/experimental-library-flag.cpp
clang/test/Lexer/has_feature_experimental_library.cpp

Modified: 
clang/docs/ClangCommandLineReference.rst
clang/include/clang/Basic/Features.def
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChain.cpp
clang/lib/Driver/ToolChains/AIX.cpp
clang/lib/Driver/ToolChains/BareMetal.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/CloudABI.cpp
clang/lib/Driver/ToolChains/CrossWindows.cpp
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/FreeBSD.cpp
clang/lib/Driver/ToolChains/Fuchsia.cpp
clang/lib/Driver/ToolChains/Hexagon.cpp
clang/lib/Driver/ToolChains/MipsLinux.cpp
clang/lib/Driver/ToolChains/NaCl.cpp
clang/lib/Driver/ToolChains/OpenBSD.cpp
clang/lib/Driver/ToolChains/VEToolchain.cpp
clang/lib/Driver/ToolChains/WebAssembly.cpp

Removed: 
clang/test/Driver/unstable-flag.cpp
clang/test/Lexer/has_feature_cxx_unstable.cpp



diff  --git a/clang/docs/ClangCommandLineReference.rst 
b/clang/docs/ClangCommandLineReference.rst
index 223990e0517f1..6d1b6000484ce 100644
--- a/clang/docs/ClangCommandLineReference.rst
+++ b/clang/docs/ClangCommandLineReference.rst
@@ -1761,6 +1761,10 @@ Enable support for exception handling
 
 .. option:: -fexec-charset=
 
+.. option:: -fexperimental-library, -fno-experimental-library
+
+Control whether unstable and experimental library features are enabled. This 
option enables various library features that are either experimental (also 
known as TSes), or have been but are not stable yet in the selected Standard 
Library implementation. It is not recommended to use this option in production 
code, since neither ABI nor API stability are guaranteed. This is intended to 
provide a preview of features that will ship in the future for experimentation 
purposes
+
 .. option:: -fexperimental-new-constant-interpreter
 
 Enable the experimental new constant interpreter
@@ -2637,10 +2641,6 @@ Turn on loop unroller
 
 .. option:: -funsigned-char, -fno-unsigned-char, --unsigned-char
 
-.. option:: -funstable, -fno-unstable
-
-Enable unstable and experimental features
-
 .. option:: -funwind-tables, -fno-unwind-tables
 
 .. option:: -fuse-cxa-atexit, -fno-use-cxa-atexit

diff  --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index a7f0ae03e0beb..7151e923ae9cf 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -179,7 +179,6 @@ FEATURE(cxx_thread_local,
 FEATURE(cxx_trailing_return, LangOpts.CPlusPlus11)
 FEATURE(cxx_unicode_literals, LangOpts.CPlusPlus11)
 FEATURE(cxx_unrestricted_unions, LangOpts.CPlusPlus11)
-FEATURE(cxx_unstable, LangOpts.Unstable)
 FEATURE(cxx_user_literals, LangOpts.CPlusPlus11)
 FEATURE(cxx_variadic_templates, LangOpts.CPlusPlus11)
 // C++14 features
@@ -235,6 +234,7 @@ FEATURE(shadow_call_stack,
 LangOpts.Sanitize.has(SanitizerKind::ShadowCallStack))
 FEATURE(tls, PP.getTargetInfo().isTLSSupported())
 FEATURE(underlying_type, LangOpts.CPlusPlus)
+FEATURE(experimental_library, LangOpts.ExperimentalLibrary)
 
 // C11 features supported by other languages as extensions.
 EXTENSION(c_alignas, true)

diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index ba6ce4e9250f4..6fb31c5655abf 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -155,7 +155,7 @@ LANGOPT(GNUAsm, 1, 1, "GNU-style inline 
assembly")
 LANGOPT(Coroutines, 1, 0, "C++20 coroutines")
 LANGOPT(DllExportInlines  , 1, 1, "dllexported classes dllexport inline 
methods")
 LANGOPT(RelaxedTemplateTemplateArgs, 1, 0, "C++17 relaxed matching of template 
template arguments")
-LANGOPT(Unstable  , 1,

[PATCH] D129886: [clang] Add -fdiagnostics-format=sarif option for future SARIF output

2022-07-19 Thread Abraham Corea Diaz via Phabricator via cfe-commits
abrahamcd updated this revision to Diff 445904.
abrahamcd marked 2 inline comments as done.
abrahamcd added a comment.
Herald added a reviewer: jdoerfert.
Herald added subscribers: abrachet, sstefan1, phosek, ormris.

Enabled both "sarif" and "SARIF" as flag spellings.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129886

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/TextDiagnostic.cpp
  clang/test/Driver/fdiagnostics-format-sarif.cpp

Index: clang/test/Driver/fdiagnostics-format-sarif.cpp
===
--- /dev/null
+++ clang/test/Driver/fdiagnostics-format-sarif.cpp
@@ -0,0 +1,5 @@
+// RUN: %clang -fsyntax-only -fdiagnostics-format=sarif %s -### 2>&1 | FileCheck %s --check-prefix=WARN
+// WARN: warning: diagnostic formatting in SARIF mode is currently unstable [-Wsarif-format-unstable]
+
+// RUN: %clang -fsyntax-only -fdiagnostics-format=SARIF %s -### 2>&1 | FileCheck %s --check-prefix=WARN2
+// WARN2: warning: diagnostic formatting in SARIF mode is currently unstable [-Wsarif-format-unstable]
Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -815,6 +815,7 @@
 
   emitFilename(PLoc.getFilename(), Loc.getManager());
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
 if (DiagOpts->ShowLine)
   OS << ':' << LineNo;
@@ -837,6 +838,7 @@
   OS << ColNo;
 }
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
   case DiagnosticOptions::Vi:OS << ':';break;
   case DiagnosticOptions::MSVC:
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -77,8 +77,8 @@
   if (Args.hasArg(options::OPT_static))
 if (const Arg *A =
 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
-  D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
-  << "-static";
+  D.Diag(diag::err_drv_argument_not_allowed_with)
+  << A->getAsString(Args) << "-static";
 }
 
 // Add backslashes to escape spaces and other backslashes.
@@ -135,8 +135,8 @@
 /// parameter in reciprocal argument strings. Return false if there is an error
 /// parsing the refinement step. Otherwise, return true and set the Position
 /// of the refinement step in the input string.
-static bool getRefinementStep(StringRef In, const Driver &D,
-  const Arg &A, size_t &Position) {
+static bool getRefinementStep(StringRef In, const Driver &D, const Arg &A,
+  size_t &Position) {
   const char RefinementStepToken = ':';
   Position = In.find(RefinementStepToken);
   if (Position != StringRef::npos) {
@@ -255,7 +255,8 @@
 
 // If the precision was not specified, also mark the double and half entry
 // as found.
-if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
+if (ValBase.back() != 'f' && ValBase.back() != 'd' &&
+ValBase.back() != 'h') {
   OptionStrings[ValBase.str() + 'd'] = true;
   OptionStrings[ValBase.str() + 'h'] = true;
 }
@@ -503,7 +504,7 @@
 }
 
 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
-  switch (Triple.getArch()){
+  switch (Triple.getArch()) {
   default:
 return false;
   case llvm::Triple::arm:
@@ -699,7 +700,7 @@
 
 /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
 static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
-   ArgStringList &CmdArgs) {
+ArgStringList &CmdArgs) {
   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
 options::OPT_fcoverage_prefix_map_EQ)) {
 StringRef Map = A->getValue();
@@ -795,13 +796,12 @@
   CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
 CSPGOGenerateArg = nullptr;
 
-  auto *ProfileGenerateArg = Args.getLastArg(
-  options::OPT_fprofile_instr_generate,
-  options::OPT_fprofile_instr_generate_EQ,
-  options::OPT_fno_profile_instr_generate);
-  if (ProfileGenerateArg &&
-  ProfileGenerateArg->getOption().matches(
-  options::OPT_fno_profile_instr_generate))
+  auto *ProfileGenerateArg =
+  Args.getLastArg(options::OPT_fprofile_instr_generate,
+  options::OPT_fprofile_instr_generate_EQ,
+

  1   2   >