[PATCH] D123478: [clangd] Fix incorrect operator< impl for HighlightingToken

2022-04-13 Thread Nathan Ridge via Phabricator via cfe-commits
nridge updated this revision to Diff 422410.
nridge added a comment.

Add semantic highlighting testcase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123478

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -797,7 +797,19 @@
 typedef int $Primitive_decl[[MyTypedef]];
 enum $Enum_decl[[MyEnum]] : $Primitive[[MyTypedef]] {};
   )cpp",
-  };
+  // Issue 1096
+  R"cpp(
+void $Function_decl[[Foo]]();
+// Use <: :> digraphs for deprecated attribute to avoid conflict with 
annotation syntax
+<:<:deprecated:>:> void $Function_decl_deprecated[[Foo]](int* 
$Parameter_decl[[x]]);
+void $Function_decl[[Foo]](int $Parameter_decl[[x]]);
+template 
+void $Function_decl[[Bar]]($TemplateParameter[[T]] 
$Parameter_decl[[x]]) {
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+}
+  )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
 // They're tested separately.
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -913,7 +913,7 @@
  std::tie(R.R, R.Kind, R.Modifiers);
 }
 bool operator<(const HighlightingToken &L, const HighlightingToken &R) {
-  return std::tie(L.R, L.Kind, R.Modifiers) <
+  return std::tie(L.R, L.Kind, L.Modifiers) <
  std::tie(R.R, R.Kind, R.Modifiers);
 }
 


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -797,7 +797,19 @@
 typedef int $Primitive_decl[[MyTypedef]];
 enum $Enum_decl[[MyEnum]] : $Primitive[[MyTypedef]] {};
   )cpp",
-  };
+  // Issue 1096
+  R"cpp(
+void $Function_decl[[Foo]]();
+// Use <: :> digraphs for deprecated attribute to avoid conflict with annotation syntax
+<:<:deprecated:>:> void $Function_decl_deprecated[[Foo]](int* $Parameter_decl[[x]]);
+void $Function_decl[[Foo]](int $Parameter_decl[[x]]);
+template 
+void $Function_decl[[Bar]]($TemplateParameter[[T]] $Parameter_decl[[x]]) {
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+}
+  )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
 // They're tested separately.
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -913,7 +913,7 @@
  std::tie(R.R, R.Kind, R.Modifiers);
 }
 bool operator<(const HighlightingToken &L, const HighlightingToken &R) {
-  return std::tie(L.R, L.Kind, R.Modifiers) <
+  return std::tie(L.R, L.Kind, L.Modifiers) <
  std::tie(R.R, R.Kind, R.Modifiers);
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] e500062 - [clangd] Fix incorrect operator< impl for HighlightingToken

2022-04-13 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2022-04-13T03:19:48-04:00
New Revision: e5000624933e11e56a1530f1561efa136c9c8bd7

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

LOG: [clangd] Fix incorrect operator< impl for HighlightingToken

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

Added: 


Modified: 
clang-tools-extra/clangd/SemanticHighlighting.cpp
clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 862cfc8edf0aa..fce83d1834a50 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -912,7 +912,7 @@ bool operator==(const HighlightingToken &L, const 
HighlightingToken &R) {
  std::tie(R.R, R.Kind, R.Modifiers);
 }
 bool operator<(const HighlightingToken &L, const HighlightingToken &R) {
-  return std::tie(L.R, L.Kind, R.Modifiers) <
+  return std::tie(L.R, L.Kind, L.Modifiers) <
  std::tie(R.R, R.Kind, R.Modifiers);
 }
 

diff  --git a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp 
b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
index 210bc7736cdd0..2f4e8e57a81f1 100644
--- a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -795,7 +795,19 @@ sizeof...($TemplateParameter[[Elements]]);
 typedef int $Primitive_decl[[MyTypedef]];
 enum $Enum_decl[[MyEnum]] : $Primitive[[MyTypedef]] {};
   )cpp",
-  };
+  // Issue 1096
+  R"cpp(
+void $Function_decl[[Foo]]();
+// Use <: :> digraphs for deprecated attribute to avoid conflict with 
annotation syntax
+<:<:deprecated:>:> void $Function_decl_deprecated[[Foo]](int* 
$Parameter_decl[[x]]);
+void $Function_decl[[Foo]](int $Parameter_decl[[x]]);
+template 
+void $Function_decl[[Bar]]($TemplateParameter[[T]] 
$Parameter_decl[[x]]) {
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+}
+  )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
 // They're tested separately.



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


[PATCH] D123478: [clangd] Fix incorrect operator< impl for HighlightingToken

2022-04-13 Thread Nathan Ridge 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 rGe5000624933e: [clangd] Fix incorrect operator< impl for 
HighlightingToken (authored by nridge).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123478

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -795,7 +795,19 @@
 typedef int $Primitive_decl[[MyTypedef]];
 enum $Enum_decl[[MyEnum]] : $Primitive[[MyTypedef]] {};
   )cpp",
-  };
+  // Issue 1096
+  R"cpp(
+void $Function_decl[[Foo]]();
+// Use <: :> digraphs for deprecated attribute to avoid conflict with 
annotation syntax
+<:<:deprecated:>:> void $Function_decl_deprecated[[Foo]](int* 
$Parameter_decl[[x]]);
+void $Function_decl[[Foo]](int $Parameter_decl[[x]]);
+template 
+void $Function_decl[[Bar]]($TemplateParameter[[T]] 
$Parameter_decl[[x]]) {
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+}
+  )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
 // They're tested separately.
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -912,7 +912,7 @@
  std::tie(R.R, R.Kind, R.Modifiers);
 }
 bool operator<(const HighlightingToken &L, const HighlightingToken &R) {
-  return std::tie(L.R, L.Kind, R.Modifiers) <
+  return std::tie(L.R, L.Kind, L.Modifiers) <
  std::tie(R.R, R.Kind, R.Modifiers);
 }
 


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -795,7 +795,19 @@
 typedef int $Primitive_decl[[MyTypedef]];
 enum $Enum_decl[[MyEnum]] : $Primitive[[MyTypedef]] {};
   )cpp",
-  };
+  // Issue 1096
+  R"cpp(
+void $Function_decl[[Foo]]();
+// Use <: :> digraphs for deprecated attribute to avoid conflict with annotation syntax
+<:<:deprecated:>:> void $Function_decl_deprecated[[Foo]](int* $Parameter_decl[[x]]);
+void $Function_decl[[Foo]](int $Parameter_decl[[x]]);
+template 
+void $Function_decl[[Bar]]($TemplateParameter[[T]] $Parameter_decl[[x]]) {
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+$Function_deprecated[[Foo]]($Parameter[[x]]); 
+}
+  )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
 // They're tested separately.
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -912,7 +912,7 @@
  std::tie(R.R, R.Kind, R.Modifiers);
 }
 bool operator<(const HighlightingToken &L, const HighlightingToken &R) {
-  return std::tie(L.R, L.Kind, R.Modifiers) <
+  return std::tie(L.R, L.Kind, L.Modifiers) <
  std::tie(R.R, R.Kind, R.Modifiers);
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121375: [clang] NFC, move the utility function CompilerInvocation::setLangDefaults to LangOptions.h

2022-04-13 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 422412.
hokein marked an inline comment as done.
hokein added a comment.

getDefaultLanguageStandard.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121375

Files:
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Basic/LangStandard.h
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Basic/LangOptions.cpp
  clang/lib/Basic/LangStandards.cpp
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3173,178 +3173,6 @@
   return Diags.getNumErrors() == NumErrorsBefore;
 }
 
-void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
- const llvm::Triple &T,
- std::vector &Includes,
- LangStandard::Kind LangStd) {
-  // Set some properties which depend solely on the input kind; it would be nice
-  // to move these to the language standard, and have the driver resolve the
-  // input kind + language standard.
-  //
-  // FIXME: Perhaps a better model would be for a single source file to have
-  // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
-  // simultaneously active?
-  if (IK.getLanguage() == Language::Asm) {
-Opts.AsmPreprocessor = 1;
-  } else if (IK.isObjectiveC()) {
-Opts.ObjC = 1;
-  }
-
-  if (LangStd == LangStandard::lang_unspecified) {
-// Based on the base language, pick one.
-switch (IK.getLanguage()) {
-case Language::Unknown:
-case Language::LLVM_IR:
-  llvm_unreachable("Invalid input kind!");
-case Language::OpenCL:
-  LangStd = LangStandard::lang_opencl12;
-  break;
-case Language::OpenCLCXX:
-  LangStd = LangStandard::lang_openclcpp10;
-  break;
-case Language::CUDA:
-  LangStd = LangStandard::lang_cuda;
-  break;
-case Language::Asm:
-case Language::C:
-#if defined(CLANG_DEFAULT_STD_C)
-  LangStd = CLANG_DEFAULT_STD_C;
-#else
-  // The PS4 uses C99 as the default C standard.
-  if (T.isPS4())
-LangStd = LangStandard::lang_gnu99;
-  else
-LangStd = LangStandard::lang_gnu17;
-#endif
-  break;
-case Language::ObjC:
-#if defined(CLANG_DEFAULT_STD_C)
-  LangStd = CLANG_DEFAULT_STD_C;
-#else
-  LangStd = LangStandard::lang_gnu11;
-#endif
-  break;
-case Language::CXX:
-case Language::ObjCXX:
-#if defined(CLANG_DEFAULT_STD_CXX)
-  LangStd = CLANG_DEFAULT_STD_CXX;
-#else
-  LangStd = LangStandard::lang_gnucxx14;
-#endif
-  break;
-case Language::RenderScript:
-  LangStd = LangStandard::lang_c99;
-  break;
-case Language::HIP:
-  LangStd = LangStandard::lang_hip;
-  break;
-case Language::HLSL:
-  LangStd = LangStandard::lang_hlsl2021;
-  break;
-}
-  }
-
-  const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
-  Opts.LangStd = LangStd;
-  Opts.LineComment = Std.hasLineComments();
-  Opts.C99 = Std.isC99();
-  Opts.C11 = Std.isC11();
-  Opts.C17 = Std.isC17();
-  Opts.C2x = Std.isC2x();
-  Opts.CPlusPlus = Std.isCPlusPlus();
-  Opts.CPlusPlus11 = Std.isCPlusPlus11();
-  Opts.CPlusPlus14 = Std.isCPlusPlus14();
-  Opts.CPlusPlus17 = Std.isCPlusPlus17();
-  Opts.CPlusPlus20 = Std.isCPlusPlus20();
-  Opts.CPlusPlus2b = Std.isCPlusPlus2b();
-  Opts.GNUMode = Std.isGNUMode();
-  Opts.GNUCVersion = 0;
-  Opts.HexFloats = Std.hasHexFloats();
-  Opts.ImplicitInt = Std.hasImplicitInt();
-  Opts.WChar = Std.isCPlusPlus();
-  Opts.Digraphs = Std.hasDigraphs();
-
-  Opts.HLSL = IK.getLanguage() == Language::HLSL;
-
-  // Set OpenCL Version.
-  Opts.OpenCL = Std.isOpenCL();
-  if (LangStd == LangStandard::lang_opencl10)
-Opts.OpenCLVersion = 100;
-  else if (LangStd == LangStandard::lang_opencl11)
-Opts.OpenCLVersion = 110;
-  else if (LangStd == LangStandard::lang_opencl12)
-Opts.OpenCLVersion = 120;
-  else if (LangStd == LangStandard::lang_opencl20)
-Opts.OpenCLVersion = 200;
-  else if (LangStd == LangStandard::lang_opencl30)
-Opts.OpenCLVersion = 300;
-  else if (LangStd == LangStandard::lang_openclcpp10)
-Opts.OpenCLCPlusPlusVersion = 100;
-  else if (LangStd == LangStandard::lang_openclcpp2021)
-Opts.OpenCLCPlusPlusVersion = 202100;
-  else if (LangStd == LangStandard::lang_hlsl2015)
-Opts.HLSLVersion = (unsigned)LangOptions::HLSL_2015;
-  else if (LangStd == LangStandard::lang_hlsl2016)
-Opts.HLSLVersion = (unsigned)LangOptions::HLSL_2016;
-  else if (LangStd == LangStandard::lang_hlsl2017)
-Opts.HLSLVersion = (unsigned)LangOptions::HLSL_2017;
-  else if (LangStd == LangStandard::lang_hlsl2018)
-Opts.HLSLVersion = (unsigned)LangOptions::HLSL_2018;
-  els

[clang] b0343a3 - Support the min of module flags when linking, use for AArch64 BTI/PAC-RET

2022-04-13 Thread Daniel Kiss via cfe-commits

Author: Daniel Kiss
Date: 2022-04-13T09:31:51+02:00
New Revision: b0343a38a5910e980bb031e4014655d77cd0c162

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

LOG: Support the min of module flags when linking, use for AArch64 BTI/PAC-RET

LTO objects might compiled with different `mbranch-protection` flags which will 
cause an error in the linker.
Such a setup is allowed in the normal build with this change that is possible.

Reviewed By: pcc

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

Added: 
llvm/test/Bitcode/upgrade-branch-protection.ll
llvm/test/LTO/AArch64/Inputs/foo.ll
llvm/test/LTO/AArch64/link-branch-target-enforcement.ll
llvm/test/LTO/AArch64/lit.local.cfg

Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/test/CodeGen/aarch64-sign-return-address.c
clang/test/CodeGen/arm-branch-protection-attr-2.c
clang/test/Frontend/arm-ignore-branch-protection-option.c
llvm/include/llvm/IR/Module.h
llvm/lib/IR/AutoUpgrade.cpp
llvm/lib/IR/Verifier.cpp
llvm/lib/Linker/IRMover.cpp
llvm/test/CodeGen/AArch64/debug-info-sve-dbg-declare.mir
llvm/test/CodeGen/AArch64/live-debugvalues-sve.mir
llvm/test/CodeGen/AArch64/memsize-remarks.ll
llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-0.ll
llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-1.ll
llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-2.ll
llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-3.ll
llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-4.ll
llvm/test/CodeGen/AArch64/pacbti-llvm-generated-funcs-2.ll
llvm/test/CodeGen/AArch64/pacbti-module-attrs.ll
llvm/test/CodeGen/AArch64/setjmp-bti-no-enforcement.ll
llvm/test/CodeGen/AArch64/setjmp-bti-outliner.ll
llvm/test/CodeGen/AArch64/setjmp-bti.ll
llvm/test/CodeGen/ARM/pacbti-module-attrs.ll
llvm/test/CodeGen/ARM/setjmp-bti-basic.ll
llvm/test/CodeGen/ARM/setjmp-bti-outliner.ll
llvm/test/CodeGen/Thumb2/LowOverheadLoops/skip-vpt-debug.mir
llvm/test/CodeGen/Thumb2/bti-const-island-multiple-jump-tables.mir
llvm/test/CodeGen/Thumb2/bti-const-island.mir
llvm/test/CodeGen/Thumb2/bti-entry-blocks.ll
llvm/test/CodeGen/Thumb2/bti-indirect-branches.ll
llvm/test/CodeGen/Thumb2/bti-jump-table.mir
llvm/test/CodeGen/Thumb2/bti-outliner-1.ll
llvm/test/CodeGen/Thumb2/bti-outliner-2.ll
llvm/test/CodeGen/Thumb2/bti-outliner-cost-1.ll
llvm/test/CodeGen/Thumb2/bti-outliner-cost-2.ll
llvm/test/CodeGen/Thumb2/bti-pac-replace-1.mir
llvm/test/CodeGen/Thumb2/bti-pac-replace-2.ll
llvm/test/CodeGen/Thumb2/pacbti-m-basic.ll
llvm/test/CodeGen/Thumb2/pacbti-m-indirect-tail-call.ll
llvm/test/CodeGen/Thumb2/pacbti-m-outliner-1.ll
llvm/test/CodeGen/Thumb2/pacbti-m-outliner-2.ll
llvm/test/CodeGen/Thumb2/pacbti-m-outliner-3.ll
llvm/test/CodeGen/Thumb2/pacbti-m-outliner-4.ll
llvm/test/CodeGen/Thumb2/pacbti-m-outliner-5.ll
llvm/test/CodeGen/Thumb2/pacbti-m-overalign.ll
llvm/test/CodeGen/Thumb2/pacbti-m-unsupported-arch.ll
llvm/test/CodeGen/Thumb2/pacbti-m-varargs-1.ll
llvm/test/CodeGen/Thumb2/pacbti-m-varargs-2.ll
llvm/test/CodeGen/Thumb2/pacbti-m-vla.ll
llvm/test/DebugInfo/AArch64/debugline-endsequence.ll
llvm/test/Instrumentation/InstrProfiling/debug-info-correlate-coverage.ll
llvm/test/Instrumentation/InstrProfiling/debug-info-correlate.ll
llvm/test/Verifier/module-flags-1.ll

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 4efcc8447d81b..b251a4a7df3d2 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -729,7 +729,10 @@ void CodeGenModule::Release() {
   // attributes, but we use module metadata to emit build attributes. This is
   // needed for LTO, where the function attributes are inside bitcode
   // serialised into a global variable by the time build attributes are
-  // emitted, so we can't access them.
+  // emitted, so we can't access them. LTO objects could be compiled with
+  // 
diff erent flags therefore module flags are set to "Min" behavior to achieve
+  // the same end result of the normal build where e.g BTI is off if any object
+  // doesn't support it.
   if (Context.getTargetInfo().hasFeature("ptrauth") &&
   LangOpts.getSignReturnAddressScope() !=
   LangOptions::SignReturnAddressScopeKind::None)
@@ -743,16 +746,16 @@ void CodeGenModule::Release() {
   Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
   Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
   Arch == llvm::Triple::aarch64_be) {
-getModule().addModuleFlag(llvm::Module::Error, "branch-target-enforcement",
+getModule().addModuleFlag(llvm::Mod

[PATCH] D123493: Support the min of module flags when linking, use for AArch64 BTI/PAC-RET

2022-04-13 Thread Daniel Kiss 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 rGb0343a38a591: Support the min of module flags when linking, 
use for AArch64 BTI/PAC-RET (authored by danielkiss).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123493

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/aarch64-sign-return-address.c
  clang/test/CodeGen/arm-branch-protection-attr-2.c
  clang/test/Frontend/arm-ignore-branch-protection-option.c
  llvm/include/llvm/IR/Module.h
  llvm/lib/IR/AutoUpgrade.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Linker/IRMover.cpp
  llvm/test/Bitcode/upgrade-branch-protection.ll
  llvm/test/CodeGen/AArch64/debug-info-sve-dbg-declare.mir
  llvm/test/CodeGen/AArch64/live-debugvalues-sve.mir
  llvm/test/CodeGen/AArch64/memsize-remarks.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-0.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-1.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-2.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-3.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-4.ll
  llvm/test/CodeGen/AArch64/pacbti-llvm-generated-funcs-2.ll
  llvm/test/CodeGen/AArch64/pacbti-module-attrs.ll
  llvm/test/CodeGen/AArch64/setjmp-bti-no-enforcement.ll
  llvm/test/CodeGen/AArch64/setjmp-bti-outliner.ll
  llvm/test/CodeGen/AArch64/setjmp-bti.ll
  llvm/test/CodeGen/ARM/pacbti-module-attrs.ll
  llvm/test/CodeGen/ARM/setjmp-bti-basic.ll
  llvm/test/CodeGen/ARM/setjmp-bti-outliner.ll
  llvm/test/CodeGen/Thumb2/LowOverheadLoops/skip-vpt-debug.mir
  llvm/test/CodeGen/Thumb2/bti-const-island-multiple-jump-tables.mir
  llvm/test/CodeGen/Thumb2/bti-const-island.mir
  llvm/test/CodeGen/Thumb2/bti-entry-blocks.ll
  llvm/test/CodeGen/Thumb2/bti-indirect-branches.ll
  llvm/test/CodeGen/Thumb2/bti-jump-table.mir
  llvm/test/CodeGen/Thumb2/bti-outliner-1.ll
  llvm/test/CodeGen/Thumb2/bti-outliner-2.ll
  llvm/test/CodeGen/Thumb2/bti-outliner-cost-1.ll
  llvm/test/CodeGen/Thumb2/bti-outliner-cost-2.ll
  llvm/test/CodeGen/Thumb2/bti-pac-replace-1.mir
  llvm/test/CodeGen/Thumb2/bti-pac-replace-2.ll
  llvm/test/CodeGen/Thumb2/pacbti-m-basic.ll
  llvm/test/CodeGen/Thumb2/pacbti-m-indirect-tail-call.ll
  llvm/test/CodeGen/Thumb2/pacbti-m-outliner-1.ll
  llvm/test/CodeGen/Thumb2/pacbti-m-outliner-2.ll
  llvm/test/CodeGen/Thumb2/pacbti-m-outliner-3.ll
  llvm/test/CodeGen/Thumb2/pacbti-m-outliner-4.ll
  llvm/test/CodeGen/Thumb2/pacbti-m-outliner-5.ll
  llvm/test/CodeGen/Thumb2/pacbti-m-overalign.ll
  llvm/test/CodeGen/Thumb2/pacbti-m-unsupported-arch.ll
  llvm/test/CodeGen/Thumb2/pacbti-m-varargs-1.ll
  llvm/test/CodeGen/Thumb2/pacbti-m-varargs-2.ll
  llvm/test/CodeGen/Thumb2/pacbti-m-vla.ll
  llvm/test/DebugInfo/AArch64/debugline-endsequence.ll
  llvm/test/Instrumentation/InstrProfiling/debug-info-correlate-coverage.ll
  llvm/test/Instrumentation/InstrProfiling/debug-info-correlate.ll
  llvm/test/LTO/AArch64/Inputs/foo.ll
  llvm/test/LTO/AArch64/link-branch-target-enforcement.ll
  llvm/test/LTO/AArch64/lit.local.cfg
  llvm/test/Verifier/module-flags-1.ll

Index: llvm/test/Verifier/module-flags-1.ll
===
--- llvm/test/Verifier/module-flags-1.ll
+++ llvm/test/Verifier/module-flags-1.ll
@@ -45,6 +45,10 @@
 ; CHECK: invalid value for 'max' module flag (expected constant integer)
 !19 = !{i32 7, !"max", !"max"}
 
+; Check that any 'min' module flags are valid.
+; CHECK: invalid value for 'min' module flag (expected constant integer)
+!20 = !{i32 8, !"min", !"min"}
+
 ; Check that any 'require' module flags are valid.
 ; CHECK: invalid requirement on flag, flag is not present in module
 !11 = !{i32 3, !"bar", !{!"no-such-flag", i32 52}}
@@ -58,4 +62,4 @@
 
 !llvm.module.flags = !{
   !0, !1, !2, !3, !4, !5, !6, !7, !8, !9, !10, !11, !12, !13, !14, !15,
-  !16, !17, !18, !19 }
+  !16, !17, !18, !19, !20 }
Index: llvm/test/LTO/AArch64/lit.local.cfg
===
--- /dev/null
+++ llvm/test/LTO/AArch64/lit.local.cfg
@@ -0,0 +1,2 @@
+if not 'AArch64' in config.root.targets:
+  config.unsupported = True
Index: llvm/test/LTO/AArch64/link-branch-target-enforcement.ll
===
--- /dev/null
+++ llvm/test/LTO/AArch64/link-branch-target-enforcement.ll
@@ -0,0 +1,38 @@
+; Testcase to check that module with different branch-target-enforcement can
+; be mixed.
+;
+; RUN: llvm-as %s -o %t1.bc
+; RUN: llvm-as %p/Inputs/foo.ll -o %t2.bc
+; RUN: llvm-lto -exported-symbol main \
+; RUN:  -exported-symbol foo \
+; RUN:  -filetype=obj \
+; RUN:   %t1.bc %t2.bc \
+; RUN:   -o %t1.exe 2>&1 | FileCheck --allow-empty %s
+; RUN: llvm-objdump -d %t1.exe | File

[PATCH] D118996: [clang-tidy] Support C++14 in bugprone-signal-handler.

2022-04-13 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 422419.
balazske added a comment.

Rebase to newer 'main' branch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118996

Files:
  clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h
  clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone-signal-handler.rst
  clang-tools-extra/docs/clang-tidy/checks/cert-msc54-cpp.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/signal.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-signal-handler/stdcpp.h
  clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-handler.c
  clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-handler.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-handler.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-handler.cpp
@@ -0,0 +1,228 @@
+// RUN: %check_clang_tidy -std=c++14 %s bugprone-signal-handler %t -- -- -isystem %S/Inputs/Headers -isystem %S/Inputs/bugprone-signal-handler
+
+#include "stdcpp.h"
+#include "stdio.h"
+
+// Functions called "signal" that are different from the system version.
+typedef void (*callback_t)(int);
+void signal(int, callback_t, int);
+namespace ns {
+void signal(int, callback_t);
+}
+
+extern "C" void handler_unsafe(int) {
+  printf("xxx");
+}
+
+extern "C" void handler_unsafe_1(int) {
+  printf("xxx");
+}
+
+namespace test_invalid_handler {
+
+void handler_non_extern_c(int) {
+  printf("xxx");
+}
+
+struct A {
+  static void handler_member(int) {
+printf("xxx");
+  }
+};
+
+void test() {
+  std::signal(SIGINT, handler_unsafe_1);
+  // CHECK-MESSAGES: :[[@LINE-17]]:3: warning: standard function 'printf' may not be asynchronous-safe; calling it from a signal handler may be dangerous [bugprone-signal-handler]
+  // CHECK-MESSAGES: :[[@LINE-2]]:23: note: function 'handler_unsafe_1' registered here as signal handler
+
+  std::signal(SIGINT, handler_non_extern_c);
+  // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: functions with other than C linkage are not allowed as signal handler (until C++17) [bugprone-signal-handler]
+  std::signal(SIGINT, A::handler_member);
+  // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: functions with other than C linkage are not allowed as signal handler (until C++17) [bugprone-signal-handler]
+  std::signal(SIGINT, [](int) { printf("xxx"); });
+  // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: lambda function is not allowed as signal handler (until C++17) [bugprone-signal-handler]
+
+  // This case is (deliberately) not found by the checker.
+  std::signal(SIGINT, [](int) -> callback_t { return &handler_unsafe; }(1));
+}
+
+} // namespace test_invalid_handler
+
+namespace test_non_standard_signal_call {
+
+struct Signal {
+  static void signal(int, callback_t);
+};
+
+void test() {
+  // No diagnostics here. All these signal calls differ from the standard system one.
+  signal(SIGINT, handler_unsafe, 1);
+  ns::signal(SIGINT, handler_unsafe);
+  Signal::signal(SIGINT, handler_unsafe);
+  system_other::signal(SIGINT, handler_unsafe);
+}
+
+} // namespace test_non_standard_signal_call
+
+namespace test_cpp_construct_in_handler {
+
+struct Struct {
+  virtual ~Struct() {}
+  void f1();
+  int *begin();
+  int *end();
+  static void f2();
+};
+struct Derived : public Struct {
+};
+
+struct X {
+  X(int, float);
+};
+
+Struct *S_Global;
+const Struct *S_GlobalConst;
+
+void f_non_extern_c() {
+}
+
+void f_default_arg(int P1 = 0) {
+}
+
+extern "C" void handler_cpp(int) {
+  using namespace ::test_cpp_construct_in_handler;
+
+  // These calls are not found as problems.
+  // (Called functions are not analyzed if the current function has already
+  // other problems.)
+  f_non_extern_c();
+  Struct::f2();
+  // 'auto' is not disallowed
+  auto Auto = 28u;
+
+  Struct S;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: C++-only construct is not allowed in signal handler (until C++17) [bugprone-signal-handler]
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: remark: internally, the statement is parsed as a 'CXXConstructExpr'
+  // CHECK-MESSAGES: :198:23: note: function 'handler_cpp' registered here as signal handler
+  S_Global->f1();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: C++-only construct is not allowed in signal handler (until C++17) [bugprone-signal-handler]
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: remark: internally, the statement is parsed as a 'CXXMemberCallExpr'
+  // CHECK-MESSAGES: :198:23: note: function 'handler_cpp' registered here as signal handler
+  const Struct &SRef = Struct();
+  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: C++-only construct is not allowed in signal handler (until C++17) [bugprone-signal-handler]
+  // CHECK-MESSAGES: :[[@LINE-

[PATCH] D105263: [X86] AVX512FP16 instructions enabling 1/6

2022-04-13 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added a comment.

Thanks @vtjnash for the information! Comments on 
https://github.com/JuliaLang/julia/issues/44829


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105263

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


[clang] 93471e6 - [clang] NFC, move CompilerInvocation::setLangDefaults to LangOptions.h

2022-04-13 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-04-13T09:44:39+02:00
New Revision: 93471e65df48372ee59bd0c2f8ba58a254ba1ca5

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

LOG: [clang] NFC, move CompilerInvocation::setLangDefaults to LangOptions.h

The function is moved from clangFrontend to clangBasic, which allows tools
(e.g. clang pseudoparser) which don't depend on clangFrontend to use.

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

Added: 


Modified: 
clang/include/clang/Basic/LangOptions.h
clang/include/clang/Basic/LangStandard.h
clang/include/clang/Frontend/CompilerInvocation.h
clang/lib/Basic/LangOptions.cpp
clang/lib/Basic/LangStandards.cpp
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index f82992877c0b4..b0cc4c98e881e 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -450,6 +450,20 @@ class LangOptions : public LangOptionsBase {
 
   LangOptions();
 
+  /// Set language defaults for the given input language and
+  /// language standard in the given LangOptions object.
+  ///
+  /// \param Opts - The LangOptions object to set up.
+  /// \param Lang - The input language.
+  /// \param T - The target triple.
+  /// \param Includes - If the language requires extra headers to be implicitly
+  ///   included, they will be appended to this list.
+  /// \param LangStd - The input language standard.
+  static void
+  setLangDefaults(LangOptions &Opts, Language Lang, const llvm::Triple &T,
+  std::vector &Includes,
+  LangStandard::Kind LangStd = LangStandard::lang_unspecified);
+
   // Define accessors/mutators for language options of enumeration type.
 #define LANGOPT(Name, Bits, Default, Description)
 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \

diff  --git a/clang/include/clang/Basic/LangStandard.h 
b/clang/include/clang/Basic/LangStandard.h
index fdfd2e7773a87..263985d6b1389 100644
--- a/clang/include/clang/Basic/LangStandard.h
+++ b/clang/include/clang/Basic/LangStandard.h
@@ -12,6 +12,10 @@
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/StringRef.h"
 
+namespace llvm {
+class Triple;
+}
+
 namespace clang {
 
 /// The language for the input, used to select and validate the language
@@ -138,6 +142,9 @@ struct LangStandard {
   static const LangStandard *getLangStandardForName(StringRef Name);
 };
 
+LangStandard::Kind getDefaultLanguageStandard(clang::Language Lang,
+  const llvm::Triple &T);
+
 }  // end namespace clang
 
 #endif

diff  --git a/clang/include/clang/Frontend/CompilerInvocation.h 
b/clang/include/clang/Frontend/CompilerInvocation.h
index 922c84a3bee2c..0753a6632f81e 100644
--- a/clang/include/clang/Frontend/CompilerInvocation.h
+++ b/clang/include/clang/Frontend/CompilerInvocation.h
@@ -219,19 +219,6 @@ class CompilerInvocation : public 
CompilerInvocationRefBase,
   /// executable), for finding the builtin compiler path.
   static std::string GetResourcesPath(const char *Argv0, void *MainAddr);
 
-  /// Set language defaults for the given input language and
-  /// language standard in the given LangOptions object.
-  ///
-  /// \param Opts - The LangOptions object to set up.
-  /// \param IK - The input language.
-  /// \param T - The target triple.
-  /// \param Includes - The affected list of included files.
-  /// \param LangStd - The input language standard.
-  static void
-  setLangDefaults(LangOptions &Opts, InputKind IK, const llvm::Triple &T,
-  std::vector &Includes,
-  LangStandard::Kind LangStd = LangStandard::lang_unspecified);
-
   /// Retrieve a module hash string that is suitable for uniquely
   /// identifying the conditions under which the module was built.
   std::string getModuleHash() const;

diff  --git a/clang/lib/Basic/LangOptions.cpp b/clang/lib/Basic/LangOptions.cpp
index b6dc73d66304d..8c19d7e86795e 100644
--- a/clang/lib/Basic/LangOptions.cpp
+++ b/clang/lib/Basic/LangOptions.cpp
@@ -78,6 +78,126 @@ std::string LangOptions::getOpenCLVersionString() const {
   return Result;
 }
 
+void LangOptions::setLangDefaults(LangOptions &Opts, Language Lang,
+  const llvm::Triple &T,
+  std::vector &Includes,
+  LangStandard::Kind LangStd) {
+  // Set some properties which depend solely on the input kind; it would be 
nice
+  // to move these to the language standard, and have the driver resolve the
+  // input kind + language standard.
+  //
+  // FIXME: Perhaps a better model would be for a single source file to have
+  // mult

[PATCH] D121375: [clang] NFC, move the utility function CompilerInvocation::setLangDefaults to LangOptions.h

2022-04-13 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 rG93471e65df48: [clang] NFC, move 
CompilerInvocation::setLangDefaults to LangOptions.h (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D121375?vs=422412&id=422423#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121375

Files:
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Basic/LangStandard.h
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Basic/LangOptions.cpp
  clang/lib/Basic/LangStandards.cpp
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3173,178 +3173,6 @@
   return Diags.getNumErrors() == NumErrorsBefore;
 }
 
-void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
- const llvm::Triple &T,
- std::vector &Includes,
- LangStandard::Kind LangStd) {
-  // Set some properties which depend solely on the input kind; it would be nice
-  // to move these to the language standard, and have the driver resolve the
-  // input kind + language standard.
-  //
-  // FIXME: Perhaps a better model would be for a single source file to have
-  // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
-  // simultaneously active?
-  if (IK.getLanguage() == Language::Asm) {
-Opts.AsmPreprocessor = 1;
-  } else if (IK.isObjectiveC()) {
-Opts.ObjC = 1;
-  }
-
-  if (LangStd == LangStandard::lang_unspecified) {
-// Based on the base language, pick one.
-switch (IK.getLanguage()) {
-case Language::Unknown:
-case Language::LLVM_IR:
-  llvm_unreachable("Invalid input kind!");
-case Language::OpenCL:
-  LangStd = LangStandard::lang_opencl12;
-  break;
-case Language::OpenCLCXX:
-  LangStd = LangStandard::lang_openclcpp10;
-  break;
-case Language::CUDA:
-  LangStd = LangStandard::lang_cuda;
-  break;
-case Language::Asm:
-case Language::C:
-#if defined(CLANG_DEFAULT_STD_C)
-  LangStd = CLANG_DEFAULT_STD_C;
-#else
-  // The PS4 uses C99 as the default C standard.
-  if (T.isPS4())
-LangStd = LangStandard::lang_gnu99;
-  else
-LangStd = LangStandard::lang_gnu17;
-#endif
-  break;
-case Language::ObjC:
-#if defined(CLANG_DEFAULT_STD_C)
-  LangStd = CLANG_DEFAULT_STD_C;
-#else
-  LangStd = LangStandard::lang_gnu11;
-#endif
-  break;
-case Language::CXX:
-case Language::ObjCXX:
-#if defined(CLANG_DEFAULT_STD_CXX)
-  LangStd = CLANG_DEFAULT_STD_CXX;
-#else
-  LangStd = LangStandard::lang_gnucxx14;
-#endif
-  break;
-case Language::RenderScript:
-  LangStd = LangStandard::lang_c99;
-  break;
-case Language::HIP:
-  LangStd = LangStandard::lang_hip;
-  break;
-case Language::HLSL:
-  LangStd = LangStandard::lang_hlsl2021;
-  break;
-}
-  }
-
-  const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
-  Opts.LangStd = LangStd;
-  Opts.LineComment = Std.hasLineComments();
-  Opts.C99 = Std.isC99();
-  Opts.C11 = Std.isC11();
-  Opts.C17 = Std.isC17();
-  Opts.C2x = Std.isC2x();
-  Opts.CPlusPlus = Std.isCPlusPlus();
-  Opts.CPlusPlus11 = Std.isCPlusPlus11();
-  Opts.CPlusPlus14 = Std.isCPlusPlus14();
-  Opts.CPlusPlus17 = Std.isCPlusPlus17();
-  Opts.CPlusPlus20 = Std.isCPlusPlus20();
-  Opts.CPlusPlus2b = Std.isCPlusPlus2b();
-  Opts.GNUMode = Std.isGNUMode();
-  Opts.GNUCVersion = 0;
-  Opts.HexFloats = Std.hasHexFloats();
-  Opts.ImplicitInt = Std.hasImplicitInt();
-  Opts.WChar = Std.isCPlusPlus();
-  Opts.Digraphs = Std.hasDigraphs();
-
-  Opts.HLSL = IK.getLanguage() == Language::HLSL;
-
-  // Set OpenCL Version.
-  Opts.OpenCL = Std.isOpenCL();
-  if (LangStd == LangStandard::lang_opencl10)
-Opts.OpenCLVersion = 100;
-  else if (LangStd == LangStandard::lang_opencl11)
-Opts.OpenCLVersion = 110;
-  else if (LangStd == LangStandard::lang_opencl12)
-Opts.OpenCLVersion = 120;
-  else if (LangStd == LangStandard::lang_opencl20)
-Opts.OpenCLVersion = 200;
-  else if (LangStd == LangStandard::lang_opencl30)
-Opts.OpenCLVersion = 300;
-  else if (LangStd == LangStandard::lang_openclcpp10)
-Opts.OpenCLCPlusPlusVersion = 100;
-  else if (LangStd == LangStandard::lang_openclcpp2021)
-Opts.OpenCLCPlusPlusVersion = 202100;
-  else if (LangStd == LangStandard::lang_hlsl2015)
-Opts.HLSLVersion = (unsigned)LangOptions::HLSL_2015;
-  else if (LangStd == LangStandard::lang_hlsl2016)
-Opts.HLSLVersion = (unsigned)LangOptions::HLSL_2016;
-  else if (LangStd == L

[clang] 5967528 - [clang][ASTImporter] Fix an import error handling related bug.

2022-04-13 Thread Balázs Kéri via cfe-commits

Author: Balázs Kéri
Date: 2022-04-13T10:11:33+02:00
New Revision: 596752863e27e6b4b89e34ecfcf5317a5bf46b52

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

LOG: [clang][ASTImporter] Fix an import error handling related bug.

This bug can cause that more import errors are generated than necessary
and many objects fail to import. Chance of an invalid AST after these
imports increases.

Reviewed By: martong

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

Added: 


Modified: 
clang/lib/AST/ASTImporter.cpp
clang/unittests/AST/ASTImporterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index b368dbf1d5ce9..d0041b83f7afb 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -138,6 +138,46 @@ namespace clang {
   To->setIsUsed();
   }
 
+  /// How to handle import errors that occur when import of a child declaration
+  /// of a DeclContext fails.
+  class ChildErrorHandlingStrategy {
+/// This context is imported (in the 'from' domain).
+/// It is nullptr if a non-DeclContext is imported.
+const DeclContext *const FromDC;
+/// Ignore import errors of the children.
+/// If true, the context can be imported successfully if a child
+/// of it failed to import. Otherwise the import errors of the child nodes
+/// are accumulated (joined) into the import error object of the parent.
+/// (Import of a parent can fail in other ways.)
+bool const IgnoreChildErrors;
+
+  public:
+ChildErrorHandlingStrategy(const DeclContext *FromDC)
+: FromDC(FromDC), IgnoreChildErrors(!isa(FromDC)) {}
+ChildErrorHandlingStrategy(const Decl *FromD)
+: FromDC(dyn_cast(FromD)),
+  IgnoreChildErrors(!isa(FromD)) {}
+
+/// Process the import result of a child (of the current declaration).
+/// \param ResultErr The import error that can be used as result of
+/// importing the parent. This may be changed by the function.
+/// \param ChildErr Result of importing a child. Can be success or error.
+void handleChildImportResult(Error &ResultErr, Error &&ChildErr) {
+  if (ChildErr && !IgnoreChildErrors)
+ResultErr = joinErrors(std::move(ResultErr), std::move(ChildErr));
+  else
+consumeError(std::move(ChildErr));
+}
+
+/// Determine if import failure of a child does not cause import failure of
+/// its parent.
+bool ignoreChildErrorOnParent(Decl *FromChildD) const {
+  if (!IgnoreChildErrors || !FromDC)
+return false;
+  return FromDC->containsDecl(FromChildD);
+}
+  };
+
   class ASTNodeImporter : public TypeVisitor,
   public DeclVisitor,
   public StmtVisitor {
@@ -1809,7 +1849,7 @@ ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, 
bool ForceImport) {
   // because there is an ODR error with two typedefs.  As another example,
   // the client may allow EnumConstantDecls with same names but with
   // 
diff erent values in two distinct translation units.
-  bool AccumulateChildErrors = isa(FromDC);
+  ChildErrorHandlingStrategy HandleChildErrors(FromDC);
 
   Error ChildErrors = Error::success();
   for (auto *From : FromDC->decls()) {
@@ -1849,20 +1889,14 @@ ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, 
bool ForceImport) {
   if (FromRecordDecl->isCompleteDefinition() &&
   !ToRecordDecl->isCompleteDefinition()) {
 Error Err = ImportDefinition(FromRecordDecl, ToRecordDecl);
-
-if (Err && AccumulateChildErrors)
-  ChildErrors =  joinErrors(std::move(ChildErrors), 
std::move(Err));
-else
-  consumeError(std::move(Err));
+HandleChildErrors.handleChildImportResult(ChildErrors,
+  std::move(Err));
   }
 }
   }
 } else {
-  if (AccumulateChildErrors)
-ChildErrors =
-joinErrors(std::move(ChildErrors), ImportedOrErr.takeError());
-  else
-consumeError(ImportedOrErr.takeError());
+  HandleChildErrors.handleChildImportResult(ChildErrors,
+ImportedOrErr.takeError());
 }
   }
 
@@ -8799,8 +8833,20 @@ Expected ASTImporter::Import(Decl *FromD) {
 
 // Set the error for all nodes which have been created before we
 // recognized the error.
-for (const auto &Path : SavedImportPaths[FromD])
+for (const auto &Path : SavedImportPaths[FromD]) {
+  // The import path contains import-dependency nodes first.
+  // Save the node that was imported as dependency of the current node.
+  Decl *PrevFromDi = FromD;
   for (Decl *FromDi : Path) {
+// 

[PATCH] D122525: [clang][ASTImporter] Fix an import error handling related bug.

2022-04-13 Thread Balázs Kéri 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 rG596752863e27: [clang][ASTImporter] Fix an import error 
handling related bug. (authored by balazske).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122525

Files:
  clang/lib/AST/ASTImporter.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5821,6 +5821,53 @@
   EXPECT_FALSE(ImportedF);
 }
 
+TEST_P(ErrorHandlingTest, DoNotInheritErrorFromNonDependentChild) {
+  // Declarations should not inherit an import error from a child object
+  // if the declaration has no direct dependence to such a child.
+  // For example a namespace should not get import error if one of the
+  // declarations inside it fails to import.
+  // There was a special case in error handling (when "import path circles" are
+  // encountered) when this property was not held. This case is provoked by the
+  // following code.
+  constexpr auto ToTUCode = R"(
+  namespace ns {
+struct Err {
+  char A;
+};
+  }
+  )";
+  constexpr auto FromTUCode = R"(
+  namespace ns {
+struct A {
+  using U = struct Err;
+};
+  }
+  namespace ns {
+struct Err {}; // ODR violation
+void f(A) {}
+  }
+  )";
+
+  Decl *ToTU = getToTuDecl(ToTUCode, Lang_CXX11);
+  static_cast(ToTU);
+  Decl *FromTU = getTuDecl(FromTUCode, Lang_CXX11);
+  auto *FromA = FirstDeclMatcher().match(
+  FromTU, cxxRecordDecl(hasName("A"), hasDefinition()));
+  ASSERT_TRUE(FromA);
+  auto *ImportedA = Import(FromA, Lang_CXX11);
+  // 'A' can not be imported: ODR error at 'Err'
+  EXPECT_FALSE(ImportedA);
+  // When import of 'A' failed there was a "saved import path circle" that
+  // contained namespace 'ns' (A - U - Err - ns - f - A). This should not mean
+  // that every object in this path fails to import.
+
+  Decl *FromNS = FirstDeclMatcher().match(
+  FromTU, namespaceDecl(hasName("ns")));
+  EXPECT_TRUE(FromNS);
+  auto *ImportedNS = Import(FromNS, Lang_CXX11);
+  EXPECT_TRUE(ImportedNS);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionBody) {
   Decl *FromTU = getTuDecl(
   R"(
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -138,6 +138,46 @@
   To->setIsUsed();
   }
 
+  /// How to handle import errors that occur when import of a child declaration
+  /// of a DeclContext fails.
+  class ChildErrorHandlingStrategy {
+/// This context is imported (in the 'from' domain).
+/// It is nullptr if a non-DeclContext is imported.
+const DeclContext *const FromDC;
+/// Ignore import errors of the children.
+/// If true, the context can be imported successfully if a child
+/// of it failed to import. Otherwise the import errors of the child nodes
+/// are accumulated (joined) into the import error object of the parent.
+/// (Import of a parent can fail in other ways.)
+bool const IgnoreChildErrors;
+
+  public:
+ChildErrorHandlingStrategy(const DeclContext *FromDC)
+: FromDC(FromDC), IgnoreChildErrors(!isa(FromDC)) {}
+ChildErrorHandlingStrategy(const Decl *FromD)
+: FromDC(dyn_cast(FromD)),
+  IgnoreChildErrors(!isa(FromD)) {}
+
+/// Process the import result of a child (of the current declaration).
+/// \param ResultErr The import error that can be used as result of
+/// importing the parent. This may be changed by the function.
+/// \param ChildErr Result of importing a child. Can be success or error.
+void handleChildImportResult(Error &ResultErr, Error &&ChildErr) {
+  if (ChildErr && !IgnoreChildErrors)
+ResultErr = joinErrors(std::move(ResultErr), std::move(ChildErr));
+  else
+consumeError(std::move(ChildErr));
+}
+
+/// Determine if import failure of a child does not cause import failure of
+/// its parent.
+bool ignoreChildErrorOnParent(Decl *FromChildD) const {
+  if (!IgnoreChildErrors || !FromDC)
+return false;
+  return FromDC->containsDecl(FromChildD);
+}
+  };
+
   class ASTNodeImporter : public TypeVisitor,
   public DeclVisitor,
   public StmtVisitor {
@@ -1809,7 +1849,7 @@
   // because there is an ODR error with two typedefs.  As another example,
   // the client may allow EnumConstantDecls with same names but with
   // different values in two distinct translation units.
-  bool AccumulateChildErrors = isa(FromDC);
+  ChildErrorHandlingStrategy HandleChildErrors(FromDC);
 
   Error ChildErr

[clang] 2978d02 - [Clang] Remove support for legacy pass manager

2022-04-13 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2022-04-13T10:21:42+02:00
New Revision: 2978d026819b82f77eef42d92b3b53919f375bd8

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

LOG: [Clang] Remove support for legacy pass manager

This removes the -flegacy-pass-manager and
-fno-experimental-new-pass-manager options, and the corresponding
support code in BackendUtil. The -fno-legacy-pass-manager and
-fexperimental-new-pass-manager options are retained as no-ops.

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

Added: 


Modified: 
clang/include/clang/Basic/CodeGenOptions.def
clang/include/clang/Driver/Options.td
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/lib/Frontend/CompilerInvocation.cpp
clang/test/Driver/flegacy-pass-manager.c

Removed: 




diff  --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 720a59ff1bdce..3aef6f75302b5 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -65,7 +65,6 @@ CODEGENOPT(DisableO0ImplyOptNone , 1, 0) ///< Don't annonate 
function with optno
 CODEGENOPT(ExperimentalStrictFloatingPoint, 1, 0) ///< Enables the new, 
experimental
   ///< strict floating point.
 CODEGENOPT(EnableNoundefAttrs, 1, 0) ///< Enable emitting `noundef` attributes 
on IR call arguments and return values
-CODEGENOPT(LegacyPassManager, 1, 0) ///< Use the legacy pass manager.
 CODEGENOPT(DebugPassManager, 1, 0) ///< Prints debug information for the new
///< pass manager.
 CODEGENOPT(DisableRedZone, 1, 0) ///< Set when -mno-red-zone is enabled.

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 322cc800f7525..9ffc79a52b0ed 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1935,15 +1935,10 @@ def fglobal_isel : Flag<["-"], "fglobal-isel">, 
Group,
   HelpText<"Enables the global instruction selector">;
 def fexperimental_isel : Flag<["-"], "fexperimental-isel">, 
Group,
   Alias;
-defm legacy_pass_manager : BoolOption<"f", "legacy-pass-manager",
-  CodeGenOpts<"LegacyPassManager">, DefaultFalse,
-  PosFlag,
-  NegFlag,
-  BothFlags<[CC1Option]>>, Group;
+def fno_legacy_pass_manager : Flag<["-"], "fno-legacy-pass-manager">,
+  Group, Flags<[CC1Option, NoArgumentUnused]>;
 def fexperimental_new_pass_manager : Flag<["-"], 
"fexperimental-new-pass-manager">,
   Group, Flags<[CC1Option]>, Alias;
-def fno_experimental_new_pass_manager : Flag<["-"], 
"fno-experimental-new-pass-manager">,
-  Group, Flags<[CC1Option,NoDriverOption]>, 
Alias;
 def fexperimental_strict_floating_point : Flag<["-"], 
"fexperimental-strict-floating-point">,
   Group, Flags<[CC1Option]>,
   HelpText<"Enables experimental strict floating point in LLVM.">,

diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index c09afefb3cc9a..c78ea45384d72 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -60,7 +60,6 @@
 #include "llvm/Transforms/IPO.h"
 #include "llvm/Transforms/IPO/AlwaysInliner.h"
 #include "llvm/Transforms/IPO/LowerTypeTests.h"
-#include "llvm/Transforms/IPO/PassManagerBuilder.h"
 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
 #include "llvm/Transforms/InstCombine/InstCombine.h"
 #include "llvm/Transforms/Instrumentation.h"
@@ -127,8 +126,6 @@ class EmitAssemblyHelper {
 return TargetIRAnalysis();
   }
 
-  void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager 
&FPM);
-
   /// Generates the TargetMachine.
   /// Leaves TM unchanged if it is unable to create the target machine.
   /// Some of our clang tests specify triples which are not built
@@ -192,60 +189,10 @@ class EmitAssemblyHelper {
 
   std::unique_ptr TM;
 
-  // Emit output using the legacy pass manager for the optimization pipeline.
-  // This will be removed soon when using the legacy pass manager for the
-  // optimization pipeline is no longer supported.
-  void EmitAssemblyWithLegacyPassManager(BackendAction Action,
- std::unique_ptr 
OS);
-
-  // Emit output using the new pass manager for the optimization pipeline. This
-  // is the default.
+  // Emit output using the new pass manager for the optimization pipeline.
   void EmitAssembly(BackendAction Action,
 std::unique_ptr OS);
 };
-
-// We need this wrapper to access LangOpts and CGOpts from extension functions
-// that we add to the PassManagerBuilder.
-class PassManagerBuilderWrapper : public PassManagerBuilder {
-public:
-  PassManagerBu

[PATCH] D123609: [Clang] Remove support for legacy pass manager

2022-04-13 Thread Nikita Popov 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 rG2978d026819b: [Clang] Remove support for legacy pass manager 
(authored by nikic).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D123609?vs=45&id=422427#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123609

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Driver/flegacy-pass-manager.c

Index: clang/test/Driver/flegacy-pass-manager.c
===
--- clang/test/Driver/flegacy-pass-manager.c
+++ clang/test/Driver/flegacy-pass-manager.c
@@ -1,29 +1,13 @@
-// RUN: %clang -### -c -flegacy-pass-manager -fno-legacy-pass-manager %s 2>&1 | FileCheck --check-prefixes=NOWARN,NEW %s
-// RUN: %clang -### -c -fno-legacy-pass-manager -flegacy-pass-manager %s 2>&1 | FileCheck --check-prefixes=NOWARN,LEGACY %s
+/// -fno-legacy-pass-manager and -fexperimental-new-pass-manager are retained
+// as no-ops. The inverted options are no longer supported.
 
-/// -fexperimental-new-pass-manager is a legacy alias. -fno-experimental-new-pass-manager has been removed.
-// RUN: %clang -### -c -fexperimental-new-pass-manager %s 2>&1 | FileCheck --check-prefixes=NOWARN,NEW %s
-// RUN: not %clang -### -fno-experimental-new-pass-manager %s
-
-// NOWARN-NOT: warning: argument unused
-
-// NEW:-fno-legacy-pass-manager
-// NEW-NOT:-flegacy-pass-manager
-
-// LEGACY: -flegacy-pass-manager
-// LEGACY-NOT: -fno-legacy-pass-manager
+// RUN: %clang -### -c -fno-legacy-pass-manager %s 2>&1 | FileCheck %s
+// RUN: not %clang -### -flegacy-pass-manager %s
 
-/// For full/Thin LTO, -fno-legacy-pass-manager passes -plugin-opt=new-pass-manager to the linker (which may not be LLD).
-// RUN: %clang -### -target x86_64-linux -flto -fno-legacy-pass-manager %s 2>&1 | FileCheck --check-prefix=LTO_NEW %s
-// RUN: %clang -### -target x86_64-linux -flto=thin -fexperimental-new-pass-manager %s 2>&1 | FileCheck --check-prefix=LTO_NEW %s
-
-// LTO_NEW:"-plugin-opt=new-pass-manager"
-
-// RUN: %clang -### -target x86_64-linux -flto -flegacy-pass-manager %s 2>&1 | FileCheck --check-prefix=LTO_LEGACY %s
+// RUN: %clang -### -c -fexperimental-new-pass-manager %s 2>&1 | FileCheck %s
+// RUN: not %clang -### -fno-experimental-new-pass-manager %s
 
-// LTO_LEGACY: "-plugin-opt=legacy-pass-manager"
+// Just check that there is no argument unused warning. There is no need to
+// pass any cc1 options.
 
-// RUN: %clang -### -target x86_64-linux -flto %s 2>&1 | FileCheck --check-prefix=DEFAULT %s
-//
-// DEFAULT-NOT: "-plugin-opt=new-pass-manager"
-// DEFAULT-NOT: "-plugin-opt=legacy-pass-manager"
+// CHECK-NOT: warning: argument unused
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -543,11 +543,6 @@
   << A->getSpelling() << T.getTriple();
   }
 
-  if (!CodeGenOpts.ProfileRemappingFile.empty() && CodeGenOpts.LegacyPassManager)
-Diags.Report(diag::err_drv_argument_only_allowed_with)
-<< Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
-<< "-fno-legacy-pass-manager";
-
   return Diags.getNumErrors() == NumErrorsBefore;
 }
 
@@ -1731,10 +1726,6 @@
 
 // -ftime-report= is only for new pass manager.
 if (A->getOption().getID() == OPT_ftime_report_EQ) {
-  if (Opts.LegacyPassManager)
-Diags.Report(diag::err_drv_argument_only_allowed_with)
-<< A->getAsString(Args) << "-fno-legacy-pass-manager";
-
   StringRef Val = A->getValue();
   if (Val == "per-pass")
 Opts.TimePassesPerRun = false;
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -626,15 +626,6 @@
  Path));
   }
 
-  // Pass an option to enable/disable the new pass manager.
-  if (auto *A = Args.getLastArg(options::OPT_flegacy_pass_manager,
-options::OPT_fno_legacy_pass_manager)) {
-if (A->getOption().matches(options::OPT_flegacy_pass_manager))
-  CmdArgs.push_back("-plugin-opt=legacy-pass-manager");
-else
-  CmdArgs.push_back("-plugin-opt=new-pass-manager");
-  }
-
   // Setup statistics file output.
   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
   if (!StatsFile.empty())
Index: clang/l

[PATCH] D123297: [flang][driver] Add support for -mmlir

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

LGTM, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123297

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


[PATCH] D123598: Clean the code, formated and add basic tests for the patch.

2022-04-13 Thread Abid via Phabricator via cfe-commits
abidmalikwaterloo added a comment.

It. should update D122255 . It should not 
create the new one.
--->
I used the following 
arc patch D122255 
"did something"
git commit -a
arc diff
>


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123598

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


[PATCH] D122255: Meta directive runtime support

2022-04-13 Thread Abid via Phabricator via cfe-commits
abidmalikwaterloo added a comment.

There should be an update to D122255 . It 
should not create the new one.D123598 
--->
I did the following :
arc patch D122255 
"did something/cleaning"
git commit -a
arc diff
>


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122255

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


[PATCH] D103094: [analyzer] Implemented RangeSet::Factory::castTo function to perform promotions, truncations and conversions

2022-04-13 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Thanks for you patience Denys! Finally I had some time for the review. Nice 
work!




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h:242
+///
+/// This function optimized for each of the six cast cases:
+/// - noop





Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:358
+  assert(!isEmpty());
+  return begin()->From().isUnsigned();
+}

Probably it is unrelated to this patch, but
Could it happen that `(++begin())->From().isUnsigned()` gives a different 
signedness? Or we had a separate assertion when we  added the second `Range`? 
The same question applies to the below two functions as well. Seems like in 
`unite` we don't have such validity check...



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:687
+
+  if (IsConversion && (!IsPromotion || !What.isUnsigned()))
+return makePersistent(convertTo(What, Ty));

Could you please explain why do we need the `|| !What.isUnsigned()` part of the 
condition?

This would make much more sense to me:
```
if (IsConversion && !IsPromotion)
return makePersistent(convertTo(What, Ty));
```



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:690
+
+  // Promotion from unsigneds to signeds/unsigneds left.
+

martong wrote:
> I think it would be more consistent with the other operations (truncate and 
> convert) if we had this logic in its own separate function: `promoteTo`. And 
> this function should be called only if `isPromotion` is set (?)
This comment is confusing, since we can get here also if
`isConversion` is false and
`isPromotion` is false 



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:690-711
+  // Promotion from unsigneds to signeds/unsigneds left.
+
+  using llvm::APInt;
+  using llvm::APSInt;
+  ContainerType Result;
+  // We definitely know the size of the result set.
+  Result.reserve(What.size());

I think it would be more consistent with the other operations (truncate and 
convert) if we had this logic in its own separate function: `promoteTo`. And 
this function should be called only if `isPromotion` is set (?)



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:740-741
+uint64_t CurrentRangeSize = (ToInt - FromInt).getZExtValue();
+// This is an optimization for specific case when we are enough to cover
+// the whole range.
+Dummy.clear();

?



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:773
+  ContainerType Result;
+  ContainerType Dummy;
+  // Divide the cast into two phases (presented as loops here).

We could certainly have a better name for this. E.g. `SecondHalf`. (And 
`FirstHalf` instead of `Result`?)



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:774-791
+  // Divide the cast into two phases (presented as loops here).
+  // First phase(loop) works when casted values go in ascending order.
+  // E.g. char{1,3,5,127} -> uint{1,3,5,127}
+  // Interrupt the first phase and go to second one when casted values start
+  // go in descending order. That means that we crossed over the middle of
+  // the type value set (aka 0 for signeds and MAX/2+1 for unsigneds).
+  // For instance:

I think this comment would be better positioned as a header comment for the 
entire function.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:792
+  //unite -> uchar(-2, 1)
+  auto CastRange = [Ty, &VF = ValueFactory](const Range &R) -> Bounds {
+// Get bounds of the given range.

Why not `-> Range`?



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:802
+  // Phase 1. Fill the first array.
+  APSInt LastFromInt = Ty.getMinValue();
+  const auto *It = What.begin();

Would it be a better name:`LastConvertedInt`? The naming `From` is confusing 
because that suggests the value we cast from, however, this variable refers to 
the casted to values, isn't it?



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:812-814
+if (NewBounds.first > NewBounds.second) {
+  Dummy.emplace_back(ValueFactory.getMinValue(Ty), NewBounds.second);
+  Result.emplace_back(NewBounds.first, ValueFactory.getMaxValue(Ty));

I think this case (wrap) deserves a comment.



Comment at: clang/unittests/StaticAnalyzer/RangeSetTest.cpp:728
+
+  using TV = TestValues;
+  constexpr auto MIN = TV::MIN;

It doesn't matter, becasue `T` and `F` are equal here, but for consistency with 
the other tests.



Comment at: clang/unittests/StaticAnalyzer/RangeSetTest.cpp:827
+  if (i

[PATCH] D123667: [clang][AST] Fix crash getting name of a template decl

2022-04-13 Thread Tom Eccles via Phabricator via cfe-commits
tblah created this revision.
tblah added a reviewer: rsmith.
Herald added a project: All.
tblah requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

NamedDecl::getIdentifier can return a nullptr when 
DeclarationName::isIdentifier is false, which leads to a null pointer 
dereference when TypePrinter::printTemplateId calls ->getName().

NamedDecl::getName does the same thing in the successful case and returns an 
empty string in the failure case.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123667

Files:
  clang/lib/AST/TypePrinter.cpp


Index: clang/lib/AST/TypePrinter.cpp
===
--- clang/lib/AST/TypePrinter.cpp
+++ clang/lib/AST/TypePrinter.cpp
@@ -1466,8 +1466,7 @@
 if (!Policy.SuppressScope)
   AppendScope(TD->getDeclContext(), OS, TD->getDeclName());
 
-IdentifierInfo *II = TD->getIdentifier();
-OS << II->getName();
+OS << TD->getName();
   } else {
 T->getTemplateName().print(OS, Policy);
   }


Index: clang/lib/AST/TypePrinter.cpp
===
--- clang/lib/AST/TypePrinter.cpp
+++ clang/lib/AST/TypePrinter.cpp
@@ -1466,8 +1466,7 @@
 if (!Policy.SuppressScope)
   AppendScope(TD->getDeclContext(), OS, TD->getDeclName());
 
-IdentifierInfo *II = TD->getIdentifier();
-OS << II->getName();
+OS << TD->getName();
   } else {
 T->getTemplateName().print(OS, Policy);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123211: [flang][driver] Add support for generating LLVM bytecode files

2022-04-13 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:491
+  // Create and configure `TargetMachine`
+  std::unique_ptr TM;
+

ekieri wrote:
> awarzynski wrote:
> > ekieri wrote:
> > > Is there a reason why use TM.reset instead of initialising TM like you do 
> > > with os below?
> > Good question!
> > 
> > Note that [[ 
> > https://github.com/llvm/llvm-project/blob/3d0e0e1027203fe5e89104ad81ee7bb53e525f95/llvm/include/llvm/MC/TargetRegistry.h#L446-L452
> >  | createTargetMachine ]] that I use below returns a plain pointer. [[ 
> > https://github.com/llvm/llvm-project/blob/3d0e0e1027203fe5e89104ad81ee7bb53e525f95/clang/include/clang/Frontend/CompilerInstance.h#L703-L706
> >  | createDefaultOutputFile ]] that I use for initialising `os` below 
> > returns `std::unique_ptr`. IIUC, I can only [[ 
> > https://en.cppreference.com/w/cpp/memory/unique_ptr/reset | reset ]] a 
> > `unique_ptr` (like `TM`) with a plain pointer.
> > 
> > Have I missed anything?
> Well, I had missed that. Thanks! Let's see if I got it right this time.
> 
> So unique_ptr has an _explicit_ constructor taking a raw pointer 
> ([[https://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr | 
> constructor (2)]]). So as you say (if I interpreted you correctly),
> 
>   std::unique_ptr TM = 
> theTarget->createTargetMachine(...);
> 
> does not work, as it requires an implicit conversion from raw to unique 
> pointer. But constructor syntax should (and does for me) work:
> 
>   std::unique_ptr 
> TM(theTarget->createTargetMachine(...));
> 
> as this makes the conversion explicit. Does this make sense, or did I miss 
> something more?
> Does this make sense, or did I miss something more?

Yes, I'm the one who missed something here :) Many thanks for pointing this out!

I convinced myself that I checked this, but clearly I didn't. And I confused 
the copy-assignment with a proper constructor. Every day is a school day!

I'll merge this shortly and I will incorporate your suggestion. Thanks for your 
patience going over this with me :)




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123211

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


[clang] dd56939 - [flang][driver] Add support for generating LLVM bytecode files

2022-04-13 Thread Andrzej Warzynski via cfe-commits

Author: Andrzej Warzynski
Date: 2022-04-13T10:19:56Z
New Revision: dd56939a4b04072a449a05701373e95d00cc494f

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

LOG: [flang][driver] Add support for generating LLVM bytecode files

Support for generating LLVM BC files is added in Flang's compiler and
frontend drivers. This requires the `BitcodeWriterPass` pass to be run
on the input LLVM IR module and is implemented as a dedicated frontend
aciton. The new functionality as seen by the user (compiler driver):
```
flang-new -c -emit-llvm file.90
```
or (frontend driver):
```
flang-new -fc1 -emit-llvm-bc file.f90
```

The new behaviour is consistent with `clang` and `clang -cc1`.

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

Added: 
flang/test/Driver/emit-llvm-bc.f90

Modified: 
clang/include/clang/Driver/Options.td
flang/include/flang/Frontend/FrontendActions.h
flang/include/flang/Frontend/FrontendOptions.h
flang/lib/Frontend/CMakeLists.txt
flang/lib/Frontend/CompilerInvocation.cpp
flang/lib/Frontend/FrontendActions.cpp
flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
flang/test/CMakeLists.txt
flang/test/Driver/driver-help.f90

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 9ffc79a52b0ed..483f0cc549ab4 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5678,8 +5678,6 @@ def emit_header_unit : Flag<["-"], "emit-header-unit">,
   HelpText<"Generate C++20 header units from header files">;
 def emit_pch : Flag<["-"], "emit-pch">,
   HelpText<"Generate pre-compiled header file">;
-def emit_llvm_bc : Flag<["-"], "emit-llvm-bc">,
-  HelpText<"Build ASTs then convert to LLVM, emit .bc file">;
 def emit_llvm_only : Flag<["-"], "emit-llvm-only">,
   HelpText<"Build ASTs and convert to LLVM, discarding output">;
 def emit_codegen_only : Flag<["-"], "emit-codegen-only">,
@@ -6143,6 +6141,8 @@ def emit_obj : Flag<["-"], "emit-obj">,
   HelpText<"Emit native object files">;
 def init_only : Flag<["-"], "init-only">,
   HelpText<"Only execute frontend initialization">;
+def emit_llvm_bc : Flag<["-"], "emit-llvm-bc">,
+  HelpText<"Build ASTs then convert to LLVM, emit .bc file">;
 
 } // let Group = Action_Group
 

diff  --git a/flang/include/flang/Frontend/FrontendActions.h 
b/flang/include/flang/Frontend/FrontendActions.h
index 34cabea590485..48836c6d41e21 100644
--- a/flang/include/flang/Frontend/FrontendActions.h
+++ b/flang/include/flang/Frontend/FrontendActions.h
@@ -192,6 +192,10 @@ class EmitLLVMAction : public CodeGenAction {
   void ExecuteAction() override;
 };
 
+class EmitLLVMBitcodeAction : public CodeGenAction {
+  void ExecuteAction() override;
+};
+
 class BackendAction : public CodeGenAction {
 public:
   enum class BackendActionTy {

diff  --git a/flang/include/flang/Frontend/FrontendOptions.h 
b/flang/include/flang/Frontend/FrontendOptions.h
index 5d97580af5a56..d0459e4bf06ff 100644
--- a/flang/include/flang/Frontend/FrontendOptions.h
+++ b/flang/include/flang/Frontend/FrontendOptions.h
@@ -37,6 +37,9 @@ enum ActionKind {
   /// Emit an .ll file
   EmitLLVM,
 
+  /// Emit a .bc file
+  EmitLLVMBitcode,
+
   /// Emit a .o file.
   EmitObj,
 

diff  --git a/flang/lib/Frontend/CMakeLists.txt 
b/flang/lib/Frontend/CMakeLists.txt
index d6520e705dc9f..45692a5342094 100644
--- a/flang/lib/Frontend/CMakeLists.txt
+++ b/flang/lib/Frontend/CMakeLists.txt
@@ -32,6 +32,7 @@ add_flang_library(flangFrontend
   FIRBuilder
   FIRCodeGen
   FIRTransforms
+  LLVMPasses
   MLIRTransforms
   MLIRLLVMToLLVMIRTranslation
   MLIRSCFToControlFlow

diff  --git a/flang/lib/Frontend/CompilerInvocation.cpp 
b/flang/lib/Frontend/CompilerInvocation.cpp
index d1f427a15005f..ea5accd76bca2 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -148,6 +148,9 @@ static bool ParseFrontendArgs(FrontendOptions &opts, 
llvm::opt::ArgList &args,
 case clang::driver::options::OPT_emit_llvm:
   opts.programAction = EmitLLVM;
   break;
+case clang::driver::options::OPT_emit_llvm_bc:
+  opts.programAction = EmitLLVMBitcode;
+  break;
 case clang::driver::options::OPT_emit_obj:
   opts.programAction = EmitObj;
   break;

diff  --git a/flang/lib/Frontend/FrontendActions.cpp 
b/flang/lib/Frontend/FrontendActions.cpp
index e30f6af7d489a..e93781e87fe00 100644
--- a/flang/lib/Frontend/FrontendActions.cpp
+++ b/flang/lib/Frontend/FrontendActions.cpp
@@ -33,6 +33,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
+#include "llvm/Bitcode/BitcodeWriterPass.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "l

[PATCH] D123211: [flang][driver] Add support for generating LLVM bytecode files

2022-04-13 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdd56939a4b04: [flang][driver] Add support for generating 
LLVM bytecode files (authored by awarzynski).

Changed prior to commit:
  https://reviews.llvm.org/D123211?vs=420862&id=422453#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123211

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/CMakeLists.txt
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm-bc.f90

Index: flang/test/Driver/emit-llvm-bc.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm-bc.f90
@@ -0,0 +1,19 @@
+! Test the options for generating LLVM byte-code `-emit-llvm-bc` option
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang -emit-llvm -c %s -o - | llvm-dis -o - | FileCheck %s
+! RUN: %flang_fc1 -emit-llvm-bc %s -o - | llvm-dis -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -71,6 +71,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm-bc  Build ASTs then convert to LLVM, emit .bc file
 ! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -55,6 +55,7 @@
   fir-opt
   tco
   bbc
+  llvm-dis
   llvm-objdump
   split-file
 )
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -37,6 +37,8 @@
 return std::make_unique();
   case EmitLLVM:
 return std::make_unique();
+  case EmitLLVMBitcode:
+return std::make_unique();
   case EmitObj:
 return std::make_unique(
 BackendAction::BackendActionTy::Backend_EmitObj);
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -33,6 +33,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
+#include "llvm/Bitcode/BitcodeWriterPass.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Passes/PassBuilder.h"
@@ -472,6 +473,48 @@
   llvmModule->print(*os, /*AssemblyAnnotationWriter=*/nullptr);
 }
 
+void EmitLLVMBitcodeAction::ExecuteAction() {
+  CompilerInstance &ci = this->instance();
+  // Generate an LLVM module if it's not already present (it will already be
+  // present if the input file is an LLVM IR/BC file).
+  if (!llvmModule)
+GenerateLLVMIR();
+
+  // Create and configure `Target`
+  std::string error;
+  std::string theTriple = llvmModule->getTargetTriple();
+  const llvm::Target *theTarget =
+  llvm::TargetRegistry::lookupTarget(theTriple, error);
+  assert(theTarget && "Failed to create Target");
+
+  // Create and configure `TargetMachine`
+  std::unique_ptr TM(
+  theTarget->createTargetMachine(theTriple, /*CPU=*/"",
+  /*Features=*/"", llvm::TargetOptions(), llvm::None));
+  assert(TM && "Failed to create TargetMachine");
+  llvmModule->setDataLayout(TM->createDataLayout());
+
+  // Generate an output file
+  std::unique_ptr os = ci.CreateDefaultOutputFile(
+  /*Binary=*/true, /*InFile=*/GetCurrentFileOrBufferName(), "bc");
+  if (!os) {
+unsigned diagID = ci.diagnostics().getCustomDiagID(
+clang::DiagnosticsEngine::Error, "failed to create the output file");
+ci.diagnostics().Report(diagID);
+return;
+  }
+
+  // Set-up the pass manager
+  llvm::ModulePassManager MPM;
+  llvm::ModuleAnalysisManager MAM;
+  llvm::PassBuilder PB(TM.get());
+  PB.registerModuleAnalyses(MAM);
+  MPM.addPass(llvm::BitcodeWriterPass(*os));
+
+  // Run the passes
+  MPM.run(*llvmModule, MAM);
+}
+
 void EmitMLIRAction::ExecuteAc

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-13 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp:15
+#include "mlir/IR/MLIRContext.h"
+#include "mlir/Pass/PassManager.h"
 #include "flang/Frontend/CompilerInstance.h"

rovka wrote:
> Nit: Should these come after the llvm/ headers? (So it's alphabetical except 
> for flang, which may go first)
Thanks, I will fix this before merging!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123297

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


[PATCH] D121915: [RISCV] CLZ Instruction

2022-04-13 Thread Chang Hu via Phabricator via cfe-commits
joker881 added a comment.

wait ,It seems the format problem have not solved,sorry


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121915

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


[clang] 46f83ca - [InlineAsm] Add support for address operands ("p").

2022-04-13 Thread Jonas Paulsson via cfe-commits

Author: Jonas Paulsson
Date: 2022-04-13T12:50:21+02:00
New Revision: 46f83caebc8f2329bcf16b3edf6785dff480c5e3

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

LOG: [InlineAsm] Add support for address operands ("p").

This patch adds support for inline assembly address operands using the "p"
constraint on X86 and SystemZ.

This was in fact broken on X86 (see example at
https://reviews.llvm.org/D110267, Nov 23).

These operands should probably be treated the same as memory operands by
CodeGenPrepare, which have been commented with "TODO" there.

Review: Xiang Zhang and Ulrich Weigand

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

Added: 
clang/test/CodeGen/SystemZ/systemz-inline-asm-03.c
llvm/test/CodeGen/SystemZ/inline-asm-addr.ll
llvm/test/CodeGen/X86/inline-asm-p-constraint.ll

Modified: 
clang/lib/Basic/Targets/SystemZ.h
clang/lib/Basic/Targets/X86.cpp
clang/test/CodeGen/asm.c
llvm/docs/LangRef.rst
llvm/include/llvm/CodeGen/TargetLowering.h
llvm/include/llvm/IR/InlineAsm.h
llvm/lib/CodeGen/CodeGenPrepare.cpp
llvm/lib/CodeGen/GlobalISel/InlineAsmLowering.cpp
llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
llvm/lib/Target/SystemZ/SystemZISelDAGToDAG.cpp
llvm/lib/Target/X86/X86ISelDAGToDAG.cpp

Removed: 




diff  --git a/clang/lib/Basic/Targets/SystemZ.h 
b/clang/lib/Basic/Targets/SystemZ.h
index 92cefeea5d264..f0306642a6656 100644
--- a/clang/lib/Basic/Targets/SystemZ.h
+++ b/clang/lib/Basic/Targets/SystemZ.h
@@ -82,6 +82,16 @@ class LLVM_LIBRARY_VISIBILITY SystemZTargetInfo : public 
TargetInfo {
   bool validateAsmConstraint(const char *&Name,
  TargetInfo::ConstraintInfo &info) const override;
 
+  std::string convertConstraint(const char *&Constraint) const override {
+switch (Constraint[0]) {
+case 'p': // Keep 'p' constraint.
+  return std::string("p");
+default:
+  break;
+}
+return TargetInfo::convertConstraint(Constraint);
+  }
+
   const char *getClobbers() const override {
 // FIXME: Is this really right?
 return "";

diff  --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index 1ec2bb9c249f0..b83b3517ddf90 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -1490,8 +1490,8 @@ std::string X86TargetInfo::convertConstraint(const char 
*&Constraint) const {
 return std::string("{si}");
   case 'D':
 return std::string("{di}");
-  case 'p': // address
-return std::string("im");
+  case 'p': // Keep 'p' constraint (address).
+return std::string("p");
   case 't': // top of floating point stack.
 return std::string("{st}");
   case 'u':// second from top of floating point stack.

diff  --git a/clang/test/CodeGen/SystemZ/systemz-inline-asm-03.c 
b/clang/test/CodeGen/SystemZ/systemz-inline-asm-03.c
new file mode 100644
index 0..3157d0ef62416
--- /dev/null
+++ b/clang/test/CodeGen/SystemZ/systemz-inline-asm-03.c
@@ -0,0 +1,35 @@
+// RUN: %clang_cc1 -no-opaque-pointers -triple s390x-linux-gnu -O2 -emit-llvm \
+// RUN:   -o - %s 2>&1 | FileCheck %s
+// REQUIRES: systemz-registered-target
+
+long *A;
+long Idx;
+unsigned long Addr;
+
+unsigned long fun_BD12_p() {
+// CHECK-LABEL: define{{.*}} i64 @fun_BD12_p()
+// CHECK: call i64 asm "lay $0, $1", "=r,p"(i64* nonnull %arrayidx)
+  asm("lay %0, %1" : "=r" (Addr) : "p" (&A[100]));
+  return Addr;
+}
+
+unsigned long fun_BDX12_p() {
+// CHECK-LABEL: define{{.*}} i64 @fun_BDX12_p()
+// CHECK: call i64 asm "lay $0, $1", "=r,p"(i64* %arrayidx)
+  asm("lay %0, %1" : "=r" (Addr) : "p" (&A[Idx + 100]));
+  return Addr;
+}
+
+unsigned long fun_BD20_p() {
+// CHECK-LABEL: define{{.*}} i64 @fun_BD20_p()
+// CHECK: call i64 asm "lay $0, $1", "=r,p"(i64* nonnull %arrayidx)
+  asm("lay %0, %1" : "=r" (Addr) : "p" (&A[1000]));
+  return Addr;
+}
+
+unsigned long fun_BDX20_p() {
+// CHECK-LABEL: define{{.*}} i64 @fun_BDX20_p()
+// CHECK: call i64 asm "lay $0, $1", "=r,p"(i64* %arrayidx)
+  asm("lay %0, %1" : "=r" (Addr) : "p" (&A[Idx + 1000]));
+  return Addr;
+}

diff  --git a/clang/test/CodeGen/asm.c b/clang/test/CodeGen/asm.c
index 99bcccd33d825..ec7e6d1556cb6 100644
--- a/clang/test/CodeGen/asm.c
+++ b/clang/test/CodeGen/asm.c
@@ -274,3 +274,13 @@ int t32(int cond)
 label_true:
   return 1;
 }
+
+void *t33(void *ptr)
+{
+  void *ret;
+  asm ("lea %1, %0" : "=r" (ret) : "p" (ptr));
+  return ret;
+
+  // CHECK: @t33
+  // CHECK: %1 = call i8* asm "lea $1, $0", 
"=r,p,~{dirflag},~{fpsr},~{flags}"(i8* %0)
+}

diff  --git a/llvm/docs/LangRef.rst b/llvm/docs/LangRef.rst
index 1a218c0a5c756..98e90a65073ad 100644
--- a/llvm/docs/LangRef.rst
+++ b/llvm/docs

[PATCH] D122220: [InlineAsm] Add support for address operands ("p").

2022-04-13 Thread Jonas Paulsson 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 rG46f83caebc8f: [InlineAsm] Add support for address operands 
("p"). (authored by jonpa).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D10?vs=420424&id=422459#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D10

Files:
  clang/lib/Basic/Targets/SystemZ.h
  clang/lib/Basic/Targets/X86.cpp
  clang/test/CodeGen/SystemZ/systemz-inline-asm-03.c
  clang/test/CodeGen/asm.c
  llvm/docs/LangRef.rst
  llvm/include/llvm/CodeGen/TargetLowering.h
  llvm/include/llvm/IR/InlineAsm.h
  llvm/lib/CodeGen/CodeGenPrepare.cpp
  llvm/lib/CodeGen/GlobalISel/InlineAsmLowering.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
  llvm/lib/Target/SystemZ/SystemZISelDAGToDAG.cpp
  llvm/lib/Target/X86/X86ISelDAGToDAG.cpp
  llvm/test/CodeGen/SystemZ/inline-asm-addr.ll
  llvm/test/CodeGen/X86/inline-asm-p-constraint.ll

Index: llvm/test/CodeGen/X86/inline-asm-p-constraint.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/inline-asm-p-constraint.ll
@@ -0,0 +1,11 @@
+; RUN: llc -mtriple=x86_64-unknown-unknown -no-integrated-as < %s 2>&1 | FileCheck %s
+
+define i8* @foo(i8* %ptr) {
+; CHECK-LABEL: foo:
+  %1 = tail call i8* asm "lea $1, $0", "=r,p,~{dirflag},~{fpsr},~{flags}"(i8* %ptr)
+; CHECK:  #APP
+; CHECK-NEXT: lea (%rdi), %rax
+; CHECK-NEXT: #NO_APP
+  ret i8* %1
+; CHECK-NEXT: retq
+}
Index: llvm/test/CodeGen/SystemZ/inline-asm-addr.ll
===
--- /dev/null
+++ llvm/test/CodeGen/SystemZ/inline-asm-addr.ll
@@ -0,0 +1,57 @@
+; RUN: llc -mtriple=s390x-linux-gnu < %s | FileCheck %s
+
+@Addr = global i64 0, align 8
+@A = global i64* null, align 8
+@Idx = global i64 0, align 8
+
+define i64 @fun_BD12_p() {
+; CHECK-LABEL: fun_BD12_p:
+; CHECK: #APP
+; CHECK: lay	%r2, 800(%r1)
+entry:
+  %0 = load i64*, i64** @A
+  %arrayidx = getelementptr inbounds i64, i64* %0, i64 100
+  %1 = tail call i64 asm "lay $0, $1", "=r,p"(i64* nonnull %arrayidx)
+  store i64 %1, i64* @Addr
+  ret i64 %1
+}
+
+define i64 @fun_BDX12_p() {
+; CHECK-LABEL: fun_BDX12_p:
+; CHECK: #APP
+; CHECK: lay	%r2, 800(%r1,%r2)
+entry:
+  %0 = load i64*, i64** @A
+  %1 = load i64, i64* @Idx
+  %add = add nsw i64 %1, 100
+  %arrayidx = getelementptr inbounds i64, i64* %0, i64 %add
+  %2 = tail call i64 asm "lay $0, $1", "=r,p"(i64* %arrayidx)
+  store i64 %2, i64* @Addr
+  ret i64 %2
+}
+
+define i64 @fun_BD20_p() {
+; CHECK-LABEL: fun_BD20_p:
+; CHECK: #APP
+; CHECK: lay	%r2, 8000(%r1)
+entry:
+  %0 = load i64*, i64** @A
+  %arrayidx = getelementptr inbounds i64, i64* %0, i64 1000
+  %1 = tail call i64 asm "lay $0, $1", "=r,p"(i64* nonnull %arrayidx)
+  store i64 %1, i64* @Addr
+  ret i64 %1
+}
+
+define i64 @fun_BDX20_p() {
+; CHECK-LABEL: fun_BDX20_p:
+; CHECK: #APP
+; CHECK: lay	%r2, 8000(%r1,%r2)
+entry:
+  %0 = load i64*, i64** @A
+  %1 = load i64, i64* @Idx
+  %add = add nsw i64 %1, 1000
+  %arrayidx = getelementptr inbounds i64, i64* %0, i64 %add
+  %2 = tail call i64 asm "lay $0, $1", "=r,p"(i64* %arrayidx)
+  store i64 %2, i64* @Addr
+  ret i64 %2
+}
Index: llvm/lib/Target/X86/X86ISelDAGToDAG.cpp
===
--- llvm/lib/Target/X86/X86ISelDAGToDAG.cpp
+++ llvm/lib/Target/X86/X86ISelDAGToDAG.cpp
@@ -6176,6 +6176,7 @@
   case InlineAsm::Constraint_v: // not offsetable??
   case InlineAsm::Constraint_m: // memory
   case InlineAsm::Constraint_X:
+  case InlineAsm::Constraint_p: // address
 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
   return true;
 break;
Index: llvm/lib/Target/SystemZ/SystemZISelDAGToDAG.cpp
===
--- llvm/lib/Target/SystemZ/SystemZISelDAGToDAG.cpp
+++ llvm/lib/Target/SystemZ/SystemZISelDAGToDAG.cpp
@@ -1700,6 +1700,7 @@
   case InlineAsm::Constraint_T:
   case InlineAsm::Constraint_m:
   case InlineAsm::Constraint_o:
+  case InlineAsm::Constraint_p:
 // Accept an address with a long displacement and an index.
 // m works the same as T, as this is the most general case.
 // We don't really have any special handling of "offsettable"
Index: llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
+++ llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
@@ -4908,13 +4908,14 @@
 case 'o': // offsetable
 case 'V': // not offsetable
   return C_Memory;
+case 'p': // Address.
+  return C_Address;
 case 'n': // Simple Integer
 case 'E': // Floating Point Constant
 case '

[PATCH] D122220: [InlineAsm] Add support for address operands ("p").

2022-04-13 Thread Jonas Paulsson via Phabricator via cfe-commits
jonpa added a comment.

-no-opaque-pointers added to SystemZ clang test, per 532dc62 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D10

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


[PATCH] D123667: [clang][AST] Fix crash getting name of a template decl

2022-04-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman edited reviewers, added: aaron.ballman; removed: lattner.
aaron.ballman added a comment.

This looks good in general, but can you add a test case for the scenario which 
previously crashed and a release note for the fix?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123667

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


[PATCH] D123668: [Testing] TestAST, a helper for writing straight-line AST tests

2022-04-13 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: hokein.
Herald added subscribers: usaxena95, kadircet, mgorny.
Herald added a project: All.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, ilya-biryukov.
Herald added a project: clang.

Tests that need ASTs have to deal with the awkward control flow of
FrontendAction in some way. There are a few idioms used:

- don't bother with unit tests, use clang -dump-ast
- create an ASTConsumer by hand, which is bulky
- use ASTMatchFinder - works pretty well if matchers are actually needed, very 
strange if they are not
- use ASTUnit - this yields nice straight-line code, but ASTUnit is a 
terrifically complicated library not designed for this purpose

TestAST provides a very simple way to write straight-line tests: specify
the code/flags and it provides an AST that is kept alive until the
object is destroyed.
It's loosely modeled after TestTU in clangd, which we've successfully
used for a variety of tests.

I've updated a couple of clang tests to use this helper, IMO they're clearer.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123668

Files:
  clang/include/clang/Basic/Diagnostic.h
  clang/include/clang/Testing/CommandLineArgs.h
  clang/include/clang/Testing/TestAST.h
  clang/lib/Basic/Diagnostic.cpp
  clang/lib/Testing/CMakeLists.txt
  clang/lib/Testing/CommandLineArgs.cpp
  clang/lib/Testing/TestAST.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/FixItTest.cpp
  clang/unittests/Tooling/StandardLibraryTest.cpp

Index: clang/unittests/Tooling/StandardLibraryTest.cpp
===
--- clang/unittests/Tooling/StandardLibraryTest.cpp
+++ clang/unittests/Tooling/StandardLibraryTest.cpp
@@ -7,10 +7,10 @@
 //===--===//
 
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
+#include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclarationName.h"
-#include "clang/Frontend/ASTUnit.h"
-#include "clang/Tooling/Tooling.h"
+#include "clang/Testing/TestAST.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/ScopedPrinter.h"
@@ -24,10 +24,9 @@
 namespace tooling {
 namespace {
 
-const NamedDecl &lookup(ASTUnit &AST, llvm::StringRef Name) {
-  auto &Ctx = AST.getASTContext();
-  TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
-  auto Result = TU->lookup(DeclarationName(&Ctx.Idents.get(Name)));
+const NamedDecl &lookup(TestAST &AST, llvm::StringRef Name) {
+  TranslationUnitDecl *TU = AST.context().getTranslationUnitDecl();
+  auto Result = TU->lookup(DeclarationName(&AST.context().Idents.get(Name)));
   assert(!Result.empty() && "Lookup failed");
   assert(Result.isSingleResult() && "Lookup returned multiple results");
   return *Result.front();
@@ -50,7 +49,7 @@
 }
 
 TEST(StdlibTest, Recognizer) {
-  std::unique_ptr AST = buildASTFromCode(R"cpp(
+  TestAST AST(R"cpp(
 namespace std {
 inline namespace inl {
 
@@ -83,17 +82,15 @@
 div_t div;
   )cpp");
 
-  auto &VectorNonstd = lookup(*AST, "vector");
-  auto *Vec =
-  cast(lookup(*AST, "vec")).getType()->getAsCXXRecordDecl();
+  auto &VectorNonstd = lookup(AST, "vector");
+  auto *Vec = cast(lookup(AST, "vec")).getType()->getAsCXXRecordDecl();
   auto *Nest =
-  cast(lookup(*AST, "nest")).getType()->getAsCXXRecordDecl();
+  cast(lookup(AST, "nest")).getType()->getAsCXXRecordDecl();
   auto *Clock =
-  cast(lookup(*AST, "clock")).getType()->getAsCXXRecordDecl();
-  auto *Sec =
-  cast(lookup(*AST, "sec")).getType()->getAsCXXRecordDecl();
+  cast(lookup(AST, "clock")).getType()->getAsCXXRecordDecl();
+  auto *Sec = cast(lookup(AST, "sec")).getType()->getAsCXXRecordDecl();
   auto *CDivT =
-  cast(lookup(*AST, "div")).getType()->getAsCXXRecordDecl();
+  cast(lookup(AST, "div")).getType()->getAsCXXRecordDecl();
 
   stdlib::Recognizer Recognizer;
 
Index: clang/unittests/Tooling/FixItTest.cpp
===
--- clang/unittests/Tooling/FixItTest.cpp
+++ clang/unittests/Tooling/FixItTest.cpp
@@ -6,9 +6,11 @@
 //
 //===--===//
 
-#include "TestVisitor.h"
-#include "clang/Basic/Diagnostic.h"
 #include "clang/Tooling/FixIt.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Testing/TestAST.h"
+#include "gtest/gtest.h"
 
 using namespace clang;
 
@@ -18,214 +20,169 @@
 
 namespace {
 
-struct CallsVisitor : TestVisitor {
-  bool VisitCallExpr(CallExpr *Expr) {
-OnCall(Expr, Context);
-return true;
-  }
-
-  std::function OnCall;
-};
-
-std::string LocationToString(SourceLocation Loc, ASTContext *Context) {
-  return Loc.printToString(Context->getSourceManager());
+const CallExpr &onlyCall(ASTContext &Ctx) {
+  using n

[PATCH] D119221: [clang][lexer] Allow u8 character literal prefixes in C2x

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

The changes LGTM (thanks for filing the issue). Please wait a day or so for Tom 
to sign off though (I've pinged him off-list).


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

https://reviews.llvm.org/D119221

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


[PATCH] D123648: Restrict lvalue-to-rvalue conversions in CGExprConstant.

2022-04-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM, thanks for catching this (sorry, pretty sure this was my bug)!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123648

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


[PATCH] D123544: [randstruct] Automatically randomize a structure of function pointers

2022-04-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D123544#3446814 , @void wrote:

> In D123544#3446416 , @aaron.ballman 
> wrote:
>
>> However, I had forgotten that the base feature *requires* the user to pass a 
>> randomization seed via a flag in addition to requiring the attribute (thank 
>> you for bringing that back to my attention). Because this feature requires a 
>> feature flag to enable it, this behavior *is* a conforming extension (the 
>> user has to take an action to get the new behavior). That said, I'm still 
>> not convinced we want to do this automagically for users -- it's *really* 
>> easy for that flag to be set in a makefile somewhere and the user has no 
>> idea that their (non-designated) initialization is now a security 
>> vulnerability. If we had error diagnostics when the user is about to shoot 
>> their foot off, I'd be more comfortable with the automatic hardening 
>> behavior.
>
> We should definitely emit an error if a user is trying to use a default 
> initializer for a structure that's up for randomization. It's something that 
> affects the whole feature, not just structs of function pointers.

Agreed.

> Let me work on that. But otherwise are you okay with this patch?

Yes, I'm okay with the direction of this patch. However, because this still 
automatically randomizes some structure layouts once the user passes the flag, 
I think the diagnostic above should perhaps land first unless there's some 
strong reason not to. (To be honest, I probably should have insisted on it in 
the first patch, but this one feels significantly more dangerous because it 
involves function pointers specifically and is more of an "automatic" feature 
than the first patch.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123544

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


[PATCH] D123127: [AST] Add a new TemplateName for templates found via a using declaration.

2022-04-13 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.

Nice fix! Just nits




Comment at: clang/include/clang/AST/TemplateName.h:197
   using StorageType =
-  llvm::PointerUnion;

nit: I'd use Decl here instead of NamedDecl.

Sure, the lowest common type is NamedDecl, but that's not really important and 
we don't use any of the NamedDecl interface.



Comment at: clang/include/clang/AST/TemplateName.h:303
+  ///
+  /// The underlying template declaration is not stored in the template name, 
it
+  /// can be retrieved via the using shadow declaration.

I think this second sentence is confusing rather than helpful to understanding 
to use this class (as opposed to its implementation).

The main way to get the underlying declaration is with `getAsTemplateDecl()`. 
From a public POV, a Using name has a using shadow decl *and* a template decl, 
the fact that we only store one of these is an implementation detail.



Comment at: clang/include/clang/AST/TemplateName.h:305
+  /// can be retrieved via the using shadow declaration.
+  UsingShadowDecl *getAsUsingShadowDecl() const;
+

If (after followup patches) you have a qualified name Q wrapping a using name 
U, I'd expect Q.getAsUsingShadowDecl() to extract the pointer from U.storage.

I'd expect this based on the first sentence of the comment here, and also 
consistent with getAsTemplateDecl() which does this sort of unwrapping.

So no changes needed if you're OK with adding that unwrapping behavior in the 
next patch, otherwise I think we need to think a bit about how to set 
expectations with this API.



Comment at: clang/lib/AST/TemplateName.cpp:86
+  if (auto *ND = Storage.dyn_cast()) {
+if (isa(ND))
+  return Template;

nit: invert this so that UsingShadowDecl is the special case and TemplateDecl 
the general one?



Comment at: clang/lib/AST/TemplateName.cpp:112
+  return TD;
+assert(isa(TemplateOrUsing));
+return cast(

and again here



Comment at: clang/lib/AST/TemplateName.cpp:256
+//
+// Similar to the UsingType behavior, std::vector is much more common, and
+// provides more information in practice, we print the underlying template

I don't understand what "std::vector is much more common" there's no ground 
truth for us to observe.
Rather maybe "using declarations are used to import names more often than to 
export them, and using the original name is most useful in this case"?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123127

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


[PATCH] D123300: [Clang] Enable opaque pointers by default

2022-04-13 Thread Paul Walker via Phabricator via cfe-commits
paulwalker-arm added a comment.

We've spotted some breakages caused by this patch within the llvm test suite 
when built for AArch64-SVE.  I've got https://reviews.llvm.org/D123670 as a WIP 
fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123300

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


[PATCH] D122468: [clang-format] Fix SeparateDefinitionBlocks breaking up function-try-block.

2022-04-13 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 422479.
curdeius marked 5 inline comments as done.
curdeius added a comment.

Address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122468

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/DefinitionBlockSeparatorTest.cpp


Index: clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
===
--- clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -43,7 +43,8 @@
 
   static void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
 const FormatStyle &Style = getLLVMStyle(),
-llvm::StringRef ExpectedCode = "") {
+llvm::StringRef ExpectedCode = "",
+bool Inverse = true) {
 ::testing::ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 bool HasOriginalCode = true;
 if (ExpectedCode == "") {
@@ -51,16 +52,18 @@
   HasOriginalCode = false;
 }
 
-FormatStyle InverseStyle = Style;
-if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
-  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
-else
-  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
 EXPECT_EQ(ExpectedCode, separateDefinitionBlocks(ExpectedCode, Style))
 << "Expected code is not stable";
-EXPECT_NE(ExpectedCode,
-  separateDefinitionBlocks(ExpectedCode, InverseStyle))
-<< "Inverse formatting makes no difference";
+if (Inverse) {
+  FormatStyle InverseStyle = Style;
+  if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
+InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
+  else
+InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  EXPECT_NE(ExpectedCode,
+separateDefinitionBlocks(ExpectedCode, InverseStyle))
+  << "Inverse formatting makes no difference";
+}
 std::string CodeToFormat =
 HasOriginalCode ? Code.str() : removeEmptyLines(Code);
 std::string Result = separateDefinitionBlocks(CodeToFormat, Style);
@@ -448,6 +451,32 @@
Style);
 }
 
+TEST_F(DefinitionBlockSeparatorTest, TryBlocks) {
+  FormatStyle Style = getLLVMStyle();
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  Style.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  verifyFormat("void FunctionWithInternalTry()\n"
+   "{\n"
+   "  try\n"
+   "  {\n"
+   "return;\n"
+   "  }\n"
+   "  catch (const std::exception &)\n"
+   "  {\n"
+   "  }\n"
+   "}",
+   Style, "", /*Inverse=*/false);
+  verifyFormat("void FunctionWithTryBlock()\n"
+   "try\n"
+   "{\n"
+   "  return;\n"
+   "}\n"
+   "catch (const std::exception &)\n"
+   "{\n"
+   "}",
+   Style, "", /*Inverse=*/false);
+}
+
 TEST_F(DefinitionBlockSeparatorTest, Leave) {
   FormatStyle Style = getLLVMStyle();
   Style.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2603,6 +2603,7 @@
   nextToken();
 }
 NeedsUnwrappedLine = false;
+Line->MustBeDeclaration = false;
 CompoundStatementIndenter Indenter(this, Style, Line->Level);
 parseBlock();
 if (Style.BraceWrapping.BeforeCatch)


Index: clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
===
--- clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -43,7 +43,8 @@
 
   static void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
 const FormatStyle &Style = getLLVMStyle(),
-llvm::StringRef ExpectedCode = "") {
+llvm::StringRef ExpectedCode = "",
+bool Inverse = true) {
 ::testing::ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 bool HasOriginalCode = true;
 if (ExpectedCode == "") {
@@ -51,16 +52,18 @@
   HasOriginalCode = false;
 }
 
-FormatStyle InverseStyle = Style;
-if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
-  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
-else
-  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
 EXPECT_EQ(ExpectedCode, separateDefinitionBlocks(ExpectedCode, Style))

[PATCH] D123672: [clangd] Export preamble AST and serialized size as metrics

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

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123672

Files:
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/TUScheduler.cpp

Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -110,6 +110,11 @@
 constexpr trace::Metric PreambleBuildFilesystemLatencyRatio(
 "preamble_fs_latency_ratio", trace::Metric::Distribution, "build_type");
 
+constexpr trace::Metric PreambleBuildSize("preamble_build_size",
+  trace::Metric::Distribution);
+constexpr trace::Metric PreambleSerializedSize("preamble_serialized_size",
+   trace::Metric::Distribution);
+
 void reportPreambleBuild(const PreambleBuildStats &Stats,
  bool IsFirstPreamble) {
   auto RecordWithLabel = [&Stats](llvm::StringRef Label) {
@@ -122,6 +127,9 @@
   static llvm::once_flag OnceFlag;
   llvm::call_once(OnceFlag, [&] { RecordWithLabel("first_build"); });
   RecordWithLabel(IsFirstPreamble ? "first_build_for_file" : "rebuild");
+
+  PreambleBuildSize.record(Stats.BuildSize);
+  PreambleSerializedSize.record(Stats.SerializedSize);
 }
 
 class ASTWorker;
Index: clang-tools-extra/clangd/Preamble.h
===
--- clang-tools-extra/clangd/Preamble.h
+++ clang-tools-extra/clangd/Preamble.h
@@ -83,6 +83,14 @@
   double TotalBuildTime;
   /// Time spent in filesystem operations during the build, in seconds.
   double FileSystemTime;
+
+  /// Estimate of the memory used while building the preamble.
+  /// This memory has been released when buildPreamble returns.
+  /// For example, this includes the size of the in-memory AST (ASTContext).
+  size_t BuildSize;
+  /// The serialized size of the preamble.
+  /// This storage is needed while the preamble is used (but may be on disk).
+  size_t SerializedSize;
 };
 
 /// Build a preamble for the new inputs unless an old one can be reused.
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -64,8 +64,9 @@
 
 class CppFilePreambleCallbacks : public PreambleCallbacks {
 public:
-  CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
-  : File(File), ParsedCallback(ParsedCallback) {}
+  CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback,
+   PreambleBuildStats *Stats)
+  : File(File), ParsedCallback(ParsedCallback), Stats(Stats) {}
 
   IncludeStructure takeIncludes() { return std::move(Includes); }
 
@@ -88,6 +89,25 @@
 IsMainFileIncludeGuarded =
 CI.getPreprocessor().getHeaderSearchInfo().isFileMultipleIncludeGuarded(
 MainFE);
+
+if (Stats) {
+  const ASTContext &AST = CI.getASTContext();
+  Stats->BuildSize = AST.getASTAllocatedMemory();
+  Stats->BuildSize += AST.getSideTableAllocatedMemory();
+  Stats->BuildSize += AST.Idents.getAllocator().getTotalMemory();
+  Stats->BuildSize += AST.Selectors.getTotalMemory();
+
+  Stats->BuildSize += AST.getSourceManager().getContentCacheSize();
+  Stats->BuildSize += AST.getSourceManager().getDataStructureSizes();
+  Stats->BuildSize +=
+  AST.getSourceManager().getMemoryBufferSizes().malloc_bytes;
+
+  const Preprocessor &PP = CI.getPreprocessor();
+  Stats->BuildSize += PP.getTotalMemory();
+  if (PreprocessingRecord *PRec = PP.getPreprocessingRecord())
+Stats->BuildSize += PRec->getTotalMemory();
+  Stats->BuildSize += PP.getHeaderSearchInfo().getTotalMemory();
+}
   }
 
   void BeforeExecute(CompilerInstance &CI) override {
@@ -135,6 +155,7 @@
   std::unique_ptr IWYUHandler = nullptr;
   const clang::LangOptions *LangOpts = nullptr;
   const SourceManager *SourceMgr = nullptr;
+  PreambleBuildStats *Stats;
 };
 
 // Represents directives other than includes, where basic textual information is
@@ -456,7 +477,7 @@
   // to read back. We rely on dynamic index for the comments instead.
   CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
-  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback);
+  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback, Stats);
   auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
   llvm::SmallString<32> AbsFileName(FileName);
   VFS->makeAbsolute(AbsFileName);
@@ -476,6 +497,12

[PATCH] D123672: [clangd] Export preamble AST and serialized size as metrics

2022-04-13 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz added inline comments.



Comment at: clang-tools-extra/clangd/Preamble.cpp:500
 
+  if (Stats != nullptr) {
+Stats->TotalBuildTime = PreambleTimer.getTime();

This is a significant change. You are now exporting this information for failed 
preamble builds. Do you think these are interesting? It might make the data a 
bit confusing (i.e. lots of small "built in <1s, did not read any files) when 
something is really wrong with preamble.

I think we should either only export on successful preamble OR add a boolean 
"success" dimension to the metric.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123672

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


[clang] 385e7df - Correctly diagnose prototype redeclaration errors in C

2022-04-13 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-04-13T08:21:31-04:00
New Revision: 385e7df33046d7292612ee1e3ac00a59d8bc0441

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

LOG: Correctly diagnose prototype redeclaration errors in C

We did not implement C99 6.7.5.3p15 fully in that we missed the rule
for compatible function types where a prior declaration has a prototype
and a subsequent definition (not just declaration) has an empty
identifier list or an identifier list with a mismatch in parameter
arity. This addresses that situation by issuing an error on code like:

void f(int);
void f() {} // type conflicts with previous declaration

(Note: we already diagnose the other type conflict situations
appropriately, this was the only situation we hadn't covered that I
could find.)

Added: 
clang/test/Sema/prototype-redecls.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/CodeGen/functions.c
clang/test/Sema/predefined-function.c
clang/test/Sema/warn-deprecated-non-prototype.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a1ff6f8787bb1..91fc57dfac595 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -144,6 +144,10 @@ Improvements to Clang's diagnostics
   cases where the deprecated declarations or definitions of a function without
   a prototype will change behavior in C2x. This diagnostic is grouped under the
   ``-Wstrict-prototypes`` warning group, but is enabled by default.
+- Clang now appropriately issues an error in C when a definition of a function
+  without a prototype and with no arguments is an invalid redeclaration of a
+  function with a prototype. e.g., ``void f(int); void f() {}`` is now properly
+  diagnosed.
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index e368726d11c66..fae0ca1fa1e09 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2803,7 +2803,7 @@ class Sema final {
   // Returns true if the function declaration is a redeclaration
   bool CheckFunctionDeclaration(Scope *S,
 FunctionDecl *NewFD, LookupResult &Previous,
-bool IsMemberSpecialization);
+bool IsMemberSpecialization, bool DeclIsDefn);
   bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
   bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
   QualType NewT, QualType OldT);
@@ -3495,7 +3495,7 @@ class Sema final {
   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
 LookupResult &OldDecls);
   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
- bool MergeTypeWithOld);
+ bool MergeTypeWithOld, bool NewDeclIsDefn);
   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
 Scope *S, bool MergeTypeWithOld);
   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index cd9e6d56a5aee..706b3daf918dc 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -3397,8 +3397,8 @@ static void 
adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
 /// merged with.
 ///
 /// Returns true if there was an error, false otherwise.
-bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
- Scope *S, bool MergeTypeWithOld) {
+bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
+ bool MergeTypeWithOld, bool NewDeclIsDefn) {
   // Verify the old decl was also a function.
   FunctionDecl *Old = OldD->getAsFunction();
   if (!Old) {
@@ -3880,6 +3880,25 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, 
NamedDecl *&OldD,
   // C: Function types need to be compatible, not identical. This handles
   // duplicate function decls like "void f(int); void f(enum X);" properly.
   if (!getLangOpts().CPlusPlus) {
+// C99 6.7.5.3p15: ...If one type has a parameter type list and the other
+// type is specified by a function definition that contains a (possibly
+// empty) identifier list, both shall agree in the number of parameters
+// and the type of each parameter shall be compatible with the type that
+// results from the application of default argument promotions to the
+// type of the c

[PATCH] D123627: Correctly diagnose prototype redeclaration errors in C

2022-04-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman marked an inline comment as done.
aaron.ballman added a comment.

Thank you for the reviews, I've landed in 
385e7df33046d7292612ee1e3ac00a59d8bc0441 
.




Comment at: clang/test/Sema/warn-deprecated-non-prototype.c:64-70
 // FIXME: we get two diagnostics here when running in pedantic mode. The first
 // comes when forming the function type for the definition, and the second
 // comes from merging the function declarations together. The second is the
 // point at which we know the behavior has changed (because we can see the
 // previous declaration at that point), but we've already issued the type
 // warning by that point. It's not ideal to be this chatty, but this situation
 // should be pretty rare.

jyknight wrote:
> Reword to indicate that the second diagnostic is now an error.
Good catch!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123627

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


[PATCH] D121915: [RISCV] CLZ Instruction

2022-04-13 Thread Chang Hu via Phabricator via cfe-commits
joker881 updated this revision to Diff 422487.
joker881 added a comment.

upadated test files, fixed the format problem


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121915

Files:
  clang/include/clang/Basic/BuiltinsRISCV.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c
  clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c


Index: clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c
===
--- clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c
+++ clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c
@@ -25,3 +25,27 @@
 long orc_b_64(long a) {
   return __builtin_riscv_orc_b_64(a);
 }
+
+// RV64ZBB-LABEL: @clz_32(
+// RV64ZBB-NEXT:  entry:
+// RV64ZBB-NEXT:[[A_ADDR:%.*]] = alloca i32, align 4
+// RV64ZBB-NEXT:store i32 [[A:%.*]], i32* [[A_ADDR]], align 4
+// RV64ZBB-NEXT:[[TMP0:%.*]] = load i32, i32* [[A_ADDR]], align 4
+// RV64ZBB-NEXT:[[TMP1:%.*]] = call i32 @llvm.ctlz.i32(i32 [[TMP0]], i1 
false)
+// RV64ZBB-NEXT:ret i32 [[TMP1]]
+//
+int clz_32(int a) {
+  return __builtin_riscv_clz_32(a);
+}
+
+// RV64ZBB-LABEL: @clz_64(
+// RV64ZBB-NEXT:  entry:
+// RV64ZBB-NEXT:[[A_ADDR:%.*]] = alloca i64, align 8
+// RV64ZBB-NEXT:store i64 [[A:%.*]], i64* [[A_ADDR]], align 8
+// RV64ZBB-NEXT:[[TMP0:%.*]] = load i64, i64* [[A_ADDR]], align 8
+// RV64ZBB-NEXT:[[TMP1:%.*]] = call i64 @llvm.ctlz.i64(i64 [[TMP0]], i1 
false)
+// RV64ZBB-NEXT:ret i64 [[TMP1]]
+//
+long clz_64(long a) {
+  return __builtin_riscv_clz_64(a);
+}
\ No newline at end of file
Index: clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c
===
--- clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c
+++ clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c
@@ -13,3 +13,15 @@
 int orc_b_32(int a) {
   return __builtin_riscv_orc_b_32(a);
 }
+
+// RV32ZBB-LABEL: @clz_32(
+// RV32ZBB-NEXT:  entry:
+// RV32ZBB-NEXT:[[A_ADDR:%.*]] = alloca i32, align 4
+// RV32ZBB-NEXT:store i32 [[A:%.*]], i32* [[A_ADDR]], align 4
+// RV32ZBB-NEXT:[[TMP0:%.*]] = load i32, i32* [[A_ADDR]], align 4
+// RV32ZBB-NEXT:[[TMP1:%.*]] = call i32 @llvm.ctlz.i32(i32 [[TMP0]], i1 
false)
+// RV32ZBB-NEXT:ret i32 [[TMP1]]
+//
+int clz_32(int a) {
+  return __builtin_riscv_clz_32(a);
+}
\ No newline at end of file
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -18861,6 +18861,8 @@
   default: llvm_unreachable("unexpected builtin ID");
   case RISCV::BI__builtin_riscv_orc_b_32:
   case RISCV::BI__builtin_riscv_orc_b_64:
+  case RISCV::BI__builtin_riscv_clz_32:
+  case RISCV::BI__builtin_riscv_clz_64:
   case RISCV::BI__builtin_riscv_clmul:
   case RISCV::BI__builtin_riscv_clmulh:
   case RISCV::BI__builtin_riscv_clmulr:
@@ -18906,6 +18908,11 @@
 case RISCV::BI__builtin_riscv_orc_b_64:
   ID = Intrinsic::riscv_orc_b;
   break;
+case RISCV::BI__builtin_riscv_clz_32:
+case RISCV::BI__builtin_riscv_clz_64: {
+  Function *F = CGM.getIntrinsic(Intrinsic::ctlz, Ops[0]->getType());
+  return Builder.CreateCall(F, {Ops[0], Builder.getInt1(false)});
+}
 
 // Zbc
 case RISCV::BI__builtin_riscv_clmul:
Index: clang/include/clang/Basic/BuiltinsRISCV.def
===
--- clang/include/clang/Basic/BuiltinsRISCV.def
+++ clang/include/clang/Basic/BuiltinsRISCV.def
@@ -18,6 +18,8 @@
 // Zbb extension
 TARGET_BUILTIN(__builtin_riscv_orc_b_32, "ZiZi", "nc", "zbb")
 TARGET_BUILTIN(__builtin_riscv_orc_b_64, "WiWi", "nc", "zbb,64bit")
+TARGET_BUILTIN(__builtin_riscv_clz_32, "ZiZi", "nc", "zbb")
+TARGET_BUILTIN(__builtin_riscv_clz_64, "WiWi", "nc", "zbb,64bit")
 
 // Zbc or Zbkc extension
 TARGET_BUILTIN(__builtin_riscv_clmul, "LiLiLi", "nc", "zbc|zbkc")


Index: clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c
===
--- clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c
+++ clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c
@@ -25,3 +25,27 @@
 long orc_b_64(long a) {
   return __builtin_riscv_orc_b_64(a);
 }
+
+// RV64ZBB-LABEL: @clz_32(
+// RV64ZBB-NEXT:  entry:
+// RV64ZBB-NEXT:[[A_ADDR:%.*]] = alloca i32, align 4
+// RV64ZBB-NEXT:store i32 [[A:%.*]], i32* [[A_ADDR]], align 4
+// RV64ZBB-NEXT:[[TMP0:%.*]] = load i32, i32* [[A_ADDR]], align 4
+// RV64ZBB-NEXT:[[TMP1:%.*]] = call i32 @llvm.ctlz.i32(i32 [[TMP0]], i1 false)
+// RV64ZBB-NEXT:ret i32 [[TMP1]]
+//
+int clz_32(int a) {
+  return __builtin_riscv_clz_32(a);
+}
+
+// RV64ZBB-LABEL: @clz_64(
+// RV64ZBB-NEXT:  entry:
+// RV64ZBB-NEXT:[[A_ADDR:%.*]] = alloca i64, align 8
+// RV64ZBB-NEXT:store i64 [[A:%.*]],

[PATCH] D123672: [clangd] Export preamble AST and serialized size as metrics

2022-04-13 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/Preamble.cpp:500
 
+  if (Stats != nullptr) {
+Stats->TotalBuildTime = PreambleTimer.getTime();

adamcz wrote:
> This is a significant change. You are now exporting this information for 
> failed preamble builds. Do you think these are interesting? It might make the 
> data a bit confusing (i.e. lots of small "built in <1s, did not read any 
> files) when something is really wrong with preamble.
> 
> I think we should either only export on successful preamble OR add a boolean 
> "success" dimension to the metric.
This doesn't change what is exported, that's still controlled by TUScheduler in 
the same way (only exporting on success).

It just changes the behavior of this function: it now populates stats instead 
of leaving them uninitialized. The function already returns a success dimension 
(either the returned pointer is null or not).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123672

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


[clang-tools-extra] f407c9e - [clangd] Export preamble AST and serialized size as metrics

2022-04-13 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-04-13T14:43:06+02:00
New Revision: f407c9ed1057c4093cd09c0f8cee16f68c63157e

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

LOG: [clangd] Export preamble AST and serialized size as metrics

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

Added: 


Modified: 
clang-tools-extra/clangd/Preamble.cpp
clang-tools-extra/clangd/Preamble.h
clang-tools-extra/clangd/TUScheduler.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Preamble.cpp 
b/clang-tools-extra/clangd/Preamble.cpp
index b3a3aec985ba0..0cc5b65a94d64 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -64,8 +64,9 @@ bool compileCommandsAreEqual(const tooling::CompileCommand 
&LHS,
 
 class CppFilePreambleCallbacks : public PreambleCallbacks {
 public:
-  CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
-  : File(File), ParsedCallback(ParsedCallback) {}
+  CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback,
+   PreambleBuildStats *Stats)
+  : File(File), ParsedCallback(ParsedCallback), Stats(Stats) {}
 
   IncludeStructure takeIncludes() { return std::move(Includes); }
 
@@ -88,6 +89,25 @@ class CppFilePreambleCallbacks : public PreambleCallbacks {
 IsMainFileIncludeGuarded =
 
CI.getPreprocessor().getHeaderSearchInfo().isFileMultipleIncludeGuarded(
 MainFE);
+
+if (Stats) {
+  const ASTContext &AST = CI.getASTContext();
+  Stats->BuildSize = AST.getASTAllocatedMemory();
+  Stats->BuildSize += AST.getSideTableAllocatedMemory();
+  Stats->BuildSize += AST.Idents.getAllocator().getTotalMemory();
+  Stats->BuildSize += AST.Selectors.getTotalMemory();
+
+  Stats->BuildSize += AST.getSourceManager().getContentCacheSize();
+  Stats->BuildSize += AST.getSourceManager().getDataStructureSizes();
+  Stats->BuildSize +=
+  AST.getSourceManager().getMemoryBufferSizes().malloc_bytes;
+
+  const Preprocessor &PP = CI.getPreprocessor();
+  Stats->BuildSize += PP.getTotalMemory();
+  if (PreprocessingRecord *PRec = PP.getPreprocessingRecord())
+Stats->BuildSize += PRec->getTotalMemory();
+  Stats->BuildSize += PP.getHeaderSearchInfo().getTotalMemory();
+}
   }
 
   void BeforeExecute(CompilerInstance &CI) override {
@@ -135,6 +155,7 @@ class CppFilePreambleCallbacks : public PreambleCallbacks {
   std::unique_ptr IWYUHandler = nullptr;
   const clang::LangOptions *LangOpts = nullptr;
   const SourceManager *SourceMgr = nullptr;
+  PreambleBuildStats *Stats;
 };
 
 // Represents directives other than includes, where basic textual information 
is
@@ -456,7 +477,7 @@ buildPreamble(PathRef FileName, CompilerInvocation CI,
   // to read back. We rely on dynamic index for the comments instead.
   CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
-  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback);
+  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback, Stats);
   auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
   llvm::SmallString<32> AbsFileName(FileName);
   VFS->makeAbsolute(AbsFileName);
@@ -476,6 +497,12 @@ buildPreamble(PathRef FileName, CompilerInvocation CI,
   // bodies.
   CI.getFrontendOpts().SkipFunctionBodies = false;
 
+  if (Stats != nullptr) {
+Stats->TotalBuildTime = PreambleTimer.getTime();
+Stats->FileSystemTime = TimedFS->getTime();
+Stats->SerializedSize = BuiltPreamble ? BuiltPreamble->getSize() : 0;
+  }
+
   if (BuiltPreamble) {
 vlog("Built preamble of size {0} for file {1} version {2} in {3} seconds",
  BuiltPreamble->getSize(), FileName, Inputs.Version,
@@ -491,10 +518,6 @@ buildPreamble(PathRef FileName, CompilerInvocation CI,
 Result->CanonIncludes = CapturedInfo.takeCanonicalIncludes();
 Result->StatCache = std::move(StatCache);
 Result->MainIsIncludeGuarded = CapturedInfo.isMainFileIncludeGuarded();
-if (Stats != nullptr) {
-  Stats->TotalBuildTime = PreambleTimer.getTime();
-  Stats->FileSystemTime = TimedFS->getTime();
-}
 return Result;
   }
 

diff  --git a/clang-tools-extra/clangd/Preamble.h 
b/clang-tools-extra/clangd/Preamble.h
index 33a308484c189..f108dd4fd69fc 100644
--- a/clang-tools-extra/clangd/Preamble.h
+++ b/clang-tools-extra/clangd/Preamble.h
@@ -83,6 +83,14 @@ struct PreambleBuildStats {
   double TotalBuildTime;
   /// Time spent in filesystem operations during the build, in seconds.
   double FileSystemTime;
+
+  /// Estimate of the memory used while building the preamble.
+  /// This memory has been released when buildPreamble returns.
+  /// For example, this includes the size of the in-memory AST (ASTContext)

[PATCH] D123672: [clangd] Export preamble AST and serialized size as metrics

2022-04-13 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf407c9ed1057: [clangd] Export preamble AST and serialized 
size as metrics (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123672

Files:
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/TUScheduler.cpp

Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -110,6 +110,11 @@
 constexpr trace::Metric PreambleBuildFilesystemLatencyRatio(
 "preamble_fs_latency_ratio", trace::Metric::Distribution, "build_type");
 
+constexpr trace::Metric PreambleBuildSize("preamble_build_size",
+  trace::Metric::Distribution);
+constexpr trace::Metric PreambleSerializedSize("preamble_serialized_size",
+   trace::Metric::Distribution);
+
 void reportPreambleBuild(const PreambleBuildStats &Stats,
  bool IsFirstPreamble) {
   auto RecordWithLabel = [&Stats](llvm::StringRef Label) {
@@ -122,6 +127,9 @@
   static llvm::once_flag OnceFlag;
   llvm::call_once(OnceFlag, [&] { RecordWithLabel("first_build"); });
   RecordWithLabel(IsFirstPreamble ? "first_build_for_file" : "rebuild");
+
+  PreambleBuildSize.record(Stats.BuildSize);
+  PreambleSerializedSize.record(Stats.SerializedSize);
 }
 
 class ASTWorker;
Index: clang-tools-extra/clangd/Preamble.h
===
--- clang-tools-extra/clangd/Preamble.h
+++ clang-tools-extra/clangd/Preamble.h
@@ -83,6 +83,14 @@
   double TotalBuildTime;
   /// Time spent in filesystem operations during the build, in seconds.
   double FileSystemTime;
+
+  /// Estimate of the memory used while building the preamble.
+  /// This memory has been released when buildPreamble returns.
+  /// For example, this includes the size of the in-memory AST (ASTContext).
+  size_t BuildSize;
+  /// The serialized size of the preamble.
+  /// This storage is needed while the preamble is used (but may be on disk).
+  size_t SerializedSize;
 };
 
 /// Build a preamble for the new inputs unless an old one can be reused.
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -64,8 +64,9 @@
 
 class CppFilePreambleCallbacks : public PreambleCallbacks {
 public:
-  CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
-  : File(File), ParsedCallback(ParsedCallback) {}
+  CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback,
+   PreambleBuildStats *Stats)
+  : File(File), ParsedCallback(ParsedCallback), Stats(Stats) {}
 
   IncludeStructure takeIncludes() { return std::move(Includes); }
 
@@ -88,6 +89,25 @@
 IsMainFileIncludeGuarded =
 CI.getPreprocessor().getHeaderSearchInfo().isFileMultipleIncludeGuarded(
 MainFE);
+
+if (Stats) {
+  const ASTContext &AST = CI.getASTContext();
+  Stats->BuildSize = AST.getASTAllocatedMemory();
+  Stats->BuildSize += AST.getSideTableAllocatedMemory();
+  Stats->BuildSize += AST.Idents.getAllocator().getTotalMemory();
+  Stats->BuildSize += AST.Selectors.getTotalMemory();
+
+  Stats->BuildSize += AST.getSourceManager().getContentCacheSize();
+  Stats->BuildSize += AST.getSourceManager().getDataStructureSizes();
+  Stats->BuildSize +=
+  AST.getSourceManager().getMemoryBufferSizes().malloc_bytes;
+
+  const Preprocessor &PP = CI.getPreprocessor();
+  Stats->BuildSize += PP.getTotalMemory();
+  if (PreprocessingRecord *PRec = PP.getPreprocessingRecord())
+Stats->BuildSize += PRec->getTotalMemory();
+  Stats->BuildSize += PP.getHeaderSearchInfo().getTotalMemory();
+}
   }
 
   void BeforeExecute(CompilerInstance &CI) override {
@@ -135,6 +155,7 @@
   std::unique_ptr IWYUHandler = nullptr;
   const clang::LangOptions *LangOpts = nullptr;
   const SourceManager *SourceMgr = nullptr;
+  PreambleBuildStats *Stats;
 };
 
 // Represents directives other than includes, where basic textual information is
@@ -456,7 +477,7 @@
   // to read back. We rely on dynamic index for the comments instead.
   CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
-  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback);
+  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback, Stats);
   auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
   llvm::SmallString<32> AbsFileName(FileName);
   VFS->makeAbsolute(AbsFileName);
@@ -476,6 +497,12 @@
   // bodies.
   CI.getFrontendOpts().SkipFunctionBodie

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

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

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

This fixes regression introduced in 
https://github.com/llvm/llvm-project/commit/5e5efd8a91f2e340e79a73bedbc6ab66ad4a4281.

Before the culprit commit, macros in WhitespaceSensitiveMacros were correctly 
formatted even if their closing parenthesis weren't followed by semicolon (or, 
to be precise, when they were followed by a newline).
That commit changed the type of the macro token type from 
TT_UntouchableMacroFunc to TT_FunctionLikeOrFreestandingMacro.

Correct formatting (with `WhitespaceSensitiveMacros = ['FOO']`):

  FOO(1+2)
  FOO(1+2);

Regressed formatting:

  FOO(1 + 2)
  FOO(1+2);


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123676

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -23540,6 +23540,11 @@
 
   // Don't use the helpers here, since 'mess up' will change the whitespace
   // and these are all whitespace sensitive by definition
+
+  // Newlines are important here.
+  EXPECT_EQ("FOO(1+2  );\n", format("FOO(1+2  );\n", Style));
+  EXPECT_EQ("FOO(1+2  )\n", format("FOO(1+2  )\n", Style));
+
   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
   EXPECT_EQ(
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1787,7 +1787,8 @@
 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
 
 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
-tokenCanStartNewLine(*FormatTok) && Text == Text.upper()) {
+tokenCanStartNewLine(*FormatTok) && Text == Text.upper() &&
+!PreviousToken->isTypeFinalized()) {
   PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
   addUnwrappedLine();
   return;
Index: clang/lib/Format/FormatTokenLexer.h
===
--- clang/lib/Format/FormatTokenLexer.h
+++ clang/lib/Format/FormatTokenLexer.h
@@ -114,7 +114,12 @@
   unsigned FirstInLineIndex;
   SmallVector Tokens;
 
-  llvm::SmallMapVector Macros;
+  struct MacroTokenInfo {
+TokenType Type;
+bool Finalized;
+  };
+
+  llvm::SmallMapVector Macros;
 
   bool FormattingDisabled;
 
Index: clang/lib/Format/FormatTokenLexer.cpp
===
--- clang/lib/Format/FormatTokenLexer.cpp
+++ clang/lib/Format/FormatTokenLexer.cpp
@@ -39,37 +39,38 @@
 
   for (const std::string &ForEachMacro : Style.ForEachMacros) {
 auto Identifier = &IdentTable.get(ForEachMacro);
-Macros.insert({Identifier, TT_ForEachMacro});
+Macros.insert({Identifier, {TT_ForEachMacro, /*Finalized=*/false}});
   }
   for (const std::string &IfMacro : Style.IfMacros) {
 auto Identifier = &IdentTable.get(IfMacro);
-Macros.insert({Identifier, TT_IfMacro});
+Macros.insert({Identifier, {TT_IfMacro, /*Finalized=*/false}});
   }
   for (const std::string &AttributeMacro : Style.AttributeMacros) {
 auto Identifier = &IdentTable.get(AttributeMacro);
-Macros.insert({Identifier, TT_AttributeMacro});
+Macros.insert({Identifier, {TT_AttributeMacro, /*Finalized=*/false}});
   }
   for (const std::string &StatementMacro : Style.StatementMacros) {
 auto Identifier = &IdentTable.get(StatementMacro);
-Macros.insert({Identifier, TT_StatementMacro});
+Macros.insert({Identifier, {TT_StatementMacro, /*Finalized=*/false}});
   }
   for (const std::string &TypenameMacro : Style.TypenameMacros) {
 auto Identifier = &IdentTable.get(TypenameMacro);
-Macros.insert({Identifier, TT_TypenameMacro});
+Macros.insert({Identifier, {TT_TypenameMacro, /*Finalized=*/false}});
   }
   for (const std::string &NamespaceMacro : Style.NamespaceMacros) {
 auto Identifier = &IdentTable.get(NamespaceMacro);
-Macros.insert({Identifier, TT_NamespaceMacro});
+Macros.insert({Identifier, {TT_NamespaceMacro, /*Finalized=*/false}});
   }
   for (const std::string &WhitespaceSensitiveMacro :
Style.WhitespaceSensitiveMacros) {
 auto Identifier = &IdentTable.get(WhitespaceSensitiveMacro);
-Macros.insert({Identifier, TT_UntouchableMacroFunc});
+Macros.insert({Identifier, {TT_UntouchableMacroFunc, /*Finalized=*/tru

[PATCH] D107636: [analyzer][solver] Compute adjustment for unsupported symbols as well

2022-04-13 Thread Gabor Marton via Phabricator via cfe-commits
martong requested changes to this revision.
martong added a comment.
This revision now requires changes to proceed.

I am not sure if this patch makes sense at all because the adjustment handling 
logic is restricted to handle SymInt expressions only.




Comment at: clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp:82-86
   if (IsExpectedEqual) {
 return assumeSymNE(State, CanonicalEquality, Zero, Zero);
   }
 
   return assumeSymEQ(State, CanonicalEquality, Zero, Zero);

ASDenysPetrov wrote:
> Do we need the same changes here as below?
I believe, the adjustment is deliberately Zero here. This is because we are 
dealing with a SymSym expr, and the adjustment logic is capable of handling 
only a SymInt expr.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107636

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


[PATCH] D123300: [Clang] Enable opaque pointers by default

2022-04-13 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D123300#3446823 , @aeubanks wrote:

> In D123300#3446023 , @nikic wrote:
>
>> @mstorsjo Thanks! I've reduced this to a crash in `-argpromotion`:
>>
>>   efine void @caller() {
>> call i32 @callee(ptr null)
>> ret void
>>   }
>>   
>>   define internal void @callee(ptr %p) {
>> ret void
>>   }
>>
>> Similar issue with function type mismatch.
>
> Should be fixed with 
> https://github.com/llvm/llvm-project/commit/51561b5e8017a3153629ba45b89d013ffa665f6c

Thanks! I think the rest of my regularly build tested code now builds fine 
after that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123300

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


[PATCH] D123649: Allow flexible array initialization in C++.

2022-04-13 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/CodeGen/CGDecl.cpp:346
+else if (!D.getFlexibleArrayInitChars(getContext()).isZero())
+  CGM.ErrorUnsupported(D.getInit(), "flexible array init");
 else if (HaveInsertPoint()) {

Can you write a test for this with a 'fixme'?  I don't see a reason why we 
shouldn't support this eventually.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:4617
   if (getLangOpts().CPlusPlus) {
+if (!InitDecl->getFlexibleArrayInitChars(getContext()).isZero())
+  ErrorUnsupported(D, "flexible array initializer");

Same comment here.



Comment at: clang/test/SemaCXX/constant-expression-cxx11.cpp:2388
+  // evaluation. Make sure we emit a sane error message, for now.
+  constexpr A c = {1, 2, 3}; // expected-warning {{flexible array 
initialization is a GNU extension}}
+  static_assert(c.arr[0] == 1, ""); // expected-error {{constant expression}} 
expected-note {{array member without known bound}}

I would expect this to be an error, not the static-assert.  The constexpr 
variable means 'initializable as a constant expression'.  

I'm guessing the problem is ACTUALLY that we support constexpr init, but not 
the operator[].  I think I'd like to have us have the initialization fail here, 
since it isn't otherwise usable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123649

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


[PATCH] D123450: [clang-format] Parse Verilog if statements

2022-04-13 Thread sstwcw via Phabricator via cfe-commits
sstwcw updated this revision to Diff 422496.
sstwcw edited the summary of this revision.
sstwcw added a comment.

abandon alias


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123450

Files:
  clang/docs/ClangFormat.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/tools/clang-format/ClangFormat.cpp
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/FormatTestUtils.h
  clang/unittests/Format/FormatTestVerilog.cpp

Index: clang/unittests/Format/FormatTestVerilog.cpp
===
--- /dev/null
+++ clang/unittests/Format/FormatTestVerilog.cpp
@@ -0,0 +1,118 @@
+//===- unittest/Format/FormatTestVerilog.cpp --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "FormatTestUtils.h"
+#include "clang/Format/Format.h"
+#include "llvm/Support/Debug.h"
+#include "gtest/gtest.h"
+
+#define DEBUG_TYPE "format-test"
+
+namespace clang {
+namespace format {
+
+class FormatTestVerilog : public ::testing::Test {
+protected:
+  static std::string format(llvm::StringRef Code, unsigned Offset,
+unsigned Length, const FormatStyle &Style) {
+LLVM_DEBUG(llvm::errs() << "---\n");
+LLVM_DEBUG(llvm::errs() << Code << "\n\n");
+std::vector Ranges(1, tooling::Range(Offset, Length));
+tooling::Replacements Replaces = reformat(Style, Code, Ranges);
+auto Result = applyAllReplacements(Code, Replaces);
+EXPECT_TRUE(static_cast(Result));
+LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
+return *Result;
+  }
+
+  static std::string format(llvm::StringRef Code, const FormatStyle &Style) {
+return format(Code, 0, Code.size(), Style);
+  }
+
+  static void verifyFormat(
+  llvm::StringRef Code,
+  const FormatStyle &Style = getLLVMStyle(FormatStyle::LK_Verilog)) {
+EXPECT_EQ(Code.str(), format(Code, Style)) << "Expected code is not stable";
+EXPECT_EQ(Code.str(),
+  format(test::messUp(Code, /*HandleHash=*/false), Style));
+  }
+};
+
+TEST_F(FormatTestVerilog, If) {
+  verifyFormat("if (x)\n"
+   "  x = x;");
+  verifyFormat("if (x)\n"
+   "  x = x;\n"
+   "x = x;");
+
+  // Test else
+  verifyFormat("if (x)\n"
+   "  x = x;\n"
+   "else if (x)\n"
+   "  x = x;\n"
+   "else\n"
+   "  x = x;");
+  verifyFormat("if (x) begin\n"
+   "  x = x;\n"
+   "end else if (x) begin\n"
+   "  x = x;\n"
+   "end else begin\n"
+   "  x = x;\n"
+   "end");
+  verifyFormat("if (x) begin : x\n"
+   "  x = x;\n"
+   "end : x else if (x) begin : x\n"
+   "  x = x;\n"
+   "end : x else begin : x\n"
+   "  x = x;\n"
+   "end : x");
+
+  // Test block keywords.
+  verifyFormat("if (x) begin\n"
+   "  x = x;\n"
+   "end");
+  verifyFormat("if (x) begin : x\n"
+   "  x = x;\n"
+   "end : x");
+  verifyFormat("if (x) begin\n"
+   "  x = x;\n"
+   "  x = x;\n"
+   "end");
+  verifyFormat("disable fork;\n"
+   "x = x;");
+  verifyFormat("rand join x x;\n"
+   "x = x;");
+  verifyFormat("if (x) fork\n"
+   "  x = x;\n"
+   "join");
+  verifyFormat("if (x) fork\n"
+   "  x = x;\n"
+   "join_any");
+  verifyFormat("if (x) fork\n"
+   "  x = x;\n"
+   "join_none");
+  verifyFormat("if (x) generate\n"
+   "  x = x;\n"
+   "endgenerate");
+  verifyFormat("if (x) generate : x\n"
+   "  x = x;\n"
+   "endgenerate : x");
+
+  // Test that concatenation braces don't get regarded as blocks.
+  verifyFormat("if (x)\n"
+   "  {x} = x;");
+  verifyFormat("if (x)\n"
+   "  x = {x};");
+  verifyFormat("if (x)\n"
+   "  x = {x};\n"
+   "else\n"
+   "  {x} = {x};");
+}
+
+} // namespace format
+} // end namespace clang
Index: clang/unittests/Format/FormatTestUtils.h
===
--- clang/unittests/Format/FormatTestUtils.h
+++ clang/unittests/Format/FormatTestUtils.h
@@ -19,7 +19,10 @@
 namespace format {
 namespace test {
 
-inline std::string messUp(llvm::StringRef Code) {
+// When HandleHash is false, preprocessor directives starting with hash will not
+// be on separate lines.  

[PATCH] D123450: [clang-format] Parse Verilog if statements

2022-04-13 Thread sstwcw via Phabricator via cfe-commits
sstwcw marked an inline comment as done.
sstwcw added inline comments.



Comment at: clang/lib/Format/FormatToken.h:374
+  /// Verilog we want to treat the backtick like a hash.
+  tok::TokenKind AliasToken = tok::unknown;
+

HazardyKnusperkeks wrote:
> sstwcw wrote:
> > HazardyKnusperkeks wrote:
> > > Can't we do that with a type?
> > > 
> > > I'm not very happy about the alias, because you can still call 
> > > `Tok.getKind()`.
> > The main problem I seek to solve with the alias thing is with `tok::hash`.  
> > In Verilog they use a backtick instead of a hash.  At first I modified all 
> > places in the code to recognize the backtick.  MyDeveloperDay said "year 
> > really not nice.. its like we can never use tok::hash again!"  Using a type 
> > also requires modifying all instances of tok::hash if I get you right.  How 
> > do I please everyone?
> Then you must hide Tok in the private part, so that no one can ever access 
> `Tok.getKind()` accidentally.
In the new version the type of `Tok` itself gets changed instead.  So an alias 
is not needed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123450

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


[PATCH] D123636: [randstruct] Add test for "-frandomize-layout-seed-file" flag

2022-04-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/unittests/AST/RandstructTest.cpp:56
+  llvm::SmallString<256> SeedFilename;
+  EXPECT_FALSE(llvm::sys::fs::createTemporaryFile("seed", "rng", SeedFileFD,
+  SeedFilename));

I think this is a case where you want to use `ASSERT_FALSE` because if this 
fails, the rest of the test also fails.



Comment at: clang/unittests/AST/RandstructTest.cpp:72
+
+  return std::tuple(AST.release(), 
ASTFileSeed.release());
+};

Why not keep these as unique pointers and move them into the tuple? Then the 
callers don't have to call delete manually.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123636

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


[PATCH] D123630: Remove connection between 'ffast-math' and 'ffp-contract'.

2022-04-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I think these changes should go through a community RFC on Discourse given that 
they alter the behavior of existing flags.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123630

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


[PATCH] D122748: [Sema] Don't check bounds for function pointer

2022-04-13 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX added a comment.

Friendly ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122748

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


[PATCH] D122748: [Sema] Don't check bounds for function pointer

2022-04-13 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added a comment.
This revision is now accepted and ready to land.

>> Friendly ping

Unfriendly LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122748

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


[PATCH] D121984: [RISCV] Moving RVV intrinsic type related util to clang/Support

2022-04-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Errr, I'm not strongly opposed, but at the same time, this doesn't feel like a 
Support kind of thing. My understanding of llvm/Support is that it's primarily 
for generally useful utilities that are going to be used across the entire llvm 
project (or beyond). This is a very specific interface that's only interesting 
to TableGen as best I can tell. Why shouldn't this live in clang/utils/TableGen 
along with the others?




Comment at: clang/include/clang/Support/RISCVVIntrinsicUtils.h:1
+//===- RISCVVIntrinsicUtils.cpp - RISC-V Vector Intrinsic Utils -*- C++ 
-*-===//
+//

Comment here seems off (this isn't a .cpp file, it's a .h)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121984

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


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

2022-04-13 Thread ksyx via Phabricator via cfe-commits
ksyx added inline comments.



Comment at: clang/lib/Format/FormatTokenLexer.h:117-120
+  struct MacroTokenInfo {
+TokenType Type;
+bool Finalized;
+  };

Would making constructor of `struct MacroTokenInfo` having default parameter or 
overloading it help avoiding the change of adding `, /*Finalized=*/false` to 
the existing initializer lists?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123676

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


[PATCH] D123655: [clang-tidy] Add portability-std-allocator-const-t check

2022-04-13 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This looks nice, my main substantive question is about matching VarDecl vs 
TypeLoc.
Maybe there's a good reason to keep it this way but I'd like to understand why.

The rest is nits, feel free to ignore any bits you disagree with.




Comment at: 
clang-tools-extra/clang-tidy/portability/PortabilityTidyModule.cpp:28
+CheckFactories.registerCheck(
+"portability-std-allocator-const-t");
   }

without the punctuation, the "t" AllocatorConstT/allocator-const-t doesn't seem 
so obvious IMO, I'd consider dropping it from the check name.

Also the docs and even the implementation are focused on containers, 
"portability-const-container" might be easier to remember/understand for people 
not immersed in the details here.

All up to you though.



Comment at: 
clang-tools-extra/clang-tidy/portability/StdAllocatorConstTCheck.cpp:25
+
+  // Match `std::vector var;` and other common containers like deque,
+  // list, and absl::flat_hash_set. Some containers like forward_list, queue,

If creating `allocator` is always invalid, why be so careful here about 
which containers we're matching?



Comment at: 
clang-tools-extra/clang-tidy/portability/StdAllocatorConstTCheck.cpp:27
+  // list, and absl::flat_hash_set. Some containers like forward_list, queue,
+  // and stack are not caught. Don't bother with std::unordered_set
+  // since libc++ does not allow it.

we can tell the "not caught" containers from the list below, but it'd be useful 
for the comment to say why



Comment at: 
clang-tools-extra/clang-tidy/portability/StdAllocatorConstTCheck.cpp:28
+  // and stack are not caught. Don't bother with std::unordered_set
+  // since libc++ does not allow it.
+  Finder->addMatcher(

coupling this check to what libc++ currently supports makes it harder to 
understand, what's the cost of including unordered_set in this list anyway?



Comment at: 
clang-tools-extra/clang-tidy/portability/StdAllocatorConstTCheck.cpp:30
+  Finder->addMatcher(
+  varDecl(
+  hasType(hasUnqualifiedDesugaredType(

Matching VarDecl specifically is an interesting choice. Maybe a good one: it 
does a good job of ensuring we diagnose at an appropriate place and only once.

Other tempting choices are:
 - typeloc(loc(...)) - requires the type to be spelled somewhere, I think this 
can work even in template instantiations
 - expr(hasType(...)) - problem is it's likely to find multiple matches for the 
same root cause

My guess is matching the TypeLoc would work better: catching some extra cases 
without much downside.



Comment at: 
clang-tools-extra/clang-tidy/portability/StdAllocatorConstTCheck.cpp:31
+  varDecl(
+  hasType(hasUnqualifiedDesugaredType(
+  recordType(hasDeclaration(classTemplateSpecializationDecl(

Maybe you'd want to handle cases where the type is buried a bit, like `vector&` 
and `vector*` etc.

Matching TypeLoc would take care of this for you, as matchers will see the 
nested TypeLoc.




Comment at: 
clang-tools-extra/clang-tidy/portability/StdAllocatorConstTCheck.cpp:50
+   "container using std::allocator is "
+   "undefined; remove const to work with libstdc++ and future libc++");
+}

I'm a bit concerned that the second half:
 - is jargon that will confuse some people
 - excludes MSVC (are there others?)
 - will be inaccurate once libc++ changes

Also nits: "undefined" might be confusingly close to "not defined" in the "no 
visible definition" sense, and "remove const to work with" reads a little oddly 
because it's a person that's removing but the code that's working.

What about "container using std::allocator is invalid; remove const"
or if focusing on the libc++ situation: "container using std::allocator is a libc++ extension; remove const for compatibility with other standard 
libraries"?



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/portability-std-allocator-const-t.rst:6
+
+Per C++ ``[allocator.requirements.general]``: "T is any cv-unqualified object
+type", ``std::allocator`` is undefined. Many standard containers use

this seems a bit standard-ese for the intro paragraph.

Maybe add a paragraph before it: "This check reports use of `vector` 
(and similar containers of const elements). These are not allowed in standard 
C++, and should usually be `vector` instead."



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/portability-std-allocator-const-t.rst:11
+
+libstdc++ never supports ``std::allocator`` and containers using them.
+Since GCC 8.0 (`PR48101 `),

It's a little confusing to call out only libstdc++ here without context when 
libc++ is the odd-one out.

Maybe first mention that l

[PATCH] D123598: Clean the code, formated and add basic tests for the patch.

2022-04-13 Thread Abid via Phabricator via cfe-commits
abidmalikwaterloo updated this revision to Diff 422504.
abidmalikwaterloo added a comment.

I submitted update but it created a new patch D123598 
. 
I marked it abandon and submitting it again.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123598

Files:
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/StmtOpenMP.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/SemaStmt.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPContext.h
  llvm/lib/Frontend/OpenMP/OMPContext.cpp

Index: llvm/lib/Frontend/OpenMP/OMPContext.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPContext.cpp
+++ llvm/lib/Frontend/OpenMP/OMPContext.cpp
@@ -19,7 +19,6 @@
 #include "llvm/ADT/Triple.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
-
 #include 
 #define DEBUG_TYPE "openmp-ir-builder"
 
@@ -340,53 +339,36 @@
   return Score;
 }
 
-/// 
 /// Takes \p VMI and \p Ctx and sort the 
 /// scores using \p A
 void llvm::omp::getArrayVariantMatchForContext(const SmallVectorImpl &VMIs,
 const OMPContext &Ctx, SmallVector> &A){
-	
-	//APInt BestScore(64, 0);
-	APInt Score (64, 0);
-	llvm::DenseMap m;
-	
-	/*for (unsigned u = 0, e = VMIs.size(); u < e; ++u) {
-		const VariantMatchInfo &VMI = VMIs[u];
-		SmallVector ConstructMatches;
-  		APInt Score = getVariantMatchScore(VMI, Ctx, ConstructMatches);
-  		m.insert({u, Score});	
-	}
-
-	*/
-	
-	for (unsigned u = 0, e = VMIs.size(); u < e; ++u) {
-		const VariantMatchInfo &VMI = VMIs[u];
-
-		SmallVector ConstructMatches;
-		// If the variant is not applicable its not the best.
-		if (!isVariantApplicableInContextHelper(VMI, Ctx, &ConstructMatches,
+   APInt Score (64, 0);
+   llvm::DenseMap m;
+   		
+   for (unsigned u = 0, e = VMIs.size(); u < e; ++u) {
+  const VariantMatchInfo &VMI = VMIs[u];
+
+  SmallVector ConstructMatches;
+  // If the variant is not applicable its not the best.
+if (!isVariantApplicableInContextHelper(VMI, Ctx, &ConstructMatches,
 /* DeviceSetOnly */ false)){
-   Score = 0;
-   m.insert({u, Score});
-  			continue;
-  		}
+  Score = 0;
+  m.insert({u, Score});
+  continue;}
   		
-   		// Check if its clearly not the best.
-		Score = getVariantMatchScore(VMI, Ctx, ConstructMatches);
+  // Check if its clearly not the best.
+Score = getVariantMatchScore(VMI, Ctx, ConstructMatches);
 		m.insert({u, Score});	
-	}
+   }
 			
-	for (auto& it : m) 
-		A.push_back(it);
+   for (auto& it : m) 	A.push_back(it);
 	
-	std::sort(A.begin(), A.end(), [] (std::pair&a,
+   std::sort(A.begin(), A.end(), [] (std::pair&a,
 	 	  std::pair&b){	
-			return a.second.ugt(b.second);
-		});	
+			return a.second.ugt(b.second);});	
 }
  
-
-
 int llvm::omp::getBestVariantMatchForContext(
 const SmallVectorImpl &VMIs, const OMPContext &Ctx) {
 
Index: llvm/include/llvm/Frontend/OpenMP/OMPContext.h
===
--- llvm/include/llvm/Frontend/OpenMP/OMPContext.h
+++ llvm/include/llvm/Frontend/OpenMP/OMPContext.h
@@ -197,7 +197,6 @@
 const SmallVectorImpl &VMIs, const OMPContext &Ctx,
 SmallVector> &A);
 
-// new--
 } // namespace omp
 
 template <> struct DenseMapInfo {
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -4793,7 +4793,6 @@
   Captures, CaptureInits, CD, RD);
   		
   CD->setBody(Res->getCapturedStmt());
-
   RD->completeDefinition();
 
   return Res;
Index: clang/lib/Sema/SemaOpenMP.cpp
===
--- clang/lib/Sema/SemaOpenMP.cpp
+++ clang/lib/Sema/SemaOpenMP.cpp
@@ -3931,7 +3931,7 @@
 
 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
   switch (DKind) {
-  case OMPD_metadirective: // added
+  case OMPD_metadirective:
   case OMPD_parallel:
   case OMPD_parallel_for:
   case OMPD_parallel_for_simd:
@@ -4341,7 +4341,6 @@
   case OMPD_declare_variant:
   case OMPD_begin_declare_variant:
   case OMPD_end_declare_variant:
-  //case OMPD_metadirective:
 //llvm_unreachable("OpenMP Directive is not allowed");
   case OMPD_unknown:
   default:
@@ -4523,8 +4522,7 @@
 }
 
 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
-  ArrayRef Clauses) {
-
+  Ar

[PATCH] D123680: Add support for ignored bitfield conditional codegen.

2022-04-13 Thread Erich Keane via Phabricator via cfe-commits
erichkeane created this revision.
erichkeane added reviewers: eli.friedman, aaron.ballman, tahonermann.
Herald added a project: All.
erichkeane requested review of this revision.

Currently we emit an error in just about every case of conditionals
with a 'non simple' branch if treated as an LValue.  This patch adds
support for the special case where this is an 'ignored' lvalue, which
permits the side effects from happening.

It also splits up the emit for conditional LValue in a way that should
be usable to handle simple assignment expressions in similar situations.


https://reviews.llvm.org/D123680

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/test/CodeGenCXX/ignored-bitfield-conditional.cpp

Index: clang/test/CodeGenCXX/ignored-bitfield-conditional.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/ignored-bitfield-conditional.cpp
@@ -0,0 +1,83 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s
+
+struct S {
+  int field1 : 5;
+  int field2 : 6;
+};
+
+void use(bool cond, struct S s1, struct S s2, int val1, int val2) {
+  // CHECK: define {{.*}}use{{.*}}(
+  // CHECK: %[[S1:.+]] = alloca %struct.S
+  // CHECK: %[[S2:.+]] = alloca %struct.S
+  // CHECK: %[[COND:.+]] = alloca i8
+  // CHECK: %[[VAL1:.+]] = alloca i32
+  // CHECK: %[[VAL2:.+]] = alloca i32
+
+  cond ? s1.field1 = val1 : s1.field2 = val2;
+  // Condition setup, branch.
+  // CHECK: %[[CONDLD:.+]] = load i8, ptr %[[COND]]
+  // CHECK: %[[TO_BOOL:.+]] = trunc i8 %[[CONDLD]] to i1
+  // CHECK: br i1 %[[TO_BOOL]], label %[[TRUE:.+]], label %[[FALSE:.+]]
+
+  // 'True', branch set the BF, branch to 'end'.
+  // CHECK: [[TRUE]]:
+  // CHECK: %[[VAL1LD:.+]] = load i32, ptr %[[VAL1]]
+  // CHECK: %[[VAL1TRUNC:.+]] = trunc i32 %[[VAL1LD]] to i16
+  // CHECK: %[[BF_LOAD:.+]] = load i16, ptr %[[S1]]
+  // CHECK: %[[BF_VAL:.+]] = and i16 %[[VAL1TRUNC]], 31
+  // CHECK: %[[BF_CLEAR:.+]] = and i16 %[[BF_LOAD]], -32
+  // CHECK: %[[BF_SET:.+]] = or i16 %[[BF_CLEAR]], %[[BF_VAL]]
+  // CHECK: store i16 %[[BF_SET]], ptr %[[S1]]
+  // CHECK: br label %[[END:.+]]
+
+  // 'False', branch set the OTHER BF, branch to 'end'.
+  // CHECK: [[FALSE]]:
+  // CHECK: %[[VAL2LD:.+]] = load i32, ptr %[[VAL2]]
+  // CHECK: %[[VAL2TRUNC:.+]] = trunc i32 %[[VAL2LD]] to i16
+  // CHECK: %[[BF_LOAD:.+]] = load i16, ptr %[[S1]]
+  // CHECK: %[[BF_VAL:.+]] = and i16 %[[VAL2TRUNC]], 63 
+  // CHECK: %[[BF_SHIFT:.+]] = shl i16 %[[BF_VAL]], 5
+  // CHECK: %[[BF_CLEAR:.+]] = and i16 %[[BF_LOAD]], -2017
+  // CHECK: %[[BF_SET:.+]] = or i16 %[[BF_CLEAR]], %[[BF_SHIFT]]
+  // CHECK: store i16 %[[BF_SET]], ptr %[[S1]]
+  // CHECK: br label %[[END:.+]]
+
+  // CHECK: [[END]]:
+  // There is nothing in the 'end' block associated with this, but it is the
+  // 'continuation' block for the rest of the function.
+
+  // Same test, has a no-op cast and parens.
+  (int)(cond ? s2.field1 = val1 : s2.field2 = val2);
+  // Condition setup, branch.
+  // CHECK: %[[CONDLD:.+]] = load i8, ptr %[[COND]]
+  // CHECK: %[[TO_BOOL:.+]] = trunc i8 %[[CONDLD]] to i1
+  // CHECK: br i1 %[[TO_BOOL]], label %[[TRUE:.+]], label %[[FALSE:.+]]
+
+  // 'True', branch set the BF, branch to 'end'.
+  // CHECK: [[TRUE]]:
+  // CHECK: %[[VAL1LD:.+]] = load i32, ptr %[[VAL1]]
+  // CHECK: %[[VAL1TRUNC:.+]] = trunc i32 %[[VAL1LD]] to i16
+  // CHECK: %[[BF_LOAD:.+]] = load i16, ptr %[[S2]]
+  // CHECK: %[[BF_VAL:.+]] = and i16 %[[VAL1TRUNC]], 31
+  // CHECK: %[[BF_CLEAR:.+]] = and i16 %[[BF_LOAD]], -32
+  // CHECK: %[[BF_SET:.+]] = or i16 %[[BF_CLEAR]], %[[BF_VAL]]
+  // CHECK: store i16 %[[BF_SET]], ptr %[[S2]]
+  // CHECK: br label %[[END:.+]]
+
+  // 'False', branch set the OTHER BF, branch to 'end'.
+  // CHECK: [[FALSE]]:
+  // CHECK: %[[VAL2LD:.+]] = load i32, ptr %[[VAL2]]
+  // CHECK: %[[VAL2TRUNC:.+]] = trunc i32 %[[VAL2LD]] to i16
+  // CHECK: %[[BF_LOAD:.+]] = load i16, ptr %[[S2]]
+  // CHECK: %[[BF_VAL:.+]] = and i16 %[[VAL2TRUNC]], 63 
+  // CHECK: %[[BF_SHIFT:.+]] = shl i16 %[[BF_VAL]], 5
+  // CHECK: %[[BF_CLEAR:.+]] = and i16 %[[BF_LOAD]], -2017
+  // CHECK: %[[BF_SET:.+]] = or i16 %[[BF_CLEAR]], %[[BF_SHIFT]]
+  // CHECK: store i16 %[[BF_SET]], ptr %[[S2]]
+  // CHECK: br label %[[END:.+]]
+
+  // CHECK: [[END]]:
+  // There is nothing in the 'end' block associated with this, but it is the
+  // 'continuation' block for the rest of the function.
+
+}
Index: clang/lib/CodeGen/CodeGenFunction.h
===
--- clang/lib/CodeGen/CodeGenFunction.h
+++ clang/lib/CodeGen/CodeGenFunction.h
@@ -3915,6 +3915,7 @@
   LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
   LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
   LValue EmitInitListLValue(const InitListExpr *E);
+  void EmitIgnoredConditionalOperator(const AbstractConditionalOperator *E);
   LValue EmitConditionalOperatorLValue(const AbstractCondition

[PATCH] D123682: [clang-tblgen] Automatically document options values

2022-04-13 Thread serge via Phabricator via cfe-commits
serge-sans-paille created this revision.
serge-sans-paille added a reviewer: MaskRay.
Herald added a subscriber: StephenFan.
Herald added a project: All.
serge-sans-paille requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is a port of f5c666742f7bb4ae79ec79c8acf61dced4d37cc9 
 to 
clang's tablegen.
The code duplication is a bit sad there :-/

Related to https://reviews.llvm.org/D122378


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123682

Files:
  clang/utils/TableGen/ClangOptionDocEmitter.cpp


Index: clang/utils/TableGen/ClangOptionDocEmitter.cpp
===
--- clang/utils/TableGen/ClangOptionDocEmitter.cpp
+++ clang/utils/TableGen/ClangOptionDocEmitter.cpp
@@ -238,6 +238,8 @@
   }
 }
 
+static StringRef DefaultMetaVarName = "";
+
 void emitOptionName(StringRef Prefix, const Record *Option, raw_ostream &OS) {
   // Find the arguments to list after the option.
   unsigned NumArgs = getNumArgsForKind(Option->getValueAsDef("Kind"), Option);
@@ -247,7 +249,7 @@
   if (HasMetaVarName)
 Args.push_back(std::string(Option->getValueAsString("MetaVarName")));
   else if (NumArgs == 1)
-Args.push_back("");
+Args.push_back(DefaultMetaVarName.str());
 
   // Fill up arguments if this option didn't provide a meta var name or it
   // supports an unlimited number of arguments. We can't see how many arguments
@@ -341,8 +343,33 @@
   OS << "\n\n";
 
   // Emit the description, if we have one.
+  const Record *R = Option.Option;
   std::string Description =
-  getRSTStringWithTextFallback(Option.Option, "DocBrief", "HelpText");
+  getRSTStringWithTextFallback(R, "DocBrief", "HelpText");
+
+  if (!isa(R->getValueInit("Values"))) {
+if (!Description.empty() && Description.back() != '.')
+  Description.push_back('.');
+
+StringRef MetaVarName;
+if (!isa(R->getValueInit("MetaVarName")))
+  MetaVarName = R->getValueAsString("MetaVarName");
+else
+  MetaVarName = DefaultMetaVarName;
+
+SmallVector Values;
+SplitString(R->getValueAsString("Values"), Values, ",");
+Description += (" " + MetaVarName + " can be ").str();
+
+if (Values.size() == 1) {
+  Description += ("'" + Values.front() + "'.").str();
+} else {
+  Description += "one of '";
+  Description += join(Values.begin(), Values.end() - 1, "', '");
+  Description += ("' or '" + Values.back() + "'.").str();
+}
+  }
+
   if (!Description.empty())
 OS << Description << "\n\n";
 }


Index: clang/utils/TableGen/ClangOptionDocEmitter.cpp
===
--- clang/utils/TableGen/ClangOptionDocEmitter.cpp
+++ clang/utils/TableGen/ClangOptionDocEmitter.cpp
@@ -238,6 +238,8 @@
   }
 }
 
+static StringRef DefaultMetaVarName = "";
+
 void emitOptionName(StringRef Prefix, const Record *Option, raw_ostream &OS) {
   // Find the arguments to list after the option.
   unsigned NumArgs = getNumArgsForKind(Option->getValueAsDef("Kind"), Option);
@@ -247,7 +249,7 @@
   if (HasMetaVarName)
 Args.push_back(std::string(Option->getValueAsString("MetaVarName")));
   else if (NumArgs == 1)
-Args.push_back("");
+Args.push_back(DefaultMetaVarName.str());
 
   // Fill up arguments if this option didn't provide a meta var name or it
   // supports an unlimited number of arguments. We can't see how many arguments
@@ -341,8 +343,33 @@
   OS << "\n\n";
 
   // Emit the description, if we have one.
+  const Record *R = Option.Option;
   std::string Description =
-  getRSTStringWithTextFallback(Option.Option, "DocBrief", "HelpText");
+  getRSTStringWithTextFallback(R, "DocBrief", "HelpText");
+
+  if (!isa(R->getValueInit("Values"))) {
+if (!Description.empty() && Description.back() != '.')
+  Description.push_back('.');
+
+StringRef MetaVarName;
+if (!isa(R->getValueInit("MetaVarName")))
+  MetaVarName = R->getValueAsString("MetaVarName");
+else
+  MetaVarName = DefaultMetaVarName;
+
+SmallVector Values;
+SplitString(R->getValueAsString("Values"), Values, ",");
+Description += (" " + MetaVarName + " can be ").str();
+
+if (Values.size() == 1) {
+  Description += ("'" + Values.front() + "'.").str();
+} else {
+  Description += "one of '";
+  Description += join(Values.begin(), Values.end() - 1, "', '");
+  Description += ("' or '" + Values.back() + "'.").str();
+}
+  }
+
   if (!Description.empty())
 OS << Description << "\n\n";
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122255: Meta directive runtime support

2022-04-13 Thread Abid via Phabricator via cfe-commits
abidmalikwaterloo updated this revision to Diff 422509.
abidmalikwaterloo added a comment.

I update it but it created a new patch D123598 
.
I marked it Abandon. Not sure how to delete it.
I am submitting it again after cleaning the codes
and adding some basic tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122255

Files:
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/StmtOpenMP.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/SemaStmt.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPContext.h
  llvm/lib/Frontend/OpenMP/OMPContext.cpp

Index: llvm/lib/Frontend/OpenMP/OMPContext.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPContext.cpp
+++ llvm/lib/Frontend/OpenMP/OMPContext.cpp
@@ -19,7 +19,6 @@
 #include "llvm/ADT/Triple.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
-
 #include 
 #define DEBUG_TYPE "openmp-ir-builder"
 
@@ -340,53 +339,36 @@
   return Score;
 }
 
-/// 
 /// Takes \p VMI and \p Ctx and sort the 
 /// scores using \p A
 void llvm::omp::getArrayVariantMatchForContext(const SmallVectorImpl &VMIs,
 const OMPContext &Ctx, SmallVector> &A){
-	
-	//APInt BestScore(64, 0);
-	APInt Score (64, 0);
-	llvm::DenseMap m;
-	
-	/*for (unsigned u = 0, e = VMIs.size(); u < e; ++u) {
-		const VariantMatchInfo &VMI = VMIs[u];
-		SmallVector ConstructMatches;
-  		APInt Score = getVariantMatchScore(VMI, Ctx, ConstructMatches);
-  		m.insert({u, Score});	
-	}
-
-	*/
-	
-	for (unsigned u = 0, e = VMIs.size(); u < e; ++u) {
-		const VariantMatchInfo &VMI = VMIs[u];
-
-		SmallVector ConstructMatches;
-		// If the variant is not applicable its not the best.
-		if (!isVariantApplicableInContextHelper(VMI, Ctx, &ConstructMatches,
+   APInt Score (64, 0);
+   llvm::DenseMap m;
+   		
+   for (unsigned u = 0, e = VMIs.size(); u < e; ++u) {
+  const VariantMatchInfo &VMI = VMIs[u];
+
+  SmallVector ConstructMatches;
+  // If the variant is not applicable its not the best.
+if (!isVariantApplicableInContextHelper(VMI, Ctx, &ConstructMatches,
 /* DeviceSetOnly */ false)){
-   Score = 0;
-   m.insert({u, Score});
-  			continue;
-  		}
+  Score = 0;
+  m.insert({u, Score});
+  continue;}
   		
-   		// Check if its clearly not the best.
-		Score = getVariantMatchScore(VMI, Ctx, ConstructMatches);
+  // Check if its clearly not the best.
+Score = getVariantMatchScore(VMI, Ctx, ConstructMatches);
 		m.insert({u, Score});	
-	}
+   }
 			
-	for (auto& it : m) 
-		A.push_back(it);
+   for (auto& it : m) 	A.push_back(it);
 	
-	std::sort(A.begin(), A.end(), [] (std::pair&a,
+   std::sort(A.begin(), A.end(), [] (std::pair&a,
 	 	  std::pair&b){	
-			return a.second.ugt(b.second);
-		});	
+			return a.second.ugt(b.second);});	
 }
  
-
-
 int llvm::omp::getBestVariantMatchForContext(
 const SmallVectorImpl &VMIs, const OMPContext &Ctx) {
 
Index: llvm/include/llvm/Frontend/OpenMP/OMPContext.h
===
--- llvm/include/llvm/Frontend/OpenMP/OMPContext.h
+++ llvm/include/llvm/Frontend/OpenMP/OMPContext.h
@@ -197,7 +197,6 @@
 const SmallVectorImpl &VMIs, const OMPContext &Ctx,
 SmallVector> &A);
 
-// new--
 } // namespace omp
 
 template <> struct DenseMapInfo {
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -4793,7 +4793,6 @@
   Captures, CaptureInits, CD, RD);
   		
   CD->setBody(Res->getCapturedStmt());
-
   RD->completeDefinition();
 
   return Res;
Index: clang/lib/Sema/SemaOpenMP.cpp
===
--- clang/lib/Sema/SemaOpenMP.cpp
+++ clang/lib/Sema/SemaOpenMP.cpp
@@ -3931,7 +3931,7 @@
 
 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
   switch (DKind) {
-  case OMPD_metadirective: // added
+  case OMPD_metadirective:
   case OMPD_parallel:
   case OMPD_parallel_for:
   case OMPD_parallel_for_simd:
@@ -4341,7 +4341,6 @@
   case OMPD_declare_variant:
   case OMPD_begin_declare_variant:
   case OMPD_end_declare_variant:
-  //case OMPD_metadirective:
 //llvm_unreachable("OpenMP Directive is not allowed");
   case OMPD_unknown:
   default:
@@ -4523,8 +4522,7 @@
 }
 
 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
-  ArrayRef Clauses) {
-

[PATCH] D123498: [clang] Adding Platform/Architecture Specific Resource Header Installation Targets

2022-04-13 Thread Qiongsi Wu via Phabricator via cfe-commits
qiongsiwu1 added a subscriber: momchil.velikov.
qiongsiwu1 added a comment.

May I get some comments from the rest of the reviewers for the respective 
platforms? 
@momchil.velikov @chill: arm
@pengfei : x86
@jdoerfert: cuda
@yaxunl : opencl
@kaz7 : ve
@bcain : hexagon
@sdardis : mips

Thanks so much!




Comment at: clang/lib/Headers/CMakeLists.txt:173
   __wmmintrin_pclmul.h
   x86gprintrin.h
   x86intrin.h

abhina.sreeskantharajan wrote:
> nit: There are some x86 headers here that appear to be x86 only. Should these 
> be moved to x86_files list?
Thanks for the comment! Yes indeed. I think currently the `x86gprintrin.h` 
header is in the `x86_files` list (list starts at line 88). Did I miss some 
other x86 files? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123498

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


[PATCH] D122255: Meta directive runtime support

2022-04-13 Thread Abid via Phabricator via cfe-commits
abidmalikwaterloo updated this revision to Diff 422512.
abidmalikwaterloo added a comment.

Added tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122255

Files:
  clang/test/OpenMP/metadirective_ast_print2.c
  clang/test/OpenMP/metadirective_ast_print3.c
  clang/test/OpenMP/metadirective_ast_print4.c
  clang/test/OpenMP/metadirective_ast_print_new1.c
  clang/test/OpenMP/metadirective_ast_print_new2.c
  clang/test/OpenMP/metadirective_ast_print_new3.c


Index: clang/test/OpenMP/metadirective_ast_print4.c
===
--- /dev/null
+++ clang/test/OpenMP/metadirective_ast_print4.c
@@ -1,23 +0,0 @@
-// RUN: %clang_cc1 -verify  -fopenmp  -ast-print %s -o - | FileCheck %s
-// expected-no-diagnostics
-
-int main() {
-  int N = 15;
-#pragma omp metadirective when(user = {condition(N > 10)} : parallel for)\
-   default(target teams) 
-  for (int i = 0; i < N; i++)
-;
-
-
-#pragma omp metadirective when(device = {arch("nvptx64")}, user = {condition(N 
>= 100)} : parallel for)\
-   default(target parallel for)
-  for (int i = 0; i < N; i++)
-;
-  return 0;
-}
-
-
-
-// CHECK: #pragma omp metadirective when(user={condition(N > 10)}: parallel 
for) default(target teams)
-// CHECK: #pragma omp metadirective when(device={arch(nvptx64)}, 
user={condition(N >= 100)}: parallel for) default(target parallel for)
-
Index: clang/test/OpenMP/metadirective_ast_print3.c
===
--- /dev/null
+++ clang/test/OpenMP/metadirective_ast_print3.c
@@ -1,29 +0,0 @@
-// RUN: %clang_cc1 -verify  -fopenmp  -ast-print %s -o - | FileCheck %s
-// expected-no-diagnostics
-
-void bar(){
-   int i=0;
-}
-
-void myfoo(void){
-
-   int N = 13;
-   int b,n;
-   int a[100];
-
-   
-   #pragma omp  metadirective when (user = {condition(N>10)}: target  
teams distribute parallel for ) \
-   when (user = {condition(N==10)}: 
parallel for )\
-   when (user = {condition(N==13)}: 
parallel for simd) \
-   when ( device={arch("arm")}:   target 
teams num_teams(512) thread_limit(32))\
-   when ( device={arch("nvptx")}: target 
teams num_teams(512) thread_limit(32))\
-   default ( parallel for)\
-
-   {   for (int i = 0; i < N; i++)
-   bar();
-   }
-}
-
-// CHECK: bar()
-// CHECK: myfoo
-// CHECK: #pragma omp metadirective when(user={condition(N > 10)}: target 
teams distribute parallel for) when(user={condition(N == 13)}: parallel for 
simd) when(device={arch(nvptx)}: target teams)
Index: clang/test/OpenMP/metadirective_ast_print2.c
===
--- /dev/null
+++ clang/test/OpenMP/metadirective_ast_print2.c
@@ -1,20 +0,0 @@
-// RUN: %clang_cc1 -verify  -fopenmp  -ast-print %s -o - | FileCheck %s
-// expected-no-diagnostics
-void bar(){
-int i=0;
-}
-
-void myfoo(void){
-
-int N = 13;
-int b,n;
-int a[100];
-
-#pragma omp metadirective when(user={condition(N>10)}:  target teams ) 
default(parallel for)
-for (int i = 0; i < N; i++)
-bar();
-
-}
-
-// CHECK: void bar()
-// CHECK: #pragma omp metadirective when(user={condition(N > 10)}: target 
teams) default(parallel for)


Index: clang/test/OpenMP/metadirective_ast_print4.c
===
--- /dev/null
+++ clang/test/OpenMP/metadirective_ast_print4.c
@@ -1,23 +0,0 @@
-// RUN: %clang_cc1 -verify  -fopenmp  -ast-print %s -o - | FileCheck %s
-// expected-no-diagnostics
-
-int main() {
-  int N = 15;
-#pragma omp metadirective when(user = {condition(N > 10)} : parallel for)\
- default(target teams) 
-  for (int i = 0; i < N; i++)
-;
-
-
-#pragma omp metadirective when(device = {arch("nvptx64")}, user = {condition(N >= 100)} : parallel for)\
-  default(target parallel for)
-  for (int i = 0; i < N; i++)
-;
-  return 0;
-}
-
-
-
-// CHECK: #pragma omp metadirective when(user={condition(N > 10)}: parallel for) default(target teams)
-// CHECK: #pragma omp metadirective when(device={arch(nvptx64)}, user={condition(N >= 100)}: parallel for) default(target parallel for)
-
Index: clang/test/OpenMP/metadirective_ast_print3.c
===
--- /dev/null
+++ clang/test/OpenMP/metadirective_ast_print3.c
@@ -1,29 +0,0 @@
-// RUN: %clang_cc1 -verify  -fopenmp  -ast-print %s -o - | FileCheck %s
-// expected-no-diagnostics
-
-void bar(){
-	int i=0;	
-}
-
-void myfoo(void){
-
-	int N = 13;
-	int b,n;
-	int a[100];
-
-	
-	#pragma omp  metadirective when (user = {condition(N>10)}: ta

[PATCH] D122069: [Object] Add binary format for bundling offloading metadata

2022-04-13 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield accepted this revision.
JonChesterfield added a comment.
This revision is now accepted and ready to land.

Couple of nits above but basically I'm convinced. The gnarly part of binary 
formats is string tables and I'm delighted that part of MC was readily 
reusable. Wrapping the string table in different bytes to align with the elf 
format may still be a good idea but it's not an obvious correctness hazard.

I like msgpack as a format but the writing machinery in llvm is not very 
reusable. Likewise elf is a great format but quite interwoven with MC. Protobuf 
seems to have the nice property of concatenating objects yielding a valid 
protobuf but the cost of codegen that isn't presently part of the llvm core, 
and is a slightly hairy dependency to pull in.

Medium term, factoring out parts of the elf handling for use here (and in lld?) 
is probably reasonable, but the leading magic bytes here are sufficient that we 
could detect that in backwards-compat fashion if the release gets ahead of us. 
The format here is essentially a string map which is likely to meet future 
requirements from other platforms adequately.

Thanks for sticking with this!




Comment at: llvm/include/llvm/Object/OffloadBinary.h:74
+
+  uint16_t getImageKind() const { return TheEntry->ImageKind; }
+  uint16_t getOffloadKind() const { return TheEntry->OffloadKind; }

these should probably be returning the enum types



Comment at: llvm/include/llvm/Object/OffloadBinary.h:97
+  struct Entry {
+uint16_t ImageKind;// The kind of the image stored.
+uint16_t OffloadKind;  // The producer of this image.

enums here as well? They have uint16_t specified in the type so layout is stable



Comment at: llvm/lib/Object/OffloadBinary.cpp:20
+
+Expected>
+OffloadBinary::create(MemoryBufferRef Buf) {

Not sure Expected<> helps hugely here - stuff only goes wrong as 'parse_failed' 
or failed to allocate, which is kind of the same thing - so we could return a 
default-initialized (null) unique_ptr on failure without loss of information



Comment at: llvm/lib/Object/OffloadBinary.cpp:41
+  // Create a null-terminated string table with all the used strings.
+  StringTableBuilder StrTab(StringTableBuilder::ELF);
+  for (auto &KeyAndValue : OffloadingData.StringData) {

this is good, string table building is by far the most tedious part of formats 
like this


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122069

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


[PATCH] D123498: [clang] Adding Platform/Architecture Specific Resource Header Installation Targets

2022-04-13 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a subscriber: Anastasia.
yaxunl added a comment.

Pls add @Anastasia for OpenCL.

LGTM for HIP. HIP headers depend on some of CUDA headers, but LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123498

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


[PATCH] D97121: [clang-tidy] Add a Standalone diagnostics mode to clang-tidy

2022-04-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I'd like to hear from @sammccall as well, but I think the changes here LGTM. 
Can you please add a release note for the fix?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97121

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


[PATCH] D123655: [clang-tidy] Add portability-std-allocator-const-t check

2022-04-13 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

Shouldn't this check be enabled only when libstdc++ is used?




Comment at: 
clang-tools-extra/docs/clang-tidy/checks/portability-std-allocator-const-t.rst:6
+
+Per C++ ``[allocator.requirements.general]``: "T is any cv-unqualified object
+type", ``std::allocator`` is undefined. Many standard containers use

sammccall wrote:
> this seems a bit standard-ese for the intro paragraph.
> 
> Maybe add a paragraph before it: "This check reports use of `vector` 
> (and similar containers of const elements). These are not allowed in standard 
> C++, and should usually be `vector` instead."
Please synchronize first sentence with Release Notes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123655

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


[PATCH] D122831: [OpenMP] Make the new offloading driver the default

2022-04-13 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

Editing the tests in place to check for new driver properties would mean we 
lose coverage for the old driver and get a lot of churn if we need to back out 
the change.

How about taking some of the more interesting driver tests, duplicating them to 
only run the new driver, changing the content so it actually matches the new 
driver and making sure they make sense. We could / should do that before 
toggling the default.

Then when the old pathway is erased, we also erase the tests which only check 
the behaviour of the old path, and the transient test near-duplication is gone.

Same effect as changing the tests in place, just more resistant to reversion 
churn and has the nice property of continuing to check we haven't accidentally 
broken the old toolchain between now and when it is removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122831

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


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

2022-04-13 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/lib/Format/FormatTokenLexer.h:117-120
+  struct MacroTokenInfo {
+TokenType Type;
+bool Finalized;
+  };

ksyx wrote:
> Would making constructor of `struct MacroTokenInfo` having default parameter 
> or overloading it help avoiding the change of adding `, /*Finalized=*/false` 
> to the existing initializer lists?
I've thought about it, but it would mean that we have a non-explicit 1-arg 
ctor. I'm not a big fan of these as they trigger implicit conversions.
I can do though:
```
  struct MacroTokenInfo {
TokenType Type;
bool Finalized{false};
  };
```
but we'd still need adding braces in:
```
Macros.insert({Identifier, {TT_ForEachMacro}});
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123676

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


[PATCH] D123601: [clang][AArch64] Split neon tests into 2 files

2022-04-13 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.

In D123601#3445601 , @tstellar wrote:

> Can't we add a timeout exception for this test in buildkite?  Splitting the 
> file in two actually increases the runtime, due to the overhead of setting up 
> each test.

I don't know, this is a recurring issue which impacts multiple tests and we've 
not really heard from people maintaining build kite integration AFAIK.

Given that the split up files still contain many functions, I'd expect the 
setup cost to have a relatively small effect.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123601

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


[clang] b58616c - [clang-format] Fix SeparateDefinitionBlocks breaking up function-try-block.

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

Author: Marek Kurdej
Date: 2022-04-13T16:44:04+02:00
New Revision: b58616c2cdf70e075b887a66edf6bbc568e2ff99

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

LOG: [clang-format] Fix SeparateDefinitionBlocks breaking up function-try-block.

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

Reviewed By: HazardyKnusperkeks, owenpan

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/DefinitionBlockSeparatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index c5594a6d66484..018a7ae3ee794 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2603,6 +2603,7 @@ void UnwrappedLineParser::parseTryCatch() {
   nextToken();
 }
 NeedsUnwrappedLine = false;
+Line->MustBeDeclaration = false;
 CompoundStatementIndenter Indenter(this, Style, Line->Level);
 parseBlock();
 if (Style.BraceWrapping.BeforeCatch)

diff  --git a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp 
b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
index 53a3c57ad59fa..cb24cc921bc05 100644
--- a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -43,7 +43,8 @@ class DefinitionBlockSeparatorTest : public ::testing::Test {
 
   static void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
 const FormatStyle &Style = getLLVMStyle(),
-llvm::StringRef ExpectedCode = "") {
+llvm::StringRef ExpectedCode = "",
+bool Inverse = true) {
 ::testing::ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 bool HasOriginalCode = true;
 if (ExpectedCode == "") {
@@ -51,16 +52,18 @@ class DefinitionBlockSeparatorTest : public ::testing::Test 
{
   HasOriginalCode = false;
 }
 
-FormatStyle InverseStyle = Style;
-if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
-  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
-else
-  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
 EXPECT_EQ(ExpectedCode, separateDefinitionBlocks(ExpectedCode, Style))
 << "Expected code is not stable";
-EXPECT_NE(ExpectedCode,
-  separateDefinitionBlocks(ExpectedCode, InverseStyle))
-<< "Inverse formatting makes no 
diff erence";
+if (Inverse) {
+  FormatStyle InverseStyle = Style;
+  if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
+InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
+  else
+InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  EXPECT_NE(ExpectedCode,
+separateDefinitionBlocks(ExpectedCode, InverseStyle))
+  << "Inverse formatting makes no 
diff erence";
+}
 std::string CodeToFormat =
 HasOriginalCode ? Code.str() : removeEmptyLines(Code);
 std::string Result = separateDefinitionBlocks(CodeToFormat, Style);
@@ -448,6 +451,32 @@ TEST_F(DefinitionBlockSeparatorTest, 
OpeningBracketOwnsLine) {
Style);
 }
 
+TEST_F(DefinitionBlockSeparatorTest, TryBlocks) {
+  FormatStyle Style = getLLVMStyle();
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  Style.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  verifyFormat("void FunctionWithInternalTry()\n"
+   "{\n"
+   "  try\n"
+   "  {\n"
+   "return;\n"
+   "  }\n"
+   "  catch (const std::exception &)\n"
+   "  {\n"
+   "  }\n"
+   "}",
+   Style, "", /*Inverse=*/false);
+  verifyFormat("void FunctionWithTryBlock()\n"
+   "try\n"
+   "{\n"
+   "  return;\n"
+   "}\n"
+   "catch (const std::exception &)\n"
+   "{\n"
+   "}",
+   Style, "", /*Inverse=*/false);
+}
+
 TEST_F(DefinitionBlockSeparatorTest, Leave) {
   FormatStyle Style = getLLVMStyle();
   Style.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;



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


[PATCH] D122468: [clang-format] Fix SeparateDefinitionBlocks breaking up function-try-block.

2022-04-13 Thread Marek Kurdej via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb58616c2cdf7: [clang-format] Fix SeparateDefinitionBlocks 
breaking up function-try-block. (authored by curdeius).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122468

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/DefinitionBlockSeparatorTest.cpp


Index: clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
===
--- clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -43,7 +43,8 @@
 
   static void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
 const FormatStyle &Style = getLLVMStyle(),
-llvm::StringRef ExpectedCode = "") {
+llvm::StringRef ExpectedCode = "",
+bool Inverse = true) {
 ::testing::ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 bool HasOriginalCode = true;
 if (ExpectedCode == "") {
@@ -51,16 +52,18 @@
   HasOriginalCode = false;
 }
 
-FormatStyle InverseStyle = Style;
-if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
-  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
-else
-  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
 EXPECT_EQ(ExpectedCode, separateDefinitionBlocks(ExpectedCode, Style))
 << "Expected code is not stable";
-EXPECT_NE(ExpectedCode,
-  separateDefinitionBlocks(ExpectedCode, InverseStyle))
-<< "Inverse formatting makes no difference";
+if (Inverse) {
+  FormatStyle InverseStyle = Style;
+  if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
+InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
+  else
+InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  EXPECT_NE(ExpectedCode,
+separateDefinitionBlocks(ExpectedCode, InverseStyle))
+  << "Inverse formatting makes no difference";
+}
 std::string CodeToFormat =
 HasOriginalCode ? Code.str() : removeEmptyLines(Code);
 std::string Result = separateDefinitionBlocks(CodeToFormat, Style);
@@ -448,6 +451,32 @@
Style);
 }
 
+TEST_F(DefinitionBlockSeparatorTest, TryBlocks) {
+  FormatStyle Style = getLLVMStyle();
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  Style.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  verifyFormat("void FunctionWithInternalTry()\n"
+   "{\n"
+   "  try\n"
+   "  {\n"
+   "return;\n"
+   "  }\n"
+   "  catch (const std::exception &)\n"
+   "  {\n"
+   "  }\n"
+   "}",
+   Style, "", /*Inverse=*/false);
+  verifyFormat("void FunctionWithTryBlock()\n"
+   "try\n"
+   "{\n"
+   "  return;\n"
+   "}\n"
+   "catch (const std::exception &)\n"
+   "{\n"
+   "}",
+   Style, "", /*Inverse=*/false);
+}
+
 TEST_F(DefinitionBlockSeparatorTest, Leave) {
   FormatStyle Style = getLLVMStyle();
   Style.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2603,6 +2603,7 @@
   nextToken();
 }
 NeedsUnwrappedLine = false;
+Line->MustBeDeclaration = false;
 CompoundStatementIndenter Indenter(this, Style, Line->Level);
 parseBlock();
 if (Style.BraceWrapping.BeforeCatch)


Index: clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
===
--- clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -43,7 +43,8 @@
 
   static void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
 const FormatStyle &Style = getLLVMStyle(),
-llvm::StringRef ExpectedCode = "") {
+llvm::StringRef ExpectedCode = "",
+bool Inverse = true) {
 ::testing::ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 bool HasOriginalCode = true;
 if (ExpectedCode == "") {
@@ -51,16 +52,18 @@
   HasOriginalCode = false;
 }
 
-FormatStyle InverseStyle = Style;
-if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
-  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
-else
-  InverseStyle.Separat

[PATCH] D123601: [clang][AArch64] Split neon tests into 2 files

2022-04-13 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.

(splitting up huge monolithic tests likely also speeds up overall testing time 
on multi-core systems)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123601

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


[clang] 0424b51 - [CUDA][HIP] Fix host used external kernel in archive

2022-04-13 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2022-04-13T10:47:16-04:00
New Revision: 0424b5115cffad73a0f6e68affed603a7ed9a692

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

LOG: [CUDA][HIP] Fix host used external kernel in archive

For -fgpu-rdc, a host function may call an external kernel
which is defined in an archive of bitcode. Since this external
kernel is only referenced in host function, the device
bitcode does not contain reference to this external
kernel, then the linker will not try to resolve this external
kernel in the archive.

To fix this issue, host-used external kernels and device
variables are tracked. A global array containing pointers
to these external kernels and variables is emitted which
serves as an artificial references to the external kernels
and variables used by host.

Reviewed by: Artem Belevich

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

Added: 
clang/test/CodeGenCUDA/host-used-extern.cu

Modified: 
clang/include/clang/AST/ASTContext.h
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/Sema/SemaCUDA.cpp
clang/lib/Sema/SemaExpr.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 490128abb2ef2..9e10571740de4 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1160,6 +1160,10 @@ class ASTContext : public RefCountedBase {
   /// Keep track of CUDA/HIP device-side variables ODR-used by host code.
   llvm::DenseSet CUDADeviceVarODRUsedByHost;
 
+  /// Keep track of CUDA/HIP external kernels or device variables ODR-used by
+  /// host code.
+  llvm::DenseSet CUDAExternalDeviceDeclODRUsedByHost;
+
   ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
  SelectorTable &sels, Builtin::Context &builtins,
  TranslationUnitKind TUKind);

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index b251a4a7df3d2..76094c73a9279 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -579,6 +579,30 @@ void CodeGenModule::Release() {
 }
   }
 
+  // Emit a global array containing all external kernels or device variables
+  // used by host functions and mark it as used for CUDA/HIP. This is necessary
+  // to get kernels or device variables in archives linked in even if these
+  // kernels or device variables are only used in host functions.
+  if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
+SmallVector UsedArray;
+for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
+  GlobalDecl GD;
+  if (auto *FD = dyn_cast(D))
+GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
+  else
+GD = GlobalDecl(D);
+  UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
+  GetAddrOfGlobal(GD), Int8PtrTy));
+}
+
+llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
+
+auto *GV = new llvm::GlobalVariable(
+getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
+llvm::ConstantArray::get(ATy, UsedArray), "gpu.used.external");
+addCompilerUsedGlobal(GV);
+  }
+
   emitLLVMUsed();
   if (SanStats)
 SanStats->finish();

diff  --git a/clang/lib/Sema/SemaCUDA.cpp b/clang/lib/Sema/SemaCUDA.cpp
index b0af13044fc29..18f9dd7fb532d 100644
--- a/clang/lib/Sema/SemaCUDA.cpp
+++ b/clang/lib/Sema/SemaCUDA.cpp
@@ -819,8 +819,13 @@ bool Sema::CheckCUDACall(SourceLocation Loc, FunctionDecl 
*Callee) {
 }
   }();
 
-  if (DiagKind == SemaDiagnosticBuilder::K_Nop)
+  if (DiagKind == SemaDiagnosticBuilder::K_Nop) {
+// For -fgpu-rdc, keep track of external kernels used by host functions.
+if (LangOpts.CUDAIsDevice && LangOpts.GPURelocatableDeviceCode &&
+Callee->hasAttr() && !Callee->isDefined())
+  getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Callee);
 return true;
+  }
 
   // Avoid emitting this error twice for the same location.  Using a hashtable
   // like this is unfortunate, but because we must continue parsing as normal

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 375bd2ec59c26..da1fed4d72aec 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -17908,8 +17908,7 @@ MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, 
Sema &SemaRef,
   }
 } else if (VarTarget == Sema::CVT_Device &&
(UserTarget == Sema::CFT_Host ||
-UserTarget == Sema::CFT_HostDevice) &&
-   !Var->hasExternalStorage()) {
+UserTarget == Sema::CFT_HostDevice)) {
   // Record a CUDA/HIP device side variable if it is ODR-used
   // by host code. This is done conservatively, when t

[PATCH] D123441: [CUDA][HIP] Fix host used external kernel in archive

2022-04-13 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
yaxunl marked an inline comment as done.
Closed by commit rG0424b5115cff: [CUDA][HIP] Fix host used external kernel in 
archive (authored by yaxunl).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D123441?vs=421680&id=422519#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123441

Files:
  clang/include/clang/AST/ASTContext.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Sema/SemaCUDA.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CodeGenCUDA/host-used-extern.cu

Index: clang/test/CodeGenCUDA/host-used-extern.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDA/host-used-extern.cu
@@ -0,0 +1,51 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -fcuda-is-device -x hip %s \
+// RUN:   -fgpu-rdc -std=c++11 -emit-llvm -o - -target-cpu gfx906 | FileCheck %s
+
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -fcuda-is-device -x hip %s \
+// RUN:   -fgpu-rdc -std=c++11 -emit-llvm -o - -target-cpu gfx906 \
+// RUN:   | FileCheck -check-prefix=NEG %s
+
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -fcuda-is-device -x hip %s \
+// RUN:   -std=c++11 -emit-llvm -o - -target-cpu gfx906 \
+// RUN:   | FileCheck -check-prefixes=NEG,NORDC %s
+
+#include "Inputs/cuda.h"
+
+// CHECK-LABEL: @gpu.used.external = appending {{.*}}global
+// CHECK-DAG: @_Z7kernel1v
+// CHECK-DAG: @_Z7kernel4v
+// CHECK-DAG: @var1
+// CHECK-LABEL: @llvm.compiler.used = {{.*}} @gpu.used.external
+
+// NEG-NOT: @gpu.used.external = {{.*}} @_Z7kernel2v
+// NEG-NOT: @gpu.used.external = {{.*}} @_Z7kernel3v
+// NEG-NOT: @gpu.used.external = {{.*}} @var2
+// NEG-NOT: @gpu.used.external = {{.*}} @var3
+// NORDC-NOT: @gpu.used.external = {{.*}} @_Z7kernel1v
+// NORDC-NOT: @gpu.used.external = {{.*}} @_Z7kernel4v
+// NORDC-NOT: @gpu.used.external = {{.*}} @var1
+
+__global__ void kernel1();
+
+// kernel2 is not marked as used since it is a definition.
+__global__ void kernel2() {}
+
+// kernel3 is not marked as used since it is not called by host function.
+__global__ void kernel3();
+
+// kernel4 is marked as used even though it is not called.
+__global__ void kernel4();
+
+extern __device__ int var1;
+
+__device__ int var2;
+
+extern __device__ int var3;
+
+void use(int *p);
+
+void test() {
+  kernel1<<<1, 1>>>();
+  void *p = (void*)kernel4;
+  use(&var1);
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -17908,8 +17908,7 @@
   }
 } else if (VarTarget == Sema::CVT_Device &&
(UserTarget == Sema::CFT_Host ||
-UserTarget == Sema::CFT_HostDevice) &&
-   !Var->hasExternalStorage()) {
+UserTarget == Sema::CFT_HostDevice)) {
   // Record a CUDA/HIP device side variable if it is ODR-used
   // by host code. This is done conservatively, when the variable is
   // referenced in any of the following contexts:
@@ -17920,7 +17919,10 @@
   // be visible in the device compilation for the compiler to be able to
   // emit template variables instantiated by host code only and to
   // externalize the static device side variable ODR-used by host code.
-  SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
+  if (!Var->hasExternalStorage())
+SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
+  else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
+SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
 }
   }
 
Index: clang/lib/Sema/SemaCUDA.cpp
===
--- clang/lib/Sema/SemaCUDA.cpp
+++ clang/lib/Sema/SemaCUDA.cpp
@@ -819,8 +819,13 @@
 }
   }();
 
-  if (DiagKind == SemaDiagnosticBuilder::K_Nop)
+  if (DiagKind == SemaDiagnosticBuilder::K_Nop) {
+// For -fgpu-rdc, keep track of external kernels used by host functions.
+if (LangOpts.CUDAIsDevice && LangOpts.GPURelocatableDeviceCode &&
+Callee->hasAttr() && !Callee->isDefined())
+  getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Callee);
 return true;
+  }
 
   // Avoid emitting this error twice for the same location.  Using a hashtable
   // like this is unfortunate, but because we must continue parsing as normal
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -579,6 +579,30 @@
 }
   }
 
+  // Emit a global array containing all external kernels or device variables
+  // used by host functions and mark it as used for CUDA/HIP. This is necessary
+  // to get kernels or device variable

[PATCH] D123498: [clang] Adding Platform/Architecture Specific Resource Header Installation Targets

2022-04-13 Thread Momchil Velikov via Phabricator via cfe-commits
chill added a comment.

Should these lists contain only source tree headers or also generated header 
files? I'm not seeing `arm_mve.h`, for example.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123498

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


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

2022-04-13 Thread ksyx via Phabricator via cfe-commits
ksyx added inline comments.



Comment at: clang/lib/Format/FormatTokenLexer.h:117-120
+  struct MacroTokenInfo {
+TokenType Type;
+bool Finalized;
+  };

curdeius wrote:
> ksyx wrote:
> > Would making constructor of `struct MacroTokenInfo` having default 
> > parameter or overloading it help avoiding the change of adding `, 
> > /*Finalized=*/false` to the existing initializer lists?
> I've thought about it, but it would mean that we have a non-explicit 1-arg 
> ctor. I'm not a big fan of these as they trigger implicit conversions.
> I can do though:
> ```
>   struct MacroTokenInfo {
> TokenType Type;
> bool Finalized{false};
>   };
> ```
> but we'd still need adding braces in:
> ```
> Macros.insert({Identifier, {TT_ForEachMacro}});
> ```
Yes they are both good point to consider and my start point is just that the 
`finalized` property is less frequently be `true`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123676

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


[libunwind] a85da64 - [libunwind][AIX] implementation of the unwinder for AIX

2022-04-13 Thread Xing Xue via cfe-commits

Author: Xing Xue
Date: 2022-04-13T11:01:59-04:00
New Revision: a85da649b9ac67afffec6bff9487e6405e1f9cba

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

LOG: [libunwind][AIX] implementation of the unwinder for AIX

Summary:
This patch contains the implementation of the unwinder for IBM AIX.

AIX does not support the eh_frame section. Instead, the traceback table located 
at the end of each function provides the information for stack unwinding and 
EH. In this patch macro _LIBUNWIND_SUPPORT_TBTAB_UNWIND is used to guard code 
for AIX traceback table based unwinding. Function getInfoFromTBTable() and 
stepWithTBTable() are added to get the EH information from the traceback table 
and to step up the stack respectively.

There are two kinds of LSDA information for EH on AIX, the state table and the 
range table. The state table is used by the previous version of the IBM XL 
compiler, i.e., xlC and xlclang++. The DWARF based range table is used by AIX 
clang++. The traceback table has flags to differentiate these cases. For the 
range table, relative addresses are calculated using a base of 
DW_EH_PE_datarel, which is the TOC base of the module where the function of the 
current frame belongs.

Two personality routines are employed to handle these two different LSDAs, 
__xlcxx_personality_v0() for the state table and __xlcxx_personality_v1() for 
the range table. Since the traceback table does not have the information of the 
personality for the state table approach, its personality 
__xlcxx_personality_v0() is dynamically resolved as the handler for the state 
table. For the range table, the locations of the LSDA and its associated 
personality routine are found in the traceback table.

Assembly code for 32- and 64-bit PowerPC in UnwindRegistersRestore.S and 
UnwindRegistersSave.S are modified so that it can be consumed by the GNU flavor 
assembler and the AIX assembler. The restoration of vector registers does not 
check VRSAVE on AIX because VRSAVE is not used in the AIX ABI.

Reviewed by: MaskRay, compnerd, cebowleratibm, sfertile, libunwind

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

Added: 
libunwind/src/Unwind_AIXExtras.cpp

Modified: 
libunwind/include/libunwind.h
libunwind/include/unwind.h
libunwind/src/AddressSpace.hpp
libunwind/src/CMakeLists.txt
libunwind/src/Registers.hpp
libunwind/src/UnwindCursor.hpp
libunwind/src/UnwindLevel1-gcc-ext.c
libunwind/src/UnwindLevel1.c
libunwind/src/UnwindRegistersRestore.S
libunwind/src/UnwindRegistersSave.S
libunwind/src/assembly.h
libunwind/src/config.h
libunwind/src/libunwind.cpp
libunwind/src/libunwind_ext.h

Removed: 




diff  --git a/libunwind/include/libunwind.h b/libunwind/include/libunwind.h
index 9a74faa48d6ff..a69e72fc132df 100644
--- a/libunwind/include/libunwind.h
+++ b/libunwind/include/libunwind.h
@@ -120,6 +120,9 @@ extern int unw_resume(unw_cursor_t *) LIBUNWIND_AVAIL;
 extern void unw_save_vfp_as_X(unw_cursor_t *) LIBUNWIND_AVAIL;
 #endif
 
+#ifdef _AIX
+extern uintptr_t unw_get_data_rel_base(unw_cursor_t *) LIBUNWIND_AVAIL;
+#endif
 
 extern const char *unw_regname(unw_cursor_t *, unw_regnum_t) LIBUNWIND_AVAIL;
 extern int unw_get_proc_info(unw_cursor_t *, unw_proc_info_t *) 
LIBUNWIND_AVAIL;

diff  --git a/libunwind/include/unwind.h b/libunwind/include/unwind.h
index b8d6020a33672..6557374fa9d31 100644
--- a/libunwind/include/unwind.h
+++ b/libunwind/include/unwind.h
@@ -160,7 +160,7 @@ extern const void *_Unwind_Find_FDE(const void *pc, struct 
dwarf_eh_bases *);
 extern void *_Unwind_FindEnclosingFunction(void *pc);
 
 // Mac OS X does not support text-rel and data-rel addressing so these 
functions
-// are unimplemented
+// are unimplemented.
 extern uintptr_t _Unwind_GetDataRelBase(struct _Unwind_Context *context)
 LIBUNWIND_UNAVAIL;
 extern uintptr_t _Unwind_GetTextRelBase(struct _Unwind_Context *context)

diff  --git a/libunwind/src/AddressSpace.hpp b/libunwind/src/AddressSpace.hpp
index 0c4dfeb4e6834..3d5c001608d05 100644
--- a/libunwind/src/AddressSpace.hpp
+++ b/libunwind/src/AddressSpace.hpp
@@ -24,11 +24,11 @@
 #include "Registers.hpp"
 
 #ifndef _LIBUNWIND_USE_DLADDR
-  #if !defined(_LIBUNWIND_IS_BAREMETAL) && !defined(_WIN32)
-#define _LIBUNWIND_USE_DLADDR 1
-  #else
-#define _LIBUNWIND_USE_DLADDR 0
-  #endif
+#if !(defined(_LIBUNWIND_IS_BAREMETAL) || defined(_WIN32) || defined(_AIX))
+#define _LIBUNWIND_USE_DLADDR 1
+#else
+#define _LIBUNWIND_USE_DLADDR 0
+#endif
 #endif
 
 #if _LIBUNWIND_USE_DLADDR
@@ -45,6 +45,13 @@ struct EHABIIndexEntry {
 };
 #endif
 
+#if defined(_AIX)
+namespace libunwind {
+char *getFuncNameFromTBTable(uintptr_t pc, uint16_t &NameLen,
+ unw_word_t *offset);
+}
+#endif
+
 #i

[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-13 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Thank you all for your feedback!

**CMake integration** 
I have a couple more data points. I've experimented with CMake using Tin's 
CMake PR . I 
confirm that together with this patch, I was able to build a small CMake 
project:

  -- The Fortran compiler identification is LLVMFlang 15.0.0
  -- Detecting Fortran compiler ABI info
  -- Detecting Fortran compiler ABI info - done
  -- Check for working Fortran compiler: /home/build/release/bin/flang-new - 
skipped
  -- Configuring done
  -- Generating done
  -- Build files have been written to: /home/work/cmake_test

As you can see, the compiler discovery worked fine (I was able to build and 
executable using the CMake generated Make files). I also tried the same 
experiment with an extra flag (Option 2 above) and that didn't work. I 
investigated a bit and discovered that internally CMake calls try_compile 

 (CMake docs ). I 
don't see  any way to pass custom compiler options there (i.e. `try_compile` 
expects `flang-new file.f90` to just work). This makes me rather hesitant to 
pursue Option 2 at all.

@sscalpone I hope that this answers your question. I'm happy to re-open that PR 
myself, but it would probably make more sense for Tin to do it (since he wrote 
it originally). Either way, we will be making sure that it's attributed to Tin.

I think that it's also worth taking into account CMake's release cycle. Based 
on the following, it looks like a new version is released every March, July and 
November:

- https://discourse.cmake.org/c/announcements/8
- https://github.com/Kitware/CMake/releases

It would be extremely helpful to align adding CMake support for LLVM Flang with 
LLVM releases.

**LLVM 15 Release**
While people seem to lean towards Option 3, I would like this change to be 
merged on time for LLVM 15. LLVM 16 will be out in 2023 - lets not wait that 
long. Also, with no public progress tracker for upstreaming, I would really 
like to make sure that there is a cut off date for this to land in LLVM.

**Other points**

In D122008#3427407 , @sscalpone wrote:

> As I said this morning, I prefer to wait with this patch until the 
> upstreaming is finished.  The reason is not only to do with upstreaming, but 
> also with a concurrent effort to button up any assertion and runtime errors 
> so the initial user experience is better.

Can you give us an indication when to expect this to be completed? Also, like 
@richard.barton.arm pointed out, people already can see the issues that you 
mentioned even without this patch (i.e. miscompilation errors are orthogonal  
to this).

Note that this is only the first step. We still need to rename `flang-new` as 
`flang`. That's likely going to require a separate discussion. In fact, from my 
experience most people new to LLVM Flang use `flang` rather than `flang-new` 
and  most (all?) find it very confusing. This change is unlikely to change 
their perception of LLVM Flang because it only affects `flang-new`.

Lastly, I don't quite understand why can't we use project's documentation to 
communicate the level of support instead of artificially delaying patches like 
this one. This is what we currently claim (extracted from index.md 
, 
contributed in https://reviews.llvm.org/D120067 by myself):

> While it is capable of generating executables for a number of examples, some 
> functionality is still missing.

I wrote that, perhaps naively, believing that this patch (or something similar) 
would soon be merged. In any case, if Flang developers are concerned how LLVM 
Flang is perceived by compiler users, then could we please fix this through 
better documentation and LLVM release notes?

**New proposal**
@rovka and @rouson , I know that you voted for Option 2, but after my CMake 
experiment I feel that we should really choose between Option 1 and 3. As there 
isn't enough support for Option 1, we should probably park this for now. Please 
let me know if Option 2 would unblock any of you (or anyone else!) and we can 
re-visit. Otherwise, lets wait a bit. Our goal is to have this merged in time 
for LLVM 15.

Thank you all for reading,
Andrzej


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122008

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


[PATCH] D123211: [flang][driver] Add support for generating LLVM bytecode files

2022-04-13 Thread Emil Kieri via Phabricator via cfe-commits
ekieri added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:491
+  // Create and configure `TargetMachine`
+  std::unique_ptr TM;
+

awarzynski wrote:
> ekieri wrote:
> > awarzynski wrote:
> > > ekieri wrote:
> > > > Is there a reason why use TM.reset instead of initialising TM like you 
> > > > do with os below?
> > > Good question!
> > > 
> > > Note that [[ 
> > > https://github.com/llvm/llvm-project/blob/3d0e0e1027203fe5e89104ad81ee7bb53e525f95/llvm/include/llvm/MC/TargetRegistry.h#L446-L452
> > >  | createTargetMachine ]] that I use below returns a plain pointer. [[ 
> > > https://github.com/llvm/llvm-project/blob/3d0e0e1027203fe5e89104ad81ee7bb53e525f95/clang/include/clang/Frontend/CompilerInstance.h#L703-L706
> > >  | createDefaultOutputFile ]] that I use for initialising `os` below 
> > > returns `std::unique_ptr`. IIUC, I can only [[ 
> > > https://en.cppreference.com/w/cpp/memory/unique_ptr/reset | reset ]] a 
> > > `unique_ptr` (like `TM`) with a plain pointer.
> > > 
> > > Have I missed anything?
> > Well, I had missed that. Thanks! Let's see if I got it right this time.
> > 
> > So unique_ptr has an _explicit_ constructor taking a raw pointer 
> > ([[https://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr | 
> > constructor (2)]]). So as you say (if I interpreted you correctly),
> > 
> >   std::unique_ptr TM = 
> > theTarget->createTargetMachine(...);
> > 
> > does not work, as it requires an implicit conversion from raw to unique 
> > pointer. But constructor syntax should (and does for me) work:
> > 
> >   std::unique_ptr 
> > TM(theTarget->createTargetMachine(...));
> > 
> > as this makes the conversion explicit. Does this make sense, or did I miss 
> > something more?
> > Does this make sense, or did I miss something more?
> 
> Yes, I'm the one who missed something here :) Many thanks for pointing this 
> out!
> 
> I convinced myself that I checked this, but clearly I didn't. And I confused 
> the copy-assignment with a proper constructor. Every day is a school day!
> 
> I'll merge this shortly and I will incorporate your suggestion. Thanks for 
> your patience going over this with me :)
> 
> 
Well, thank you! I also learned something new.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123211

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


[PATCH] D123498: [clang] Adding Platform/Architecture Specific Resource Header Installation Targets

2022-04-13 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett added a comment.

Is there any reason to have an AArch64 specific section? A lot of the files do 
apply to both Arm and AArch64 but for example the mve file Momchil mentioned 
does not.

Would make sense if you wanted AArch64 only there'd be an 
`aarch64-resource-headers`, even if it just makes the config command clearer. 
(I would expect some overlap in the file list though)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123498

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


[PATCH] D123498: [clang] Adding Platform/Architecture Specific Resource Header Installation Targets

2022-04-13 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett added a comment.

Then again a lot of Arm systems can run 32 bit code as well so there is a 
situation where you might include both.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123498

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


[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-13 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 422525.
awarzynski added a comment.

Updates based on feedback from @MaskRay (thank you!)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122008

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  flang/include/flang/Runtime/stop.h
  flang/runtime/CMakeLists.txt
  flang/runtime/FortranMain/CMakeLists.txt
  flang/runtime/FortranMain/Fortran_main.c
  flang/test/CMakeLists.txt
  flang/test/Driver/linker-flags.f90

Index: flang/test/Driver/linker-flags.f90
===
--- /dev/null
+++ flang/test/Driver/linker-flags.f90
@@ -0,0 +1,30 @@
+! Verify that the Fortran runtime libraries are present in the linker
+! invocation. These libraries are added on top of other standard runtime
+! libraries that the Clang driver will include.
+
+! NOTE: The additional linker flags tested here are currently specified in
+! clang/lib/Driver/Toolchains/Gnu.cpp. This makes the current implementation GNU
+! (Linux) specific. The following line will make sure that this test is skipped
+! on Windows. Ideally we should find a more robust way of testing this.
+! REQUIRES: shell
+! UNSUPPORTED: darwin, macos
+
+!
+! RUN COMMAND
+!
+! RUN: %flang -### --ld-path=/usr/bin/ld %S/Inputs/hello.f90 2>&1 | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! Compiler invocation to generate the object file
+! CHECK-LABEL: {{.*}} "-emit-obj"
+! CHECK-SAME:  "-o" "[[object_file:.*]]" {{.*}}Inputs/hello.f90
+
+! Linker invocation to generate the executable
+! CHECK-LABEL:  "/usr/bin/ld"
+! CHECK-SAME: "[[object_file]]"
+! CHECK-SAME: -lFortran_main
+! CHECK-SAME: -lFortranRuntime
+! CHECK-SAME: -lFortranDecimal
+! CHECK-SAME: -lm
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -58,6 +58,9 @@
   llvm-dis
   llvm-objdump
   split-file
+  FortranRuntime
+  Fortran_main
+  FortranDecimal
 )
 
 if (FLANG_INCLUDE_TESTS)
Index: flang/runtime/FortranMain/Fortran_main.c
===
--- /dev/null
+++ flang/runtime/FortranMain/Fortran_main.c
@@ -0,0 +1,21 @@
+//===-- runtime/FortranMain/Fortran_main.c ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "flang/Runtime/main.h"
+#include "flang/Runtime/stop.h"
+
+/* main entry into PROGRAM */
+void _QQmain();
+
+/* C main stub */
+int main(int argc, const char *argv[], const char *envp[]) {
+  RTNAME(ProgramStart)(argc, argv, envp);
+  _QQmain();
+  RTNAME(ProgramEndStatement)();
+  return 0;
+}
Index: flang/runtime/FortranMain/CMakeLists.txt
===
--- /dev/null
+++ flang/runtime/FortranMain/CMakeLists.txt
@@ -0,0 +1,3 @@
+llvm_add_library(Fortran_main STATIC
+  Fortran_main.c
+)
Index: flang/runtime/CMakeLists.txt
===
--- flang/runtime/CMakeLists.txt
+++ flang/runtime/CMakeLists.txt
@@ -30,6 +30,8 @@
 # with different names
 include_directories(AFTER ${CMAKE_CURRENT_BINARY_DIR})
 
+add_subdirectory(FortranMain)
+
 add_flang_library(FortranRuntime
   ISO_Fortran_binding.cpp
   allocatable.cpp
Index: flang/include/flang/Runtime/stop.h
===
--- flang/include/flang/Runtime/stop.h
+++ flang/include/flang/Runtime/stop.h
@@ -27,7 +27,7 @@
 NORETURN void RTNAME(ProgramEndStatement)(NO_ARGUMENTS);
 
 // Extensions
-NORETURN void RTNAME(Exit)(int status = EXIT_SUCCESS);
+NORETURN void RTNAME(Exit)(int status DEFAULT_VALUE(EXIT_SUCCESS));
 NORETURN void RTNAME(Abort)(NO_ARGUMENTS);
 
 // Crash with an error message when the program dynamically violates a Fortran
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -382,6 +382,28 @@
  Exec, CmdArgs, Inputs, Output));
 }
 
+static void addFortranRuntimeLibraryPath(const ToolChain &TC,
+ const ArgList &Args,
+ ArgStringList &CmdArgs) {
+  // Default to the /../lib directory. This works fine on the
+  // platforms that we have tested so far. We will probably have to re-fine
+  // this in the future. In particular:
+  //* on some platforms, we may need to use lib64 instead of lib
+  //* this logic should also work on other similar platforms too, so we

[libunwind] 9c0152c - [libunwind][AIX] implementation of the unwinder for AIX

2022-04-13 Thread Xing Xue via cfe-commits

Author: Xing Xue
Date: 2022-04-13T11:29:37-04:00
New Revision: 9c0152cda35f58ad9916b698c7a645d4a4dfeaf2

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

LOG: [libunwind][AIX] implementation of the unwinder for AIX

Summary:
This is an add-on patch to address comments.
- Replace #elif in file  with #else as suggested;
- Reversed the indentation changes in the main patch.

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

Added: 


Modified: 
libunwind/src/assembly.h
libunwind/src/config.h

Removed: 




diff  --git a/libunwind/src/assembly.h b/libunwind/src/assembly.h
index 9554ca8cc62b1..fb07d04071af3 100644
--- a/libunwind/src/assembly.h
+++ b/libunwind/src/assembly.h
@@ -209,7 +209,7 @@
 #if defined(__powerpc64__)
 #define VBYTE_LEN 8
 #define CSECT_ALIGN 3
-#elif defined(__ppc__)
+#else
 #define VBYTE_LEN 4
 #define CSECT_ALIGN 2
 #endif

diff  --git a/libunwind/src/config.h b/libunwind/src/config.h
index 7fd6b7334053e..e751860bd936e 100644
--- a/libunwind/src/config.h
+++ b/libunwind/src/config.h
@@ -60,13 +60,13 @@
   #define _LIBUNWIND_EXPORT
   #define _LIBUNWIND_HIDDEN
 #else
-#if !defined(__ELF__) && !defined(__MACH__) && !defined(_AIX)
-#define _LIBUNWIND_EXPORT __declspec(dllexport)
-#define _LIBUNWIND_HIDDEN
-#else
-#define _LIBUNWIND_EXPORT __attribute__((visibility("default")))
-#define _LIBUNWIND_HIDDEN __attribute__((visibility("hidden")))
-#endif
+  #if !defined(__ELF__) && !defined(__MACH__) && !defined(_AIX)
+#define _LIBUNWIND_EXPORT __declspec(dllexport)
+#define _LIBUNWIND_HIDDEN
+  #else
+#define _LIBUNWIND_EXPORT __attribute__((visibility("default")))
+#define _LIBUNWIND_HIDDEN __attribute__((visibility("hidden")))
+  #endif
 #endif
 
 #define STR(a) #a



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


[PATCH] D119221: [clang][lexer] Allow u8 character literal prefixes in C2x

2022-04-13 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann accepted this revision.
tahonermann added a comment.

Looks good to me! Thank you for filing the separate issue.




Comment at: clang/test/Lexer/utf8-char-literal.cpp:23
+char f = u8'ab';// expected-error {{Unicode character literals may 
not contain multiple characters}}
+char g = u8'\x80';  // expected-warning {{implicit conversion from 
'int' to 'char' changes value from 128 to -128}}
 #endif

aaron.ballman wrote:
> tahonermann wrote:
> > aaron.ballman wrote:
> > > One more test I'd like to see added, just to make sure we're covering 
> > > 6.4.4.4p9 properly:
> > > ```
> > > _Static_assert(
> > >   _Generic(u8'a',
> > >default: 0,
> > >unsigned char : 1),
> > >   "Surprise!");  
> > > ```
> > > We expect the type of a u8 character literal to be `unsigned char` at the 
> > > moment, which is different from a u8 string literal, which uses `char`.
> > > 
> > > However, WG14 is also going to be considering 
> > > http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2653.htm for C2x at our 
> > > meeting next week.
> > Good suggestion. I believe the following update will be needed 
> > to`Sema::ActOnCharacterConstant()` in `clang/lib/Sema/SemaExpr.cpp`:
> >   ...
> >   else if (Literal.isUTF8() && getLangOpts().C2x)
> > Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in c2x.
> >   else if Literal.isUTF8() && getLangOpts().Char8)
> > Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
> >   ...
> > 
> > However, WG14 is also going to be considering 
> > http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2653.htm for C2x at our 
> > meeting next week.
> 
> I have an update on this. We discussed the paper and took a straw poll:
> ```
> Does WG14 wish to adopt N2653 in C23? 18/0/2 (consensus)
> ```
> So we should make sure that we all agree this patch is in line with the 
> changes from that paper. I believe your changes agree, but it'd be nice for 
> @tahonermann to confirm.
Confirmed. N2653 technically changes the type of `u8` character literals to 
`char8_t`, but since that is just a typedef of `unsigned char`, these changes 
still align with the semantic intent. Ideally, we would maybe try to reflect 
the typedef, but 1) the typedef isn't necessarily available, 2) Clang doesn't 
do similarly for any of the other character (or string) literals, and 3) no one 
is likely to care anyway.


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

https://reviews.llvm.org/D119221

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


[PATCH] D123498: [clang] Adding Platform/Architecture Specific Resource Header Installation Targets

2022-04-13 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei accepted this revision.
pengfei added a comment.

LGTM for X86.




Comment at: clang/lib/Headers/CMakeLists.txt:88
+
+set(x86_files
+# Intrinsics

Verified the list is correct to X86. Nit: should make them in alphabetical 
order?



Comment at: clang/lib/Headers/CMakeLists.txt:194
+set(utility_files
+  mm_malloc.h
+)

Is it only used by X86 for now?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123498

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


[PATCH] D123685: [clang][ASTImporter] Add isNewDecl

2022-04-13 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: balazske, steakhal.
Herald added subscribers: gamesh411, Szelethus, dkrupp, rnkovacs.
Herald added a reviewer: a.sidorin.
Herald added a reviewer: shafik.
Herald added a project: All.
martong requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Add a new function with which we can query if a Decl had been newly
created during the import process. This feature is a must if we want to
have a different static analysis strategy for such newly created
declarations.

This is a dependent patch that is needed for the new CTU implementation
discribed at
https://discourse.llvm.org/t/rfc-much-faster-cross-translation-unit-ctu-analysis-implementation/61728


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123685

Files:
  clang/include/clang/AST/ASTImporterSharedState.h
  clang/lib/AST/ASTImporter.cpp
  clang/unittests/AST/ASTImporterTest.cpp


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -7527,6 +7527,38 @@
   EXPECT_TRUE(ToA->isCompleteDefinition());
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, isNewDecl) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  int bar() {
+return 0;
+  }
+  void other() {
+bar();
+  }
+  )",
+  Lang_CXX11);
+  Decl *ToTU = getToTuDecl(
+  R"(
+  int bar() {
+return 0;
+  }
+  )",
+  Lang_CXX11);
+  auto *FromOther = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("other")));
+  ASSERT_TRUE(FromOther);
+
+  auto *ToOther = Import(FromOther, Lang_CXX11);
+  ASSERT_TRUE(ToOther);
+
+  auto *ToBar = FirstDeclMatcher().match(
+  ToTU, functionDecl(hasName("bar")));
+
+  EXPECT_TRUE(SharedStatePtr->isNewDecl(ToOther));
+  EXPECT_FALSE(SharedStatePtr->isNewDecl(ToBar));
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -245,6 +245,7 @@
   ToD = CreateFun(std::forward(args)...);
   // Keep track of imported Decls.
   Importer.RegisterImportedDecl(FromD, ToD);
+  Importer.SharedState->setNewDecl(ToD);
   InitializeImportedDecl(FromD, ToD);
   return false; // A new Decl is created.
 }
Index: clang/include/clang/AST/ASTImporterSharedState.h
===
--- clang/include/clang/AST/ASTImporterSharedState.h
+++ clang/include/clang/AST/ASTImporterSharedState.h
@@ -39,6 +39,9 @@
   /// never cleared (like ImportedFromDecls).
   llvm::DenseMap ImportErrors;
 
+  /// Set of the newly created declarations.
+  llvm::DenseSet NewDecls;
+
   // FIXME put ImportedFromDecls here!
   // And from that point we can better encapsulate the lookup table.
 
@@ -74,6 +77,10 @@
   void setImportDeclError(Decl *To, ImportError Error) {
 ImportErrors[To] = Error;
   }
+
+  bool isNewDecl(const Decl *ToD) const { return NewDecls.count(ToD); }
+
+  void setNewDecl(Decl *ToD) { NewDecls.insert(ToD); }
 };
 
 } // namespace clang


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -7527,6 +7527,38 @@
   EXPECT_TRUE(ToA->isCompleteDefinition());
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, isNewDecl) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  int bar() {
+return 0;
+  }
+  void other() {
+bar();
+  }
+  )",
+  Lang_CXX11);
+  Decl *ToTU = getToTuDecl(
+  R"(
+  int bar() {
+return 0;
+  }
+  )",
+  Lang_CXX11);
+  auto *FromOther = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("other")));
+  ASSERT_TRUE(FromOther);
+
+  auto *ToOther = Import(FromOther, Lang_CXX11);
+  ASSERT_TRUE(ToOther);
+
+  auto *ToBar = FirstDeclMatcher().match(
+  ToTU, functionDecl(hasName("bar")));
+
+  EXPECT_TRUE(SharedStatePtr->isNewDecl(ToOther));
+  EXPECT_FALSE(SharedStatePtr->isNewDecl(ToBar));
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -245,6 +245,7 @@
   ToD = CreateFun(std::forward(args)...);
   // Keep track of imported Decls.
   Importer.RegisterImportedDecl(FromD, ToD);
+  Importer.SharedState->setNewDecl(ToD);
   InitializeImportedDecl(FromD, ToD);
   return false; // A new Decl is created.

[PATCH] D123680: Add support for ignored bitfield conditional codegen.

2022-04-13 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

This is basically what I expected; the general approach seems fine.




Comment at: clang/lib/CodeGen/CGExpr.cpp:200
+  E->IgnoreParenNoopCasts(getContext( {
+if (CondOp->getObjectKind() == OK_BitField)
+  return EmitIgnoredConditionalOperator(CondOp);

Is there some reason we need to special-case bitfields here?



Comment at: clang/lib/CodeGen/CGExpr.cpp:4635
+  eval.begin(CGF);
+  Info.LHS = EmitLValueOrThrowExpression(CGF, E->getTrueExpr());
+  eval.end(CGF);

If we're calling this from EmitIgnoredConditionalOperator, should we be calling 
back into EmitIgnoredExpr, instead of using EmitLValueOrThrowExpression?  
Consider, e.g. `cond ? s1.field1 = val1 : cond2 ? s1.field2 = val2 : s1.field3 
= val3;`.


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

https://reviews.llvm.org/D123680

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


[PATCH] D123680: Add support for ignored bitfield conditional codegen.

2022-04-13 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/CodeGen/CGExpr.cpp:200
+  E->IgnoreParenNoopCasts(getContext( {
+if (CondOp->getObjectKind() == OK_BitField)
+  return EmitIgnoredConditionalOperator(CondOp);

efriedma wrote:
> Is there some reason we need to special-case bitfields here?
I don't think it ends up being a problem to support the 'simple' case (or 
perhaps even the matrix/vector cases?), but I was not really motivated to write 
test cases for all of those cases (nor write error handling, since that is 
already so well handled).




Comment at: clang/lib/CodeGen/CGExpr.cpp:4635
+  eval.begin(CGF);
+  Info.LHS = EmitLValueOrThrowExpression(CGF, E->getTrueExpr());
+  eval.end(CGF);

efriedma wrote:
> If we're calling this from EmitIgnoredConditionalOperator, should we be 
> calling back into EmitIgnoredExpr, instead of using 
> EmitLValueOrThrowExpression?  Consider, e.g. `cond ? s1.field1 = val1 : cond2 
> ? s1.field2 = val2 : s1.field3 = val3;`.
First, this is the 'generic function' that is called by the normal 
ConditionalOperator handling as well, so there would be a bit of branching/etc 
perhaps to make this call 'ignored'.

That said, I'm not really sure what the implications of that would be.  I don't 
really see harm in the example you gave though, so I can put a patch together 
to do that.


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

https://reviews.llvm.org/D123680

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


[clang] b870620 - [NFC] Add CMake cache file for HLSL

2022-04-13 Thread Chris Bieneman via cfe-commits

Author: Chris Bieneman
Date: 2022-04-13T11:28:18-05:00
New Revision: b870620c29814b71b0c9788f17f8054f04ae2d40

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

LOG: [NFC] Add CMake cache file for HLSL

This just adds a trivial CMake cache file (which will grow over time)
to handle the common build configuration for the HLSL compiler.

Added: 
clang/cmake/caches/HLSL.cmake

Modified: 


Removed: 




diff  --git a/clang/cmake/caches/HLSL.cmake b/clang/cmake/caches/HLSL.cmake
new file mode 100644
index 0..e2d02b6b281a3
--- /dev/null
+++ b/clang/cmake/caches/HLSL.cmake
@@ -0,0 +1,11 @@
+# Including the native target is important because some of LLVM's tests fail if
+# you don't.
+set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
+
+# Include the DirectX target for DXIL code generation, eventually we'll include
+# SPIR-V here too.
+set(LLVM_EXPERIMENTAL_TARGETS_TO_BUILD DirectX CACHE STRING "")
+
+# HLSL support is currently limted to clang, eventually it will expand to
+# clang-tools-extra too.
+set(LLVM_ENABLE_PROJECTS "clang" CACHE STRING "")



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


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

2022-04-13 Thread Alex Brachet via Phabricator via cfe-commits
abrachet added a comment.

In D121560#3439570 , @MaskRay wrote:

> If you need a -static-libstdc++ not subject to unused argument warning, 
> --start-no-unused-arguments and D53238  
> (-static=c++stdlib) may be better choices.

That patch might help for `-static-libstdc++` in particular and other -static-* 
flags, however there are other flags that this will help with in the future. 
What about `-nostdlib -noprofilelib`. I'm currently only interested with 
`-nostdlib` and haven't looked into other flags but I suspect this could help 
in other instances too. Could be helpful with sanitizers too, but all their 
flags get read into SanitizerArgs so there are never warnings there.

I don't think --start-no-unused arguments is as good as a solution here. For a 
large project build, I think `--{start,end}-no-unused-arguments` is too heavy a 
hand. You would just end up putting it everywhere and lose any warnings that 
might be useful. This patch is specifically trying to reduce the need for those.


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

https://reviews.llvm.org/D121560

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


[PATCH] D123680: Add support for ignored bitfield conditional codegen.

2022-04-13 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 422539.
erichkeane added a comment.

Added support for chained-conditional operators as requested.  All of the 
variants I could come up with that I was afraid would be breaking ended up 
having an rvalue conversion (which makes it 'work').


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

https://reviews.llvm.org/D123680

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/test/CodeGenCXX/ignored-bitfield-conditional.cpp

Index: clang/test/CodeGenCXX/ignored-bitfield-conditional.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/ignored-bitfield-conditional.cpp
@@ -0,0 +1,147 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s
+
+struct S {
+  int field1 : 5;
+  int field2 : 6;
+  int field3 : 3;
+};
+
+void use(bool cond, struct S s1, struct S s2, int val1, int val2) {
+  // CHECK: define {{.*}}use{{.*}}(
+  // CHECK: %[[S1:.+]] = alloca %struct.S
+  // CHECK: %[[S2:.+]] = alloca %struct.S
+  // CHECK: %[[COND:.+]] = alloca i8
+  // CHECK: %[[VAL1:.+]] = alloca i32
+  // CHECK: %[[VAL2:.+]] = alloca i32
+
+  cond ? s1.field1 = val1 : s1.field2 = val2;
+  // Condition setup, branch.
+  // CHECK: %[[CONDLD:.+]] = load i8, ptr %[[COND]]
+  // CHECK: %[[TO_BOOL:.+]] = trunc i8 %[[CONDLD]] to i1
+  // CHECK: br i1 %[[TO_BOOL]], label %[[TRUE:.+]], label %[[FALSE:.+]]
+
+  // 'True', branch set the BF, branch to 'end'.
+  // CHECK: [[TRUE]]:
+  // CHECK: %[[VAL1LD:.+]] = load i32, ptr %[[VAL1]]
+  // CHECK: %[[VAL1TRUNC:.+]] = trunc i32 %[[VAL1LD]] to i16
+  // CHECK: %[[BF_LOAD:.+]] = load i16, ptr %[[S1]]
+  // CHECK: %[[BF_VAL:.+]] = and i16 %[[VAL1TRUNC]], 31
+  // CHECK: %[[BF_CLEAR:.+]] = and i16 %[[BF_LOAD]], -32
+  // CHECK: %[[BF_SET:.+]] = or i16 %[[BF_CLEAR]], %[[BF_VAL]]
+  // CHECK: store i16 %[[BF_SET]], ptr %[[S1]]
+  // CHECK: br label %[[END:.+]]
+
+  // 'False', branch set the OTHER BF, branch to 'end'.
+  // CHECK: [[FALSE]]:
+  // CHECK: %[[VAL2LD:.+]] = load i32, ptr %[[VAL2]]
+  // CHECK: %[[VAL2TRUNC:.+]] = trunc i32 %[[VAL2LD]] to i16
+  // CHECK: %[[BF_LOAD:.+]] = load i16, ptr %[[S1]]
+  // CHECK: %[[BF_VAL:.+]] = and i16 %[[VAL2TRUNC]], 63 
+  // CHECK: %[[BF_SHIFT:.+]] = shl i16 %[[BF_VAL]], 5
+  // CHECK: %[[BF_CLEAR:.+]] = and i16 %[[BF_LOAD]], -2017
+  // CHECK: %[[BF_SET:.+]] = or i16 %[[BF_CLEAR]], %[[BF_SHIFT]]
+  // CHECK: store i16 %[[BF_SET]], ptr %[[S1]]
+  // CHECK: br label %[[END:.+]]
+
+  // CHECK: [[END]]:
+  // There is nothing in the 'end' block associated with this, but it is the
+  // 'continuation' block for the rest of the function.
+
+  // Same test, has a no-op cast and parens.
+  (void)(cond ? s2.field1 = val1 : s2.field2 = val2);
+  // Condition setup, branch.
+  // CHECK: %[[CONDLD:.+]] = load i8, ptr %[[COND]]
+  // CHECK: %[[TO_BOOL:.+]] = trunc i8 %[[CONDLD]] to i1
+  // CHECK: br i1 %[[TO_BOOL]], label %[[TRUE:.+]], label %[[FALSE:.+]]
+
+  // 'True', branch set the BF, branch to 'end'.
+  // CHECK: [[TRUE]]:
+  // CHECK: %[[VAL1LD:.+]] = load i32, ptr %[[VAL1]]
+  // CHECK: %[[VAL1TRUNC:.+]] = trunc i32 %[[VAL1LD]] to i16
+  // CHECK: %[[BF_LOAD:.+]] = load i16, ptr %[[S2]]
+  // CHECK: %[[BF_VAL:.+]] = and i16 %[[VAL1TRUNC]], 31
+  // CHECK: %[[BF_CLEAR:.+]] = and i16 %[[BF_LOAD]], -32
+  // CHECK: %[[BF_SET:.+]] = or i16 %[[BF_CLEAR]], %[[BF_VAL]]
+  // CHECK: store i16 %[[BF_SET]], ptr %[[S2]]
+  // CHECK: br label %[[END:.+]]
+
+  // 'False', branch set the OTHER BF, branch to 'end'.
+  // CHECK: [[FALSE]]:
+  // CHECK: %[[VAL2LD:.+]] = load i32, ptr %[[VAL2]]
+  // CHECK: %[[VAL2TRUNC:.+]] = trunc i32 %[[VAL2LD]] to i16
+  // CHECK: %[[BF_LOAD:.+]] = load i16, ptr %[[S2]]
+  // CHECK: %[[BF_VAL:.+]] = and i16 %[[VAL2TRUNC]], 63 
+  // CHECK: %[[BF_SHIFT:.+]] = shl i16 %[[BF_VAL]], 5
+  // CHECK: %[[BF_CLEAR:.+]] = and i16 %[[BF_LOAD]], -2017
+  // CHECK: %[[BF_SET:.+]] = or i16 %[[BF_CLEAR]], %[[BF_SHIFT]]
+  // CHECK: store i16 %[[BF_SET]], ptr %[[S2]]
+  // CHECK: br label %[[END:.+]]
+
+  // CHECK: [[END]]:
+  // CHECK-NOT: phi
+  // There is nothing in the 'end' block associated with this, but it is the
+  // 'continuation' block for the rest of the function.
+
+}
+
+
+void use2(bool cond1, bool cond2, struct S s1, int val1, int val2, int val3) {
+  // CHECK: define {{.*}}use2{{.*}}(
+  // CHECK: %[[S1:.+]] = alloca %struct.S
+  // CHECK: %[[COND1:.+]] = alloca i8
+  // CHECK: %[[COND2:.+]] = alloca i8
+  // CHECK: %[[VAL1:.+]] = alloca i32
+  // CHECK: %[[VAL2:.+]] = alloca i32
+  // CHECK: %[[VAL3:.+]] = alloca i32
+
+  cond1 ? s1.field1 = val1 : cond2 ? s1.field2 = val2 : s1.field3 = val3;
+  // First Condition setup, branch.
+  // CHECK: %[[CONDLD:.+]] = load i8, ptr %[[COND1]]
+  // CHECK: %[[TO_BOOL:.+]] = trunc i8 %[[CONDLD]] to i1
+  // CHECK: br i1 %[[TO_BOOL]], label %[[TRUE:.+]], label %[[FALSE:.+]]
+
+  // First 'True' branch, sets field1 to va

[PATCH] D122069: [Object] Add binary format for bundling offloading metadata

2022-04-13 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 422544.
jhuber6 added a comment.

Maxing suggested changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122069

Files:
  llvm/include/llvm/Object/OffloadBinary.h
  llvm/lib/Object/CMakeLists.txt
  llvm/lib/Object/OffloadBinary.cpp
  llvm/unittests/Object/CMakeLists.txt
  llvm/unittests/Object/OffloadingTest.cpp

Index: llvm/unittests/Object/OffloadingTest.cpp
===
--- /dev/null
+++ llvm/unittests/Object/OffloadingTest.cpp
@@ -0,0 +1,65 @@
+#include "llvm/Object/OffloadBinary.h"
+
+#include "llvm/Testing/Support/Error.h"
+#include "gtest/gtest.h"
+#include 
+
+TEST(OffloadingTest, checkOffloadingBinary) {
+  // Create random data to fill the image.
+  std::mt19937 Rng(std::random_device{}());
+  std::uniform_int_distribution SizeDist(0, 256);
+  std::uniform_int_distribution KindDist(0);
+  std::uniform_int_distribution BinaryDist(
+  std::numeric_limits::min(), std::numeric_limits::max());
+  std::uniform_int_distribution StringDist('!', '~');
+  std::vector Image(SizeDist(Rng));
+  std::generate(Image.begin(), Image.end(), [&]() { return BinaryDist(Rng); });
+  std::vector> Strings(SizeDist(Rng));
+  for (auto &KeyAndValue : Strings) {
+std::string Key(SizeDist(Rng), '\0');
+std::string Value(SizeDist(Rng), '\0');
+
+std::generate(Key.begin(), Key.end(), [&]() { return StringDist(Rng); });
+std::generate(Value.begin(), Value.end(),
+  [&]() { return StringDist(Rng); });
+
+KeyAndValue = std::make_pair(Key, Value);
+  }
+
+  // Create the image.
+  llvm::StringMap StringData;
+  for (auto &KeyAndValue : Strings)
+StringData[KeyAndValue.first] = KeyAndValue.second;
+  std::unique_ptr ImageData =
+  llvm::MemoryBuffer::getMemBuffer(
+  {reinterpret_cast(Image.data()), Image.size()}, "", false);
+
+  llvm::OffloadBinary::OffloadingImage Data;
+  Data.TheImageKind = static_cast(KindDist(Rng));
+  Data.TheOffloadKind = static_cast(KindDist(Rng));
+  Data.Flags = KindDist(Rng);
+  Data.StringData = StringData;
+  Data.Image = *ImageData;
+
+  auto BinaryBuffer = llvm::OffloadBinary::write(Data);
+
+  auto BinaryOrErr = llvm::OffloadBinary::create(*BinaryBuffer);
+  if (!BinaryOrErr)
+FAIL();
+
+  // Make sure we get the same data out.
+  auto &Binary = **BinaryOrErr;
+  ASSERT_EQ(Data.TheImageKind, Binary.getImageKind());
+  ASSERT_EQ(Data.TheOffloadKind, Binary.getOffloadKind());
+  ASSERT_EQ(Data.Flags, Binary.getFlags());
+
+  for (auto &KeyAndValue : Strings)
+ASSERT_TRUE(StringData[KeyAndValue.first] ==
+Binary.getString(KeyAndValue.first));
+
+  EXPECT_TRUE(Data.Image.getBuffer() == Binary.getImage());
+
+  // Ensure the size and alignment of the data is correct.
+  EXPECT_TRUE(Binary.getSize() % llvm::OffloadBinary::getAlignment() == 0);
+  EXPECT_TRUE(Binary.getSize() == BinaryBuffer->getBuffer().size());
+}
Index: llvm/unittests/Object/CMakeLists.txt
===
--- llvm/unittests/Object/CMakeLists.txt
+++ llvm/unittests/Object/CMakeLists.txt
@@ -11,6 +11,7 @@
   ELFTest.cpp
   MinidumpTest.cpp
   ObjectFileTest.cpp
+  OffloadingTest.cpp
   SymbolSizeTest.cpp
   SymbolicFileTest.cpp
   XCOFFObjectFileTest.cpp
Index: llvm/lib/Object/OffloadBinary.cpp
===
--- /dev/null
+++ llvm/lib/Object/OffloadBinary.cpp
@@ -0,0 +1,144 @@
+//===- Offloading.cpp - Utilities for handling offloading code  -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "llvm/Object/OffloadBinary.h"
+
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/MC/StringTableBuilder.h"
+#include "llvm/Object/Error.h"
+#include "llvm/Support/FileOutputBuffer.h"
+
+using namespace llvm;
+
+namespace llvm {
+
+Expected>
+OffloadBinary::create(MemoryBufferRef Buf) {
+  if (Buf.getBufferSize() < sizeof(Header) + sizeof(Entry))
+return errorCodeToError(llvm::object::object_error::parse_failed);
+
+  // Check for 0x10FF1OAD magic bytes.
+  if (!Buf.getBuffer().startswith("\x10\xFF\x10\xAD"))
+return errorCodeToError(llvm::object::object_error::parse_failed);
+
+  const char *Start = Buf.getBufferStart();
+  const Header *TheHeader = reinterpret_cast(Start);
+  const Entry *TheEntry =
+  reinterpret_cast(&Start[TheHeader->EntryOffset]);
+
+  return std::unique_ptr(
+  new OffloadBinary(Buf.getBufferStart(), TheHeader, TheEntry));
+}
+
+std::unique_ptr
+OffloadBinary::write(const OffloadingImage &OffloadingData) {
+  // Create a null-terminated string table with all the used strings.
+  St

[PATCH] D119136: [clang] Implement Change scope of lambda trailing-return-type

2022-04-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM! When landing, please revert the changes to SemaDecl.cpp (no need to churn 
that file) and apply the one suggested refactoring (I commented to make it more 
clear which one I mean).




Comment at: clang/lib/Sema/SemaLambda.cpp:1127-1132
+  auto it = LSI->DelayedCaptures.end();
+  if (Var)
+it = llvm::find_if(LSI->DelayedCaptures, [&Var](auto &&Pair) {
+  return Pair.second.Var == Var;
+});
+  if (it != LSI->DelayedCaptures.end()) {

ChuanqiXu wrote:
> I feel like my suggested change is simpler.
+1 to this suggestion being a bit easier to read.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119136

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


[PATCH] D123498: [clang] Adding Platform/Architecture Specific Resource Header Installation Targets

2022-04-13 Thread Abhina Sree via Phabricator via cfe-commits
abhina.sreeskantharajan added inline comments.



Comment at: clang/lib/Headers/CMakeLists.txt:173
   __wmmintrin_pclmul.h
   x86gprintrin.h
   x86intrin.h

qiongsiwu1 wrote:
> abhina.sreeskantharajan wrote:
> > nit: There are some x86 headers here that appear to be x86 only. Should 
> > these be moved to x86_files list?
> Thanks for the comment! Yes indeed. I think currently the `x86gprintrin.h` 
> header is in the `x86_files` list (list starts at line 88). Did I miss some 
> other x86 files? 
Ah sorry, you're right, I think I read the list wrong. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123498

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


[PATCH] D122683: [OpenMP] Use new offloading binary when embedding offloading images

2022-04-13 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 422547.
jhuber6 added a comment.

Cleanup.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122683

Files:
  clang/include/clang/Basic/CodeGenOptions.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/openmp-offload-gpu.c
  clang/test/Frontend/embed-object.c
  clang/test/Frontend/embed-object.ll
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  llvm/include/llvm/Object/OffloadBinary.h
  llvm/include/llvm/Transforms/Utils/ModuleUtils.h
  llvm/lib/Transforms/Utils/ModuleUtils.cpp

Index: llvm/lib/Transforms/Utils/ModuleUtils.cpp
===
--- llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -265,15 +265,15 @@
 }
 
 void llvm::embedBufferInModule(Module &M, MemoryBufferRef Buf,
-   StringRef SectionName) {
-  // Embed the buffer into the module.
+   StringRef SectionName, Align Alignment) {
+  // Embed the memory buffer into the module.
   Constant *ModuleConstant = ConstantDataArray::get(
   M.getContext(), makeArrayRef(Buf.getBufferStart(), Buf.getBufferSize()));
   GlobalVariable *GV = new GlobalVariable(
-  M, ModuleConstant->getType(), true, GlobalValue::ExternalLinkage,
-  ModuleConstant, SectionName.drop_front());
+  M, ModuleConstant->getType(), true, GlobalValue::PrivateLinkage,
+  ModuleConstant, "llvm.embedded.object");
   GV->setSection(SectionName);
-  GV->setVisibility(GlobalValue::HiddenVisibility);
+  GV->setAlignment(Alignment);
 
   appendToCompilerUsed(M, GV);
 }
Index: llvm/include/llvm/Transforms/Utils/ModuleUtils.h
===
--- llvm/include/llvm/Transforms/Utils/ModuleUtils.h
+++ llvm/include/llvm/Transforms/Utils/ModuleUtils.h
@@ -14,6 +14,7 @@
 #define LLVM_TRANSFORMS_UTILS_MODULEUTILS_H
 
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Alignment.h"
 #include "llvm/Support/MemoryBufferRef.h"
 #include  // for std::pair
 
@@ -109,7 +110,8 @@
 
 /// Embed the memory buffer \p Buf into the module \p M as a global using the
 /// specified section name.
-void embedBufferInModule(Module &M, MemoryBufferRef Buf, StringRef SectionName);
+void embedBufferInModule(Module &M, MemoryBufferRef Buf, StringRef SectionName,
+ Align Alignment = Align(1));
 
 class CallInst;
 namespace VFABI {
Index: llvm/include/llvm/Object/OffloadBinary.h
===
--- llvm/include/llvm/Object/OffloadBinary.h
+++ llvm/include/llvm/Object/OffloadBinary.h
@@ -73,6 +73,7 @@
 
   ImageKind getImageKind() const { return TheEntry->TheImageKind; }
   OffloadKind getOffloadKind() const { return TheEntry->TheOffloadKind; }
+  uint32_t getVersion() const { return TheHeader->Version; }
   uint32_t getFlags() const { return TheEntry->Flags; }
   uint64_t getSize() const { return TheHeader->Size; }
 
Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -29,6 +29,7 @@
 #include "llvm/Object/ArchiveWriter.h"
 #include "llvm/Object/Binary.h"
 #include "llvm/Object/ObjectFile.h"
+#include "llvm/Object/OffloadBinary.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Errc.h"
 #include "llvm/Support/FileOutputBuffer.h"
@@ -146,8 +147,8 @@
 static codegen::RegisterCodeGenFlags CodeGenFlags;
 
 /// Magic section string that marks the existence of offloading data. The
-/// section string will be formatted as `.llvm.offloading..`.
-#define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading."
+/// section will contain one or more offloading binaries stored contiguously.
+#define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading"
 
 /// Information for a device offloading file extracted from the host.
 struct DeviceFile {
@@ -201,16 +202,6 @@
 llvm::errs() << *IC << (std::next(IC) != IE ? " " : "\n");
 }
 
-static StringRef getDeviceFileExtension(StringRef DeviceTriple,
-bool IsBitcode = false) {
-  Triple TheTriple(DeviceTriple);
-  if (TheTriple.isAMDGPU() || IsBitcode)
-return "bc";
-  if (TheTriple.isNVPTX())
-return "cubin";
-  return "o";
-}
-
 std::string getMainExecutable(const char *Name) {
   void *Ptr = (void *)(intptr_t)&getMainExecutable;
   auto COWPath = sys::fs::getMainExecutable(Name, Ptr);
@@ -296,39 +287,58 @@
   StringRef Prefix = sys::path::stem(Obj.getFileName());
   SmallVector ToBeStripped;
 
-  // Extract data from sections of the form `.llvm.offloading..`.
+  // Extract offloading binaries from sections with the name `.llvm.offloading`.
   for (const SectionRef &Sec : Obj

[PATCH] D119136: [clang] Implement Change scope of lambda trailing-return-type

2022-04-13 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/Sema/SemaLambda.cpp:1127-1132
+  auto it = LSI->DelayedCaptures.end();
+  if (Var)
+it = llvm::find_if(LSI->DelayedCaptures, [&Var](auto &&Pair) {
+  return Pair.second.Var == Var;
+});
+  if (it != LSI->DelayedCaptures.end()) {

aaron.ballman wrote:
> ChuanqiXu wrote:
> > I feel like my suggested change is simpler.
> +1 to this suggestion being a bit easier to read.
With that changes, a capture that is not in the delayed capture list forces us 
to go through the list of capture anyway, which seems like a waste.
So this is not just about readability. it should still work,  and only really 
matter for error cases, but it's still not identical code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119136

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


[PATCH] D119136: [clang] Implement Change scope of lambda trailing-return-type

2022-04-13 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/Sema/SemaLambda.cpp:1127-1132
+  auto it = LSI->DelayedCaptures.end();
+  if (Var)
+it = llvm::find_if(LSI->DelayedCaptures, [&Var](auto &&Pair) {
+  return Pair.second.Var == Var;
+});
+  if (it != LSI->DelayedCaptures.end()) {

cor3ntin wrote:
> aaron.ballman wrote:
> > ChuanqiXu wrote:
> > > I feel like my suggested change is simpler.
> > +1 to this suggestion being a bit easier to read.
> With that changes, a capture that is not in the delayed capture list forces 
> us to go through the list of capture anyway, which seems like a waste.
> So this is not just about readability. it should still work,  and only really 
> matter for error cases, but it's still not identical code.
Alternatively, I guess I can change the order of operation to ensure Var is 
never null here, and that would probably be cleaner!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119136

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


[PATCH] D119136: [clang] Implement Change scope of lambda trailing-return-type

2022-04-13 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaLambda.cpp:1127-1132
+  auto it = LSI->DelayedCaptures.end();
+  if (Var)
+it = llvm::find_if(LSI->DelayedCaptures, [&Var](auto &&Pair) {
+  return Pair.second.Var == Var;
+});
+  if (it != LSI->DelayedCaptures.end()) {

cor3ntin wrote:
> cor3ntin wrote:
> > aaron.ballman wrote:
> > > ChuanqiXu wrote:
> > > > I feel like my suggested change is simpler.
> > > +1 to this suggestion being a bit easier to read.
> > With that changes, a capture that is not in the delayed capture list forces 
> > us to go through the list of capture anyway, which seems like a waste.
> > So this is not just about readability. it should still work,  and only 
> > really matter for error cases, but it's still not identical code.
> Alternatively, I guess I can change the order of operation to ensure Var is 
> never null here, and that would probably be cleaner!
Ah, thank you for pointing out that this was also about performance. If you're 
able to clean it up by changing the order of operations, that'd be good, but if 
it turns into a slog, I don't insist.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119136

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


[PATCH] D119136: [clang] Implement Change scope of lambda trailing-return-type

2022-04-13 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 422557.
cor3ntin added a comment.

Cleanup SemaLambda as discussed with Aaron


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119136

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Scope.h
  clang/include/clang/Sema/ScopeInfo.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Sema/Scope.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaCXXScopeSpec.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/TreeTransform.h
  clang/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp
  clang/test/SemaCXX/lambda-capture-type-deduction.cpp
  clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1356,7 +1356,7 @@
 
   Change scope of lambda trailing-return-type
   https://wg21.link/P2036R3";>P2036R3
-  No
+  Clang 15
 
 
   Multidimensional subscript operator
Index: clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
===
--- clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
+++ clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
@@ -95,7 +95,7 @@
 #ifdef AVOID
   auto l4 = [var = param] (int param) { ; }; // no warning
 #else
-  auto l4 = [var = param] (int param) { ; }; // expected-warning {{declaration shadows a local variable}}
+  auto l4 = [var = param](int param) { ; }; // expected-warning 2{{declaration shadows a local variable}}
 #endif
 
   // Make sure that inner lambdas work as well.
Index: clang/test/SemaCXX/lambda-capture-type-deduction.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/lambda-capture-type-deduction.cpp
@@ -0,0 +1,156 @@
+// RUN: %clang_cc1 -std=c++2b -verify -fsyntax-only %s
+
+template 
+constexpr bool is_same = false;
+
+template 
+constexpr bool is_same = true;
+
+void f() {
+
+  int y;
+
+  static_assert(is_same decltype((x)) { return x; }())>);
+
+  static_assert(is_same decltype((x)) { return x; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  auto ref = [&x = y](
+ decltype([&](decltype(x)) { return 0; }) y) {
+return x;
+  };
+}
+
+void test_noexcept() {
+
+  int y;
+
+  static_assert(noexcept([x = 1] noexcept(is_same) {}()));
+  static_assert(noexcept([x = 1] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([y] noexcept(is_same) {}()));
+  static_assert(noexcept([y] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([=] noexcept(is_same) {}()));
+  static_assert(noexcept([=] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([&] noexcept(is_same) {}()));
+  static_assert(noexcept([&] mutable noexcept(is_same) {}()));
+
+  static_assert(noexcept([&] mutable noexcept(!is_same) {}())); //expected-error {{static_assert failed due}}
+}
+
+void test_requires() {
+
+  int x;
+
+  [x = 1]() requires is_same {}
+  ();
+  [x = 1]() mutable requires is_same {}
+  ();
+  [x]() requires is_same {}
+  ();
+  [x]() mutable requires is_same {}
+  ();
+  [=]() requires is_same {}
+  ();
+  [=]() mutable requires is_same {}
+  ();
+  [&]() requires is_same {}
+  ();
+  [&]() mutable requires is_same {}
+  ();
+  [&x]() requires is_same {}
+  ();
+  [&x]() mutable requires is_same {}
+  ();
+
+  [x = 1]() requires is_same {} (); //expected-error {{no matching function for call to object of type}} \
+   // expected-note {{candidate function not viable}} \
+   // expected-note {{'is_same' evaluated to false}}
+  [x = 1]() mutable requires is_same {} (); // expected-error {{no matching function for call to object of type}} \
+ // expected-note {{candidate function not viable}} \
+ // expected-note {{'is_same' evaluated to false}}
+}
+
+void err() {
+  int y, z;// expected-note 2{{declared here}}
+  auto implicit_tpl = [=]( // expected-note {{variable 'y' is captured here}}
+  decltype(
+  [&] { return 0; }) y) { //expected-error{{captured variable 'y' cannot appear here}}
+return y;
+  };
+
+  auto init_tpl = [x = 1](  // expected-note{{explicitly captured her

[libunwind] 7165edc - [libunwind][AIX] implementation of the unwinder for AIX

2022-04-13 Thread Xing Xue via cfe-commits

Author: Xing Xue
Date: 2022-04-13T13:18:10-04:00
New Revision: 7165edcad76fec2e025414ddf44e76363806fc3d

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

LOG: [libunwind][AIX] implementation of the unwinder for AIX

NFC - revert identation changes in AddressSpace.hpp from the previous commit

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

Added: 


Modified: 
libunwind/src/AddressSpace.hpp

Removed: 




diff  --git a/libunwind/src/AddressSpace.hpp b/libunwind/src/AddressSpace.hpp
index 3d5c001608d05..5fc9ee3fe6c38 100644
--- a/libunwind/src/AddressSpace.hpp
+++ b/libunwind/src/AddressSpace.hpp
@@ -24,11 +24,11 @@
 #include "Registers.hpp"
 
 #ifndef _LIBUNWIND_USE_DLADDR
-#if !(defined(_LIBUNWIND_IS_BAREMETAL) || defined(_WIN32) || defined(_AIX))
-#define _LIBUNWIND_USE_DLADDR 1
-#else
-#define _LIBUNWIND_USE_DLADDR 0
-#endif
+  #if !(defined(_LIBUNWIND_IS_BAREMETAL) || defined(_WIN32) || defined(_AIX))
+#define _LIBUNWIND_USE_DLADDR 1
+  #else
+#define _LIBUNWIND_USE_DLADDR 0
+  #endif
 #endif
 
 #if _LIBUNWIND_USE_DLADDR



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


  1   2   >