[PATCH] D95479: [clang-format] Avoid considering include directive as a template closer.

2021-01-27 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 rGe3713f156b8c: [clang-format] Avoid considering include 
directive as a template closer. (authored by curdeius).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95479

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10248,6 +10248,21 @@
"{\n"
"};",
Style);
+
+  verifyFormat("#include \"stdint.h\"\n"
+   "namespace rep {}",
+   Style);
+  verifyFormat("#include \n"
+   "namespace rep {}",
+   Style);
+  verifyFormat("#include \n"
+   "namespace rep {}",
+   "#include \n"
+   "namespace rep {\n"
+   "\n"
+   "\n"
+   "}",
+   Style);
 }
 
 TEST_F(FormatTest, SplitEmptyStruct) {
Index: clang/lib/Format/UnwrappedLineFormatter.cpp
===
--- clang/lib/Format/UnwrappedLineFormatter.cpp
+++ clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -371,7 +371,7 @@
 if (Previous->is(tok::comment))
   Previous = Previous->getPreviousNonComment();
 if (Previous) {
-  if (Previous->is(tok::greater))
+  if (Previous->is(tok::greater) && !I[-1]->InPPDirective)
 return 0;
   if (Previous->is(tok::identifier)) {
 const FormatToken *PreviousPrevious =


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10248,6 +10248,21 @@
"{\n"
"};",
Style);
+
+  verifyFormat("#include \"stdint.h\"\n"
+   "namespace rep {}",
+   Style);
+  verifyFormat("#include \n"
+   "namespace rep {}",
+   Style);
+  verifyFormat("#include \n"
+   "namespace rep {}",
+   "#include \n"
+   "namespace rep {\n"
+   "\n"
+   "\n"
+   "}",
+   Style);
 }
 
 TEST_F(FormatTest, SplitEmptyStruct) {
Index: clang/lib/Format/UnwrappedLineFormatter.cpp
===
--- clang/lib/Format/UnwrappedLineFormatter.cpp
+++ clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -371,7 +371,7 @@
 if (Previous->is(tok::comment))
   Previous = Previous->getPreviousNonComment();
 if (Previous) {
-  if (Previous->is(tok::greater))
+  if (Previous->is(tok::greater) && !I[-1]->InPPDirective)
 return 0;
   if (Previous->is(tok::identifier)) {
 const FormatToken *PreviousPrevious =
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95479: [clang-format] Avoid considering include directive as a template closer.

2021-01-27 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a subscriber: tstellar.
curdeius added a comment.

@tstellar, could this be cherry-picked to 12.x branch? As noted above and 
discussed in D93839 , this fixes PR48891 
 bug that introduced an unintended change in 
behaviour of clang-format.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95479

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


[PATCH] D95229: [clangd] Treat optional field type mismatches as soft failures

2021-01-27 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/Protocol.cpp:837
 return false;
+  tryMap(Params, "triggerCharacter", R.triggerCharacter, P);
   R.triggerKind = static_cast(TriggerKind);

why are we no longer checking the value?



Comment at: clang-tools-extra/clangd/Protocol.cpp:33
+template 
+bool mapOptionalOrLog(llvm::json::ObjectMapper &O, llvm::StringLiteral Prop,
+  T &Out) {

sammccall wrote:
> I would call this tryMap for brevity
Sorry... now that it can fail, I don't think `tryMap` is a great name anymore.

`mapOptOrNull`? `mapNullable`? 

up to you


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95229

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


[PATCH] D95246: [SystemZ][z/OS] Fix No such file or directory expression error matching in lit tests - continued

2021-01-27 Thread James Henderson via Phabricator via cfe-commits
jhenderson added a comment.

In D95246#2522913 , 
@abhina.sreeskantharajan wrote:

> Please let me know if there are other guides I will need to update that I'm 
> not aware of.

There's also the lit CommandGuide located at `llvm/docs/CommandGuide/lit.rst`.




Comment at: clang/test/Driver/clang-offload-bundler.c:73-74
 
-// RUN: not clang-offload-bundler -type=i 
-targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu
 -inputs=%t.i,%t.tgt1,%t.tgt2.notexist -outputs=%t.bundle.i 2>&1 | FileCheck %s 
-DFILE=%t.tgt2.notexist --check-prefix CK-ERR5
-// RUN: not clang-offload-bundler -type=i 
-targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu
 -outputs=%t.i,%t.tgt1,%t.tgt2 -inputs=%t.bundle.i.notexist -unbundle 2>&1 | 
FileCheck %s -DFILE=%t.bundle.i.notexist --check-prefix CK-ERR5
-// CK-ERR5: error: '[[FILE]]': {{N|n}}o such file or directory
+// RUN: not clang-offload-bundler -type=i 
-targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu
 -inputs=%t.i,%t.tgt1,%t.tgt2.notexist -outputs=%t.bundle.i 2>&1 | FileCheck %s 
-DFILE=%t.tgt2.notexist -DMSG=%errc_ENOENT --check-prefix CK-ERR5
+// RUN: not clang-offload-bundler -type=i 
-targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu
 -outputs=%t.i,%t.tgt1,%t.tgt2 -inputs=%t.bundle.i.notexist -unbundle 2>&1 | 
FileCheck %s -DFILE=%t.bundle.i.notexist -DMSG=%errc_ENOENT --check-prefix 
CK-ERR5
+// CK-ERR5: error: '[[FILE]]': [[MSG]]

Nit: These are probably good candidates to split up over multiple lines, as in 
the inline edit.



Comment at: lld/CMakeLists.txt:115
+if (LLD_BUILT_STANDALONE)
+  set(LLVM_HOST_TRIPLE ${TARGET_TRIPLE})
+endif()

The target and the host may be two completely different things. This variable 
setting doesn't look right to me. In a situation where someone is building LLD 
to run on Windows but targeting Linux, the host triple value will end up being 
set to a Linux triple, and the tests would fail.

The variable setting can also be moved inside the earlier if about 5 lines up, 
because that block is hit when `LLD_BUILD_STANDALONE` is set.



Comment at: llvm/docs/TestingGuide.rst:545-547
+   Example (%errc_ENOENT): ``No such file or directory``
+
+   Example (%errc_ENOENT): ``no such file or directory``

This is a slightly different format to the other examples above. I think it 
should be like the inline edit. this also helps distinguish the difference 
between the two.

Note: I can't remember which way around the two versions are, so you might need 
to swap them!



Comment at: llvm/utils/lit/lit/llvm/config.py:349-351
+triple = ""
+if hasattr(self.config, 'host_triple'):
+triple = self.config.host_triple

I'm concerned that someone might start using these substitutions in a project 
for the first time, and get confused why they don't work on non-windows 
platforms. Maybe the solution is simply to require LLVM_HOST_TRIPLE to be set 
in all projects, i.e. go back to what you were doing before, and letting python 
fail if it isn't set.

Happy to hear other ideas too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95246

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


[PATCH] D95347: [clang][cli] Port LangOpts to marshalling system, pt.2

2021-01-27 Thread Jan Svoboda 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 rGdfb558b82d3f: [clang][cli] Port LangOpts to marshalling 
system, pt.2 (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D95347?vs=318961&id=319491#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95347

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -432,6 +432,9 @@
   if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
 Diags.Report(diag::warn_c_kext);
 
+  if (Args.hasArg(OPT_fconcepts_ts))
+Diags.Report(diag::warn_fe_concepts_ts_flag);
+
   if (LangOpts.NewAlignOverride &&
   !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
@@ -2076,11 +2079,6 @@
 
   // OpenCL has half keyword
   Opts.Half = Opts.OpenCL;
-
-  // C++ has wchar_t keyword.
-  Opts.WChar = Opts.CPlusPlus;
-
-  Opts.AlignedAllocation = Opts.CPlusPlus17;
 }
 
 /// Check if input file kind and language standard are compatible.
@@ -2356,47 +2354,16 @@
  Opts.SYCLIsDevice ||
  Args.hasArg(OPT_fconvergent_functions);
 
-  Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
-  Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
-  Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Opts.CPlusPlus20);
   Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
   if (!Opts.NoBuiltin)
 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
-  Opts.AlignedAllocation =
-  Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation,
-   Opts.AlignedAllocation);
-  Opts.AlignedAllocationUnavailable =
-  Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable);
-  if (Args.hasArg(OPT_fconcepts_ts))
-Diags.Report(diag::warn_fe_concepts_ts_flag);
-  Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
   Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128)
 ? 128
 : Args.hasArg(OPT_mlong_double_64) ? 64 : 0;
-  Opts.EnableAIXExtendedAltivecABI = Args.hasArg(OPT_mabi_EQ_vec_extabi);
-  Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
-  Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
-|| Args.hasArg(OPT_fdump_record_layouts);
   if (Opts.FastRelaxedMath)
 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
-  Opts.XLPragmaPack = Args.hasArg(OPT_fxl_pragma_pack);
   llvm::sort(Opts.ModuleFeatures);
 
-  Opts.ArmSveVectorBits =
-  getLastArgIntValue(Args, options::OPT_msve_vector_bits_EQ, 0, Diags);
-
-  // __declspec is enabled by default for the PS4 by the driver, and also
-  // enabled for Microsoft Extensions or Borland Extensions, here.
-  //
-  // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
-  // CUDA extension. However, it is required for supporting
-  // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has
-  // been rewritten in terms of something more generic, remove the Opts.CUDA
-  // term here.
-  Opts.DeclSpecKeyword =
-  Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
-   (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA));
-
   // -mrtd option
   if (Arg *A = Args.getLastArg(OPT_mrtd)) {
 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
@@ -2519,11 +2486,6 @@
   Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
   Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
 
-  // Record whether the __DEPRECATED define was requested.
-  Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
- OPT_fno_deprecated_macro,
- Opts.Deprecated);
-
   // FIXME: Eliminate this dependency.
   unsigned Opt = getOptimizationLevel(Args, IK, Diags),
OptSize = getOptimizationLevelSize(Args);
@@ -2554,20 +2516,6 @@
   Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
   }
 
-  LangOptions::FPExceptionModeKind FPEB = LangOptions::FPE_Ignore;
-  if (Arg *A = Args.getLastArg(OPT_ffp_exception_behavior_EQ)) {
-StringRef Val = A->getValue();
-if (Val.equals("ignore"))
-  FPEB = LangOptions::FPE_Ignore;
-else if (Val.equals("maytrap"))
-  FPEB = LangOptions::FPE_MayTrap;
-else if (Val.equals("strict"))
-  FPEB = LangOptions::FPE_Strict;
-else
-  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
-  }
-  Opts.setFPExceptionMode(FPEB);
-
   // Parse -fsanitize= arguments.
 

[PATCH] D95244: [clang][AST] Handle overload callee type in CallExpr::getCallReturnType.

2021-01-27 Thread Gabor Marton via Phabricator via cfe-commits
martong added reviewers: rsmith, majnemer.
martong added subscribers: majnemer, rsmith.
martong added a comment.

Adding reviewers. 
@rsmith as code owner, 
@majnemer based on git blame of CallExpr::getCallReturnType.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95244

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


[PATCH] D95439: [clangd] Add include-fixer fixit for field_incomplete_or_sizeless diagnostic.

2021-01-27 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 319492.
hokein added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95439

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

Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -38,8 +38,9 @@
 using ::testing::Field;
 using ::testing::IsEmpty;
 using ::testing::Pair;
-using testing::SizeIs;
+using ::testing::SizeIs;
 using ::testing::UnorderedElementsAre;
+using testing::UnorderedElementsAreArray;
 
 ::testing::Matcher WithFix(::testing::Matcher FixMatcher) {
   return Field(&Diag::Fixes, ElementsAre(FixMatcher));
@@ -770,6 +771,10 @@
 }
 
 ns::X $return[[func]]() {}
+
+class T {
+  ns::X $field[[x]];
+};
   )cpp");
   auto TU = TestTU::withCode(Test.code());
   TU.ExtraArgs.push_back("-std=c++17");
@@ -779,57 +784,64 @@
 
   EXPECT_THAT(
   TU.build().getDiagnostics(),
-  UnorderedElementsAre(
-  AllOf(Diag(Test.range("nested"),
- "incomplete type 'ns::X' named in nested name specifier"),
-DiagName("incomplete_nested_name_spec"),
-WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
-"Add include \"x.h\" for symbol ns::X"))),
-  AllOf(Diag(Test.range("base"), "base class has incomplete type"),
-DiagName("incomplete_base_class"),
-WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
-"Add include \"x.h\" for symbol ns::X"))),
-  AllOf(Diag(Test.range("access"),
- "member access into incomplete type 'ns::X'"),
-DiagName("incomplete_member_access"),
-WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
-"Add include \"x.h\" for symbol ns::X"))),
-  AllOf(
-  Diag(Test.range("type"),
+  UnorderedElementsAreArray(
+  {AllOf(Diag(Test.range("nested"),
+  "incomplete type 'ns::X' named in nested name specifier"),
+ DiagName("incomplete_nested_name_spec"),
+ WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
+ "Add include \"x.h\" for symbol ns::X"))),
+   AllOf(Diag(Test.range("base"), "base class has incomplete type"),
+ DiagName("incomplete_base_class"),
+ WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
+ "Add include \"x.h\" for symbol ns::X"))),
+   AllOf(Diag(Test.range("access"),
+  "member access into incomplete type 'ns::X'"),
+ DiagName("incomplete_member_access"),
+ WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
+ "Add include \"x.h\" for symbol ns::X"))),
+   AllOf(
+   Diag(
+   Test.range("type"),
"incomplete type 'ns::X' where a complete type is required"),
-  DiagName("incomplete_type"),
-  WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
-  "Add include \"x.h\" for symbol ns::X"))),
-  AllOf(Diag(Test.range("incomplete"),
- "variable has incomplete type 'ns::X'"),
-DiagName("typecheck_decl_incomplete_type"),
-WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
-"Add include \"x.h\" for symbol ns::X"))),
-  AllOf(
-  Diag(Test.range("tag"), "incomplete definition of type 'ns::X'"),
-  DiagName("typecheck_incomplete_tag"),
-  WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
-  "Add include \"x.h\" for symbol ns::X"))),
-  AllOf(
-  Diag(Test.range("use"), "invalid use of incomplete type 'ns::X'"),
-  DiagName("invalid_incomplete_type_use"),
-  WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
-  "Add include \"x.h\" for symbol ns::X"))),
-  AllOf(Diag(Test.range("sizeof"), "invalid application of 'sizeof' to "
-   "an incomplete type 'ns::X'"),
-DiagName("sizeof_alignof_incomplete_or_sizeless_type"),
-WithFix(Fix(Test.range("insert"), "#include \"x.h\"\n",
-"Add include \"x.h\" for symbol ns::X"))),
-  AllOf(Diag(Test.range("for"),
- "cannot use incomplete type 'ns::X' as a range"),
-DiagName("for_range_incomplete_type"),
-WithFix(Fix(Test.r

[PATCH] D95439: [clangd] Add include-fixer fixit for field_incomplete_or_sizeless diagnostic.

2021-01-27 Thread Haojian Wu via Phabricator via cfe-commits
hokein marked an inline comment as done.
hokein added inline comments.



Comment at: clang-tools-extra/clangd/IncludeFixer.cpp:81
   case diag::err_func_def_incomplete_result:
+  case diag::err_field_incomplete_or_sizeless:
 // Incomplete type diagnostics should have a QualType argument for the

kadircet wrote:
> what about the `sizless` case ? we'll attach a fixit, but it is not going to 
> fix the issue :(
The [sizeless](https://reviews.llvm.org/D62962) type is a clang extension, I 
think our indexer doesn't index this kind of symbols, so we will not attach a 
fixit for them. 

And I think sizeless case is rare in practice, I would not too worry about it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95439

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


[PATCH] D76802: [InstrProfiling] Use !associated metadata for counters, data and values

2021-01-27 Thread Petr Hosek via Phabricator via cfe-commits
phosek updated this revision to Diff 319493.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76802

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  compiler-rt/test/profile/instrprof-gc-sections.c
  llvm/include/llvm/Transforms/Instrumentation.h
  llvm/include/llvm/Transforms/Instrumentation/InstrProfiling.h
  llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
  llvm/test/Instrumentation/InstrProfiling/icall.ll
  llvm/test/Instrumentation/InstrProfiling/linkage.ll
  llvm/test/Transforms/PGOProfile/associated.ll
  llvm/test/Transforms/PGOProfile/counter_promo.ll
  llvm/test/Transforms/PGOProfile/counter_promo_mexits.ll

Index: llvm/test/Transforms/PGOProfile/counter_promo_mexits.ll
===
--- llvm/test/Transforms/PGOProfile/counter_promo_mexits.ll
+++ llvm/test/Transforms/PGOProfile/counter_promo_mexits.ll
@@ -69,7 +69,7 @@
 ; PROMO-NEXT:  %pgocount{{.*}} = load {{.*}} @__profc_foo{{.*}} 4)
 ; PROMO-NEXT: add 
 ; PROMO-NEXT: store {{.*}}@__profc_foo{{.*}}4)
-; PROMO-NOT: @__profc_foo
+; PROMO-NOT: @__profc_foo{{.*}})
 
 
 bb15: ; preds = %bb14, %bb4
Index: llvm/test/Transforms/PGOProfile/counter_promo.ll
===
--- llvm/test/Transforms/PGOProfile/counter_promo.ll
+++ llvm/test/Transforms/PGOProfile/counter_promo.ll
@@ -60,7 +60,7 @@
 ; ATOMIC_PROMO: atomicrmw add {{.*}} @__profc_foo{{.*}}0), i64 %[[LIVEOUT1]] seq_cst
 ; ATOMIC_PROMO-NEXT: atomicrmw add {{.*}} @__profc_foo{{.*}}1), i64 %[[LIVEOUT2]] seq_cst
 ; ATOMIC_PROMO-NEXT: atomicrmw add {{.*}} @__profc_foo{{.*}}2), i64 %[[LIVEOUT3]] seq_cst
-; PROMO-NOT: @__profc_foo
+; PROMO-NOT: @__profc_foo{{.*}})
 
 
 }
Index: llvm/test/Transforms/PGOProfile/associated.ll
===
--- /dev/null
+++ llvm/test/Transforms/PGOProfile/associated.ll
@@ -0,0 +1,11 @@
+; RUN: opt < %s -pgo-instr-gen -instrprof -counter-associated-metadata -S | FileCheck %s
+; RUN: opt < %s -passes=pgo-instr-gen,instrprof -counter-associated-metadata -S | FileCheck %s
+
+; CHECK: @__profc_foo = private global [1 x i64] zeroinitializer, section "__llvm_prf_cnts", align 8, !associated !0
+; CHECK: @__profd_foo = private global {{.*}}, section "__llvm_prf_data", align 8, !associated !0
+
+define void @foo() {
+  ret void
+}
+
+; CHECK: !0 = !{[1 x i64]* @__profc_foo}
Index: llvm/test/Instrumentation/InstrProfiling/linkage.ll
===
--- llvm/test/Instrumentation/InstrProfiling/linkage.ll
+++ llvm/test/Instrumentation/InstrProfiling/linkage.ll
@@ -8,6 +8,8 @@
 ; RUN: opt < %s -mtriple=x86_64-unknown-linux -passes=instrprof -S | FileCheck %s --check-prefixes=POSIX,LINUX
 ; RUN: opt < %s -mtriple=x86_64-unknown-fuchsia -passes=instrprof -S | FileCheck %s --check-prefixes=POSIX,LINUX
 ; RUN: opt < %s  -mtriple=x86_64-pc-win32-coff -passes=instrprof -S | FileCheck %s --check-prefixes=COFF
+; RUN: opt < %s -mtriple=x86_64-unknown-linux -instrprof -counter-associated-metadata -S | FileCheck %s --check-prefixes=LINUX,POSIX,METADATA
+; RUN: opt < %s -mtriple=x86_64-unknown-linux -passes=instrprof -counter-associated-metadata -S | FileCheck %s --check-prefixes=LINUX,POSIX,METADATA
 
 ; MACHO: @__llvm_profile_runtime = external global i32
 ; LINUX-NOT: @__llvm_profile_runtime = external global i32
@@ -19,7 +21,9 @@
 @__profn_foo_extern = linkonce_odr hidden constant [10 x i8] c"foo_extern"
 
 ; POSIX: @__profc_foo = hidden global
+; METADATA-SAME: !associated !0
 ; POSIX: @__profd_foo = hidden global
+; METADATA-SAME: !associated !0
 ; COFF: @__profc_foo = internal global
 ; COFF-NOT: comdat
 ; COFF: @__profd_foo = internal global
@@ -29,7 +33,9 @@
 }
 
 ; POSIX: @__profc_foo_weak = weak hidden global
+; METADATA: !associated !1
 ; POSIX: @__profd_foo_weak = weak hidden global
+; METADATA: !associated !1
 ; COFF: @__profc_foo_weak = internal global
 ; COFF: @__profd_foo_weak = internal global
 define weak void @foo_weak() {
@@ -38,7 +44,9 @@
 }
 
 ; POSIX: @"__profc_linkage.ll:foo_internal" = internal global
+; METADATA-SAME: !associated !2
 ; POSIX: @"__profd_linkage.ll:foo_internal" = internal global
+; METADATA-SAME: !associated !2
 ; COFF: @"__profc_linkage.ll:foo_internal" = internal global
 ; COFF: @"__profd_linkage.ll:foo_internal" = internal global
 define internal void @foo_internal() {
@@ -47,7 +55,9 @@
 }
 
 ; POSIX: @__profc_foo_inline = linkonce_odr hidden global
+; METADATA-SAME: !associated !3
 ; POSIX: @__profd_foo_inline = linkonce_odr hidden global
+; METADATA-SAME: !associated !3
 ; COFF: @__profc_foo_inline = internal global{{.*}} section ".lprfc$M", align 8
 ; COFF: @__profd_foo_inline = internal global{{.*}} section ".lprfd$M", align 8
 define linkon

[PATCH] D76802: [InstrProfiling] Use !associated metadata for counters, data and values

2021-01-27 Thread Petr Hosek via Phabricator via cfe-commits
phosek added a comment.

In D76802#2524039 , @MaskRay wrote:

> - `__llvm_prf_cnts` does not need to have a self link `SHF_LINK_ORDER`. 
> `__llvm_prf_data` linking to `__llvm_prf_cnts` suffices. This is on the 
> premise that only `__llvm_prf_data` may reference `__llvm_prf_cnts`

Discussed with @MaskRay over chat, this is necessary because `__llvm_prf_cnts` 
is a C identifier.

> - Please update `InstrProfiling/icall.ll` to test `__profvp_` 
> (`-vp-static-alloc=true`). `__llvm_prf_vals` should link to `__llvm_prf_cnts`.

Done.

> - From the current organization of tests, I think `linkage.ll` is a better 
> place than a separate `associated.ll`. The tests there are more comprehensive 
> (needs-comdat and non-needs-comdat cases). You can add the new associated 
> mode to `linkage.ll`.

Done.

> -fbinutils-version is now available. You can condition the associated feature 
> on 2.36 now.

Done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76802

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


[PATCH] D95488: Itanium Mangling: In 'enable_if', omit X/E around .

2021-01-27 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95488

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


[PATCH] D95487: Itanium Mangling: Fix handling of in .

2021-01-27 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/AST/ItaniumMangle.cpp:3912
+IsPrimaryExpr = false;
+  };
+

I think it might be more reasonable to just check for the relatively small 
number of primary-expression cases in `mangleTemplateArgExpr` and skip the 
`X...E` there rather than pushing it down into this function.



Comment at: clang/lib/AST/ItaniumMangle.cpp:5159
+  // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
+  // the proper 'Xfp_E'.
   E = E->IgnoreParenImpCasts();

Oops.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95487

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


[PATCH] D93922: Itanium Mangling: Mangle `__alignof__` differently than `alignof`.

2021-01-27 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

This change looks good to me given the follow-up commits.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93922

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


[PATCH] D89909: [SYCL] Implement SYCL address space attributes handling

2021-01-27 Thread Alexey Bader via Phabricator via cfe-commits
bader added a comment.

Ping^2.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89909

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


[PATCH] D94844: [VFS] Add support to RedirectingFileSystem for mapping a virtual directory to one in the external FS.

2021-01-27 Thread Nathan Hawes via Phabricator via cfe-commits
nathawes updated this revision to Diff 319505.
nathawes added a comment.

- Updated the yaml for the new kind of virtual directory (that maps to a 
directory in the external filesystem) to have a distinct value for its 'type' 
field ('directory-remap') to better distinguish it from the existing 
'directory' type that behaves quite differently.
- Updated lookupPath to return a structure giving both the matched Entry and 
the ExternalRedirect path, rather than returning the matched Entry and setting 
the ExternalRedirect path via an out parameter. This makes it clearer where the 
ExternalRedirect path is computed vs used.
- Updated RedirectingFileSystem::dir_begin to respect the 'use-external-names' 
setting for DirectoryRemapEntry.
- Added unit tests covering directory iteration (dir_begin) with 
DirectoryRemapEntry support.
- Expanded on the documentation comments for RedirectingFileSystem to hopefully 
make the difference between 'directory' and 'directory-remap' entries clearer.


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

https://reviews.llvm.org/D94844

Files:
  clang/test/VFS/Inputs/vfsoverlay-directory-relative.yaml
  clang/test/VFS/Inputs/vfsoverlay-directory.yaml
  clang/test/VFS/directory.c
  lldb/source/Host/common/FileSystem.cpp
  llvm/include/llvm/Support/VirtualFileSystem.h
  llvm/lib/Support/VirtualFileSystem.cpp
  llvm/unittests/Support/VirtualFileSystemTest.cpp

Index: llvm/unittests/Support/VirtualFileSystemTest.cpp
===
--- llvm/unittests/Support/VirtualFileSystemTest.cpp
+++ llvm/unittests/Support/VirtualFileSystemTest.cpp
@@ -1328,6 +1328,7 @@
 
 TEST_F(VFSFromYAMLTest, MappedFiles) {
   IntrusiveRefCntPtr Lower(new DummyFileSystem());
+  Lower->addDirectory("//root/foo/bar");
   Lower->addRegularFile("//root/foo/bar/a");
   IntrusiveRefCntPtr FS = getFromYAMLString(
   "{ 'roots': [\n"
@@ -1343,6 +1344,17 @@
   "  'type': 'file',\n"
   "  'name': 'file2',\n"
   "  'external-contents': '//root/foo/b'\n"
+  "},\n"
+  "{\n"
+  "  'type': 'directory-remap',\n"
+  "  'name': 'mappeddir',\n"
+  "  'external-contents': '//root/foo/bar'\n"
+  "},\n"
+  "{\n"
+  "  'type': 'directory-remap',\n"
+  "  'name': 'mappeddir2',\n"
+  "  'use-external-name': false,\n"
+  "  'external-contents': '//root/foo/bar'\n"
   "}\n"
   "  ]\n"
   "}\n"
@@ -1380,12 +1392,221 @@
   EXPECT_TRUE(S->isDirectory());
   EXPECT_TRUE(S->equivalent(*O->status("//root/"))); // non-volatile UniqueID
 
+  // remapped directory
+  S = O->status("//root/mappeddir");
+  ASSERT_FALSE(S.getError());
+  EXPECT_TRUE(S->isDirectory());
+  EXPECT_TRUE(S->IsVFSMapped);
+  EXPECT_TRUE(S->equivalent(*O->status("//root/foo/bar")));
+
+  SLower = O->status("//root/foo/bar");
+  EXPECT_EQ("//root/foo/bar", SLower->getName());
+  EXPECT_TRUE(S->equivalent(*SLower));
+  EXPECT_FALSE(SLower->IsVFSMapped);
+
+  // file in remapped directory
+  S = O->status("//root/mappeddir/a");
+  ASSERT_FALSE(S.getError());
+  ASSERT_FALSE(S->isDirectory());
+  ASSERT_TRUE(S->IsVFSMapped);
+  ASSERT_EQ("//root/foo/bar/a", S->getName());
+
+  // file in remapped directory, with use-external-name=false
+  S = O->status("//root/mappeddir2/a");
+  ASSERT_FALSE(S.getError());
+  ASSERT_FALSE(S->isDirectory());
+  ASSERT_TRUE(S->IsVFSMapped);
+  ASSERT_EQ("//root/mappeddir2/a", S->getName());
+
+  // file contents in remapped directory
+  OpenedF = O->openFileForRead("//root/mappeddir/a");
+  ASSERT_FALSE(OpenedF.getError());
+  OpenedS = (*OpenedF)->status();
+  ASSERT_FALSE(OpenedS.getError());
+  EXPECT_EQ("//root/foo/bar/a", OpenedS->getName());
+  EXPECT_TRUE(OpenedS->IsVFSMapped);
+
+  // file contents in remapped directory, with use-external-name=false
+  OpenedF = O->openFileForRead("//root/mappeddir2/a");
+  ASSERT_FALSE(OpenedF.getError());
+  OpenedS = (*OpenedF)->status();
+  ASSERT_FALSE(OpenedS.getError());
+  EXPECT_EQ("//root/mappeddir2/a", OpenedS->getName());
+  EXPECT_TRUE(OpenedS->IsVFSMapped);
+
   // broken mapping
   EXPECT_EQ(O->status("//root/file2").getError(),
 llvm::errc::no_such_file_or_directory);
   EXPECT_EQ(0, NumDiagnostics);
 }
 
+TEST_F(VFSFromYAMLTest, MappedRoot) {
+  IntrusiveRefCntPtr Lower(new DummyFileSystem());
+  Lower->addDirectory("//root/foo/bar");
+  Lower->addRegularFile("//root/foo/bar/a");
+  IntrusiveRefCntPtr FS =
+  getFromYAMLString("{ 'roots': [\n"
+"{\n"
+"  'type': 'directory-remap',\n"
+"  'name': '//mappedroot/',\n"
+"  'external-contents': '//root/foo/bar'\n"
+"}\n"

[PATCH] D95061: [OpenCL][Docs] Moved information about internals from UsersManual into OpenCLSupport

2021-01-27 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh added a comment.

Please build the docs and check the build log, as you might break some 
references?




Comment at: clang/docs/UsersManual.rst:2951
   address space map can be added using the :ref:`-ffake-address-space-map
   ` flag.
 

Is this a dead reference now that you moved it to a different file?



Comment at: clang/docs/UsersManual.rst:2962
+enabled by passing the ``-finclude-default-header`` flag (see :ref:`flags
+description ` for more details).
 

Is this a dead reference now that you moved it to a different file?


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

https://reviews.llvm.org/D95061

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


[PATCH] D95061: [OpenCL][Docs] Moved information about internals from UsersManual into OpenCLSupport

2021-01-27 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/docs/UsersManual.rst:2951
   address space map can be added using the :ref:`-ffake-address-space-map
   ` flag.
 

svenvh wrote:
> Is this a dead reference now that you moved it to a different file?
It is moved to another doc but the labels are globally visible. 


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

https://reviews.llvm.org/D95061

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


[PATCH] D95061: [OpenCL][Docs] Moved information about internals from UsersManual into OpenCLSupport

2021-01-27 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh accepted this revision.
svenvh added a comment.
This revision is now accepted and ready to land.

LGTM then, thanks!




Comment at: clang/docs/UsersManual.rst:2951
   address space map can be added using the :ref:`-ffake-address-space-map
   ` flag.
 

Anastasia wrote:
> svenvh wrote:
> > Is this a dead reference now that you moved it to a different file?
> It is moved to another doc but the labels are globally visible. 
Cool, I wasn't expecting that.


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

https://reviews.llvm.org/D95061

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


[PATCH] D94476: [analyzer] Implement conversion from Clang diagnostics to PathDiagnostics.

2021-01-27 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 319513.
NoQ marked 22 inline comments as done.
NoQ added a comment.

Address review comments!


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

https://reviews.llvm.org/D94476

Files:
  clang/include/clang/Analysis/PathDiagnosticConverterDiagnosticConsumer.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/PathDiagnosticConverterDiagnosticConsumer.cpp
  clang/unittests/Analysis/CMakeLists.txt
  clang/unittests/Analysis/PathDiagnosticConverterDiagnosticConsumer.cpp

Index: clang/unittests/Analysis/PathDiagnosticConverterDiagnosticConsumer.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/PathDiagnosticConverterDiagnosticConsumer.cpp
@@ -0,0 +1,246 @@
+//===- PathDiagnosticConverterDiagnosticConsumer.cpp *- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+///
+/// \file
+/// This file provides unittests for PathDiagnosticConverterDiagnosticConsumer.
+///
+//===--===//
+
+#include "clang/Analysis/PathDiagnosticConverterDiagnosticConsumer.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace ento;
+using namespace llvm;
+
+struct ExpectedLocationTy {
+  unsigned Line;
+  unsigned Column;
+
+  void testEquality(SourceLocation L, SourceManager &SM) const {
+EXPECT_EQ(SM.getSpellingLineNumber(L), Line);
+EXPECT_EQ(SM.getSpellingColumnNumber(L), Column);
+  }
+};
+
+struct ExpectedRangeTy {
+  ExpectedLocationTy Begin;
+  ExpectedLocationTy End;
+
+  void testEquality(SourceRange R, SourceManager &SM) const {
+Begin.testEquality(R.getBegin(), SM);
+End.testEquality(R.getEnd(), SM);
+  }
+};
+
+struct ExpectedPieceTy {
+  ExpectedLocationTy Loc;
+  std::string Text;
+  std::vector Ranges;
+
+  void testEquality(const PathDiagnosticPiece &Piece, SourceManager &SM) {
+Loc.testEquality(Piece.getLocation().asLocation(), SM);
+EXPECT_EQ(Piece.getString(), Text);
+EXPECT_EQ(Ranges.size(), Piece.getRanges().size());
+for (const auto &RangeItem : llvm::enumerate(Piece.getRanges()))
+  Ranges[RangeItem.index()].testEquality(RangeItem.value(), SM);
+  }
+};
+
+struct ExpectedDiagTy {
+  ExpectedLocationTy Loc;
+  std::string VerboseDescription;
+  std::string ShortDescription;
+  std::string CheckerName;
+  std::string BugType;
+  std::string Category;
+  std::vector Path;
+
+  void testEquality(const PathDiagnostic &Diag, SourceManager &SM) {
+Loc.testEquality(Diag.getLocation().asLocation(), SM);
+EXPECT_EQ(Diag.getVerboseDescription(), VerboseDescription);
+EXPECT_EQ(Diag.getShortDescription(), ShortDescription);
+EXPECT_EQ(Diag.getCheckerName(), CheckerName);
+EXPECT_EQ(Diag.getBugType(), BugType);
+EXPECT_EQ(Diag.getCategory(), Category);
+
+EXPECT_EQ(Path.size(), Diag.path.size());
+for (const auto &PieceItem : llvm::enumerate(Diag.path))
+  Path[PieceItem.index()].testEquality(*PieceItem.value(), SM);
+  }
+};
+
+using ExpectedDiagsTy = std::vector;
+
+namespace {
+class TestPathDiagnosticConsumer : public PathDiagnosticConsumer {
+  ExpectedDiagsTy ExpectedDiags;
+  SourceManager &SM;
+
+public:
+  TestPathDiagnosticConsumer(ExpectedDiagsTy &&ExpectedDiags, SourceManager &SM)
+  : ExpectedDiags(std::move(ExpectedDiags)), SM(SM) {}
+
+  StringRef getName() const override { return "test"; }
+
+  void FlushDiagnosticsImpl(std::vector &Diags,
+FilesMade *filesMade) override {
+EXPECT_EQ(Diags.size(), ExpectedDiags.size());
+for (const auto &Item : llvm::enumerate(Diags))
+  ExpectedDiags[Item.index()].testEquality(*Item.value(), SM);
+  }
+};
+
+PathDiagnosticConverterDiagnosticConsumer::BugTypeInfo
+bugTypeInfoProvider(const Diagnostic &) {
+  return PathDiagnosticConverterDiagnosticConsumer::BugTypeInfo{
+  "test check name", "test bug type", "test bug category"};
+}
+
+class TestASTConsumer : public ASTConsumer {
+  ExpectedDiagsTy ExpectedDiags;
+  ASTContext &ACtx;
+
+  void performTest(const Decl *D) {
+if (!D->hasBody())
+  return;
+
+assert(!ExpectedDiags.empty() && "Consumer invoked more than once!");
+TestPathDiagnosticConsumer TestPDC{std::move(ExpectedDiags),
+   ACtx.getSourceManager()};
+// Sanitize storage after move so that the above assertion actually worked.
+ExpectedDiags.clear();
+
+PathDiagnosticConsumers PathConsumers = {&TestPDC};
+
+llvm::IntrusiveRefCntPtr DiagEngine =
+new DiagnosticsEngine(new DiagnosticIDs, new DiagnosticOptions);
+PathDiagnost

[PATCH] D94476: [analyzer] Implement conversion from Clang diagnostics to PathDiagnostics.

2021-01-27 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

> [Warning, Note, Remark, Warning, Remark]

I excluded remarks for now with an assertion. Other tests added :)




Comment at: 
clang/include/clang/Analysis/PathDiagnosticConverterDiagnosticConsumer.h:53-56
+  /// Inform the consumer that the last diagnostic has been sent. This is
+  /// necessary because the consumer does not know whether more notes are
+  /// going to be attached to the last warning.
+  void finalize() { flushPartialDiagnostic(); }

steakhal wrote:
> Overriding the `virtual void clang::DiagnosticConsumer::finish()` can't 
> accomplish the same thing?
*mind blown*



Comment at: clang/lib/Analysis/PathDiagnosticConverterDiagnosticConsumer.cpp:38
+  Msg[0] = toupper(Msg[0]);
+  std::string CleanMsg = Msg.str().substr(0, Msg.str().find('[') - 1).str();
+

NoQ wrote:
> steakhal wrote:
> > vsavchenko wrote:
> > > I think this type of stuff should be covered by a comment or a 
> > > descriptive function name.
> > Eh, I don't think it's gonna work this way.
> > We can not assume that the `[` won't appear in the payload of the message.
> > Eg.:
> > `NewDelete-checker-test.cpp:193`
> > ```
> > // newdelete-warning{{Argument to 'delete[]' is the address of the local 
> > variable 'i', which is not memory allocated by 'new[]'}}
> > ```
> > 
> > The best you could do is to do a reverse search.
> > Do we emit the `[mypackage.mychecker]` suffix for all the reports? If not, 
> > then we have a problem.
> Uh-oh, mmm, indeed. I should definitely make this optional as well.
> Do we emit the [mypackage.mychecker] suffix for all the reports? If not, then 
> we have a problem.

This was supposed to be a workaround for clang-tidy doing this to us. I think 
it's actually better to teach clang-tidy not to do this when it's pumping 
output to us. PathDiagnosticConsumers will re-add the checker name when 
appropriate (eg., in text output but not in plist output).



Comment at: 
clang/lib/Analysis/PathDiagnosticConverterDiagnosticConsumer.cpp:74-77
+  PathDiagnosticPieceRef Piece =
+  std::make_shared(PDLoc, CleanMsg);
+
+  PD->setEndOfPath(std::move(Piece));

steakhal wrote:
> Why not construct in place?
With these classes typically there's a bunch of stuff in between, such as 
`Piece->addRange()`. Wait a sec, I can actually handle ranges pretty quickly. 
Let me add them so that this place wasn't empty :D



Comment at: 
clang/unittests/Analysis/PathDiagnosticConverterDiagnosticConsumer.cpp:139
+
+class PathDiagnosticConverterDiagnosticConsumerTestAction
+: public ASTFrontendAction {

steakhal wrote:
> vsavchenko wrote:
> > WE NEED MORE NOUNS!
> What about calling this `DiagnosticMock`?
We still need to discriminate between `FrontendAction` mock, `ASTConsumer` 
mock, and `PathDiagnosticConsumer` mock. Dropped some of the nouns though.


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

https://reviews.llvm.org/D94476

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


[PATCH] D95403: [clang-tidy][analyzer][WIP] Clang-tidy reverse integration into Static Analyzer.

2021-01-27 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 319514.
NoQ added a comment.

Unforget to `git add` tests.


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

https://reviews.llvm.org/D95403

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  clang/include/clang/StaticAnalyzer/Frontend/AnalysisConsumer.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  clang/lib/StaticAnalyzer/Frontend/CMakeLists.txt
  clang/test/Analysis/tidy-integration.c

Index: clang/test/Analysis/tidy-integration.c
===
--- /dev/null
+++ clang/test/Analysis/tidy-integration.c
@@ -0,0 +1,38 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN: -analyzer-tidy-checker=bugprone-assert-side-effect \
+// RUN: -verify=bugprone-assert-side-effect
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN: -analyzer-tidy-checker=bugprone-infinite-loop \
+// RUN: -verify=bugprone-infinite-loop
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN: -analyzer-tidy-checker=cppcoreguidelines-init-variables \
+// RUN: -verify=cppcoreguidelines-init-variables
+
+// Test multiple conflicting -analyzer-tidy-checker flags.
+// RUN: %clang_analyze_cc1 %s \
+// RUN: -analyzer-tidy-checker=bugprone-infinite-loop \
+// RUN: -analyzer-tidy-checker=-bugprone-* \
+// RUN: -analyzer-tidy-checker=cppcoreguidelines-init-variables \
+// RUN: -verify=cppcoreguidelines-init-variables
+
+// Test enabling checkers by default.
+// RUN: %clang --analyze %s \
+// RUN: -Xclang -verify=bugprone-assert-side-effect,bugprone-infinite-loop
+
+void test_bugprone_assert_side_effect() {
+  void exit(int);
+  #define assert(x) if (!(x)) exit(1);
+  int x = 0;
+  assert((++x) == 1); // bugprone-assert-side-effect-warning-re^}}Found assert() with side effect [bugprone-assert-side-effect]{{$
+}
+
+void test_bugprone_infinite_loop(int y) {
+  for (int x = 0; x < 10; ++y) { // bugprone-infinite-loop-warning-re^}}This loop is infinite; none of its condition variables (x) are updated in the loop body [bugprone-infinite-loop]{{$
+  }
+}
+
+void test_cppcoreguidelines_init_variables() {
+  int x; // cppcoreguidelines-init-variables-warning-re^}}Variable 'x' is not initialized [cppcoreguidelines-init-variables]{{$
+}
Index: clang/lib/StaticAnalyzer/Frontend/CMakeLists.txt
===
--- clang/lib/StaticAnalyzer/Frontend/CMakeLists.txt
+++ clang/lib/StaticAnalyzer/Frontend/CMakeLists.txt
@@ -1,3 +1,7 @@
+configure_file(
+  ${CMAKE_SOURCE_DIR}/../clang-tools-extra/clang-tidy/clang-tidy-config.h.cmake
+  ${CMAKE_CURRENT_BINARY_DIR}/clang-tidy-config.h)
+
 include_directories( ${CMAKE_CURRENT_BINARY_DIR}/../Checkers )
 
 set(LLVM_LINK_COMPONENTS
@@ -23,6 +27,31 @@
   clangLex
   clangStaticAnalyzerCheckers
   clangStaticAnalyzerCore
+  clangTidy
+  clangTidyAbseilModule
+  clangTidyAndroidModule
+  clangTidyAlteraModule
+  clangTidyBoostModule
+  clangTidyBugproneModule
+  clangTidyCERTModule
+  clangTidyConcurrencyModule
+  clangTidyCppCoreGuidelinesModule
+  clangTidyDarwinModule
+  clangTidyFuchsiaModule
+  clangTidyGoogleModule
+  clangTidyHICPPModule
+  clangTidyLinuxKernelModule
+  clangTidyLLVMModule
+  clangTidyLLVMLibcModule
+  clangTidyMiscModule
+  clangTidyModernizeModule
+  clangTidyMPIModule
+  clangTidyObjCModule
+  clangTidyOpenMPModule
+  clangTidyPerformanceModule
+  clangTidyPortabilityModule
+  clangTidyReadabilityModule
+  clangTidyZirconModule
 
   DEPENDS
   omp_gen
Index: clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -16,15 +16,20 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Analysis/Analyses/LiveVariables.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/CallGraph.h"
 #include "clang/Analysis/CodeInjector.h"
 #include "clang/Analysis/PathDiagnostic.h"
 #include "clang/Analysis/PathDiagnosticConsumers.h"
+#include "clang/Analysis/PathDiagnosticConverterDiagnosticConsumer.h"
+#include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/CrossTU/CrossTranslationUnit.h"
 #include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/MultiplexConsumer.h"
+#include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Rewrite/Core/Rewriter.h"
 #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
@@ -38,21 +43,35 @@
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
+#include "llvm/Support/Registry.h"
+#in

[PATCH] D93630: [Attr] Apply GNU-style attributes to expression statements

2021-01-27 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 319516.
vsavchenko added a comment.
Herald added a subscriber: dexonsmith.

Add extension for backward compatibility checks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93630

Files:
  clang/include/clang/Basic/Features.def
  clang/lib/Parse/ParseStmt.cpp
  clang/test/Parser/stmt-attributes.c
  clang/test/Parser/stmt-attributes.cpp
  clang/test/Parser/stmt-attributes.m

Index: clang/test/Parser/stmt-attributes.m
===
--- /dev/null
+++ clang/test/Parser/stmt-attributes.m
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -verify %s \
+// RUN:   -fblocks -fobjc-exceptions -fexceptions -fsyntax-only \
+// RUN:   -Wno-unused-value -Wno-unused-getter-return-value
+
+@interface Base
+@end
+
+@interface Test : Base
+@property(getter=hasFoobar) int foobar;
+- (void)foo;
+- (void)bar;
+@end
+
+Test *getTest();
+
+@implementation Test
+- (void)foo __attribute__((nomerge)) {
+  // expected-error@-1 {{'nomerge' attribute only applies to functions and statements}}
+}
+
+- (void)bar {
+  __attribute__(()) [self foo];
+  // expected-error@-1 {{missing '[' at start of message send expression}}
+  // expected-error@-2 {{expected ']'}}
+  // expected-error@-3 {{expected identifier or '('}}
+  // expected-note@-4 {{to match this '['}}
+  __attribute__((nomerge)) [self foo];
+  // expected-warning@-1 {{nomerge attribute is ignored because there exists no call expression inside the statement}}
+  __attribute__((nomerge)) [getTest() foo];
+
+  __attribute__(()) ^{};
+  // expected-error@-1 {{expected identifier or '('}}
+  __attribute__((nomerge)) ^{};
+  // expected-warning@-1 {{nomerge attribute is ignored because there exists no call expression inside the statement}}
+  __attribute__((nomerge)) ^{ [self foo]; }();
+
+  __attribute__(()) @try {
+[self foo];
+  } @finally {
+  }
+
+  __attribute__((nomerge)) @try {
+[getTest() foo];
+  } @finally {
+  }
+
+  __attribute__((nomerge)) (__bridge void *)self;
+  // expected-warning@-1 {{nomerge attribute is ignored because there exists no call expression inside the statement}}
+
+  __attribute__((nomerge)) self.hasFoobar;
+  // expected-warning@-1 {{nomerge attribute is ignored because there exists no call expression inside the statement}}
+}
+@end
Index: clang/test/Parser/stmt-attributes.cpp
===
--- /dev/null
+++ clang/test/Parser/stmt-attributes.cpp
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -std=c++11 -fcxx-exceptions -fexceptions -fsyntax-only -verify %s
+
+template 
+class __attribute__((nomerge)) A {
+  // expected-error@-1 {{'nomerge' attribute only applies to functions and statements}}
+};
+
+class B : public A<> {
+public:
+  void bar();
+};
+
+void bar();
+
+void foo(A<> *obj) {
+  __attribute__((nomerge)) static_cast(obj)->bar();
+  __attribute__((nomerge))[obj]() { static_cast(obj)->bar(); }
+  ();
+  __attribute__(()) try {
+bar();
+  } catch (...) {
+  }
+}
Index: clang/test/Parser/stmt-attributes.c
===
--- /dev/null
+++ clang/test/Parser/stmt-attributes.c
@@ -0,0 +1,86 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+void foo(int i) {
+
+  __attribute__((unknown_attribute)); // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  __attribute__(()) {}
+  __attribute__(()) if (0) {}
+  __attribute__(()) for (;;);
+  __attribute__(()) do {
+__attribute__(()) continue;
+  }
+  while (0)
+;
+  __attribute__(()) while (0);
+
+  __attribute__(()) switch (i) {
+__attribute__(()) case 0 :
+__attribute__(()) default :
+__attribute__(()) break;
+  }
+
+  __attribute__(()) goto here;
+  __attribute__(()) here :
+
+  __attribute__(()) return;
+
+  __attribute__((noreturn)) {} // expected-error {{'noreturn' attribute cannot be applied to a statement}}
+  __attribute__((noreturn)) if (0) {}  // expected-error {{'noreturn' attribute cannot be applied to a statement}}
+  __attribute__((noreturn)) for (;;);  // expected-error {{'noreturn' attribute cannot be applied to a statement}}
+  __attribute__((noreturn)) do {   // expected-error {{'noreturn' attribute cannot be applied to a statement}}
+__attribute__((unavailable)) continue; // expected-error {{'unavailable' attribute cannot be applied to a statement}}
+  }
+  while (0)
+;
+  __attribute__((unknown_attribute)) while (0); // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+
+  __attribute__((unused)) switch (i) { // expected-error {{'unused' attribute cannot be applied to a statement}}
+  __attribute__((uuid)) case 0:// expected-warning {{unknown attribute 'uuid' ignored}}
+  __attribute__((visibility)) default: // expected-error {{'visibility' attribute cannot be applied to a statement}}
+__at

[PATCH] D94844: [VFS] Add support to RedirectingFileSystem for mapping a virtual directory to one in the external FS.

2021-01-27 Thread Nathan Hawes via Phabricator via cfe-commits
nathawes marked 6 inline comments as done.
nathawes added a comment.

@JDevlieghere and @dexonsmith would you mind taking another look?

I ended up changing the 'lookup' functions to drop the ExternalRedirect out 
param and supply that via a new 'LookupResult' return value that also gives the 
matched Entry. Hopefully that avoids any confusion over where it's computed vs 
used. It also served as a good home for the duplicated code and the logic in 
the old SetExternalRedirect closure, as Jonas had mentioned. While adding the 
extra directory iteration tests Duncan suggested I noticed I wasn't respecting 
the 'use-external-names' setting in the return items, so I've also added a new 
directory iterator implementation (RedirectingFSDirRemapIterImpl). That one's 
used to wrap the iterator the external file system gives for the directory 
being mapped to, and updates the paths in the items it returns to refer to the 
virtual directory's path instead, before passing them along.


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

https://reviews.llvm.org/D94844

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


[PATCH] D94596: [clang][AST] Encapsulate DeclarationNameLoc, NFCI

2021-01-27 Thread Mikhail Maltsev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG30d9ca1bd9de: [clang][AST] Encapsulate DeclarationNameLoc, 
NFCI (authored by miyuki).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94596

Files:
  clang/include/clang/AST/DeclarationName.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/DeclarationName.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/tools/libclang/CIndex.cpp

Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -3351,10 +3351,8 @@
 Pieces.push_back(*TemplateArgsLoc);
 
   if (Kind == DeclarationName::CXXOperatorName) {
-Pieces.push_back(SourceLocation::getFromRawEncoding(
-NI.getInfo().CXXOperatorName.BeginOpNameLoc));
-Pieces.push_back(SourceLocation::getFromRawEncoding(
-NI.getInfo().CXXOperatorName.EndOpNameLoc));
+Pieces.push_back(NI.getInfo().getCXXOperatorNameBeginLoc());
+Pieces.push_back(NI.getInfo().getCXXOperatorNameEndLoc());
   }
 
   if (WantSinglePiece) {
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -5413,19 +5413,15 @@
   case DeclarationName::CXXConstructorName:
   case DeclarationName::CXXDestructorName:
   case DeclarationName::CXXConversionFunctionName:
-AddTypeSourceInfo(DNLoc.NamedType.TInfo);
+AddTypeSourceInfo(DNLoc.getNamedTypeInfo());
 break;
 
   case DeclarationName::CXXOperatorName:
-AddSourceLocation(SourceLocation::getFromRawEncoding(
-DNLoc.CXXOperatorName.BeginOpNameLoc));
-AddSourceLocation(
-SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
+AddSourceRange(DNLoc.getCXXOperatorNameRange());
 break;
 
   case DeclarationName::CXXLiteralOperatorName:
-AddSourceLocation(SourceLocation::getFromRawEncoding(
-DNLoc.CXXLiteralOperatorName.OpNameLoc));
+AddSourceLocation(DNLoc.getCXXLiteralOperatorNameLoc());
 break;
 
   case DeclarationName::Identifier:
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -8737,25 +8737,18 @@
 
 DeclarationNameLoc
 ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
-  DeclarationNameLoc DNLoc;
   switch (Name.getNameKind()) {
   case DeclarationName::CXXConstructorName:
   case DeclarationName::CXXDestructorName:
   case DeclarationName::CXXConversionFunctionName:
-DNLoc.NamedType.TInfo = readTypeSourceInfo();
-break;
+return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo());
 
   case DeclarationName::CXXOperatorName:
-DNLoc.CXXOperatorName.BeginOpNameLoc
-  = readSourceLocation().getRawEncoding();
-DNLoc.CXXOperatorName.EndOpNameLoc
-  = readSourceLocation().getRawEncoding();
-break;
+return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange());
 
   case DeclarationName::CXXLiteralOperatorName:
-DNLoc.CXXLiteralOperatorName.OpNameLoc
-  = readSourceLocation().getRawEncoding();
-break;
+return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc(
+readSourceLocation());
 
   case DeclarationName::Identifier:
   case DeclarationName::ObjCZeroArgSelector:
@@ -8765,7 +8758,7 @@
   case DeclarationName::CXXDeductionGuideName:
 break;
   }
-  return DNLoc;
+  return DeclarationNameLoc();
 }
 
 DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -14334,11 +14334,9 @@
 SourceLocation RBrace;
 
 if (DeclRefExpr *DRE = dyn_cast(Callee)) {
-DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
-LBrace = SourceLocation::getFromRawEncoding(
-NameLoc.CXXOperatorName.BeginOpNameLoc);
-RBrace = SourceLocation::getFromRawEncoding(
-NameLoc.CXXOperatorName.EndOpNameLoc);
+  DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
+  LBrace = NameLoc.getCXXOperatorNameBeginLoc();
+  RBrace = NameLoc.getCXXOperatorNameEndLoc();
 } else {
   LBrace = Callee->getBeginLoc();
   RBrace = OpLoc;
Index: clang/lib/Sema/SemaLambda.cpp
===
--- clang/lib/Sema/SemaLambda.cpp
+++ clang/lib/Sema/SemaLambda.cpp
@@ -386,11 +386,8 @@
   //   trailing-return-type respectively.
   DeclarationName MethodName
 = Co

[PATCH] D95448: [flang][driver] Add support for `-J/-module-dir`

2021-01-27 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

@arnamoy10,  thank you for this patch and for working on this! I have a few 
high-level suggestions (+ some inline comments):

**Q1**
`-module-dir` and `-J` in Options.td should be aliases - otherwise we need to 
duplicate some code. I've not used Aliases myself, but perhaps this example 

 could be helpful. You might discover that supporting 2 different spellings for 
one options is currently not possible. In such case we should start with one 
spelling.

**Q2**
Could you try moving your changes from FrontendActions.cpp to 
CompilerInvocation.cpp/CompilerInstance.cpp? Ideally, `CompilerInvocation` 
should encapsulate all compiler and langauge options relevant to the current 
invocation. Once we enter `FrontendActions::ExecuteAction`, all of them should 
be set and ready. This way `ExecuteAction` focuses on the action itself rather 
than setting it up. Also, adding `Fortran::semantics::SemanticsContext` to 
`CompilerInstance` could help with encapsulation.

**Q3**
What about help text for `-J`?

Thank you, this is looking really good and it's great to see more people 
working on the new driver!




Comment at: clang/include/clang/Driver/Options.td:1006-1007
   MarshallingInfoString>;
+def module_dir : Separate<["-"], "module-dir">,
+  Flags<[FlangOption,FC1Option]>, HelpText<"Add to the list of directories to 
be searched by an USE statement">;
 def dsym_dir : JoinedOrSeparate<["-"], "dsym-dir">,

As we are trying to follow `gfortran`, I suggest that we copy the help message 
from there:

```
$ gfortran --help=separate | grep '\-J'
  -J   Put MODULE files in 'directory'
```
Also, we can add the long version (via `DocBrief` field) from here 
https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html:
```
This option specifies where to put .mod files for compiled modules. It is also 
added to the list of directories to searched by an USE statement.

The default is the current directory.
```

I appreciate that this patch only implements the 2nd part of what the option is 
intended to offer (i.e. updates the search patch for module files). But I think 
that it's worthwhile to make the intent behind this option clear from the very 
beginning. We can use the commit message to document the current limitations.

Also, please keep in mind that this help message is going to be re-used by 
`-J`, which belongs to `gfortran_Group`. So the description needs to be valid 
for both.



Comment at: clang/lib/Driver/ToolChains/Flang.cpp:24
+  Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I,
+options::OPT_J, options::OPT_module_dir});
 }

Are `-J` and `-module-dir` really preprocessor options? Wouldn't `OPT_J` and 
`OPT_module_dir` be better suited in `ConstructJob` (or some other method for 
other options)?



Comment at: clang/lib/Driver/ToolChains/Flang.cpp:92
 
-  const auto& D = C.getDriver();
+  const auto &D = C.getDriver();
   // TODO: Replace flang-new with flang once the new driver replaces the

This is an unrelated change. I'm fine with this, but ideally as a separate NFC 
patch (otherwise the history is distorted).



Comment at: flang/include/flang/Frontend/PreprocessorOptions.h:34
+  // Module directory specified by -J
+  std::string moduleDirJ;
+

IMHO `searchDirectoryFromDashJ` would be::
* more consistent (matches `searchDirectoryFromDashI`) 
* more accurate (internally this is only used for defining search directories)



Comment at: flang/include/flang/Parser/parsing.h:35
   std::vector searchDirectories;
+  std::string moduleDirectory;
   std::vector predefinitions;

This is merely module _search_ directory, right? Perhaps worth renaming as 
`moduleSearchDirectory`? 

Also, is it required by the parser? IIUC, it's only used when calling 
`set_moduleDirectory`, which is part of `Fortran::semantics::SemanticsContext`.



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:186
+opts.moduleDirJ = currentArg->getValue();
+opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
+  }

`searchDirectoriesFromDashI` contains search directories specified with `-I`. 
If we add things from `-J` then the name is no longer valid :) One option is to 
rename the variable. Personally I think that we can skip this line.



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:205
   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
-  const unsigned includedFlagsBitmask =
-  clang::driver::options::FC1Option;
+  const unsigned includedFlagsBitmask = clang::driver::options::FC1Option;
   unsigned missingArgIndex, missingArgCount;


[PATCH] D95472: clang-cl: Add /winsdkdir and /winsdkversion flags

2021-01-27 Thread Nico Weber via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa5d85cbec58e: clang-cl: Add /winsdkdir and /winsdkversion 
flags (authored by thakis).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95472

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/MSVC.cpp
  clang/lib/Driver/ToolChains/MSVC.h
  clang/test/Driver/cl-options.c

Index: clang/test/Driver/cl-options.c
===
--- clang/test/Driver/cl-options.c
+++ clang/test/Driver/cl-options.c
@@ -696,8 +696,16 @@
 // VCTOOLSDIR: "-triple" "{{[a-zA-Z0-9_-]*}}-pc-windows-msvc19.11.0"
 
 // Validate that built-in include paths are based on the supplied path
-// RUN: %clang_cl -vctoolsdir "/fake" -### -- %s 2>&1 | FileCheck %s --check-prefix FAKEDIR
+// RUN: %clang_cl -vctoolsdir "/fake" -winsdkdir "/foo" -winsdkversion 10.0.12345.0 -### -- %s 2>&1 | FileCheck %s --check-prefix FAKEDIR
 // FAKEDIR: "-internal-isystem" "/fake{{/|}}include"
 // FAKEDIR: "-internal-isystem" "/fake{{/|}}atlmfc{{/|}}include"
+// FAKEDIR: "-internal-isystem" "/foo{{/|}}Include{{/|}}10.0.12345.0{{/|}}ucrt"
+// FAKEDIR: "-internal-isystem" "/foo{{/|}}Include{{/|}}10.0.12345.0{{/|}}shared"
+// FAKEDIR: "-internal-isystem" "/foo{{/|}}Include{{/|}}10.0.12345.0{{/|}}um"
+// FAKEDIR: "-internal-isystem" "/foo{{/|}}Include{{/|}}10.0.12345.0{{/|}}winrt"
+// FAKEDIR: "-libpath:/fake{{/|}}lib{{/|}}
+// FAKEDIR: "-libpath:/fake{{/|}}atlmfc{{/|}}lib{{/|}}
+// FAKEDIR: "-libpath:/foo{{/|}}Lib{{/|}}10.0.12345.0{{/|}}ucrt
+// FAKEDIR: "-libpath:/foo{{/|}}Lib{{/|}}10.0.12345.0{{/|}}um
 
 void f() { }
Index: clang/lib/Driver/ToolChains/MSVC.h
===
--- clang/lib/Driver/ToolChains/MSVC.h
+++ clang/lib/Driver/ToolChains/MSVC.h
@@ -126,9 +126,10 @@
   void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs,
  llvm::opt::ArgStringList &CC1Args) const override;
 
-  bool getWindowsSDKLibraryPath(std::string &path) const;
-  /// Check if Universal CRT should be used if available
-  bool getUniversalCRTLibraryPath(std::string &path) const;
+  bool getWindowsSDKLibraryPath(
+  const llvm::opt::ArgList &Args, std::string &path) const;
+  bool getUniversalCRTLibraryPath(const llvm::opt::ArgList &Args,
+  std::string &path) const;
   bool useUniversalCRT() const;
   VersionTuple
   computeMSVCVersion(const Driver *D,
Index: clang/lib/Driver/ToolChains/MSVC.cpp
===
--- clang/lib/Driver/ToolChains/MSVC.cpp
+++ clang/lib/Driver/ToolChains/MSVC.cpp
@@ -81,8 +81,9 @@
 }
 
 // Check various environment variables to try and find a toolchain.
-static bool findVCToolChainViaEnvironment(std::string &Path,
-  MSVCToolChain::ToolsetLayout &VSLayout) {
+static bool
+findVCToolChainViaEnvironment(std::string &Path,
+  MSVCToolChain::ToolsetLayout &VSLayout) {
   // These variables are typically set by vcvarsall.bat
   // when launching a developer command prompt.
   if (llvm::Optional VCToolsInstallDir =
@@ -355,13 +356,13 @@
 
 if (TC.useUniversalCRT()) {
   std::string UniversalCRTLibPath;
-  if (TC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
+  if (TC.getUniversalCRTLibraryPath(Args, UniversalCRTLibPath))
 CmdArgs.push_back(
 Args.MakeArgString(Twine("-libpath:") + UniversalCRTLibPath));
 }
 
 std::string WindowsSdkLibPath;
-if (TC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
+if (TC.getWindowsSDKLibraryPath(Args, WindowsSdkLibPath))
   CmdArgs.push_back(
   Args.MakeArgString(std::string("-libpath:") + WindowsSdkLibPath));
   }
@@ -1088,12 +1089,43 @@
   return !SDKVersion.empty();
 }
 
+static bool getWindowsSDKDirViaCommandLine(const ArgList &Args,
+   std::string &Path, int &Major,
+   std::string &Version) {
+  if (Arg *A = Args.getLastArg(options::OPT__SLASH_winsdkdir)) {
+// Don't validate the input; trust the value supplied by the user.
+// The motivation is to prevent unnecessary file and registry access.
+Path = A->getValue();
+if (Arg *A = Args.getLastArg(options::OPT__SLASH_winsdkversion)) {
+  StringRef WinSdkVersion = A->getValue();
+  Version = WinSdkVersion.str();
+  if (WinSdkVersion.consumeInteger(10, Major))
+return false;
+  if (!(WinSdkVersion.empty() || WinSdkVersion.startswith(".")))
+return false;
+} else if (getWindows10SDKVersionFromPath(Path, Version)) {
+  Major = 10;

[PATCH] D95514: [clang][cli] Teach CompilerInvocation to allocate strings on its own

2021-01-27 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: dexonsmith, Bigcheese.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Some members of CompilerInvocation store `StringRef`s pointing to the command 
line arguments.

When round-tripping, those `StringRef`s will reference strings we generated 
ourselves. To ensure they live long enough, this patch creates a string storage 
inside CompilerInvocation itself.

To prevent iterator invalidation, `std::forward_list` was used.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95514

Files:
  clang/include/clang/Frontend/CompilerInvocation.h


Index: clang/include/clang/Frontend/CompilerInvocation.h
===
--- clang/include/clang/Frontend/CompilerInvocation.h
+++ clang/include/clang/Frontend/CompilerInvocation.h
@@ -22,6 +22,8 @@
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/ArrayRef.h"
+
+#include 
 #include 
 #include 
 
@@ -138,6 +140,9 @@
   /// Options controlling preprocessed output.
   PreprocessorOutputOptions PreprocessorOutputOpts;
 
+  /// Container holding strings allocated during round-trip.
+  mutable std::forward_list AllocatedStrings;
+
 public:
   CompilerInvocation() : AnalyzerOpts(new AnalyzerOptions()) {}
 
@@ -188,6 +193,13 @@
   std::string getModuleHash() const;
 
   using StringAllocator = llvm::function_ref;
+
+  /// Allocates a string whose lifetime is tied to the lifetime of this object.
+  const char *AllocateString(const llvm::Twine &Value) const {
+AllocatedStrings.push_front(Value.str());
+return AllocatedStrings.front().c_str();
+  }
+
   /// Generate a cc1-compatible command line arguments from this instance.
   ///
   /// \param [out] Args - The generated arguments. Note that the caller is


Index: clang/include/clang/Frontend/CompilerInvocation.h
===
--- clang/include/clang/Frontend/CompilerInvocation.h
+++ clang/include/clang/Frontend/CompilerInvocation.h
@@ -22,6 +22,8 @@
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/ArrayRef.h"
+
+#include 
 #include 
 #include 
 
@@ -138,6 +140,9 @@
   /// Options controlling preprocessed output.
   PreprocessorOutputOptions PreprocessorOutputOpts;
 
+  /// Container holding strings allocated during round-trip.
+  mutable std::forward_list AllocatedStrings;
+
 public:
   CompilerInvocation() : AnalyzerOpts(new AnalyzerOptions()) {}
 
@@ -188,6 +193,13 @@
   std::string getModuleHash() const;
 
   using StringAllocator = llvm::function_ref;
+
+  /// Allocates a string whose lifetime is tied to the lifetime of this object.
+  const char *AllocateString(const llvm::Twine &Value) const {
+AllocatedStrings.push_front(Value.str());
+return AllocatedStrings.front().c_str();
+  }
+
   /// Generate a cc1-compatible command line arguments from this instance.
   ///
   /// \param [out] Args - The generated arguments. Note that the caller is
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D94472: [WIP][clang][cli] Command line round-trip for HeaderSearch options

2021-01-27 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 319526.
jansvoboda11 added a comment.

Compare once and twice generated arguments, fix re-ordering of UserEntries


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94472

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/Option/ArgList.h
  llvm/lib/Option/ArgList.cpp

Index: llvm/lib/Option/ArgList.cpp
===
--- llvm/lib/Option/ArgList.cpp
+++ llvm/lib/Option/ArgList.cpp
@@ -90,11 +90,22 @@
 }
 
 std::vector ArgList::getAllArgValues(OptSpecifier Id) const {
+  recordQueriedOpts(Id);
   SmallVector Values;
   AddAllArgValues(Values, Id);
   return std::vector(Values.begin(), Values.end());
 }
 
+void ArgList::AddAllArgsExcept(ArgStringList &Output,
+   const DenseSet &ExcludeIds) const {
+  for (const Arg *Arg : *this) {
+if (!ExcludeIds.contains(Arg->getOption().getID())) {
+  Arg->claim();
+  Arg->render(*this, Output);
+}
+  }
+}
+
 void ArgList::AddAllArgsExcept(ArgStringList &Output,
ArrayRef Ids,
ArrayRef ExcludeIds) const {
Index: llvm/include/llvm/Option/ArgList.h
===
--- llvm/include/llvm/Option/ArgList.h
+++ llvm/include/llvm/Option/ArgList.h
@@ -137,6 +137,16 @@
   /// The first and last index of each different OptSpecifier ID.
   DenseMap OptRanges;
 
+  /// The OptSpecifiers that were queried from this argument list.
+  mutable DenseSet QueriedOpts;
+
+  /// Record the queried OptSpecifiers.
+  template 
+  void recordQueriedOpts(OptSpecifiers... Ids) const {
+SmallVector OptsSpecifiers({toOptSpecifier(Ids).getID()...});
+QueriedOpts.insert(OptsSpecifiers.begin(), OptsSpecifiers.end());
+  }
+
   /// Get the range of indexes in which options with the specified IDs might
   /// reside, or (0, 0) if there are no such options.
   OptRange getRange(std::initializer_list Ids) const;
@@ -203,6 +213,7 @@
   template
   iterator_range>
   filtered(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.begin() + Range.first;
 auto E = Args.begin() + Range.second;
@@ -214,6 +225,7 @@
   template
   iterator_range>
   filtered_reverse(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.rend() - Range.second;
 auto E = Args.rend() - Range.first;
@@ -308,6 +320,10 @@
   A->render(*this, Output);
   }
 
+  /// AddAllArgsExcept - Render all arguments not matching any of the excluded
+  /// ids.
+  void AddAllArgsExcept(ArgStringList &Output,
+const DenseSet &ExcludeIds) const;
   /// AddAllArgsExcept - Render all arguments matching any of the given ids
   /// and not matching any of the excluded ids.
   void AddAllArgsExcept(ArgStringList &Output, ArrayRef Ids,
@@ -342,6 +358,12 @@
   ///
   void ClaimAllArgs() const;
 
+  /// Return the OptSpecifiers queried from this argument list.
+  const DenseSet &getQueriedOpts() const { return QueriedOpts; }
+
+  /// Clear the set of queried OptSpecifiers.
+  void clearQueriedOpts() const { QueriedOpts.clear(); }
+
   /// @}
   /// @name Arg Synthesis
   /// @{
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -48,6 +48,7 @@
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/CachedHashString.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/FloatingPointMode.h"
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/None.h"
@@ -204,7 +205,7 @@
   const char *Spelling,
   CompilerInvocation::StringAllocator SA,
   Option::OptionClass OptClass, unsigned,
-  Twine Value) {
+  const Twine &Value) {
   switch (OptClass) {
   case Option::SeparateClass:
   case Option::JoinedOrSeparateClass:
@@ -523,9 +524,94 @@
   return 0;
 }
 
-static std::string GetOptName(llvm::opt::OptSpecifier OptSpecifier) {
-  static const OptTable &OptTable = getDriverOptTable();
-  return OptTable.getOption(OptSpecifier).getPrefixedName();
+static void GenerateArg(SmallVectorImpl &Args,
+llvm::opt::OptSpecifier OptSpecifier,
+CompilerInvocation::StringAllocator SA) {
+  Option Opt = getDriverOptTable().getOption(OptSpecifier);
+  denormalizeSimpleFlag(Args, SA(Opt.getPrefix() + Opt.getName()

[PATCH] D95516: [clang][cli] Benchmark command line round-trip

2021-01-27 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
Herald added a subscriber: mgorny.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch adds a micro-benchmark for command line round-tripping.

The hard-coded arguments come from the longest record in LLVM's 
`compile_commands.json` on Linux.

Results for release build with assertions:

  
  Benchmark Time   CPU Iterations
  
  BM_CompilerInvocationNoRoundTrip2653056 ns2652398 ns269
  BM_CompilerInvocationDoRoundTrip2932063 ns2931050 ns239

Results for release build without assertions:

  
  Benchmark Time   CPU Iterations
  
  BM_CompilerInvocationNoRoundTrip2474006 ns2473101 ns276
  BM_CompilerInvocationDoRoundTrip2741366 ns2740046 ns259

This is a 10% increase in run-time in both scenarios.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95516

Files:
  clang/CMakeLists.txt
  clang/benchmarks/CMakeLists.txt
  clang/benchmarks/CompilerInvocationBench.cpp

Index: clang/benchmarks/CompilerInvocationBench.cpp
===
--- /dev/null
+++ clang/benchmarks/CompilerInvocationBench.cpp
@@ -0,0 +1,115 @@
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Frontend/TextDiagnosticBuffer.h"
+
+#include "benchmark/benchmark.h"
+
+using namespace llvm;
+using namespace clang;
+
+static std::vector GetArgs() {
+  return {"-DHAVE___CXA_THREAD_ATEXIT_IMPL",
+  "-D_GNU_SOURCE",
+  "-D_LIBCPP_BUILDING_LIBRARY",
+  "-D_LIBCPP_DISABLE_EXTERN_TEMPLATE",
+  "-D_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS",
+  "-D_LIBCXXABI_BUILDING_LIBRARY",
+  "-D_LIBCXXABI_LINK_PTHREAD_LIB",
+  "-D__STDC_CONSTANT_MACROS",
+  "-D__STDC_FORMAT_MACROS",
+  "-D__STDC_LIMIT_MACROS",
+  "-Iprojects/libcxxabi/src",
+  "-I/home/user/llvm-project/libcxxabi/src",
+  "-Iinclude",
+  "-I/home/user/llvm-project/llvm/include",
+  "-I/home/user/llvm-project/libcxxabi/include",
+  "-I/home/user/llvm-project/libcxxabi/../libcxx/include",
+  "-fPIC",
+  "-fvisibility-inlines-hidden",
+  "-Werror=date-time",
+  "-Werror=unguarded-availability-new",
+  "-Wall",
+  "-Wextra",
+  "-Wno-unused-parameter",
+  "-Wwrite-strings",
+  "-Wcast-qual",
+  "-Wmissing-field-initializers",
+  "-pedantic",
+  "-Wno-long-long",
+  "-Wimplicit-fallthrough",
+  "-Wcovered-switch-default",
+  "-Wno-noexcept-type",
+  "-Wnon-virtual-dtor",
+  "-Wdelete-non-virtual-dtor",
+  "-Wsuggest-override",
+  "-Wstring-conversion",
+  "-fdiagnostics-color",
+  "-ffunction-sections",
+  "-fdata-sections",
+  "-O2",
+  "-DNDEBUG",
+  "-fPIC",
+  "-nostdinc++",
+  "-Werror=return-type",
+  "-W",
+  "-Wall",
+  "-Wchar-subscripts",
+  "-Wconversion",
+  "-Wmismatched-tags",
+  "-Wmissing-braces",
+  "-Wnewline-eof",
+  "-Wunused-function",
+  "-Wshadow",
+  "-Wshorten-64-to-32",
+  "-Wsign-compare",
+  "-Wsign-conversion",
+  "-Wstrict-aliasing=2",
+  "-Wstrict-overflow=4",
+  "-Wunused-parameter",
+  "-Wunused-variable",
+  "-Wwrite-strings",
+  "-Wundef",
+  "-Wno-suggest-override",
+  "-Wno-error",
+  "-pedantic",
+  "-fstrict-aliasing",
+  "-funwind-tables",
+  "-D_DEBUG",
+  "-UNDEBUG",
+  "-std=c++20",
+  "-o",
+  "/dev/null",
+  "-c",
+  "/home/user/llvm-project/libcxxabi/src/cxa_exception_storage.cpp"};
+}
+
+static IntrusiveRefCntPtr GetDiags() {
+  return CompilerInstance::createDiagnostics(new DiagnosticOptions(),
+ new TextDiagnosticBuffer());
+}
+
+static void BM_CompilerInvocationNoRoundTrip(benchmark::State &State) {
+  auto Args = GetArgs();
+  auto Diags = GetDiags();
+
+  for (auto _ : State) {
+CompilerInvocation Invocation;
+CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+  }
+}
+
+static void BM_CompilerInvocationDoRoundTrip(benchmark::State &State) {
+  auto Args = GetArgs();
+  Args.push_back("-round-trip-args");
+ 

[PATCH] D95061: [OpenCL][Docs] Moved information about internals from UsersManual into OpenCLSupport

2021-01-27 Thread Anastasia Stulova via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd7cc3a083fce: [OpenCL][Docs] Moved info from UsersManual 
into OpenCLSupport. (authored by Anastasia).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D95061?vs=317943&id=319529#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95061

Files:
  clang/docs/OpenCLSupport.rst
  clang/docs/UsersManual.rst

Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -2914,6 +2914,10 @@
 
  $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl
 
+
+Many flags used for the compilation for C sources can also be passed while
+compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
+
 Some extra options are available to support special OpenCL features.
 
 .. option:: -finclude-default-header
@@ -2944,56 +2948,7 @@
 In this example it is assumed that the kernel code contains
 ``#include `` just as a regular C include.
 
-.. _opencl_cl_ext:
-
-.. option:: -cl-ext
-
-Disables support of OpenCL extensions. All OpenCL targets provide a list
-of extensions that they support. Clang allows to amend this using the ``-cl-ext``
-flag with a comma-separated list of extensions prefixed with ``'+'`` or ``'-'``.
-The syntax: ``-cl-ext=<(['-'|'+'][,])+>``,  where extensions
-can be either one of `the OpenCL published extensions
-`_
-or any vendor extension. Alternatively, ``'all'`` can be used to enable
-or disable all known extensions.
-
-Note that this is a frontend-only flag and therefore it requires the use of
-flags that forward options to the frontend e.g. ``-cc1`` or ``-Xclang``.
-
-Example disabling double support for the 64-bit SPIR target:
-
-   .. code-block:: console
-
- $ clang -cc1 -triple spir64-unknown-unknown -cl-ext=-cl_khr_fp64 test.cl
-
-Enabling all extensions except double support in R600 AMD GPU can be done using:
-
-   .. code-block:: console
-
- $ clang -cc1 -triple r600-unknown-unknown -cl-ext=-all,+cl_khr_fp16 test.cl
-
-.. _opencl_fake_address_space_map:
-
-.. option:: -ffake-address-space-map
-
-Overrides the target address space map with a fake map.
-This allows adding explicit address space IDs to the bitcode for non-segmented
-memory architectures that do not have separate IDs for each of the OpenCL
-logical address spaces by default. Passing ``-ffake-address-space-map`` will
-add/override address spaces of the target compiled for with the following values:
-``1-global``, ``2-constant``, ``3-local``, ``4-generic``. The private address
-space is represented by the absence of an address space attribute in the IR (see
-also :ref:`the section on the address space attribute `).
-
-   .. code-block:: console
-
- $ clang -cc1 -ffake-address-space-map test.cl
-
-Note that this is a frontend-only flag and therefore it requires the use of
-flags that forward options to the frontend e.g. ``-cc1`` or ``-Xclang``.
-
-Some other flags used for the compilation for C can also be passed while
-compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
+More options are documented in :doc:`OpenCLSupport`.
 
 OpenCL Targets
 --
@@ -3058,10 +3013,10 @@
 -
 
 By default Clang will not include standard headers and therefore OpenCL builtin
-functions and some types (i.e. vectors) are unknown. The default CL header is,
-however, provided in the Clang installation and can be enabled by passing the
-``-finclude-default-header`` flag (see :ref:`flags description `
-for more details).
+functions and some types (i.e. vectors) are unknown during compilation. The
+default CL header is, however, provided in the Clang installation and can be
+enabled by passing the ``-finclude-default-header`` flag (see :ref:`flags
+description ` for more details).
 
.. code-block:: console
 
@@ -3125,27 +3080,6 @@
 Extensions Documentation
 `_.
 
-OpenCL Metadata

-
-Clang uses metadata to provide additional OpenCL semantics in IR needed for
-backends and OpenCL runtime.
-
-Each kernel will have function metadata attached to it, specifying the arguments.
-Kernel argument metadata is used to provide source level information for querying
-at runtime, for example using the `clGetKernelArgInfo 
-`_
-call.
-
-Note that ``-cl-kernel-arg-info`` enables more information about the original CL
-code to be added e.g. kernel parameter names will appear in the OpenCL metadata
-along with other information. 
-
-The IDs used to encode the OpenCL's logical address spaces in the argument info
-metadata follows the SPIR address space m

[PATCH] D94865: [ASTMatchers] Add callOrConstruct matcher

2021-01-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:2867
+extern const internal::MapAnyOfMatcher
+callOrConstruct;
+

steveire wrote:
> aaron.ballman wrote:
> > steveire wrote:
> > > aaron.ballman wrote:
> > > > steveire wrote:
> > > > > aaron.ballman wrote:
> > > > > > I'm not super keen on this name. It's certainly descriptive, but I 
> > > > > > do wonder if it's a bit too specific and should perhaps be 
> > > > > > something more like `callableExpr()`, `callLikeExpr()`, or 
> > > > > > something more generic. For instance, I could imagine wanting this 
> > > > > > to match on something like:
> > > > > > ```
> > > > > > struct S {
> > > > > >   void setter(int val) {}
> > > > > >   __declspec(property(put = setter)) int x;
> > > > > > };
> > > > > > 
> > > > > > int main() {
> > > > > >   S s;
> > > > > >   s.x = 12; // Match here
> > > > > >   // Because the above code actually does this:
> > > > > >   // s.setter(12);
> > > > > > }
> > > > > > ```
> > > > > > because this also has an expression that isn't really a call (as 
> > > > > > far as our AST is concerned) but is a call as far as program 
> > > > > > semantics are concerned. I'm not suggesting to make the matcher 
> > > > > > support that right now (unless you felt like doing it), but 
> > > > > > thinking about the future and avoiding a name that may paint us 
> > > > > > into a corner.
> > > > > > 
> > > > > > WDYT about using a more generic name?
> > > > > I haven't seen code like that before (ms extension?) 
> > > > > https://godbolt.org/z/anvd43 but I think that should be matched by 
> > > > > `binaryOperator` instead. That already matches based on what the code 
> > > > > looks like, rather than what it is in the AST.
> > > > > 
> > > > > This `callOrConstruct` is really for using `hasArgument` and related 
> > > > > submatchers with nodes which support it. As such I think the name is 
> > > > > fine. I don't like `callableExpr` or `callLikeExpr` because they 
> > > > > don't bring to mind the possibility that construction is also 
> > > > > supported.
> > > > > I haven't seen code like that before (ms extension?)
> > > > 
> > > > Yes, it's an MS extension.
> > > > 
> > > > > That already matches based on what the code looks like, rather than 
> > > > > what it is in the AST.
> > > > 
> > > > Yes, but these are AST matchers, so it's reasonable to match on what's 
> > > > in the AST (as well as what the code looks like, of course). I'm not 
> > > > arguing it needs to be supported so much as pointing out that there are 
> > > > other AST nodes this notionally applies to where the name is a bit too 
> > > > specific.
> > > > 
> > > > > This callOrConstruct is really for using hasArgument and related 
> > > > > submatchers with nodes which support it. As such I think the name is 
> > > > > fine. I don't like callableExpr or callLikeExpr because they don't 
> > > > > bring to mind the possibility that construction is also supported.
> > > > 
> > > > I'm pretty sure we've extended what `hasArgument` can be applied to in 
> > > > the past (but I've not verified), so the part that worries me is 
> > > > specifically naming the nodes as part of the identifier. This 
> > > > effectively means that if we ever find another AST node for 
> > > > `hasArgument`, we either need a different API like 
> > > > `callConstructOrWhatever` or we're stuck with a poor name.
> > > > 
> > > > Another (smaller) concern with the name is that `callOrConstruct` can 
> > > > describe declarations as well as expressions, to some degree as you can 
> > > > declare calls and constructors. It's a smaller concern because those at 
> > > > least share a common base class. `callOrConstructExpr` would clarify 
> > > > this easily enough.
> > > > 
> > > > I see you added `ObjCMessageExpr` as well, thank you for that! It's a 
> > > > perhaps better example of why this name feels awkward to me. In ObjC, 
> > > > you don't call an `ObjCMessageExpr`, you "send" it to the given object 
> > > > or class. That suggests to me that `callableExpr` or `callLikeExpr` is 
> > > > also not a great name either.
> > > > 
> > > > Perhaps `executableExpr` because you're executing some code?
> > > > Perhaps `executableExpr` because you're executing some code?
> > > 
> > > The thing that this really does is make it possible to use `hasArgument` 
> > > and related matchers with the nodes that that matcher supports. So, 
> > > something with `argument` in the name probably makes sense. Like 
> > > `argumentExpr`. 
> > > 
> > > The thing that this really does is make it possible to use hasArgument 
> > > and related matchers with the nodes that that matcher supports. So, 
> > > something with argument in the name probably makes sense. Like 
> > > argumentExpr.
> > 
> > A name like `argumentExpr()` would make me think we're trying to match the 
> > `42` in an expression like `foo(42)` (e.g., it makes me think we're goin

[PATCH] D95460: [flang][driver] Add forced form flags and -ffixed-line-length

2021-01-27 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Thank you for working on this @FarisRehman ! I've left a few inline comments, 
but nothing major. Really nice to see this being added and working as expected!




Comment at: clang/include/clang/Driver/Options.td:4074-4076
+def ffixed_line_length_VALUE : Joined<["-"], "ffixed-line-length-">, 
Flags<[FlangOption, FC1Option]>, 
+  HelpText<"Set column after which characters are ignored in typical 
fixed-form lines in the source file">,
+  Group;

This is a fairly long help message. This is what `gfortran` prints:
```
gfortran --help=joined | grep 'ffixed-line-length'
  -ffixed-line-length- Use n as character line width in fixed mode
```
A long version could be added using `DocBrief` field.



Comment at: clang/include/clang/Driver/Options.td:4110-4111
 defm f2c : BooleanFFlag<"f2c">, Group;
-defm fixed_form : BooleanFFlag<"fixed-form">, Group;
-defm free_form : BooleanFFlag<"free-form">, Group;
+defm fixed_form : BooleanFFlag<"fixed-form">, Flags<[FlangOption, FC1Option]>, 
Group;
+defm free_form : BooleanFFlag<"free-form">, Flags<[FlangOption, FC1Option]>, 
Group;
 defm frontend_optimize : BooleanFFlag<"frontend-optimize">, 
Group;

We can't have help text for these, can we? Perhaps worth mentioning in the 
commit message that this needs fixing. We are likely to experience this with 
other options too.



Comment at: clang/lib/Driver/ToolChains/Flang.cpp:24-26
+  Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I,
+options::OPT_ffixed_form, options::OPT_ffree_form,
+options::OPT_ffixed_line_length_VALUE});

IIUC, you are adding Fortran dialect rather then preprocessor options here. See 
also `gfortran` docs: 
https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html.



Comment at: flang/include/flang/Frontend/FrontendOptions.h:77-87
+enum class FortranForm {
+  /// The user has not specified a form. Base the form off the file extension.
+  Unknown,
+
+  /// -ffree-form
+  FixedForm,
+

[nit] Perhaps `Source file layout` above `enum class FortranForm`?



Comment at: flang/lib/Frontend/CompilerInstance.cpp:151-158
+  if (invoc.frontendOpts().fortranForm_ == FortranForm::Unknown) {
+// Switch between fixed and free form format based on the input file
+// extension. Ideally we should have all Fortran options set before
+// entering this loop (i.e. processing any input files). However, we
+// can't decide between fixed and free form based on the file extension
+// earlier than this.
+invoc.fortranOpts().isFixedForm = fif.IsFixedForm();

Hm, unwanted TABs? 

Also, please keep note of: https://reviews.llvm.org/D95464 (there should be no 
conflicts from what I can tell).



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:166-171
+if (currentArg->getOption().matches(
+clang::driver::options::OPT_ffixed_form)) {
+  opts.fortranForm_ = FortranForm::FixedForm;
+} else {
+  opts.fortranForm_ = FortranForm::FreeForm;
+}

Could be simplified using the ternary operator:
```
opts.fortranForm_ = 
(currentArg->getOption().matches(clang::driver::options::OPT_ffixed_form) ? 
FortranForm::FixedForm : FortranForm::FreeForm;
```
To me this would be more concise, but semantically it's identical. So please 
decide!

(similar comment for the bit below)



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:182
+  columns = 0;
+} else if (argValue.getAsInteger(10, columns)) {
+  columns = -1;

Please, could you comment hard-coded args:
```
 } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
```
See [[ https://llvm.org/docs/CodingStandards.html#comment-formatting | LLVM's 
coding style ]]



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:319-323
+  if (frontendOptions.fortranForm_ == FortranForm::FixedForm) {
+fortranOptions.isFixedForm = true;
+  } else if (frontendOptions.fortranForm_ == FortranForm::FreeForm) {
+fortranOptions.isFixedForm = false;
+  }

Hm, wouldn't this work:
```
fortranOptions.isFixedForm = (frontendOptions.fortranForm_ == 
FortranForm::FixedForm) ? true : false;
 ```



Comment at: flang/test/Flang-Driver/Inputs/fixed-line-length-test.f:4
+  end
\ No newline at end of file


FIXME



Comment at: flang/test/Flang-Driver/fixed-free-flag.f90:8-9
+!--
+! RUN: not %flang-new -fsyntax-only -ffree-form %S/Inputs/fixed-form-test.f 
%S/Inputs/free-form-test.f90  2>&1 | FileCheck %s --check-prefix=FREEFORM
+! RUN: %flang-new -fsyntax-only -ffixed-form %S/Inputs/free-form-test.f90 
%S/Inputs/fixed-form-test.f  2>&1 | FileCheck %s --check-prefix=FIXEDFO

[PATCH] D94627: [PowerPC][PC Rel] Implement option to omit P10 instructions from stubs

2021-01-27 Thread Stefan Pintilie via Phabricator via cfe-commits
stefanp added a comment.

I have a few comments. Most of them are nits but there is a functional issue as 
well.

For the testing:
Do we have a test for the `PPC64R2SaveStub` in the situation where the offset 
fits in 34 bits?




Comment at: lld/ELF/Driver.cpp:768
+  // This handles the --no-power10-stubs option.
+  bool NoP10 = args.hasArg(OPT_no_power10_stubs);
+

nit:
You can probably get rid of this temp and have the condition down below change 
to:
```
if (!args.hasArg(OPT_power10_stubs_eq) &&
args.hasArg(OPT_no_power10_stubs))
  return P10Stub::No;
```
Mainly because you only use `NoP10` in one place at this point.



Comment at: lld/ELF/Options.td:445
 
+def power10_stubs: F<"power10-stubs">, HelpText<"Alias for 
--power10-stubs=yes">;
+

nit:
This is not checked in `getP10StubOpt`.
This is no longer an alias for `power10-stubs=yes` it is an alias for default.



Comment at: lld/ELF/Thunks.cpp:932
+write32(buf + 4, addis); // addis r12, 0, top of offset
+write32(buf + 8, addi);  // addi  r12, r12, bottom of offset
+nextInstOffset = 12;

This sequence does not match with what you are using as an offset.
The `tocOffset` is the difference between the TOC pointer (in r2) and the 
address of the destination function (the callee). However, the add instructions 
are using that offset and adding it to zero (`addis r12, 0, top of offset`) 
which is not the TOC pointer. At the end of this sequence the register `r12` 
will not have the address of the callee but simply the difference between that 
address and the TOC pointer.

Since you have a valid `r2` and are computing the offset from the TOC pointer 
you should be adding to that.



Comment at: lld/ELF/Thunks.cpp:935
+  } else {
+write32(buf + 4, addi); // addi r12, 0, offset
+nextInstOffset = 8;

Same here as above.



Comment at: lld/ELF/Thunks.cpp:971
+uint32_t d = destination.getVA(addend);
+uint32_t off = d - getThunkTargetSym()->getVA();
+write32(buf + 0, 0x7c0802a6);  // mflr r12

nit:
The variable `d` is only used in one place so you can just inline it.
Also, for the future try to avoid single letter variable names.



Comment at: lld/ELF/Thunks.cpp:977
+write32(buf + 16, 0x3d8c | ha(off));   // addis r12,r11,off@ha
+write32(buf + 20, 0x398c | (uint16_t)(off)-8); // addi r12,r12,off@l
+nextInstOffset = 24;

You need to have the `off-8` in both cases. The way that this is done is quite 
confusing beause in one case you subtract 8 in the lambda and in the other you 
just subtract here inline. I would say just subtract in the computation of 
`off` and then you don't have to do it twice in two different places.

Secondly, instead of casting to `uint16_t` you are better off just using a mask 
(`off & 0x`).



Comment at: lld/ELF/Thunks.cpp:1010
+uint32_t d = destination.getVA(addend);
+uint32_t off = d - getThunkTargetSym()->getVA();
+write32(buf + 0, 0x7c0802a6);// mflr r12

nit:
Similar to above it is probably better to compute `off` with the `-8` included 
than to add the adjustment to the lambdas. 



Comment at: lld/ELF/Thunks.cpp:1057
+  if (config->Power10Stub == P10Stub::No) {
+auto ha = [](uint32_t v) -> uint16_t { return (v + 0x8000 - 8) >> 16; };
+uint32_t d = destination.getVA(addend);

I see that these lambdas are used in a lot of places to do the same thing. It 
might be better to have a static function instead of defining the same lambda 
three times.



Comment at: lld/ELF/Thunks.cpp:1059
+uint32_t d = destination.getVA(addend);
+uint32_t off = d - getThunkTargetSym()->getVA();
+write32(buf + 0, 0x7c0802a6);  // mflr r12

nit: Same as above. Just add compute the offset with the 8 difference here. 



Comment at: lld/test/ELF/ppc64-pcrel-call-to-toc.s:18
 
+# RUN: llvm-mc -filetype=obj -triple=powerpc64 %s -o %t.o
+# RUN: ld.lld -T %t.script %t.o -o %t --no-power10-stubs

nit:
Do the LE version of the test instead of the BE version. 



Comment at: llvm/include/llvm/Object/ELF.h:94
+  LD_R12_NO_DISP = 0xE980,
+  LD_R12_TO_R12_NO_DISP = 0xE98C,
   MTCTR_R12 = 0x7D8903A6,

Are these two instruction masks used?


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

https://reviews.llvm.org/D94627

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


[PATCH] D95516: [clang][cli] Benchmark command line round-trip

2021-01-27 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: clang/benchmarks/CMakeLists.txt:3
+
+target_link_libraries(CompilerInvocationBench
+  PRIVATE

Not sure if we should do anything else here. I mostly cargo-culted this from 
clangd.



Comment at: clang/benchmarks/CompilerInvocationBench.cpp:11
+static std::vector GetArgs() {
+  return {"-DHAVE___CXA_THREAD_ATEXIT_IMPL",
+  "-D_GNU_SOURCE",

It would be nice to load this from a file (e.g. `./Inputs/short-args.txt`).

What is the best approach here? Some options:
* copy the `.txt` file to the build folder via CMake and load it using 
`llvm::sys::fs::current_path`,
* leave the `.txt` file in source directory and hard-code the path via 
`CMAKE_CURRENT_SOURCE_DIR`,
* require users to supply path to the `.txt` file through command line.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95516

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


[PATCH] D94472: [clang][cli] Command line round-trip for HeaderSearch options

2021-01-27 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

In D94472#2523053 , @Bigcheese wrote:

> The only issue I have with this if always parsing twice has a noticeable 
> performance impact for any users of Clang. Can we measure the impact? If it's 
> small (< 100ms ?) then that's fine. I'm also concerned about users like cling 
> and clangd.

I've created a micro-benchmark in D95516 . I 
think we should be fine.

In D94472#2523490 , @dexonsmith wrote:

> I think the idea is only to parse twice when `-round-trip-args` is on, which 
> the driver will only set by default in asserts mode. Good to measure the 
> impact nevertheless.

I must've misunderstood you earlier. I've updated the patch so that we 
round-trip only when cc1 is given `-round-trip-args` (which happens 
automatically only in assert builds).
We check that the once- and twice- generated arguments match, and we make sure 
the `CompilerInvocation` resulting from the second parse gets used in the rest 
of compilation.




Comment at: clang/lib/Frontend/CompilerInvocation.cpp:604
+ GenArgs2Strs.end(), [](const char *A, const char *B) {
+   return StringRef(A) == StringRef(B);
+ });

There must be a better way to do this...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94472

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


[PATCH] D95348: [clang][cli] Port OpenMP-related LangOpts to marshalling system

2021-01-27 Thread Jan Svoboda 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 rG9ad94c126aac: [clang][cli] Port OpenMP-related LangOpts to 
marshalling system (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95348

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -477,6 +477,12 @@
   << A->getSpelling() << T.getTriple();
   }
 
+  // Report if OpenMP host file does not exist.
+  if (!LangOpts.OMPHostIRFile.empty() &&
+  !llvm::sys::fs::exists(LangOpts.OMPHostIRFile))
+Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
+<< LangOpts.OMPHostIRFile;
+
   if (!CodeGenOpts.ProfileRemappingFile.empty() && 
CodeGenOpts.LegacyPassManager)
 Diags.Report(diag::err_drv_argument_only_allowed_with)
 << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
@@ -2382,13 +2388,6 @@
   bool IsSimdSpecified =
   Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
/*Default=*/false);
-  Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
-  Opts.OpenMPUseTLS =
-  Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
-  Opts.OpenMPIsDevice =
-  Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
-  Opts.OpenMPIRBuilder =
-  Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
   bool IsTargetSpecified =
   Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
 
@@ -2462,15 +2461,6 @@
 }
   }
 
-  // Get OpenMP host file path if any and report if a non existent file is
-  // found
-  if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
-Opts.OMPHostIRFile = A->getValue();
-if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
-  Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
-  << Opts.OMPHostIRFile;
-  }
-
   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
   Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
 Args.hasArg(options::OPT_fopenmp_cuda_mode);
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2145,18 +2145,24 @@
 def fopenmp_use_tls : Flag<["-"], "fopenmp-use-tls">, Group,
   Flags<[NoArgumentUnused, HelpHidden]>;
 def fnoopenmp_use_tls : Flag<["-"], "fnoopenmp-use-tls">, Group,
-  Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
+  Flags<[CC1Option, NoArgumentUnused, HelpHidden]>,
+  MarshallingInfoNegativeFlag, !strconcat("(bool)", 
fopenmp.KeyPath)>,
+  ShouldParseIf;
 def fopenmp_targets_EQ : CommaJoined<["-"], "fopenmp-targets=">, 
Flags<[NoXarchOption, CC1Option]>,
   HelpText<"Specify comma-separated list of triples OpenMP offloading targets 
to be supported">;
 def fopenmp_relocatable_target : Flag<["-"], "fopenmp-relocatable-target">,
   Group, Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
 def fnoopenmp_relocatable_target : Flag<["-"], "fnoopenmp-relocatable-target">,
   Group, Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
-def fopenmp_simd : Flag<["-"], "fopenmp-simd">, Group, 
Flags<[CC1Option, NoArgumentUnused]>,
-  HelpText<"Emit OpenMP code only for SIMD-based constructs.">;
+defm openmp_simd : BoolFOption<"openmp-simd",
+  LangOpts<"OpenMPSimd">, DefaultFalse,
+  PosFlag,
+  NegFlag, BothFlags<[CC1Option, NoArgumentUnused]>>,
+  ShouldParseIf;
 def fopenmp_enable_irbuilder : Flag<["-"], "fopenmp-enable-irbuilder">, 
Group, Flags<[CC1Option, NoArgumentUnused, HelpHidden]>,
-  HelpText<"Use the experimental OpenMP-IR-Builder codegen path.">;
-def fno_openmp_simd : Flag<["-"], "fno-openmp-simd">, Group, 
Flags<[CC1Option, NoArgumentUnused]>;
+  HelpText<"Use the experimental OpenMP-IR-Builder codegen path.">,
+  MarshallingInfoFlag>,
+  ShouldParseIf;
 def fopenmp_cuda_mode : Flag<["-"], "fopenmp-cuda-mode">, Group,
   Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
 def fno_openmp_cuda_mode : Flag<["-"], "fno-openmp-cuda-mode">, Group,
@@ -5367,9 +5373,12 @@
 
//===--===//
 
 def fopenmp_is_device : Flag<["-"], "fopenmp-is-device">,
-  HelpText<"Generate code only for an OpenMP target device.">;
+  HelpText<"Generate code only for an OpenMP target device.">,
+  MarshallingInfoFlag>,
+  ShouldParseIf;
 def fopenmp_host_ir_file_path : Separate<["-"], "fopenmp-host-ir-file-path">,
-  HelpText<"Path to the IR file produced by the frontend for the host.">;
+  HelpText<"Path to the IR fi

[PATCH] D95519: [clang-tidy] bugprone-assert-side-effect: Warn on NSAssert by default.

2021-01-27 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ created this revision.
NoQ added reviewers: alexfh, gribozavr2, vsavchenko.
NoQ added a project: clang-tools-extra.
Herald added subscribers: martong, Charusso, xazax.hun.
NoQ requested review of this revision.

This is basically standard Objective-C assert. While we could always pass it as 
an option, i believe it makes perfect sense to warn on it by default.

The same applies to `NSCAssert` which drops additional support for displaying 
Objective-C method information so it acts exactly like C `assert`.

I tested it on live code with actual Foundation headers and it seems to work 
correctly out of the box.

I'm also interested in making an even more agressive step in this direction and 
adding an option to accept any macro that ends with "...assert" suffix, 
case-insensitively. This would probably go under an off-by-default flag. Would 
this be acceptable?


https://reviews.llvm.org/D95519

Files:
  clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone-assert-side-effect.m


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-assert-side-effect.m
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-assert-side-effect.m
@@ -0,0 +1,53 @@
+// RUN: %check_clang_tidy %s bugprone-assert-side-effect %t
+
+int abort();
+
+@interface NSObject
+@end
+
+@interface NSString
+@end
+
+@interface NSAssertionHandler
++ (NSAssertionHandler *)currentHandler;
+- handleFailureInMethod:(SEL)cmd object:(NSObject *)obj desc:(NSString *)desc;
+- handleFailureInFunction:(NSString *)desc;
+@end
+
+#ifndef NDEBUG
+#define NSAssert(condition, description, ...)  
  \
+  do { 
  \
+if (__builtin_expect(!(condition), 0)) {   
  \
+  [[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd  
  \
+  object:self  
  \
+
desc:(description)]; \
+}  
  \
+  } while (0);
+#define NSCAssert(condition, description, ...) 
\
+  do { 
\
+if (__builtin_expect(!(condition), 0)) {   
\
+  [[NSAssertionHandler currentHandler] 
handleFailureInFunction:(description)]; \
+}  
\
+  } while (0);
+#else
+#define NSAssert(condition, description, ...) do {} while (0)
+#define NSCAssert(condition, description, ...) do {} while (0)
+#endif
+
+@interface I : NSObject
+- (void)foo;
+@end
+
+@implementation I
+- (void)foo {
+  int x = 0;
+  NSAssert((++x) == 1, @"Ugh.");
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in NSAssert() 
condition discarded in release builds [bugprone-assert-side-effect]
+}
+@end
+
+void foo() {
+  int x = 0;
+  NSCAssert((++x) == 1, @"Ugh.");
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in NSCAssert() 
condition discarded in release builds [bugprone-assert-side-effect]
+}
Index: clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
@@ -72,7 +72,8 @@
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   CheckFunctionCalls(Options.get("CheckFunctionCalls", false)),
-  RawAssertList(Options.get("AssertMacros", "assert")) {
+  RawAssertList(Options.get("AssertMacros",
+"assert,NSAssert,NSCAssert")) {
   StringRef(RawAssertList).split(AssertMacros, ",", -1, false);
 }
 


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-assert-side-effect.m
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-assert-side-effect.m
@@ -0,0 +1,53 @@
+// RUN: %check_clang_tidy %s bugprone-assert-side-effect %t
+
+int abort();
+
+@interface NSObject
+@end
+
+@interface NSString
+@end
+
+@interface NSAssertionHandler
++ (NSAssertionHandler *)currentHandler;
+- handleFailureInMethod:(SEL)cmd object:(NSObject *)obj desc:(NSString *)desc;
+- handleFailureInFunction:(NSString *)desc;
+@end
+
+#ifndef NDEBUG
+#define NSAssert(condition, description, ...)\
+  do {   \
+if (__builtin_expect(!(condition), 0)) { \
+  [[NSAssertionHandler currentHandler

[PATCH] D94802: [clang][cli] Parse HeaderSearch options separately

2021-01-27 Thread Jan Svoboda 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 rG05127fba4b66: [clang][cli] Parse HeaderSearch options 
separately (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94802

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1827,7 +1827,23 @@
 }
 
 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
+  DiagnosticsEngine &Diags,
   const std::string &WorkingDir) {
+  HeaderSearchOptions *HeaderSearchOpts = &Opts;
+  bool Success = true;
+
+#define HEADER_SEARCH_OPTION_WITH_MARSHALLING( 
\
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,
\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   
\
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, 
\
+MERGER, EXTRACTOR, TABLE_INDEX)
\
+  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,
\
+SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,  
\
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,  
\
+MERGER, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
+
   if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
 
@@ -2774,7 +2790,7 @@
   LangOpts.IsHeaderFile);
   ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
   llvm::Triple T(Res.getTargetOpts().Triple);
-  ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args,
+  ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags,
 Res.getFileSystemOpts().WorkingDir);
   if (DashX.getFormat() == InputKind::Precompiled ||
   DashX.getLanguage() == Language::LLVM_IR) {
@@ -2995,6 +3011,7 @@
EXTRACTOR, TABLE_INDEX)
 
 #define DIAG_OPTION_WITH_MARSHALLING OPTION_WITH_MARSHALLING
+#define HEADER_SEARCH_OPTION_WITH_MARSHALLING OPTION_WITH_MARSHALLING
 #define LANG_OPTION_WITH_MARSHALLING OPTION_WITH_MARSHALLING
 #define CODEGEN_OPTION_WITH_MARSHALLING OPTION_WITH_MARSHALLING
 
@@ -3002,6 +3019,7 @@
 
 #undef CODEGEN_OPTION_WITH_MARSHALLING
 #undef LANG_OPTION_WITH_MARSHALLING
+#undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
 #undef DIAG_OPTION_WITH_MARSHALLING
 #undef OPTION_WITH_MARSHALLING
 #undef GENERATE_OPTION_WITH_MARSHALLING
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -256,7 +256,7 @@
 class CodeGenOpts
   : KeyPathAndMacro<"CodeGenOpts.", base, "CODEGEN_"> {}
 class HeaderSearchOpts
-  : KeyPathAndMacro<"HeaderSearchOpts->", base> {}
+  : KeyPathAndMacro<"HeaderSearchOpts->", base, "HEADER_SEARCH_"> {}
 class PreprocessorOpts
   : KeyPathAndMacro<"PreprocessorOpts->", base> {}
 class FileSystemOpts


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1827,7 +1827,23 @@
 }
 
 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
+  DiagnosticsEngine &Diags,
   const std::string &WorkingDir) {
+  HeaderSearchOptions *HeaderSearchOpts = &Opts;
+  bool Success = true;
+
+#define HEADER_SEARCH_OPTION_WITH_MARSHALLING( \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,\
+SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,  \
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,  \
+MERGER, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
+
   if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
 
@@ -2774,7 +2790,7 @@
   

[PATCH] D95519: [clang-tidy] bugprone-assert-side-effect: Warn on NSAssert by default.

2021-01-27 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

LGTM, but it would be great if code owners take a look as well.


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

https://reviews.llvm.org/D95519

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


[PATCH] D69560: [clang-tidy] Add 'bugprone-easily-swappable-parameters' check

2021-01-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:58
+
+namespace {
+

Is there a need for the anonymous namespace? (We typically only use them when 
defining a class and try to make them as narrow in scope as possible, and use 
`static` for function declarations instead.)



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:67
+/// The language features involved in allowing the mix between two parameters.
+enum MixFlags : unsigned char {
+  MIX_Invalid = 0, //< Sentinel bit pattern. DO NOT USE!

Does using the fixed underlying type buy us something? As best I can tell, this 
will introduce a fair amount of implicit promotions to `int` anyway.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:90-91
+
+  void sanitise() {
+assert(Flags != MIX_Invalid && "sanitise() called on invalid bitvec");
+// TODO: There will be statements here in further extensions of the check.

Heh, I don't know if we have any guidance on US English vs British English 
spellings. ;-)



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:105
+
+  void sanitise() { Data.sanitise(); }
+  MixFlags flags() const { return Data.Flags; }





Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:176-177
+   const FunctionDecl *FD,
+   const std::size_t StartIndex) {
+  const std::size_t NumParams = FD->getNumParams();
+  assert(StartIndex < NumParams && "out of bounds for start");

Outside of field declarations, we typically only `const`-qualify 
pointer/reference types.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:177
+   const std::size_t StartIndex) {
+  const std::size_t NumParams = FD->getNumParams();
+  assert(StartIndex < NumParams && "out of bounds for start");

Some interesting test cases to consider: varargs functions and K&R C functions



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:196
+// parameters that can be messed up at a call site.
+decltype(Ret.Mixes) MixesOfIth;
+for (std::size_t J = StartIndex; J < I; ++J) {

Preferable to spell this type out to make it easier on someone reading the code 
to understand the type.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:255
+  std::string NodeTypeName =
+  Node->getType().getAsString(Node->getASTContext().getPrintingPolicy());
+  StringRef CaptureName{NodeTypeName};

Hmm, one downside to using the printing policy to get the node name is that 
there can be alternative spellings for the same type that the user might 
reasonably expect to be applied. e.g., if the user expects to ignore `bool` 
datatypes and the printing policy wants to spell the type as `_Bool`, this 
won't behave as expected.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:284
+/// The default value for the MinimumLength check option.
+static constexpr unsigned DefaultMinimumLength = 2;
+

It might be good to move this to a more prominent location since it's a default 
value.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:301
+ "Iterator", "inputit", "InputIt", "forwardit",
+ "FowardIt", "bidirit", "BidirIt", "constiterator",
+ "const_iterator", "Const_Iterator", "Constiterator",

If we're going to include `ForwardIt`, we probably want things like `RandomIt` 
as well?



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:302
+ "FowardIt", "bidirit", "BidirIt", "constiterator",
+ "const_iterator", "Const_Iterator", "Constiterator",
+ "ConstIterator"});

`reverse_iterator` and `reverse_const_iterator` too?

How about ranges?



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:402-403
+
+// Unfortunately, undersquiggly highlights are for some reason chewed up
+// and not respected by diagnostics from Clang-Tidy. :(
+diag(First->getLocation(), "the first parameter in the range is '%0'",

Can you post a screenshot of what you mean?



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.h:30
+  void storeOptions(ClangTidyOptions

[PATCH] D95519: [clang-tidy] bugprone-assert-side-effect: Warn on NSAssert by default.

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

LGTM!

> I'm also interested in making an even more agressive step in this direction 
> and adding an option to accept any macro that ends with "...assert" suffix, 
> case-insensitively. This would probably go under an off-by-default flag. 
> Would this be acceptable?

I think that makes sense to me. We should probably look at popular OS SDKs and 
CRTs to see what creative ways they spell assertion macros to make sure those 
are covered as well, like 
https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/assert-asserte-assert-expr-macros?view=msvc-160
 and 
https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-assertmsg


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

https://reviews.llvm.org/D95519

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


[PATCH] D94803: [clang][cli] Generate HeaderSearch options separately

2021-01-27 Thread Jan Svoboda 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 rGd0e8a9e5a2f0: [clang][cli] Generate HeaderSearch options 
separately (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D94803?vs=317002&id=319546#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94803

Files:
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -400,6 +400,23 @@
 MERGER(KEYPATH, static_cast(*MaybeValue));  
\
   }
 
+// Capture the extracted value as a lambda argument to avoid potential issues
+// with lifetime extension of the reference.
+#define GENERATE_OPTION_WITH_MARSHALLING(  
\
+ARGS, STRING_ALLOCATOR, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH,   
\
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR,  
\
+TABLE_INDEX)   
\
+  if ((FLAGS)&options::CC1Option) {
\
+[&](const auto &Extracted) {   
\
+  if (ALWAYS_EMIT ||   
\
+  (Extracted !=
\
+   static_cast((IMPLIED_CHECK) ? (IMPLIED_VALUE)
\
+  : (DEFAULT_VALUE 
\
+DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class,
\
+ TABLE_INDEX, Extracted);  
\
+}(EXTRACTOR(KEYPATH)); 
\
+  }
+
 static const StringRef GetInputKindName(InputKind IK);
 
 static void FixupInvocation(CompilerInvocation &Invocation,
@@ -1826,6 +1843,22 @@
   return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
 }
 
+static void GenerateHeaderSearchArgs(const HeaderSearchOptions &Opts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA) {
+  const HeaderSearchOptions *HeaderSearchOpts = &Opts;
+#define HEADER_SEARCH_OPTION_WITH_MARSHALLING( 
\
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,
\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   
\
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, 
\
+MERGER, EXTRACTOR, TABLE_INDEX)
\
+  GENERATE_OPTION_WITH_MARSHALLING(
\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,
\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
+}
+
 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
   DiagnosticsEngine &Diags,
   const std::string &WorkingDir) {
@@ -2983,23 +3016,6 @@
 
 void CompilerInvocation::generateCC1CommandLine(
 SmallVectorImpl &Args, StringAllocator SA) const {
-  // Capture the extracted value as a lambda argument to avoid potential issues
-  // with lifetime extension of the reference.
-#define GENERATE_OPTION_WITH_MARSHALLING(  
\
-ARGS, STRING_ALLOCATOR, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH,   
\
-DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR,  
\
-TABLE_INDEX)   
\
-  if ((FLAGS)&options::CC1Option) {
\
-[&](const auto &Extracted) {   
\
-  if (ALWAYS_EMIT ||   
\
-  (Extracted !=
\
-   static_cast((IMPLIED_CHECK) ? (IMPLIED_VALUE)
\
-  : (DEFAULT_VALUE 
\
-DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class,
\
- TABLE_INDEX, Extracted);  
\
-}(EXTRACTOR(KEYPATH)); 
\
-  }
-
 #define OPTION_WITH_MARSHALLING(   
\
 PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,
\
 HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARS

[PATCH] D95246: [SystemZ][z/OS] Fix No such file or directory expression error matching in lit tests - continued

2021-01-27 Thread Abhina Sree via Phabricator via cfe-commits
abhina.sreeskantharajan updated this revision to Diff 319543.
abhina.sreeskantharajan added a comment.

I've changed the host check to use python's sys.platform to determine the host 
as an alternative to using LLVM_HOST_TRIPLE. It will save us the effort of 
making sure it's defined in all projects as well.

I noticed that llvm/docs/CommandGuide/lit.rst only lists substitutions that are 
done in TestRunner.py and refers to llvm/docs/TestingGuide.rst for information 
on the remaining substitutions. I think if we move the error substitution code 
into TestRunner.py, then it would be appropriate to update the lit.rst. Where 
do you think is the appropriate place to define the error substitutions, 
TestRunner.py or config.py?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95246

Files:
  clang/test/Driver/clang-offload-bundler.c
  clang/test/Frontend/output-failures.c
  clang/test/Frontend/stats-file.c
  lld/test/ELF/basic.s
  llvm/docs/TestingGuide.rst
  llvm/test/Object/archive-extract.test
  llvm/test/Object/directory.ll
  llvm/test/tools/llvm-ar/move.test
  llvm/utils/lit/lit/llvm/config.py

Index: llvm/utils/lit/lit/llvm/config.py
===
--- llvm/utils/lit/lit/llvm/config.py
+++ llvm/utils/lit/lit/llvm/config.py
@@ -345,6 +345,17 @@
 self.config.substitutions.extend(substitutions)
 return True
 
+def add_err_msg_substitutions(self):
+if (sys.platform == 'zos'):
+self.config.substitutions.append(('%errc_ENOENT', '\'EDC5129I No such file or directory.\''))
+self.config.substitutions.append(('%errc_EISDIR', '\'EDC5123I Is a directory.\''))
+elif (sys.platform == 'win32'):
+self.config.substitutions.append(('%errc_ENOENT', '\'no such file or directory\''))
+self.config.substitutions.append(('%errc_EISDIR', '\'is a directory\''))
+else:
+self.config.substitutions.append(('%errc_ENOENT', '\'No such file or directory\''))
+self.config.substitutions.append(('%errc_EISDIR', '\'Is a directory\''))
+
 def use_default_substitutions(self):
 tool_patterns = [
 ToolSubst('FileCheck', unresolved='fatal'),
@@ -358,6 +369,8 @@
 self.add_tool_substitutions(
 tool_patterns, [self.config.llvm_tools_dir])
 
+self.add_err_msg_substitutions()
+
 def use_llvm_tool(self, name, search_env=None, required=False, quiet=False):
 """Find the executable program 'name', optionally using the specified
 environment variable as an override before searching the
Index: llvm/test/tools/llvm-ar/move.test
===
--- llvm/test/tools/llvm-ar/move.test
+++ llvm/test/tools/llvm-ar/move.test
@@ -82,9 +82,9 @@
 ## Member does not exist:
 # RUN: llvm-ar rc %t/missing.a %t/1.o %t/2.o %t/3.o
 # RUN: not llvm-ar m %t/missing.a %t/missing.txt 2>&1 \
-# RUN:   | FileCheck %s --check-prefix=MISSING-FILE -DFILE=%t/missing.txt
+# RUN:   | FileCheck %s --check-prefix=MISSING-FILE -DFILE=%t/missing.txt -DMSG=%errc_ENOENT
 
-# MISSING-FILE: error: [[FILE]]: {{[nN]}}o such file or directory
+# MISSING-FILE: error: [[FILE]]: [[MSG]]
 
 --- !ELF
 FileHeader:
Index: llvm/test/Object/directory.ll
===
--- llvm/test/Object/directory.ll
+++ llvm/test/Object/directory.ll
@@ -1,6 +1,6 @@
 ;RUN: rm -rf %t && mkdir -p %t
-;RUN: not llvm-ar r %t/test.a . 2>&1 | FileCheck %s
-;CHECK: .: {{I|i}}s a directory
+;RUN: not llvm-ar r %t/test.a . 2>&1 | FileCheck -DMSG=%errc_EISDIR %s
+;CHECK: .: [[MSG]]
 
 ;RUN: rm -f %t/test.a
 ;RUN: touch %t/a-very-long-file-name
Index: llvm/test/Object/archive-extract.test
===
--- llvm/test/Object/archive-extract.test
+++ llvm/test/Object/archive-extract.test
@@ -57,5 +57,5 @@
 RUN: llvm-ar p %p/Inputs/thin.a evenlen | FileCheck %s --check-prefix=EVENLEN
 EVENLEN: evenlen
 
-RUN: not llvm-ar p %p/Inputs/thin-path.a t/test2.o 2>&1 | FileCheck %s --check-prefix=MISSING
-MISSING: error: {{N|n}}o such file or directory
+RUN: not llvm-ar p %p/Inputs/thin-path.a t/test2.o 2>&1 | FileCheck %s --DMSG=%errc_ENOENT --check-prefix=MISSING
+MISSING: error: [[MSG]]
Index: llvm/docs/TestingGuide.rst
===
--- llvm/docs/TestingGuide.rst
+++ llvm/docs/TestingGuide.rst
@@ -537,6 +537,14 @@
 
Example: ``%:s: C\Desktop Files\foo_test.s.tmp``
 
+``%errc_``
+
+ Some error messages may be substituted to allow different spellings
+ based on the host platform.
+
+   Example: ``Linux %errc_ENOENT: No such file or directory``
+
+   Example: ``Windows %errc_ENOENT: no such file or directory``
 
 **LLVM-specific substitutions:**
 
Index: lld/test/ELF/basic.s
=

[PATCH] D95246: [SystemZ][z/OS] Fix No such file or directory expression error matching in lit tests - continued

2021-01-27 Thread Abhina Sree via Phabricator via cfe-commits
abhina.sreeskantharajan marked 2 inline comments as done.
abhina.sreeskantharajan added inline comments.



Comment at: llvm/utils/lit/lit/llvm/config.py:349-351
+triple = ""
+if hasattr(self.config, 'host_triple'):
+triple = self.config.host_triple

jhenderson wrote:
> I'm concerned that someone might start using these substitutions in a project 
> for the first time, and get confused why they don't work on non-windows 
> platforms. Maybe the solution is simply to require LLVM_HOST_TRIPLE to be set 
> in all projects, i.e. go back to what you were doing before, and letting 
> python fail if it isn't set.
> 
> Happy to hear other ideas too.
I think using sys.platform or platform.system() could be a better alternative. 
What do you think?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95246

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


[PATCH] D93585: [AArch64][Clang][Linux] Enable out-of-line atomics by default.

2021-01-27 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6448
+  CmdArgs.push_back("-target-feature");
+  CmdArgs.push_back("+outline-atomics");
+}

This needs a Clang driver tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93585

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


[PATCH] D95166: Disable rosegment for old Android versions.

2021-01-27 Thread dmajor via Phabricator via cfe-commits
dmajor added a comment.

Firefox has a build break from this change. In certain Android configurations 
we use bfd or gold. The statement in the commit message "Android only supports 
LLD" is news to me, could you point me to any references for this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95166

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


[PATCH] D95246: [SystemZ][z/OS] Fix No such file or directory expression error matching in lit tests - continued

2021-01-27 Thread Abhina Sree via Phabricator via cfe-commits
abhina.sreeskantharajan updated this revision to Diff 319547.
abhina.sreeskantharajan added a comment.

Fix CI: Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95246

Files:
  clang/test/Driver/clang-offload-bundler.c
  clang/test/Frontend/output-paths.c
  clang/test/Frontend/stats-file.c
  lld/test/ELF/basic.s
  llvm/docs/TestingGuide.rst
  llvm/test/Object/archive-extract.test
  llvm/test/Object/directory.ll
  llvm/test/tools/llvm-ar/move.test
  llvm/utils/lit/lit/llvm/config.py

Index: llvm/utils/lit/lit/llvm/config.py
===
--- llvm/utils/lit/lit/llvm/config.py
+++ llvm/utils/lit/lit/llvm/config.py
@@ -345,6 +345,17 @@
 self.config.substitutions.extend(substitutions)
 return True
 
+def add_err_msg_substitutions(self):
+if (sys.platform == 'zos'):
+self.config.substitutions.append(('%errc_ENOENT', '\'EDC5129I No such file or directory.\''))
+self.config.substitutions.append(('%errc_EISDIR', '\'EDC5123I Is a directory.\''))
+elif (sys.platform == 'win32'):
+self.config.substitutions.append(('%errc_ENOENT', '\'no such file or directory\''))
+self.config.substitutions.append(('%errc_EISDIR', '\'is a directory\''))
+else:
+self.config.substitutions.append(('%errc_ENOENT', '\'No such file or directory\''))
+self.config.substitutions.append(('%errc_EISDIR', '\'Is a directory\''))
+
 def use_default_substitutions(self):
 tool_patterns = [
 ToolSubst('FileCheck', unresolved='fatal'),
@@ -358,6 +369,8 @@
 self.add_tool_substitutions(
 tool_patterns, [self.config.llvm_tools_dir])
 
+self.add_err_msg_substitutions()
+
 def use_llvm_tool(self, name, search_env=None, required=False, quiet=False):
 """Find the executable program 'name', optionally using the specified
 environment variable as an override before searching the
Index: llvm/test/tools/llvm-ar/move.test
===
--- llvm/test/tools/llvm-ar/move.test
+++ llvm/test/tools/llvm-ar/move.test
@@ -82,9 +82,9 @@
 ## Member does not exist:
 # RUN: llvm-ar rc %t/missing.a %t/1.o %t/2.o %t/3.o
 # RUN: not llvm-ar m %t/missing.a %t/missing.txt 2>&1 \
-# RUN:   | FileCheck %s --check-prefix=MISSING-FILE -DFILE=%t/missing.txt
+# RUN:   | FileCheck %s --check-prefix=MISSING-FILE -DFILE=%t/missing.txt -DMSG=%errc_ENOENT
 
-# MISSING-FILE: error: [[FILE]]: {{[nN]}}o such file or directory
+# MISSING-FILE: error: [[FILE]]: [[MSG]]
 
 --- !ELF
 FileHeader:
Index: llvm/test/Object/directory.ll
===
--- llvm/test/Object/directory.ll
+++ llvm/test/Object/directory.ll
@@ -1,6 +1,6 @@
 ;RUN: rm -rf %t && mkdir -p %t
-;RUN: not llvm-ar r %t/test.a . 2>&1 | FileCheck %s
-;CHECK: .: {{I|i}}s a directory
+;RUN: not llvm-ar r %t/test.a . 2>&1 | FileCheck -DMSG=%errc_EISDIR %s
+;CHECK: .: [[MSG]]
 
 ;RUN: rm -f %t/test.a
 ;RUN: touch %t/a-very-long-file-name
Index: llvm/test/Object/archive-extract.test
===
--- llvm/test/Object/archive-extract.test
+++ llvm/test/Object/archive-extract.test
@@ -57,5 +57,5 @@
 RUN: llvm-ar p %p/Inputs/thin.a evenlen | FileCheck %s --check-prefix=EVENLEN
 EVENLEN: evenlen
 
-RUN: not llvm-ar p %p/Inputs/thin-path.a t/test2.o 2>&1 | FileCheck %s --check-prefix=MISSING
-MISSING: error: {{N|n}}o such file or directory
+RUN: not llvm-ar p %p/Inputs/thin-path.a t/test2.o 2>&1 | FileCheck %s --DMSG=%errc_ENOENT --check-prefix=MISSING
+MISSING: error: [[MSG]]
Index: llvm/docs/TestingGuide.rst
===
--- llvm/docs/TestingGuide.rst
+++ llvm/docs/TestingGuide.rst
@@ -537,6 +537,14 @@
 
Example: ``%:s: C\Desktop Files\foo_test.s.tmp``
 
+``%errc_``
+
+ Some error messages may be substituted to allow different spellings
+ based on the host platform.
+
+   Example: ``Linux %errc_ENOENT: No such file or directory``
+
+   Example: ``Windows %errc_ENOENT: no such file or directory``
 
 **LLVM-specific substitutions:**
 
Index: lld/test/ELF/basic.s
===
--- lld/test/ELF/basic.s
+++ lld/test/ELF/basic.s
@@ -219,8 +219,8 @@
 # INVRSP: invalid response file quoting: patatino
 
 # RUN: not ld.lld %t.foo -o /dev/null 2>&1 | \
-# RUN:  FileCheck --check-prefix=MISSING %s
-# MISSING: cannot open {{.*}}.foo: {{[Nn]}}o such file or directory
+# RUN:  FileCheck -DMSG=%errc_ENOENT --check-prefix=MISSING %s
+# MISSING: cannot open {{.*}}.foo: [[MSG]]
 
 # RUN: not ld.lld -o /dev/null 2>&1 | \
 # RUN:  FileCheck --check-prefix=NO_INPUT %s
Index: clang/test/Frontend/stats-file.c

[PATCH] D95349: [clangd] Allow diagnostics to be suppressed with configuration

2021-01-27 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX added inline comments.



Comment at: clang-tools-extra/clangd/ParsedAST.cpp:319
 
-if (!CTChecks.empty()) {
-  ASTDiags.setLevelAdjuster([&CTContext](DiagnosticsEngine::Level 
DiagLevel,
- const clang::Diagnostic &Info) {
+ASTDiags.setLevelAdjuster([&, &Cfg(Config::current())](
+  DiagnosticsEngine::Level DiagLevel,

This line breaks GCC 5.4 build with the following log:
```
llvm-project/clang-tools-extra/clangd/ParsedAST.cpp:319:55: error: binding 
‘const clang::clangd::Config’ to reference of type ‘clang::clangd::Config&’ 
discards qualifiers
 ASTDiags.setLevelAdjuster([&, &Cfg(Config::current())](
   ^
```
Unsure is it a compiler bug or not. Moving `Cfg` out of the capture list or 
using a cast to `Config &` solves the problem.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95349

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


[PATCH] D95439: [clangd] Add include-fixer fixit for field_incomplete_or_sizeless diagnostic.

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

LGTM!




Comment at: clang-tools-extra/clangd/IncludeFixer.cpp:81
   case diag::err_func_def_incomplete_result:
+  case diag::err_field_incomplete_or_sizeless:
 // Incomplete type diagnostics should have a QualType argument for the

hokein wrote:
> kadircet wrote:
> > what about the `sizless` case ? we'll attach a fixit, but it is not going 
> > to fix the issue :(
> The [sizeless](https://reviews.llvm.org/D62962) type is a clang extension, I 
> think our indexer doesn't index this kind of symbols, so we will not attach a 
> fixit for them. 
> 
> And I think sizeless case is rare in practice, I would not too worry about it.
ah ok, i thought this was something more common like a recorddecl without any 
members and with a specific attribute. thanks for the link!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95439

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


[PATCH] D95229: [clangd] Treat optional field type mismatches as soft failures

2021-01-27 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 319551.
kadircet marked 2 inline comments as done.
kadircet added a comment.

- rename to mapOptOrNull
- revert leftover changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95229

Files:
  clang-tools-extra/clangd/Protocol.cpp

Index: clang-tools-extra/clangd/Protocol.cpp
===
--- clang-tools-extra/clangd/Protocol.cpp
+++ clang-tools-extra/clangd/Protocol.cpp
@@ -27,6 +27,21 @@
 
 namespace clang {
 namespace clangd {
+namespace {
+
+// Helper that doesn't treat `null` and absent fields as failures.
+template 
+bool mapOptOrNull(const llvm::json::Value &Params, llvm::StringLiteral Prop,
+  T &Out, llvm::json::Path P) {
+  auto *O = Params.getAsObject();
+  assert(O);
+  auto *V = O->get(Prop);
+  // Field is missing or null.
+  if (!V || V->getAsNull().hasValue())
+return true;
+  return fromJSON(*V, Out, P.field(Prop));
+}
+} // namespace
 
 char LSPError::ID;
 
@@ -490,7 +505,7 @@
   return O && O.map("textDocument", R.textDocument) &&
  O.map("contentChanges", R.contentChanges) &&
  O.map("wantDiagnostics", R.wantDiagnostics) &&
- O.mapOptional("forceRebuild", R.forceRebuild);
+ mapOptOrNull(Params, "forceRebuild", R.forceRebuild, P);
 }
 
 bool fromJSON(const llvm::json::Value &E, FileChangeType &Out,
@@ -580,10 +595,10 @@
   llvm::json::Path P) {
   llvm::json::ObjectMapper O(Params, P);
   return O && O.map("range", R.range) && O.map("message", R.message) &&
- O.mapOptional("severity", R.severity) &&
- O.mapOptional("category", R.category) &&
- O.mapOptional("code", R.code) && O.mapOptional("source", R.source);
-  return true;
+ mapOptOrNull(Params, "severity", R.severity, P) &&
+ mapOptOrNull(Params, "category", R.category, P) &&
+ mapOptOrNull(Params, "code", R.code, P) &&
+ mapOptOrNull(Params, "source", R.source, P);
 }
 
 llvm::json::Value toJSON(const PublishDiagnosticsParams &PDP) {
@@ -818,7 +833,7 @@
   llvm::json::ObjectMapper O(Params, P);
   int TriggerKind;
   if (!O || !O.map("triggerKind", TriggerKind) ||
-  !O.mapOptional("triggerCharacter", R.triggerCharacter))
+  !mapOptOrNull(Params, "triggerCharacter", R.triggerCharacter, P))
 return false;
   R.triggerKind = static_cast(TriggerKind);
   return true;
@@ -1121,8 +1136,8 @@
   llvm::json::ObjectMapper O(Params, P);
   if (!O)
 return true; // 'any' type in LSP.
-  return O.mapOptional("compilationDatabaseChanges",
-   S.compilationDatabaseChanges);
+  return mapOptOrNull(Params, "compilationDatabaseChanges",
+  S.compilationDatabaseChanges, P);
 }
 
 bool fromJSON(const llvm::json::Value &Params, InitializationOptions &Opts,
@@ -1133,8 +1148,8 @@
 
   return fromJSON(Params, Opts.ConfigSettings, P) &&
  O.map("compilationDatabasePath", Opts.compilationDatabasePath) &&
- O.mapOptional("fallbackFlags", Opts.fallbackFlags) &&
- O.mapOptional("clangdFileStatus", Opts.FileStatus);
+ mapOptOrNull(Params, "fallbackFlags", Opts.fallbackFlags, P) &&
+ mapOptOrNull(Params, "clangdFileStatus", Opts.FileStatus, P);
 }
 
 bool fromJSON(const llvm::json::Value &E, TypeHierarchyDirection &Out,
@@ -1190,10 +1205,11 @@
   return O && O.map("name", I.name) && O.map("kind", I.kind) &&
  O.map("uri", I.uri) && O.map("range", I.range) &&
  O.map("selectionRange", I.selectionRange) &&
- O.mapOptional("detail", I.detail) &&
- O.mapOptional("deprecated", I.deprecated) &&
- O.mapOptional("parents", I.parents) &&
- O.mapOptional("children", I.children) && O.mapOptional("data", I.data);
+ mapOptOrNull(Params, "detail", I.detail, P) &&
+ mapOptOrNull(Params, "deprecated", I.deprecated, P) &&
+ mapOptOrNull(Params, "parents", I.parents, P) &&
+ mapOptOrNull(Params, "children", I.children, P) &&
+ mapOptOrNull(Params, "data", I.data, P);
 }
 
 bool fromJSON(const llvm::json::Value &Params,
@@ -1238,7 +1254,7 @@
   return O && O.map("name", I.name) && O.map("kind", I.kind) &&
  O.map("uri", I.uri) && O.map("range", I.range) &&
  O.map("selectionRange", I.selectionRange) &&
- O.mapOptional("data", I.data);
+ mapOptOrNull(Params, "data", I.data, P);
 }
 
 bool fromJSON(const llvm::json::Value &Params,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95229: [clangd] Treat optional field type mismatches as soft failures

2021-01-27 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/Protocol.cpp:837
 return false;
+  tryMap(Params, "triggerCharacter", R.triggerCharacter, P);
   R.triggerKind = static_cast(TriggerKind);

sammccall wrote:
> why are we no longer checking the value?
oops, i was trying something different at some point and looks like i forgot to 
revert some of those changes ..



Comment at: clang-tools-extra/clangd/Protocol.cpp:33
+template 
+bool mapOptionalOrLog(llvm::json::ObjectMapper &O, llvm::StringLiteral Prop,
+  T &Out) {

sammccall wrote:
> sammccall wrote:
> > I would call this tryMap for brevity
> Sorry... now that it can fail, I don't think `tryMap` is a great name anymore.
> 
> `mapOptOrNull`? `mapNullable`? 
> 
> up to you
going with `mapOptOrNull`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95229

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


[PATCH] D95442: [OpenCL] Add diagnostics for references to functions

2021-01-27 Thread Marco Antognini via Phabricator via cfe-commits
mantognini added a comment.

Looks sensible to me.




Comment at: clang/test/SemaOpenCLCXX/members.cl:17
-
-template  struct remove_reference { typedef T type; };
-template  struct remove_reference { typedef T type; };

I wonder, do we lose coverage by removing these templates?

In other words, is the same code for error detection used for templates and 
non-template?



Comment at: clang/test/SemaOpenCLCXX/references.cl:25
+#endif // FPTREXT
+typedef void (&ref2fct_t)();
+#ifndef FPTREXT

This re-uses the same name as above. Could that be an issue?


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

https://reviews.llvm.org/D95442

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


[PATCH] D69560: [clang-tidy] Add 'bugprone-easily-swappable-parameters' check

2021-01-27 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:58
+
+namespace {
+

aaron.ballman wrote:
> Is there a need for the anonymous namespace? (We typically only use them when 
> defining a class and try to make them as narrow in scope as possible, and use 
> `static` for function declarations instead.)
There will be two major parts, the modelling (and which is extended down the 
line with new models like implicit conversions) and the filtering (which throws 
away or breaks up results). Should I cut out the anonymous namespace? How about 
the inner namespaces, may they stay?



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:67
+/// The language features involved in allowing the mix between two parameters.
+enum MixFlags : unsigned char {
+  MIX_Invalid = 0, //< Sentinel bit pattern. DO NOT USE!

aaron.ballman wrote:
> Does using the fixed underlying type buy us something? As best I can tell, 
> this will introduce a fair amount of implicit promotions to `int` anyway.
Will it? I thought if I use the proper LLVM bitmask/flag enum thing it will 
work properly. For now, it is good for the bit flag debug print, because it 
only prints 8 numbers, not 32.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:90-91
+
+  void sanitise() {
+assert(Flags != MIX_Invalid && "sanitise() called on invalid bitvec");
+// TODO: There will be statements here in further extensions of the check.

aaron.ballman wrote:
> Heh, I don't know if we have any guidance on US English vs British English 
> spellings. ;-)
Reflexes, my bad. (Similarly how I put the pointer `*` to the left side, where 
Stroustrup intended. At least my local pre-commit hooks take care of that.) 
Will try to remember this.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:255
+  std::string NodeTypeName =
+  Node->getType().getAsString(Node->getASTContext().getPrintingPolicy());
+  StringRef CaptureName{NodeTypeName};

aaron.ballman wrote:
> Hmm, one downside to using the printing policy to get the node name is that 
> there can be alternative spellings for the same type that the user might 
> reasonably expect to be applied. e.g., if the user expects to ignore `bool` 
> datatypes and the printing policy wants to spell the type as `_Bool`, this 
> won't behave as expected.
But then the diagnostic is inconsistent with what the compiler is configured to 
output as diagnostics, isn't it? Can I stringify through Clang with some 
"default" printing policy?



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:402-403
+
+// Unfortunately, undersquiggly highlights are for some reason chewed up
+// and not respected by diagnostics from Clang-Tidy. :(
+diag(First->getLocation(), "the first parameter in the range is '%0'",

aaron.ballman wrote:
> Can you post a screenshot of what you mean?
Given

```
Diag << SourceRange{First->getSourceRange().getBegin(), 
Last->getSourceRange().getEnd()};
```

The diagnostic is still produced with only a `^` at the original 
`diag(Location)`, ignoring the fed `SourceRange`:

```
/home/whisperity/LLVM/Build/../llvm-project/clang-tools-extra/test/clang-tidy/checkers/bugprone-easily-swappable-parameters-len2.cpp:21:18:
 warning: 3 adjacent parameters of 'redeclChain' of similar type ('int') are 
easily swapped by mistake [bugprone-easily-swappable-parameters]
void redeclChain(int I, int J, int K) {}
 ^
```

Instead of putting all the squigglies in as the range-location highlight, like 
how `Sema` can diagnose:

```
/home/whisperity/LLVM/Build/../llvm-project/clang-tools-extra/test/clang-tidy/checkers/bugprone-easily-swappable-parameters-len2.cpp:21:18:
 warning: 3 adjacent parameters of 'redeclChain' of similar type ('int') are 
easily swapped by mistake [bugprone-easily-swappable-parameters]
void redeclChain(int I, int J, int K) {}
 ^~~
```

I would not want to put additional note tags in an otherwise already verbose 
output.

Back in 2019 I was investigating this issue specifically for another checker I 
was working on, but hit the wall... Somewhere deep inside where Tidy diagnostic 
stuff is translated and consumed to Clang stuff, it goes away. It shouldn't, 
because there are statements that seemingly copy the `Diag.Ranges` array over, 
but it still does not come out.

... EDIT: I found [[ 
http://lists.llvm.org/pipermail/cfe-dev/2019-October/063676.html | the relevant 
mailing list post ]].



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.h:30
+  void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
+
+  /// The minimum length of an

[PATCH] D95349: [clangd] Allow diagnostics to be suppressed with configuration

2021-01-27 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/ParsedAST.cpp:319
 
-if (!CTChecks.empty()) {
-  ASTDiags.setLevelAdjuster([&CTContext](DiagnosticsEngine::Level 
DiagLevel,
- const clang::Diagnostic &Info) {
+ASTDiags.setLevelAdjuster([&, &Cfg(Config::current())](
+  DiagnosticsEngine::Level DiagLevel,

ArcsinX wrote:
> This line breaks GCC 5.4 build with the following log:
> ```
> llvm-project/clang-tools-extra/clangd/ParsedAST.cpp:319:55: error: binding 
> ‘const clang::clangd::Config’ to reference of type ‘clang::clangd::Config&’ 
> discards qualifiers
>  ASTDiags.setLevelAdjuster([&, &Cfg(Config::current())](
>^
> ```
> Unsure is it a compiler bug or not. Moving `Cfg` out of the capture list or 
> using a cast to `Config &` solves the problem.
Thanks! Appears to be https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66735

Landed the workaround as 12de8e1399fecf691639ba430b3824acb1311e70


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95349

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


[PATCH] D95523: [OpenCL] Add cl_khr_subgroup_ballot to TableGen BIFs

2021-01-27 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh created this revision.
svenvh added a reviewer: Anastasia.
Herald added a subscriber: yaxunl.
svenvh requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Add the builtin functions brought by the `cl_khr_subgroup_ballot`
extension to `-fdeclare-opencl-builtins`.

Also add placeholder comments for the other Extended Subgroup
Functions from the OpenCL Extension Specification.

I have verified (semi-manually) that this adds the same ballot functions
that are also in `opencl-c.h` already.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95523

Files:
  clang/lib/Sema/OpenCLBuiltins.td


Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -53,6 +53,7 @@
 // FunctionExtension definitions.
 def FuncExtNone  : FunctionExtension<"">;
 def FuncExtKhrSubgroups  : 
FunctionExtension<"cl_khr_subgroups">;
+def FuncExtKhrSubgroupBallot : 
FunctionExtension<"cl_khr_subgroup_ballot">;
 def FuncExtKhrGlobalInt32BaseAtomics : 
FunctionExtension<"cl_khr_global_int32_base_atomics">;
 def FuncExtKhrGlobalInt32ExtendedAtomics : 
FunctionExtension<"cl_khr_global_int32_extended_atomics">;
 def FuncExtKhrLocalInt32BaseAtomics  : 
FunctionExtension<"cl_khr_local_int32_base_atomics">;
@@ -344,6 +345,7 @@
 // GenType definitions for multiple base types (e.g. all floating point types,
 // or all integer types).
 // All types
+def AGenType1  : GenericType<"AGenType1", TLAll, Vec1>;
 def AGenTypeN  : GenericType<"AGenTypeN", TLAll, VecAndScalar>;
 def AGenTypeNNoScalar  : GenericType<"AGenTypeNNoScalar", TLAll, 
VecNoScalar>;
 // All integer
@@ -1498,6 +1500,44 @@
   }
 }
 
+// OpenCL Extension v3.0 s38 - Extended Subgroup Functions
+
+// Section 38.4.1 - cl_khr_subgroup_extended_types
+// TODO
+
+// Section 38.5.1 - cl_khr_subgroup_non_uniform_vote
+// TODO
+
+// Section 38.6.1 - cl_khr_subgroup_ballot
+let Extension = FuncExtKhrSubgroupBallot in {
+  def : Builtin<"sub_group_non_uniform_broadcast", [AGenTypeN, AGenTypeN, 
UInt]>;
+  def : Builtin<"sub_group_broadcast_first", [AGenType1, AGenType1]>;
+  def : Builtin<"sub_group_ballot", [VectorType, Int]>;
+  def : Builtin<"sub_group_inverse_ballot", [Int, VectorType], 
Attr.Const>;
+  def : Builtin<"sub_group_ballot_bit_extract", [Int, VectorType, 
UInt], Attr.Const>;
+  def : Builtin<"sub_group_ballot_bit_count", [UInt, VectorType], 
Attr.Const>;
+  def : Builtin<"sub_group_ballot_inclusive_scan", [UInt, VectorType]>;
+  def : Builtin<"sub_group_ballot_exclusive_scan", [UInt, VectorType]>;
+  def : Builtin<"sub_group_ballot_find_lsb", [UInt, VectorType]>;
+  def : Builtin<"sub_group_ballot_find_msb", [UInt, VectorType]>;
+
+  foreach op = ["eq", "ge", "gt", "le", "lt"] in {
+def : Builtin<"get_sub_group_" # op # "_mask", [VectorType], 
Attr.Const>;
+  }
+}
+
+// Section 38.7.1 - cl_khr_subgroup_non_uniform_arithmetic
+// TODO
+
+// Section 38.8.1 - cl_khr_subgroup_shuffle
+// TODO
+
+// Section 38.9.1 - cl_khr_subgroup_shuffle_relative
+// TODO
+
+// Section 38.10.1 - cl_khr_subgroup_clustered_reduce
+// TODO
+
 //
 // Arm extensions.
 let Extension = ArmIntegerDotProductInt8 in {


Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -53,6 +53,7 @@
 // FunctionExtension definitions.
 def FuncExtNone  : FunctionExtension<"">;
 def FuncExtKhrSubgroups  : FunctionExtension<"cl_khr_subgroups">;
+def FuncExtKhrSubgroupBallot : FunctionExtension<"cl_khr_subgroup_ballot">;
 def FuncExtKhrGlobalInt32BaseAtomics : FunctionExtension<"cl_khr_global_int32_base_atomics">;
 def FuncExtKhrGlobalInt32ExtendedAtomics : FunctionExtension<"cl_khr_global_int32_extended_atomics">;
 def FuncExtKhrLocalInt32BaseAtomics  : FunctionExtension<"cl_khr_local_int32_base_atomics">;
@@ -344,6 +345,7 @@
 // GenType definitions for multiple base types (e.g. all floating point types,
 // or all integer types).
 // All types
+def AGenType1  : GenericType<"AGenType1", TLAll, Vec1>;
 def AGenTypeN  : GenericType<"AGenTypeN", TLAll, VecAndScalar>;
 def AGenTypeNNoScalar  : GenericType<"AGenTypeNNoScalar", TLAll, VecNoScalar>;
 // All integer
@@ -1498,6 +1500,44 @@
   }
 }
 
+// OpenCL Extension v3.0 s38 - Extended Subgroup Functions
+
+// Section 38.4.1 - cl_khr_subgroup_extended_types
+// TODO
+
+// Section 38.5.1 - cl_khr_subgroup_non_uniform_vote
+// TODO
+
+// Section 38.6.1 - cl_khr_subgroup_ballot
+let Extension = FuncExtKhrSubgroupBallot in {
+  def : Builtin<"sub_group_non_uniform_broadcast", [AGenTypeN, AGenTypeN, UInt]>;
+  def : B

[PATCH] D95487: Itanium Mangling: Fix handling of in .

2021-01-27 Thread James Y Knight via Phabricator via cfe-commits
jyknight added inline comments.



Comment at: clang/lib/AST/ItaniumMangle.cpp:3912
+IsPrimaryExpr = false;
+  };
+

rjmccall wrote:
> I think it might be more reasonable to just check for the relatively small 
> number of primary-expression cases in `mangleTemplateArgExpr` and skip the 
> `X...E` there rather than pushing it down into this function.
I started out writing it that way, but it's more complex than it first seems.

First you have the 9 expression types that always fit into  -- 
those are simple enough, but that's already a lot more than one might think. 
But, then you also need to handle recusing on all the cases with no output 
(ParenExprClass etc. -- 10 cases of this). And, finally, you have complex cases 
like DeclRefExpr, CXXConstructExprClass, and UnaryExprOrTypeTraitExprClass, 
which sometimes emit a primary expression and sometimes do not.

Putting all of that together, the number of cases to handle with a separate 
function was large enough -- and duplicative enough -- that it seemed more 
confusing to have such an implementation split than it was helpful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95487

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


[PATCH] D95514: [clang][cli] Teach CompilerInvocation to allocate strings on its own

2021-01-27 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.

Can you include the use in the patch? I’m not sure having the AllocateString 
API totally makes sense, vs moving in a string pool that was independently used 
during generation, but maybe in context?

I also wonder what command-line option is forcing this. Ideally we could 
arrange the generated -cc1 command line to only use generated strings for 
numbers / enums, which will not need long-term storage as stringrefs. String 
arguments could reuse the original char*. It seems better to drop frivolous `=` 
than carrying this around.

Consider that some callers may parse the full command-line and then drop 
everything but one options class. That pattern wouldn’t work anymore since the 
StringRefs won’t be valid.




Comment at: clang/include/clang/Frontend/CompilerInvocation.h:144
+  /// Container holding strings allocated during round-trip.
+  mutable std::forward_list AllocatedStrings;
+

I suggest using llvm::StringPool instead, which also uniques the strings and is 
used elsewhere for this kind of thing. Probably in an Optional to make it more 
clear it’s not always used.

Maybe the name RoundTrippedStrings? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95514

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


[PATCH] D95229: [clangd] Treat optional field type mismatches as soft failures

2021-01-27 Thread Kadir Cetinkaya 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 rGaf20232b8e18: [clangd] Treat "null" optional 
fields as missing (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95229

Files:
  clang-tools-extra/clangd/Protocol.cpp

Index: clang-tools-extra/clangd/Protocol.cpp
===
--- clang-tools-extra/clangd/Protocol.cpp
+++ clang-tools-extra/clangd/Protocol.cpp
@@ -27,6 +27,21 @@
 
 namespace clang {
 namespace clangd {
+namespace {
+
+// Helper that doesn't treat `null` and absent fields as failures.
+template 
+bool mapOptOrNull(const llvm::json::Value &Params, llvm::StringLiteral Prop,
+  T &Out, llvm::json::Path P) {
+  auto *O = Params.getAsObject();
+  assert(O);
+  auto *V = O->get(Prop);
+  // Field is missing or null.
+  if (!V || V->getAsNull().hasValue())
+return true;
+  return fromJSON(*V, Out, P.field(Prop));
+}
+} // namespace
 
 char LSPError::ID;
 
@@ -490,7 +505,7 @@
   return O && O.map("textDocument", R.textDocument) &&
  O.map("contentChanges", R.contentChanges) &&
  O.map("wantDiagnostics", R.wantDiagnostics) &&
- O.mapOptional("forceRebuild", R.forceRebuild);
+ mapOptOrNull(Params, "forceRebuild", R.forceRebuild, P);
 }
 
 bool fromJSON(const llvm::json::Value &E, FileChangeType &Out,
@@ -580,10 +595,10 @@
   llvm::json::Path P) {
   llvm::json::ObjectMapper O(Params, P);
   return O && O.map("range", R.range) && O.map("message", R.message) &&
- O.mapOptional("severity", R.severity) &&
- O.mapOptional("category", R.category) &&
- O.mapOptional("code", R.code) && O.mapOptional("source", R.source);
-  return true;
+ mapOptOrNull(Params, "severity", R.severity, P) &&
+ mapOptOrNull(Params, "category", R.category, P) &&
+ mapOptOrNull(Params, "code", R.code, P) &&
+ mapOptOrNull(Params, "source", R.source, P);
 }
 
 llvm::json::Value toJSON(const PublishDiagnosticsParams &PDP) {
@@ -818,7 +833,7 @@
   llvm::json::ObjectMapper O(Params, P);
   int TriggerKind;
   if (!O || !O.map("triggerKind", TriggerKind) ||
-  !O.mapOptional("triggerCharacter", R.triggerCharacter))
+  !mapOptOrNull(Params, "triggerCharacter", R.triggerCharacter, P))
 return false;
   R.triggerKind = static_cast(TriggerKind);
   return true;
@@ -1121,8 +1136,8 @@
   llvm::json::ObjectMapper O(Params, P);
   if (!O)
 return true; // 'any' type in LSP.
-  return O.mapOptional("compilationDatabaseChanges",
-   S.compilationDatabaseChanges);
+  return mapOptOrNull(Params, "compilationDatabaseChanges",
+  S.compilationDatabaseChanges, P);
 }
 
 bool fromJSON(const llvm::json::Value &Params, InitializationOptions &Opts,
@@ -1133,8 +1148,8 @@
 
   return fromJSON(Params, Opts.ConfigSettings, P) &&
  O.map("compilationDatabasePath", Opts.compilationDatabasePath) &&
- O.mapOptional("fallbackFlags", Opts.fallbackFlags) &&
- O.mapOptional("clangdFileStatus", Opts.FileStatus);
+ mapOptOrNull(Params, "fallbackFlags", Opts.fallbackFlags, P) &&
+ mapOptOrNull(Params, "clangdFileStatus", Opts.FileStatus, P);
 }
 
 bool fromJSON(const llvm::json::Value &E, TypeHierarchyDirection &Out,
@@ -1190,10 +1205,11 @@
   return O && O.map("name", I.name) && O.map("kind", I.kind) &&
  O.map("uri", I.uri) && O.map("range", I.range) &&
  O.map("selectionRange", I.selectionRange) &&
- O.mapOptional("detail", I.detail) &&
- O.mapOptional("deprecated", I.deprecated) &&
- O.mapOptional("parents", I.parents) &&
- O.mapOptional("children", I.children) && O.mapOptional("data", I.data);
+ mapOptOrNull(Params, "detail", I.detail, P) &&
+ mapOptOrNull(Params, "deprecated", I.deprecated, P) &&
+ mapOptOrNull(Params, "parents", I.parents, P) &&
+ mapOptOrNull(Params, "children", I.children, P) &&
+ mapOptOrNull(Params, "data", I.data, P);
 }
 
 bool fromJSON(const llvm::json::Value &Params,
@@ -1238,7 +1254,7 @@
   return O && O.map("name", I.name) && O.map("kind", I.kind) &&
  O.map("uri", I.uri) && O.map("range", I.range) &&
  O.map("selectionRange", I.selectionRange) &&
- O.mapOptional("data", I.data);
+ mapOptOrNull(Params, "data", I.data, P);
 }
 
 bool fromJSON(const llvm::json::Value &Params,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D94466: [X86] merge "={eax}" and "~{eax}" into "=&eax" for MSInlineASM

2021-01-27 Thread Freddy, Ye via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1edb76cc91e7: [X86] merge "={eax}" and 
"~{eax}" into "=&eax" for MSInlineASM (authored by 
FreddyYe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94466

Files:
  clang/lib/CodeGen/CGStmt.cpp
  clang/test/CodeGen/ms-inline-asm.c
  clang/test/CodeGenCXX/ms-inline-asm-return.cpp

Index: clang/test/CodeGenCXX/ms-inline-asm-return.cpp
===
--- clang/test/CodeGenCXX/ms-inline-asm-return.cpp
+++ clang/test/CodeGenCXX/ms-inline-asm-return.cpp
@@ -13,7 +13,17 @@
   }
 }
 // CHECK-LABEL: define dso_local i64 @f_i64()
-// CHECK: %[[r:[^ ]*]] = call i64 asm sideeffect inteldialect "mov eax, $$1\0A\09mov edx, $$1", "=A,~{eax},{{.*}}"
+// CHECK: %[[r:[^ ]*]] = call i64 asm sideeffect inteldialect "mov eax, $$1\0A\09mov edx, $$1", "=&A,{{.*}}"
+// CHECK: ret i64 %[[r]]
+
+long long f_i64_reverse() {
+  __asm {
+mov edx, 1
+mov eax, 1
+  }
+}
+// CHECK-LABEL: define dso_local i64 @f_i64_reverse()
+// CHECK: %[[r:[^ ]*]] = call i64 asm sideeffect inteldialect "mov edx, $$1\0A\09mov eax, $$1", "=&A,{{.*}}"
 // CHECK: ret i64 %[[r]]
 
 int f_i32() {
@@ -23,7 +33,26 @@
   }
 }
 // CHECK-LABEL: define dso_local i32 @f_i32()
-// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "mov eax, $$1\0A\09mov edx, $$1", "={eax},~{eax},{{.*}}"
+// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "mov eax, $$1\0A\09mov edx, $$1", "=&{eax},~{edx},{{.*}}"
+// CHECK: ret i32 %[[r]]
+
+int f_i32_reverse() {
+  __asm {
+mov edx, 1
+mov eax, 1
+  }
+}
+// CHECK-LABEL: define dso_local i32 @f_i32_reverse()
+// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "mov edx, $$1\0A\09mov eax, $$1", "=&{eax},~{edx},{{.*}}"
+// CHECK: ret i32 %[[r]]
+
+int f_i32_edx() {
+  __asm {
+mov edx, 1
+  }
+}
+// CHECK-LABEL: define dso_local i32 @f_i32_edx()
+// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "mov edx, $$1", "={eax},~{edx},{{.*}}"
 // CHECK: ret i32 %[[r]]
 
 short f_i16() {
@@ -33,7 +62,7 @@
   }
 }
 // CHECK-LABEL: define dso_local signext i16 @f_i16()
-// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "mov eax, $$1\0A\09mov edx, $$1", "={eax},~{eax},{{.*}}"
+// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "mov eax, $$1\0A\09mov edx, $$1", "=&{eax},~{edx},{{.*}}"
 // CHECK: %[[r_i16:[^ ]*]] = trunc i32 %[[r]] to i16
 // CHECK: ret i16 %[[r_i16]]
 
@@ -44,7 +73,7 @@
   }
 }
 // CHECK-LABEL: define dso_local signext i8 @f_i8()
-// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "mov eax, $$1\0A\09mov edx, $$1", "={eax},~{eax},{{.*}}"
+// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "mov eax, $$1\0A\09mov edx, $$1", "=&{eax},~{edx},{{.*}}"
 // CHECK: %[[r_i8:[^ ]*]] = trunc i32 %[[r]] to i8
 // CHECK: ret i8 %[[r_i8]]
 
@@ -55,7 +84,7 @@
   }
 }
 // CHECK-LABEL: define dso_local zeroext i1 @f_i1()
-// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "mov eax, $$1\0A\09mov edx, $$1", "={eax},~{eax},{{.*}}"
+// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "mov eax, $$1\0A\09mov edx, $$1", "=&{eax},~{edx},{{.*}}"
 // CHECK: %[[r_i8:[^ ]*]] = trunc i32 %[[r]] to i8
 // CHECK: store i8 %[[r_i8]], i8* %{{.*}}
 // CHECK: %[[r_i1:[^ ]*]] = load i1, i1* %{{.*}}
@@ -70,7 +99,7 @@
   }
 }
 // CHECK-LABEL: define dso_local i32 @f_s4()
-// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "mov eax, $$16843009", "={eax},~{eax},{{.*}}"
+// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "mov eax, $$16843009", "=&{eax},{{.*}}"
 // CHECK: store i32 %[[r]], i32* %{{.*}}
 // CHECK: %[[r_i32:[^ ]*]] = load i32, i32* %{{.*}}
 // CHECK: ret i32 %[[r_i32]]
@@ -85,7 +114,7 @@
   }
 }
 // CHECK-LABEL: define dso_local i64 @f_s8()
-// CHECK: %[[r:[^ ]*]] = call i64 asm sideeffect inteldialect "mov eax, $$16843009\0A\09mov edx, $$85", "=A,~{eax},{{.*}}"
+// CHECK: %[[r:[^ ]*]] = call i64 asm sideeffect inteldialect "mov eax, $$16843009\0A\09mov edx, $$85", "=&A,{{.*}}"
 // CHECK: store i64 %[[r]], i64* %{{.*}}
 // CHECK: %[[r_i64:[^ ]*]] = load i64, i64* %{{.*}}
 // CHECK: ret i64 %[[r_i64]]
@@ -96,5 +125,5 @@
   __asm xor eax, eax
 }
 // CHECK-LABEL: define dso_local i32 @main()
-// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "xor eax, eax", "={eax},{{.*}}"
+// CHECK: %[[r:[^ ]*]] = call i32 asm sideeffect inteldialect "xor eax, eax", "=&{eax},{{.*}}"
 // CHECK: ret i32 %[[r]]
Index: clang/test/CodeGen/ms-inline-asm.c
===
--- clang/test/CodeGen/ms-inline-asm.c
+++ clang/test/CodeGen/ms-inline-asm.c
@@ -114,7 +114,7 @@
 // CHECK: call i32 asm sideeffect inteldialect
 // CHECK-SAME: mov eax, $2
 // CHECK-SAME: mov $0, eax
-// CHECK-SAME: "=*m,={eax},*m,~{eax},~{dirflag},~{fpsr},~{flags}"(i32* %{{.*}}, i3

[PATCH] D89909: [SYCL] Implement SYCL address space attributes handling

2021-01-27 Thread Alexey Bader via Phabricator via cfe-commits
bader updated this revision to Diff 319566.
bader added a comment.

Rebase patch on ToT and applied small refactoring.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89909

Files:
  clang/include/clang/AST/Type.h
  clang/include/clang/Basic/AddressSpaces.h
  clang/include/clang/Sema/ParsedAttr.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/Basic/Targets.cpp
  clang/lib/Basic/Targets/AMDGPU.cpp
  clang/lib/Basic/Targets/NVPTX.h
  clang/lib/Basic/Targets/SPIR.h
  clang/lib/Basic/Targets/TCE.h
  clang/lib/Basic/Targets/X86.h
  clang/lib/CodeGen/TargetInfo.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGenSYCL/address-space-cond-op.cpp
  clang/test/CodeGenSYCL/address-space-of-returns.cpp
  clang/test/CodeGenSYCL/address-space-parameter-conversions.cpp
  clang/test/CodeGenSYCL/address-spaces-struct.cpp
  clang/test/CodeGenSYCL/address-spaces.cpp
  clang/test/SemaSYCL/address-space-parameter-conversions.cpp
  clang/test/SemaTemplate/address_space-dependent.cpp
  llvm/include/llvm/ADT/Triple.h
  llvm/lib/Support/Triple.cpp

Index: llvm/lib/Support/Triple.cpp
===
--- llvm/lib/Support/Triple.cpp
+++ llvm/lib/Support/Triple.cpp
@@ -247,6 +247,8 @@
   case Musl: return "musl";
   case MuslEABI: return "musleabi";
   case MuslEABIHF: return "musleabihf";
+  case SYCLDevice:
+return "sycldevice";
   case Simulator: return "simulator";
   }
 
@@ -554,6 +556,7 @@
   .StartsWith("itanium", Triple::Itanium)
   .StartsWith("cygnus", Triple::Cygnus)
   .StartsWith("coreclr", Triple::CoreCLR)
+  .StartsWith("sycldevice", Triple::SYCLDevice)
   .StartsWith("simulator", Triple::Simulator)
   .StartsWith("macabi", Triple::MacABI)
   .Default(Triple::UnknownEnvironment);
Index: llvm/include/llvm/ADT/Triple.h
===
--- llvm/include/llvm/ADT/Triple.h
+++ llvm/include/llvm/ADT/Triple.h
@@ -222,8 +222,9 @@
 Itanium,
 Cygnus,
 CoreCLR,
+SYCLDevice,
 Simulator, // Simulator variants of other systems, e.g., Apple's iOS
-MacABI, // Mac Catalyst variant of Apple's iOS deployment target.
+MacABI,// Mac Catalyst variant of Apple's iOS deployment target.
 LastEnvironmentType = MacABI
   };
   enum ObjectFormatType {
@@ -497,6 +498,10 @@
isMacCatalystEnvironment()));
   }
 
+  bool isSYCLDeviceEnvironment() const {
+return getEnvironment() == Triple::SYCLDevice;
+  }
+
   bool isOSNetBSD() const {
 return getOS() == Triple::NetBSD;
   }
Index: clang/test/SemaTemplate/address_space-dependent.cpp
===
--- clang/test/SemaTemplate/address_space-dependent.cpp
+++ clang/test/SemaTemplate/address_space-dependent.cpp
@@ -43,7 +43,7 @@
 
 template 
 void tooBig() {
-  __attribute__((address_space(I))) int *bounds; // expected-error {{address space is larger than the maximum supported (8388593)}}
+  __attribute__((address_space(I))) int *bounds; // expected-error {{address space is larger than the maximum supported (8388590)}}
 }
 
 template 
@@ -101,7 +101,7 @@
   car<1, 2, 3>(); // expected-note {{in instantiation of function template specialization 'car<1, 2, 3>' requested here}}
   HasASTemplateFields<1> HASTF;
   neg<-1>(); // expected-note {{in instantiation of function template specialization 'neg<-1>' requested here}}
-  correct<0x71>();
+  correct<0x7FFFED>();
   tooBig<8388650>(); // expected-note {{in instantiation of function template specialization 'tooBig<8388650>' requested here}}
 
   __attribute__((address_space(1))) char *x;
Index: clang/test/SemaSYCL/address-space-parameter-conversions.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/address-space-parameter-conversions.cpp
@@ -0,0 +1,57 @@
+// RUN: %clang_cc1 -fsycl -fsycl-is-device -verify -fsyntax-only -x c++ %s
+
+void bar(int &Data) {}
+void bar2(int &Data) {}
+void bar(__attribute__((opencl_private)) int &Data) {}
+void foo(int *Data) {}
+void foo2(int *Data) {}
+void foo(__attribute__((opencl_private)) int *Data) {}
+
+template 
+void tmpl(T *t) {}
+
+void usages() {
+  __attribute__((opencl_global)) int *GLOB;
+  __attribute__((opencl_private)) int *PRIV;
+  __attribute__((opencl_local)) int *LOC;
+  int *NoAS;
+
+  bar(*GLOB);
+  bar2(*GLOB);
+
+  bar(*PRIV);
+  bar2(*PRIV);
+
+  bar(*NoAS);
+  bar2(*NoAS);
+
+  bar(*LOC);
+  bar2(*LOC);
+
+  foo(GLOB);
+  foo2(GLOB);
+  foo(PRIV);
+  foo2(PRIV);
+  foo(NoAS);
+  foo2(NoAS);
+  foo(LOC);
+  foo2(LOC);
+
+  tmpl(GLOB);
+  tmpl(PRIV);
+  tmpl(NoAS);
+  tmpl(LOC);
+
+  (void)static_cast(GLOB);
+  (void)static_cast(GLOB);
+  // FIXME: determine if we can warn on the below conversions.
+  int *i = GLOB;
+  void 

[PATCH] D95526: [Syntax] Add syntax-tree-dump in clang-check.

2021-01-27 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added a subscriber: mgorny.
hokein requested review of this revision.
Herald added a project: clang.

This is useful to experiment/develop syntax trees.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95526

Files:
  clang/test/Tooling/clang-check-syntax-tree-dump.cpp
  clang/tools/clang-check/CMakeLists.txt
  clang/tools/clang-check/ClangCheck.cpp


Index: clang/tools/clang-check/ClangCheck.cpp
===
--- clang/tools/clang-check/ClangCheck.cpp
+++ clang/tools/clang-check/ClangCheck.cpp
@@ -24,6 +24,9 @@
 #include "clang/Rewrite/Frontend/FrontendActions.h"
 #include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
 #include "clang/Tooling/CommonOptionsParser.h"
+#include "clang/Tooling/Syntax/BuildTree.h"
+#include "clang/Tooling/Syntax/Tokens.h"
+#include "clang/Tooling/Syntax/Tree.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Option/OptTable.h"
@@ -82,6 +85,10 @@
 cl::desc(Options.getOptionHelpText(options::OPT_fix_what_you_can)),
 cl::cat(ClangCheckCategory));
 
+static cl::opt SyntaxTreeDump("syntax-tree-dump",
+cl::desc("dump the syntax tree"),
+cl::cat(ClangCheckCategory));
+
 namespace {
 
 // FIXME: Move FixItRewriteInPlace from 
lib/Rewrite/Frontend/FrontendActions.cpp
@@ -131,6 +138,28 @@
   }
 };
 
+class BuildSyntaxTree : public clang::ASTFrontendAction {
+public:
+  std::unique_ptr
+  CreateASTConsumer(clang::CompilerInstance &CI, StringRef InFile) override {
+class Consumer : public clang::ASTConsumer {
+public:
+  Consumer(clang::CompilerInstance &CI) : Collector(CI.getPreprocessor()) 
{}
+
+  void HandleTranslationUnit(clang::ASTContext &AST) override {
+clang::syntax::TokenBuffer TB = std::move(Collector).consume();
+clang::syntax::Arena A(AST.getSourceManager(), AST.getLangOpts(), TB);
+llvm::outs() << clang::syntax::buildSyntaxTree(A, AST)->dump(
+AST.getSourceManager());
+  }
+
+private:
+  clang::syntax::TokenCollector Collector;
+};
+return std::make_unique(CI);
+  }
+};
+
 class ClangCheckActionFactory {
 public:
   std::unique_ptr newASTConsumer() {
@@ -182,6 +211,8 @@
 FrontendFactory = newFrontendActionFactory();
   else if (Fixit)
 FrontendFactory = newFrontendActionFactory();
+  else if (SyntaxTreeDump)
+FrontendFactory = newFrontendActionFactory();
   else
 FrontendFactory = newFrontendActionFactory(&CheckFactory);
 
Index: clang/tools/clang-check/CMakeLists.txt
===
--- clang/tools/clang-check/CMakeLists.txt
+++ clang/tools/clang-check/CMakeLists.txt
@@ -18,4 +18,5 @@
   clangSerialization
   clangStaticAnalyzerFrontend
   clangTooling
+  clangToolingSyntax
   )
Index: clang/test/Tooling/clang-check-syntax-tree-dump.cpp
===
--- /dev/null
+++ clang/test/Tooling/clang-check-syntax-tree-dump.cpp
@@ -0,0 +1,9 @@
+// RUN: clang-check -syntax-tree-dump "%s" -- 2>&1 | FileCheck %s
+int abc;
+// CHECK:  TranslationUnit Detached
+// CHECK-NEXT: `-SimpleDeclaration
+// CHECK-NEXT:   |-'int'
+// CHECK-NEXT:   |-DeclaratorList Declarators
+// CHECK-NEXT:   | `-SimpleDeclarator ListElement
+// CHECK-NEXT:   |   `-'abc'
+// CHECK-NEXT:   `-';'


Index: clang/tools/clang-check/ClangCheck.cpp
===
--- clang/tools/clang-check/ClangCheck.cpp
+++ clang/tools/clang-check/ClangCheck.cpp
@@ -24,6 +24,9 @@
 #include "clang/Rewrite/Frontend/FrontendActions.h"
 #include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
 #include "clang/Tooling/CommonOptionsParser.h"
+#include "clang/Tooling/Syntax/BuildTree.h"
+#include "clang/Tooling/Syntax/Tokens.h"
+#include "clang/Tooling/Syntax/Tree.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Option/OptTable.h"
@@ -82,6 +85,10 @@
 cl::desc(Options.getOptionHelpText(options::OPT_fix_what_you_can)),
 cl::cat(ClangCheckCategory));
 
+static cl::opt SyntaxTreeDump("syntax-tree-dump",
+cl::desc("dump the syntax tree"),
+cl::cat(ClangCheckCategory));
+
 namespace {
 
 // FIXME: Move FixItRewriteInPlace from lib/Rewrite/Frontend/FrontendActions.cpp
@@ -131,6 +138,28 @@
   }
 };
 
+class BuildSyntaxTree : public clang::ASTFrontendAction {
+public:
+  std::unique_ptr
+  CreateASTConsumer(clang::CompilerInstance &CI, StringRef InFile) override {
+class Consumer : public clang::ASTConsumer {
+public:
+  Consumer(clang::CompilerInstance &CI) : Collector(CI.getPreprocessor()) {}
+
+  void HandleTranslationUnit(clang::ASTContext &AST) override {
+clang::syntax::TokenBuffer TB = std::m

[PATCH] D95488: Itanium Mangling: In 'enable_if', omit X/E around .

2021-01-27 Thread James Y Knight via Phabricator via cfe-commits
jyknight updated this revision to Diff 319578.
jyknight added a comment.

Add neglected clang-abi-compat.cpp change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95488

Files:
  clang/lib/AST/ItaniumMangle.cpp
  clang/test/CodeGen/enable_if.c
  clang/test/CodeGenCXX/clang-abi-compat.cpp
  clang/test/CodeGenCXX/enable_if.cpp

Index: clang/test/CodeGenCXX/enable_if.cpp
===
--- clang/test/CodeGenCXX/enable_if.cpp
+++ clang/test/CodeGenCXX/enable_if.cpp
@@ -5,7 +5,7 @@
 template 
 T test5(T) __attribute__((enable_if(1, "better than non-template")));
 
-// CHECK: @_Z5test5IiEUa9enable_ifIXLi1EEET_S0_
+// CHECK: @_Z5test5IiEUa9enable_ifILi1EET_S0_
 int (*Ptr)(int) = &test5;
 
 // Test itanium mangling for attribute enable_if
Index: clang/test/CodeGenCXX/clang-abi-compat.cpp
===
--- clang/test/CodeGenCXX/clang-abi-compat.cpp
+++ clang/test/CodeGenCXX/clang-abi-compat.cpp
@@ -130,4 +130,9 @@
 template using matrix1xN = int __attribute__((matrix_type(1, N)));
 template void test8(matrix1xN a) {}
 template void test8<2>(matrix1xN<2> a);
+
+// PRE12: @_ZN12expr_primary5test9EUa9enable_ifIXLi1EEEv
+// V12:   @_ZN12expr_primary5test9EUa9enable_ifILi1EEv
+void test9(void) __attribute__((enable_if(1, ""))) {}
+
 }
Index: clang/test/CodeGen/enable_if.c
===
--- clang/test/CodeGen/enable_if.c
+++ clang/test/CodeGen/enable_if.c
@@ -31,22 +31,22 @@
 void bar(int m) __attribute__((overloadable, enable_if(1, "")));
 // CHECK-LABEL: define{{.*}} void @test2
 void test2() {
-  // CHECK: store void (i32)* @_Z3barUa9enable_ifIXLi1EEEi
+  // CHECK: store void (i32)* @_Z3barUa9enable_ifILi1EEi
   void (*p)(int) = bar;
-  // CHECK: store void (i32)* @_Z3barUa9enable_ifIXLi1EEEi
+  // CHECK: store void (i32)* @_Z3barUa9enable_ifILi1EEi
   void (*p2)(int) = &bar;
-  // CHECK: store void (i32)* @_Z3barUa9enable_ifIXLi1EEEi
+  // CHECK: store void (i32)* @_Z3barUa9enable_ifILi1EEi
   p = bar;
-  // CHECK: store void (i32)* @_Z3barUa9enable_ifIXLi1EEEi
+  // CHECK: store void (i32)* @_Z3barUa9enable_ifILi1EEi
   p = &bar;
 
-  // CHECK: store i8* bitcast (void (i32)* @_Z3barUa9enable_ifIXLi1EEEi to i8*)
+  // CHECK: store i8* bitcast (void (i32)* @_Z3barUa9enable_ifILi1EEi to i8*)
   void *vp1 = (void*)&bar;
-  // CHECK: store i8* bitcast (void (i32)* @_Z3barUa9enable_ifIXLi1EEEi to i8*)
+  // CHECK: store i8* bitcast (void (i32)* @_Z3barUa9enable_ifILi1EEi to i8*)
   void *vp2 = (void*)bar;
-  // CHECK: store i8* bitcast (void (i32)* @_Z3barUa9enable_ifIXLi1EEEi to i8*)
+  // CHECK: store i8* bitcast (void (i32)* @_Z3barUa9enable_ifILi1EEi to i8*)
   vp1 = (void*)&bar;
-  // CHECK: store i8* bitcast (void (i32)* @_Z3barUa9enable_ifIXLi1EEEi to i8*)
+  // CHECK: store i8* bitcast (void (i32)* @_Z3barUa9enable_ifILi1EEi to i8*)
   vp1 = (void*)bar;
 }
 
@@ -54,13 +54,13 @@
 void baz(int m) __attribute__((overloadable));
 // CHECK-LABEL: define{{.*}} void @test3
 void test3() {
-  // CHECK: store void (i32)* @_Z3bazUa9enable_ifIXLi1EEEi
+  // CHECK: store void (i32)* @_Z3bazUa9enable_ifILi1EEi
   void (*p)(int) = baz;
-  // CHECK: store void (i32)* @_Z3bazUa9enable_ifIXLi1EEEi
+  // CHECK: store void (i32)* @_Z3bazUa9enable_ifILi1EEi
   void (*p2)(int) = &baz;
-  // CHECK: store void (i32)* @_Z3bazUa9enable_ifIXLi1EEEi
+  // CHECK: store void (i32)* @_Z3bazUa9enable_ifILi1EEi
   p = baz;
-  // CHECK: store void (i32)* @_Z3bazUa9enable_ifIXLi1EEEi
+  // CHECK: store void (i32)* @_Z3bazUa9enable_ifILi1EEi
   p = &baz;
 }
 
@@ -71,13 +71,13 @@
 void qux(int m) __attribute__((overloadable, enable_if(1, "")));
 // CHECK-LABEL: define{{.*}} void @test4
 void test4() {
-  // CHECK: store void (i32)* @_Z3quxUa9enable_ifIXLi1EEXLi1EEEi
+  // CHECK: store void (i32)* @_Z3quxUa9enable_ifILi1ELi1EEi
   void (*p)(int) = qux;
-  // CHECK: store void (i32)* @_Z3quxUa9enable_ifIXLi1EEXLi1EEEi
+  // CHECK: store void (i32)* @_Z3quxUa9enable_ifILi1ELi1EEi
   void (*p2)(int) = &qux;
-  // CHECK: store void (i32)* @_Z3quxUa9enable_ifIXLi1EEXLi1EEEi
+  // CHECK: store void (i32)* @_Z3quxUa9enable_ifILi1ELi1EEi
   p = qux;
-  // CHECK: store void (i32)* @_Z3quxUa9enable_ifIXLi1EEXLi1EEEi
+  // CHECK: store void (i32)* @_Z3quxUa9enable_ifILi1ELi1EEi
   p = &qux;
 }
 
@@ -90,6 +90,6 @@
   int foo(char *i __attribute__((pass_object_size(0
   __attribute__((enable_if(1, ""), overloadable));
 
-  // CHECK: call i32 @_Z3fooUa9enable_ifIXLi1EEEPcU17pass_object_size0
+  // CHECK: call i32 @_Z3fooUa9enable_ifILi1EEPcU17pass_object_size0
   foo((void*)0);
 }
Index: clang/lib/AST/ItaniumMangle.cpp
===
--- clang/lib/AST/ItaniumMangle.cpp
+++ clang/lib/AST/ItaniumMangle.cpp
@@ -726,9 +726,17 @@
   EnableIfAttr *EIA = dyn_cast(

[PATCH] D71016: [SYCL] Implement OpenCL kernel function generation

2021-01-27 Thread Alexey Bader via Phabricator via cfe-commits
bader updated this revision to Diff 319579.
bader added a comment.

Depends on D89909 

Apply improvements developed in out-of-tree repository, which mostly are 
refactoring of SemaSYCL.cpp file.
Rebase on ToT + D89909  (which only impacts 
lit test checks).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D71016

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Parse/ParseAST.cpp
  clang/lib/Sema/SemaSYCL.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/CodeGenSYCL/Inputs/sycl.hpp
  clang/test/CodeGenSYCL/basic-opencl-kernel.cpp
  clang/test/CodeGenSYCL/device-functions.cpp
  clang/test/SemaSYCL/Inputs/sycl.hpp
  clang/test/SemaSYCL/accessors-targets.cpp
  clang/test/SemaSYCL/basic-opencl-kernel.cpp
  clang/test/SemaSYCL/built-in-type-kernel-arg.cpp
  clang/test/SemaSYCL/fake-accessors.cpp
  clang/test/SemaSYCL/mangle-kernel.cpp

Index: clang/test/SemaSYCL/mangle-kernel.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/mangle-kernel.cpp
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -triple spir64-unknown-unknown-unknown -I %S/Inputs -I %S/../Headers/Inputs/include/ -fsycl -fsycl-is-device -ast-dump %s | FileCheck %s --check-prefix=CHECK-64
+// RUN: %clang_cc1 -triple spir-unknown-unknown-unknown -I %S/Inputs -I %S/../Headers/Inputs/include/ -fsycl -fsycl-is-device -ast-dump %s | FileCheck %s --check-prefix=CHECK-32
+#include 
+#include 
+
+template 
+__attribute__((sycl_kernel)) void kernel(Func kernelFunc) {
+  kernelFunc();
+}
+
+template 
+class SimpleVadd;
+
+int main() {
+  kernel>(
+  [=](){});
+
+  kernel>(
+  [=](){});
+
+  kernel>(
+  [=](){});
+  return 0;
+}
+
+// CHECK: _ZTS10SimpleVaddIiE
+// CHECK: _ZTS10SimpleVaddIdE
+// CHECK-64: _ZTS10SimpleVaddImE
+// CHECK-32: _ZTS10SimpleVaddIjE
Index: clang/test/SemaSYCL/fake-accessors.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/fake-accessors.cpp
@@ -0,0 +1,56 @@
+// RUN: %clang_cc1 -I %S/Inputs -fsycl -fsycl-is-device -ast-dump %s | FileCheck %s
+
+#include 
+
+namespace foo {
+namespace cl {
+namespace sycl {
+class accessor {
+public:
+  int field;
+};
+} // namespace sycl
+} // namespace cl
+} // namespace foo
+
+class accessor {
+public:
+  int field;
+};
+
+typedef cl::sycl::accessor
+MyAccessorTD;
+
+using MyAccessorA = cl::sycl::accessor;
+
+template 
+__attribute__((sycl_kernel)) void kernel(Func kernelFunc) {
+  kernelFunc();
+}
+
+int main() {
+  foo::cl::sycl::accessor acc = {1};
+  accessor acc1 = {1};
+
+  cl::sycl::accessor accessorA;
+  cl::sycl::accessor accessorB;
+  cl::sycl::accessor accessorC;
+kernel(
+[=]() {
+  accessorA.use((void*)(acc.field + acc1.field));
+});
+kernel(
+[=]() {
+  accessorB.use((void*)(acc.field + acc1.field));
+});
+kernel(
+[=]() {
+  accessorC.use((void*)(acc.field + acc1.field));
+});
+  return 0;
+}
+// CHECK: fake_accessors 'void (__global int *, cl::sycl::range<1>, cl::sycl::range<1>, cl::sycl::id<1>, foo::cl::sycl::accessor, accessor)
+// CHECK: accessor_typedef 'void (__global int *, cl::sycl::range<1>, cl::sycl::range<1>, cl::sycl::id<1>, foo::cl::sycl::accessor, accessor)
+// CHECK: accessor_alias 'void (__global int *, cl::sycl::range<1>, cl::sycl::range<1>, cl::sycl::id<1>, foo::cl::sycl::accessor, accessor)
Index: clang/test/SemaSYCL/built-in-type-kernel-arg.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/built-in-type-kernel-arg.cpp
@@ -0,0 +1,70 @@
+// RUN: %clang_cc1 -I %S/Inputs -fsycl -fsycl-is-device -ast-dump %s | FileCheck %s
+
+// This test checks that compiler generates correct initialization for arguments
+// that have struct or built-in type inside the OpenCL kernel
+
+#include 
+
+template 
+__attribute__((sycl_kernel)) void kernel(Func kernelFunc) {
+  kernelFunc();
+}
+
+struct test_struct {
+  int data;
+};
+
+void test(const int some_const) {
+  kernel(
+  [=]() {
+int a = some_const;
+  });
+}
+
+int main() {
+  int data = 5;
+  test_struct s;
+  s.data = data;
+  kernel(
+  [=]() {
+int kernel_data = data;
+  });
+  kernel(
+  [=]() {
+test_struct k_s;
+k_s = s;
+  });
+  const int some_const = 10;
+  test(some_const);
+  return 0;
+}
+// Check kernel parameters
+// CHECK: FunctionDecl {{.*}}kernel_const{{.*}} 'void (const int)'
+// CHECK: ParmVarDecl {{.*}} used _arg_ 'const int'
+
+// Check that lambda field of const built-in type is initialized
+// CHECK: VarDecl {{.*}}'(lambda at {{.*}}built-in-type-kernel-arg.cpp{{.*}})'
+// CHECK-NEXT: InitListExpr
+// CHECK-NEXT: ImplicitCastExpr {{.*}} 'int' 
+// CHECK-N

[PATCH] D95532: [clang][cli] Use variadic macros for parsing/generating

2021-01-27 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch makes all macros forwarding to `PARSE_OPTION_WITH_MARSHALLING` and 
`GENERATE_OPTION_WITH_MARSHALLING` variadic.

Sice we will be splitting up all CompilerInvocation parts, this will allow us 
to avoid a lot of boilerplate code.

The local macros prefix forwarded arguments with local variables required by 
the main macros. The `{THIS,NO}_PREFIX` macros make it possible for forwarding 
macros in member functions (`parseSimpleArgs`, `generateCC1CommandLine`) to 
prefix keypaths with `this->`. (Some build bots seem to require that.)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95532

Files:
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -385,36 +385,44 @@
   return KeyPath & Value;
 }
 
-#define PARSE_OPTION_WITH_MARSHALLING(ARGS, DIAGS, SUCCESS, ID, FLAGS, PARAM,  \
-  SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,\
-  IMPLIED_CHECK, IMPLIED_VALUE,\
-  NORMALIZER, MERGER, TABLE_INDEX) \
+#define THIS_PREFIX(KEYPATH) this->KEYPATH
+#define NO_PREFIX(KEYPATH) KEYPATH
+
+#define PARSE_OPTION_WITH_MARSHALLING( \
+ARGS, DIAGS, SUCCESS, PREFIX_KEYPATH, PREFIX_TYPE, NAME, ID, KIND, GROUP,  \
+ALIAS, ALIASARGS, FLAGS, PARAM, HELPTEXT, METAVAR, VALUES, SPELLING,   \
+SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK,  \
+IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX)   \
   if ((FLAGS)&options::CC1Option) {\
-KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE);  \
+PREFIX_KEYPATH(KEYPATH) = MERGER(PREFIX_KEYPATH(KEYPATH), DEFAULT_VALUE);  \
 if (IMPLIED_CHECK) \
-  KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE);\
+  PREFIX_KEYPATH(KEYPATH) =\
+  MERGER(PREFIX_KEYPATH(KEYPATH), IMPLIED_VALUE);  \
 if (SHOULD_PARSE)  \
   if (auto MaybeValue =\
   NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS, SUCCESS)) \
-KEYPATH =  \
-MERGER(KEYPATH, static_cast(*MaybeValue));  \
+PREFIX_KEYPATH(KEYPATH) = MERGER(  \
+KEYPATH,   \
+static_cast(*MaybeValue));  \
   }
 
 // Capture the extracted value as a lambda argument to avoid potential issues
 // with lifetime extension of the reference.
 #define GENERATE_OPTION_WITH_MARSHALLING(  \
-ARGS, STRING_ALLOCATOR, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH,   \
-DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR,  \
+ARGS, STRING_ALLOCATOR, PREFIX_KEYPATH, PREFIX_TYPE, NAME, ID, KIND,   \
+GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, HELPTEXT, METAVAR, VALUES,  \
+SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,   \
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \
 TABLE_INDEX)   \
   if ((FLAGS)&options::CC1Option) {\
 [&](const auto &Extracted) {   \
   if (ALWAYS_EMIT ||   \
   (Extracted !=\
-   static_cast((IMPLIED_CHECK) ? (IMPLIED_VALUE)\
-  : (DEFAULT_VALUE \
+   static_cast( \
+   (IMPLIED_CHECK) ? (IMPLIED_VALUE) : (DEFAULT_VALUE  \
 DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class,\
  TABLE_INDEX, Extracted);  \
-}(EXTRACTOR(KEYPATH)); \
+}(EXTRACTOR(PREFIX_KEYPATH(KEYPATH))); \
   }
 
 static const StringRef GetInputKindName(InputKind IK);
@@ -986,15 +994,8 @@
   // variable name and type.
   const LangOptions *Lang

[PATCH] D95534: clang-cl: Invent a /winsysroot concept

2021-01-27 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.
thakis added a reviewer: hans.
Herald added subscribers: dang, pengfei.
Herald added a reviewer: jansvoboda11.
thakis requested review of this revision.

On non-Windows platforms, --sysroot can be used to make the compiler use
a single, hermetic directory for all header and library files.

This is useful, but difficult to do on Windows. After D95472 
 it's
possible to achieve this with two flags:

  out/gn/bin/clang-cl win.c -fuse-ld=lld \
  /vctoolsdir path/to/VC/Tools/MSVC/14.26.28801 \
  /winsdkdir path/to/win_sdk

But that's still cumbersome: It requires two flags instead of one, and
it requires writing down the (changing) VC/Tools/MSVC version.

Require a new /winsysroot  flag that's effectively an alias to these two
flags. `/winsysroot ` is effetively an alias for these two flags.

It adds `/vctoolsdir /VC/Tools/MSVC/`, where
 is the subdirectory of VC/Tools/MSVC with the highest
number. (This also adds a flag /vctoolsversion to explicitly set that
version for full determinism, similar to /winsdkversion>).
Given that %VCToolsInstallDir% is something like
"C:\Program Files (x86)\Microsoft Visual 
Studio\2019\Professional\VC\Tools\MSVC\14.25.28610\"
looking at VC/Tools/... below /winsysroot seems like an obvious choice.

%WindowsSDKDir% and %UniversalCRTDir% both expand to
"C:\Program Files (x86)\Windows Kits\10\", so it's less obvious
an what subdirectory /winsdkdir should be below the sysroot.
"Windows Kits/10" has the drawback that it contains a space and
yet another number. Ideally the contents of that directory
would be available under some short name, so I went with
`/winsdkdir /win_sdk`. I'm not married to this though.
Maybe `/WinSdk` looks move like `VC/Tools/MSVC`?

---

This is missing the actual code change for now. I figured I'd send out the CL 
description early so we can get a head start on discussing the path names.


https://reviews.llvm.org/D95534

Files:
  clang/include/clang/Driver/Options.td


Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -5762,10 +5762,15 @@
 def _SLASH_TP : CLCompileFlag<"TP">, HelpText<"Treat all source files as C++">;
 def _SLASH_vctoolsdir : CLJoinedOrSeparate<"vctoolsdir">,
   HelpText<"Path to the VCToolChain">, MetaVarName<"">;
+def _SLASH_vctoolsversion : CLJoinedOrSeparate<"vctoolsversion">,
+  HelpText<"For use with /winsysroot, defaults to newest found">;
 def _SLASH_winsdkdir : CLJoinedOrSeparate<"winsdkdir">,
   HelpText<"Path to the Windows SDK">, MetaVarName<"">;
 def _SLASH_winsdkversion : CLJoinedOrSeparate<"winsdkversion">,
-  HelpText<"Full version of the Windows SDK">;
+  HelpText<"Full version of the Windows SDK, defaults to newest found">;
+def _SLASH_winsysroot : CLJoinedOrSeparate<"winsysroot">,
+  HelpText<"Same as /vctoolsdir/VC/Tools/MSVC/ 
/winsdkdir/win_sdk">,
+  MetaVarName<"">;
 def _SLASH_volatile_iso : Option<["/", "-"], "volatile:iso", KIND_FLAG>,
   Group<_SLASH_volatile_Group>, Flags<[CLOption, NoXarchOption]>,
   HelpText<"Volatile loads and stores have standard semantics">;


Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -5762,10 +5762,15 @@
 def _SLASH_TP : CLCompileFlag<"TP">, HelpText<"Treat all source files as C++">;
 def _SLASH_vctoolsdir : CLJoinedOrSeparate<"vctoolsdir">,
   HelpText<"Path to the VCToolChain">, MetaVarName<"">;
+def _SLASH_vctoolsversion : CLJoinedOrSeparate<"vctoolsversion">,
+  HelpText<"For use with /winsysroot, defaults to newest found">;
 def _SLASH_winsdkdir : CLJoinedOrSeparate<"winsdkdir">,
   HelpText<"Path to the Windows SDK">, MetaVarName<"">;
 def _SLASH_winsdkversion : CLJoinedOrSeparate<"winsdkversion">,
-  HelpText<"Full version of the Windows SDK">;
+  HelpText<"Full version of the Windows SDK, defaults to newest found">;
+def _SLASH_winsysroot : CLJoinedOrSeparate<"winsysroot">,
+  HelpText<"Same as /vctoolsdir/VC/Tools/MSVC/ /winsdkdir/win_sdk">,
+  MetaVarName<"">;
 def _SLASH_volatile_iso : Option<["/", "-"], "volatile:iso", KIND_FLAG>,
   Group<_SLASH_volatile_Group>, Flags<[CLOption, NoXarchOption]>,
   HelpText<"Volatile loads and stores have standard semantics">;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D93101: [Clang][Codegen] Truncate initializers of union bitfield members

2021-01-27 Thread Lucas Prates via Phabricator via cfe-commits
pratlucas accepted this revision.
pratlucas added a comment.
This revision is now accepted and ready to land.

The truncate conditions look a lot better and the test coverage seems 
reasonable now.
LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93101

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


[PATCH] D95514: [clang][cli] Teach CompilerInvocation to allocate strings on its own

2021-01-27 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

In D95514#2525255 , @dexonsmith wrote:

> Can you include the use in the patch?
> I also wonder what command-line option is forcing this.

The use-case that requires it is here: 
https://github.com/llvm/llvm-project/blob/f3449ed6073cac58efd9b62d0eb285affa650238/clang/lib/Frontend/CompilerInvocation.cpp#L734.
Clang accepts analyzer arguments in form of `-analyzer-config key=value`. 
Reference to the `key` sub-string is stored as an index in a `StringMap` 
(`AnalyzerOptions::Config`) and values are held by `std::string`. More entries 
get stored into the map in `parseAnalyzerConfigs`.

> String arguments could reuse the original char*.

Interesting idea. We could avoid allocation (and the need for owning strings) 
by grabbing the map key substring, scanning past its end until we hit `\0` and 
putting the whole thing into generated arguments. Keys in the `StringMap` that 
are not followed by `=value` most likely only come from `parseAnalyzerConfigs`, 
but we don't need to generate those.
This could work, but I'm worried it's somewhat brittle.

> It seems better to drop frivolous `=` than carrying this around.

Cool, this could save us allocations in some cases. Not sure dropping `=` 
between key-value pairs would result in good user experience though.

> I’m not sure having the AllocateString API totally makes sense, vs moving in 
> a string pool that was independently used during generation, but maybe in 
> context?

What exactly do you mean here?

> Consider that some callers may parse the full command-line and then drop 
> everything but one options class. That pattern wouldn’t work anymore since 
> the StringRefs won’t be valid.

Ah, that's right. So if we don't go with the allocation-less approach, we'd 
need to take `StringAllocator` from the client that also ensures proper 
lifetimes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95514

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


[PATCH] D95514: [clang][cli] Teach CompilerInvocation to allocate strings on its own

2021-01-27 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: clang/include/clang/Frontend/CompilerInvocation.h:144
+  /// Container holding strings allocated during round-trip.
+  mutable std::forward_list AllocatedStrings;
+

dexonsmith wrote:
> I suggest using llvm::StringPool instead, which also uniques the strings and 
> is used elsewhere for this kind of thing. Probably in an Optional to make it 
> more clear it’s not always used.
> 
> Maybe the name RoundTrippedStrings? 
From the documentation of `StringPool`, it seems like we would need to store 
`PooledStringPtr`s in order to keep them alive. How would that work with the 
`const char *` API we have?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95514

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


[PATCH] D95442: [OpenCL] Add diagnostics for references to functions

2021-01-27 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/test/SemaOpenCLCXX/members.cl:17
-
-template  struct remove_reference { typedef T type; };
-template  struct remove_reference { typedef T type; };

mantognini wrote:
> I wonder, do we lose coverage by removing these templates?
> 
> In other words, is the same code for error detection used for templates and 
> non-template?
I just think that this pattern has become untestable which means it is also not 
customer visible i.e. I used these to create a function pointer type in a 
template via template argument that was a reference to function. But now that 
we don't have neither pointers nor references to functions I don't think it is 
possible to write a template that would have any of those two after the 
substitution? I think the error will occur before - either when we specify the 
template argument or create a variable of those invalid types to be deduced in 
the templates.



Comment at: clang/test/SemaOpenCLCXX/references.cl:25
+#endif // FPTREXT
+typedef void (&ref2fct_t)();
+#ifndef FPTREXT

mantognini wrote:
> This re-uses the same name as above. Could that be an issue?
Not in this case because the type alias has not been created i.e. the parser 
just restarts over as if the first line with this type alias has not existed.


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

https://reviews.llvm.org/D95442

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


[PATCH] D77811: [clangd] WIP playing with semantic highlighting modifiers

2021-01-27 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 319591.
sammccall added a comment.
Herald added subscribers: llvm-commits, hiraditya.
Herald added a project: LLVM.

Rebase, polish, add tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77811

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SemanticHighlighting.h
  clang-tools-extra/clangd/refactor/tweaks/AnnotateHighlightings.cpp
  clang-tools-extra/clangd/test/initialize-params.test
  clang-tools-extra/clangd/test/semantic-tokens.test
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
  clang-tools-extra/clangd/unittests/tweaks/AnnotateHighlightingsTests.cpp
  llvm/lib/Testing/Support/Annotations.cpp

Index: llvm/lib/Testing/Support/Annotations.cpp
===
--- llvm/lib/Testing/Support/Annotations.cpp
+++ llvm/lib/Testing/Support/Annotations.cpp
@@ -53,7 +53,8 @@
   continue;
 }
 if (Text.consume_front("$")) {
-  Name = Text.take_while(llvm::isAlnum);
+  Name =
+  Text.take_while([](char C) { return llvm::isAlnum(C) || C == '_'; });
   Text = Text.drop_front(Name->size());
   continue;
 }
Index: clang-tools-extra/clangd/unittests/tweaks/AnnotateHighlightingsTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/AnnotateHighlightingsTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/AnnotateHighlightingsTests.cpp
@@ -18,15 +18,17 @@
 TEST_F(AnnotateHighlightingsTest, Test) {
   EXPECT_AVAILABLE("^vo^id^ ^f(^) {^}^"); // available everywhere.
   EXPECT_AVAILABLE("[[int a; int b;]]");
-  EXPECT_EQ("void /* entity.name.function.cpp */f() {}", apply("void ^f() {}"));
+  EXPECT_EQ("void /* Function [decl] */f() {}", apply("void ^f() {}"));
 
-  EXPECT_EQ(apply("[[void f1(); void f2();]]"),
-"void /* entity.name.function.cpp */f1(); "
-"void /* entity.name.function.cpp */f2();");
+  EXPECT_EQ(
+  apply("[[int f1(); const int x = f1();]]"),
+  "int /* Function [decl] */f1(); "
+  "const int /* Variable [decl] [readonly] */x = /* Function */f1();");
 
+  // Only the targeted range is annotated.
   EXPECT_EQ(apply("void f1(); void f2() {^}"),
 "void f1(); "
-"void /* entity.name.function.cpp */f2() {}");
+"void /* Function [decl] */f2() {}");
 }
 
 } // namespace
Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -18,6 +18,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/ScopedPrinter.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
 #include 
 
@@ -86,7 +87,8 @@
 return L.R.start < R.R.start;
   }));
 
-  std::string Result;
+  std::string Buf;
+  llvm::raw_string_ostream OS(Buf);
   unsigned NextChar = 0;
   for (auto &T : Tokens) {
 unsigned StartOffset = llvm::cantFail(positionToOffset(Input, T.R.start));
@@ -94,14 +96,18 @@
 assert(StartOffset <= EndOffset);
 assert(NextChar <= StartOffset);
 
-Result += Input.substr(NextChar, StartOffset - NextChar);
-Result += std::string(
-llvm::formatv("${0}[[{1}]]", T.Kind,
-  Input.substr(StartOffset, EndOffset - StartOffset)));
+OS << Input.substr(NextChar, StartOffset - NextChar);
+OS << '$' << T.Kind;
+for (unsigned I = 0;
+ I < static_cast(HighlightingModifier::LastModifier); ++I) {
+  if (T.Modifiers & (1 << I))
+OS << '_' << static_cast(I);
+}
+OS << "[[" << Input.substr(StartOffset, EndOffset - StartOffset) << "]]";
 NextChar = EndOffset;
   }
-  Result += Input.substr(NextChar);
-  return Result;
+  OS << Input.substr(NextChar);
+  return std::move(OS.str());
 }
 
 void checkHighlightings(llvm::StringRef Code,
@@ -160,337 +166,340 @@
 TEST(SemanticHighlighting, GetsCorrectTokens) {
   const char *TestCases[] = {
   R"cpp(
-  struct $Class[[AS]] {
-double $Field[[SomeMember]];
+  struct $Class_decl[[AS]] {
+double $Field_decl[[SomeMember]];
   };
   struct {
-  } $Variable[[S]];
-  void $Function[[foo]](int $Parameter[[A]], $Class[[AS]] $Parameter[[As]]) {
-$Primitive[[auto]] $LocalVariable[[VeryLongVariableName]] = 12312;
-$Class[[AS]] $LocalVariable[[AA]];
-$Primitive[[auto]] $LocalVariable[[L]] = $LocalVariable[[AA]].$Field[[SomeMember]] + $Parameter[[A]];
-auto $LocalVariable[[FN]] = [ $LocalVariable[[AA]]](int $Parameter[[A]]) -> void {};
+  } $Variable_decl[[S]];
+  void $Function_decl[[foo]](int $Parameter_decl

[PATCH] D95536: [clang][sema] Note decl location on missing member

2021-01-27 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, rsmith, rjmccall, rtrieu.
Herald added subscribers: lxfind, jdoerfert.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Hi,

when trying to access a member of a namespace/class/struct/enum, clang 
currently just prints that the given namespace does not have a member with the 
given name, for example:

  ./enum.cpp:12:7: error: no member named 'b' in 'Foo'
foo.b = 10;
~~~ ^
  1 error generated.

However, for programmers it is usually also important to know where the 
namespace has been declared, e.g. in the example above it would be useful to 
know where `foo`'s type has been declared. The following patch adds support for 
this by simply printing a note:

  ./enum.cpp:12:7: error: no member named 'b' in 'Foo'
foo.b = 10;
~~~ ^
  ./enum.cpp:3:7: note: 'Foo' declared here
  class Foo {
^~~
  1 error generated.

That is of course a very simple example, but I think this adds value in 
real-world scenarios.

The patch is unfortunately all over the place and mostly updating test cases 
with the additional expected note.

In addition to the usual review I'd like opinions on the following open 
questions:

- There are now three places where the patch adds the exact same code, would a 
helper function (in `Sema`?) be better and if so, where is the best place for 
it?
- The notes are pretty clunky to read when the namespace is created by a 
lambda: " note: '(lambda at enum.cpp:41:12)' declared here" - should lambdas 
simply be ignored (how to do that?) or should I handle them differently?
- The patch only emits the note if clang does not output a typo correction. I 
thought it might not be as useful in this case since it would clutter the 
output and chances are that the typo fix _is_ the right thing to show. Opinions 
on this?

Thanks,
Timm


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95536

Files:
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprMember.cpp
  clang/test/CXX/basic/basic.lookup/basic.lookup.classref/p1-cxx11.cpp
  clang/test/CXX/basic/basic.lookup/basic.lookup.classref/p1.cpp
  clang/test/CXX/class.access/class.friend/p1.cpp
  clang/test/CXX/class/class.mfct/class.mfct.non-static/p3.cpp
  clang/test/CXX/drs/dr1xx.cpp
  clang/test/CXX/drs/dr21xx.cpp
  clang/test/CXX/drs/dr3xx.cpp
  clang/test/CXX/drs/dr6xx.cpp
  clang/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp
  clang/test/CXX/module/module.interface/p2.cpp
  clang/test/CXX/special/class.copy/p28-cxx11.cpp
  clang/test/CXX/special/class.dtor/p10-0x.cpp
  clang/test/CXX/temp/temp.decls/temp.class/temp.mem.enum/p1.cpp
  clang/test/CXX/temp/temp.res/temp.local/p3.cpp
  clang/test/CXX/temp/temp.res/temp.local/p9.cpp
  clang/test/CXX/temp/temp.spec/temp.expl.spec/p19.cpp
  clang/test/Misc/diag-template.cpp
  clang/test/Modules/Inputs/redecl_namespaces_left.h
  clang/test/Modules/cxx-templates.cpp
  clang/test/Modules/module-private.cpp
  clang/test/Modules/redecl-namespaces.mm
  clang/test/OpenMP/target_map_messages.cpp
  clang/test/OpenMP/target_teams_map_messages.cpp
  clang/test/PCH/decl-attrs.cpp
  clang/test/Parser/recovery.c
  clang/test/Parser/recovery.cpp
  clang/test/Sema/MicrosoftExtensions.c
  clang/test/Sema/anonymous-struct-union.c
  clang/test/Sema/typo-correction-ambiguity.cpp
  clang/test/Sema/typo-correction-no-hang.cpp
  clang/test/Sema/typo-correction-recursive.cpp
  clang/test/SemaCXX/MicrosoftExtensions.cpp
  clang/test/SemaCXX/anonymous-union.cpp
  clang/test/SemaCXX/attr-cleanup.cpp
  clang/test/SemaCXX/co_await-range-for.cpp
  clang/test/SemaCXX/constructor-initializer.cpp
  clang/test/SemaCXX/conversion-function.cpp
  clang/test/SemaCXX/coroutines.cpp
  clang/test/SemaCXX/cxx1y-deduced-return-type.cpp
  clang/test/SemaCXX/cxx1y-generic-lambdas.cpp
  clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
  clang/test/SemaCXX/friend.cpp
  clang/test/SemaCXX/invalid-member-expr.cpp
  clang/test/SemaCXX/member-operator-expr.cpp
  clang/test/SemaCXX/missing-members.cpp
  clang/test/SemaCXX/nested-name-spec.cpp
  clang/test/SemaCXX/pseudo-destructors.cpp
  clang/test/SemaCXX/qualified-id-lookup.cpp
  clang/test/SemaCXX/typo-correction-delayed.cpp
  clang/test/SemaCXX/typo-correction.cpp
  clang/test/SemaCXX/unknown-type-name.cpp
  clang/test/SemaObjCXX/deduction.mm
  clang/test/SemaObjCXX/interface-return-type.mm
  clang/test/SemaTemplate/attributes.cpp
  clang/test/SemaTemplate/cxx1z-using-declaration.cpp
  clang/test/SemaTemplate/dependent-base-classes.cpp
  clang/test/SemaTemplate/instantiate-method.cpp
  clang/test/SemaTemplate/instantiate-non-dependent-types.cpp
  clang/test/SemaTemplate/member-access-ambig.cpp
  clang/test/SemaTemplate/member-access-expr.cpp
  clang/test/SemaTemplate/ms-lookup-template-base-classes.cpp

Index: clang/test/SemaTemplate/ms-lookup-template-base-classes.cpp
===

[PATCH] D77811: [clangd] Implement semanticTokens modifiers

2021-01-27 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 319592.
sammccall retitled this revision from "[clangd] WIP playing with semantic 
highlighting modifiers" to "[clangd] Implement semanticTokens modifiers".
sammccall edited the summary of this revision.
sammccall added a comment.

Update phab with commit message


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77811

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SemanticHighlighting.h
  clang-tools-extra/clangd/refactor/tweaks/AnnotateHighlightings.cpp
  clang-tools-extra/clangd/test/initialize-params.test
  clang-tools-extra/clangd/test/semantic-tokens.test
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
  clang-tools-extra/clangd/unittests/tweaks/AnnotateHighlightingsTests.cpp
  llvm/lib/Testing/Support/Annotations.cpp

Index: llvm/lib/Testing/Support/Annotations.cpp
===
--- llvm/lib/Testing/Support/Annotations.cpp
+++ llvm/lib/Testing/Support/Annotations.cpp
@@ -53,7 +53,8 @@
   continue;
 }
 if (Text.consume_front("$")) {
-  Name = Text.take_while(llvm::isAlnum);
+  Name =
+  Text.take_while([](char C) { return llvm::isAlnum(C) || C == '_'; });
   Text = Text.drop_front(Name->size());
   continue;
 }
Index: clang-tools-extra/clangd/unittests/tweaks/AnnotateHighlightingsTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/AnnotateHighlightingsTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/AnnotateHighlightingsTests.cpp
@@ -18,15 +18,17 @@
 TEST_F(AnnotateHighlightingsTest, Test) {
   EXPECT_AVAILABLE("^vo^id^ ^f(^) {^}^"); // available everywhere.
   EXPECT_AVAILABLE("[[int a; int b;]]");
-  EXPECT_EQ("void /* entity.name.function.cpp */f() {}", apply("void ^f() {}"));
+  EXPECT_EQ("void /* Function [decl] */f() {}", apply("void ^f() {}"));
 
-  EXPECT_EQ(apply("[[void f1(); void f2();]]"),
-"void /* entity.name.function.cpp */f1(); "
-"void /* entity.name.function.cpp */f2();");
+  EXPECT_EQ(
+  apply("[[int f1(); const int x = f1();]]"),
+  "int /* Function [decl] */f1(); "
+  "const int /* Variable [decl] [readonly] */x = /* Function */f1();");
 
+  // Only the targeted range is annotated.
   EXPECT_EQ(apply("void f1(); void f2() {^}"),
 "void f1(); "
-"void /* entity.name.function.cpp */f2() {}");
+"void /* Function [decl] */f2() {}");
 }
 
 } // namespace
Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -18,6 +18,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/ScopedPrinter.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
 #include 
 
@@ -86,7 +87,8 @@
 return L.R.start < R.R.start;
   }));
 
-  std::string Result;
+  std::string Buf;
+  llvm::raw_string_ostream OS(Buf);
   unsigned NextChar = 0;
   for (auto &T : Tokens) {
 unsigned StartOffset = llvm::cantFail(positionToOffset(Input, T.R.start));
@@ -94,14 +96,18 @@
 assert(StartOffset <= EndOffset);
 assert(NextChar <= StartOffset);
 
-Result += Input.substr(NextChar, StartOffset - NextChar);
-Result += std::string(
-llvm::formatv("${0}[[{1}]]", T.Kind,
-  Input.substr(StartOffset, EndOffset - StartOffset)));
+OS << Input.substr(NextChar, StartOffset - NextChar);
+OS << '$' << T.Kind;
+for (unsigned I = 0;
+ I < static_cast(HighlightingModifier::LastModifier); ++I) {
+  if (T.Modifiers & (1 << I))
+OS << '_' << static_cast(I);
+}
+OS << "[[" << Input.substr(StartOffset, EndOffset - StartOffset) << "]]";
 NextChar = EndOffset;
   }
-  Result += Input.substr(NextChar);
-  return Result;
+  OS << Input.substr(NextChar);
+  return std::move(OS.str());
 }
 
 void checkHighlightings(llvm::StringRef Code,
@@ -160,337 +166,340 @@
 TEST(SemanticHighlighting, GetsCorrectTokens) {
   const char *TestCases[] = {
   R"cpp(
-  struct $Class[[AS]] {
-double $Field[[SomeMember]];
+  struct $Class_decl[[AS]] {
+double $Field_decl[[SomeMember]];
   };
   struct {
-  } $Variable[[S]];
-  void $Function[[foo]](int $Parameter[[A]], $Class[[AS]] $Parameter[[As]]) {
-$Primitive[[auto]] $LocalVariable[[VeryLongVariableName]] = 12312;
-$Class[[AS]] $LocalVariable[[AA]];
-$Primitive[[auto]] $LocalVariable[[L]] = $LocalVariable[[AA]].$Field[[SomeMember]] + $Parameter[[A]];
-auto $LocalVariable[[FN]] = [ $LocalVariable[[AA

[PATCH] D95442: [OpenCL] Add diagnostics for references to functions

2021-01-27 Thread Marco Antognini via Phabricator via cfe-commits
mantognini accepted this revision.
mantognini added a comment.
This revision is now accepted and ready to land.

Right, thanks for the explanations. They make sense.


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

https://reviews.llvm.org/D95442

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


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-01-27 Thread Zakk Chen via Phabricator via cfe-commits
khchen updated this revision to Diff 319488.
khchen marked 21 inline comments as done.
khchen added a comment.

1. address @jrtc27's comments. I really appreciate your help very much.
2. use downstream test generator and move all tests to rvv-intrinsics-generic 
and rvv-intrinsics.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95016

Files:
  clang/include/clang/Basic/BuiltinsRISCV.def
  clang/include/clang/Basic/CMakeLists.txt
  clang/include/clang/Basic/riscv_vector.td
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/CMakeLists.txt
  clang/test/CodeGen/RISCV/rvv-intrinsics-generic/vadd.c
  clang/test/CodeGen/RISCV/rvv-intrinsics-generic/vfadd.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vadd.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vfadd.c
  clang/test/CodeGen/RISCV/vadd.c
  clang/test/Headers/riscv-vector-header.c
  clang/utils/TableGen/CMakeLists.txt
  clang/utils/TableGen/RISCVVEmitter.cpp
  clang/utils/TableGen/TableGen.cpp
  clang/utils/TableGen/TableGenBackends.h
  llvm/docs/CommandGuide/tblgen.rst

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


[PATCH] D95119: Prefer /usr/bin/env xxx over /usr/bin/xxx where xxx = perl, python, awk

2021-01-27 Thread Harmen Stoppels via Phabricator via cfe-commits
haampie added a comment.

@JDevlieghere, would you care to review? This is another instance of moving 
away from system binaries to whatever the user / package manager wants the 
build to use.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95119

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


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-01-27 Thread Zakk Chen via Phabricator via cfe-commits
khchen added inline comments.



Comment at: clang/test/CodeGen/RISCV/riscv-rvv-intrinsics-generic/vadd.c:10
+
+// ASM-NOT: warning
+#include 

jrtc27 wrote:
> Asm checks are discouraged in Clang. If you want to check for Clang warnings, 
> use -verify, and in this case you want `// expected-no-diagnostics`.
RVV is the scalable vector type similar to SVE, so I added this check.
please see https://reviews.llvm.org/D82943.



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:48-55
+  bool Float, Bool, Signed;
+  // Constant indices are "int", but have the constant expression.
+  bool Immediate;
+  bool Void;
+  // const qualifier.
+  bool Constant;
+  bool Pointer;

jrtc27 wrote:
> These are poor names; many of them don't sound like bools, and are some of 
> them not mutually exclusive? If so, an enum would be better.
Those variables are used to descript the property of RVVType, I think maybe 
rename as IsXXX could become more clear.
ps. I implement RVVType similar to SveType [[ 
https://github.com/llvm/llvm-project/blob/main/clang/utils/TableGen/SveEmitter.cpp#L68-L70
 | did ]].
Do you mean only mutually exclusive property should be represented in an enum?



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:308
+return false;
+  if (Float && ElementBitwidth == 8)
+return false;

jrtc27 wrote:
> or 1? Clearer to move this into the switch below IMO.
This checks illegal type float8_t .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95016

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


[PATCH] D95534: clang-cl: Invent a /winsysroot concept

2021-01-27 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Maybe we should just go with `Windows Kits/10" -- the space is only seen at the 
driver->cc1 boundary and it works fine there, and the 10 can be inferred from 
/winsdkversion.

On the other hand, thinking about how to create such a sysroot directory, 
saying "just copy %vctoolsinstalldir% to somedir/vctools and %windowssdkdir% to 
somedir/win_sdk" would be nice too.  On the other hand, it'd break relative 
paths from vc\tools\msvc\XXX to (say) vc\tools\llvm. I don't know if anything 
needs such relative paths.


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

https://reviews.llvm.org/D95534

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


[PATCH] D77811: [clangd] Implement semanticTokens modifiers

2021-01-27 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 319594.
sammccall added a comment.

Tidy up, explain static


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77811

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SemanticHighlighting.h
  clang-tools-extra/clangd/refactor/tweaks/AnnotateHighlightings.cpp
  clang-tools-extra/clangd/test/initialize-params.test
  clang-tools-extra/clangd/test/semantic-tokens.test
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
  clang-tools-extra/clangd/unittests/tweaks/AnnotateHighlightingsTests.cpp
  llvm/lib/Testing/Support/Annotations.cpp

Index: llvm/lib/Testing/Support/Annotations.cpp
===
--- llvm/lib/Testing/Support/Annotations.cpp
+++ llvm/lib/Testing/Support/Annotations.cpp
@@ -53,7 +53,8 @@
   continue;
 }
 if (Text.consume_front("$")) {
-  Name = Text.take_while(llvm::isAlnum);
+  Name =
+  Text.take_while([](char C) { return llvm::isAlnum(C) || C == '_'; });
   Text = Text.drop_front(Name->size());
   continue;
 }
Index: clang-tools-extra/clangd/unittests/tweaks/AnnotateHighlightingsTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/AnnotateHighlightingsTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/AnnotateHighlightingsTests.cpp
@@ -18,15 +18,17 @@
 TEST_F(AnnotateHighlightingsTest, Test) {
   EXPECT_AVAILABLE("^vo^id^ ^f(^) {^}^"); // available everywhere.
   EXPECT_AVAILABLE("[[int a; int b;]]");
-  EXPECT_EQ("void /* entity.name.function.cpp */f() {}", apply("void ^f() {}"));
+  EXPECT_EQ("void /* Function [decl] */f() {}", apply("void ^f() {}"));
 
-  EXPECT_EQ(apply("[[void f1(); void f2();]]"),
-"void /* entity.name.function.cpp */f1(); "
-"void /* entity.name.function.cpp */f2();");
+  EXPECT_EQ(
+  apply("[[int f1(); const int x = f1();]]"),
+  "int /* Function [decl] */f1(); "
+  "const int /* Variable [decl] [readonly] */x = /* Function */f1();");
 
+  // Only the targeted range is annotated.
   EXPECT_EQ(apply("void f1(); void f2() {^}"),
 "void f1(); "
-"void /* entity.name.function.cpp */f2() {}");
+"void /* Function [decl] */f2() {}");
 }
 
 } // namespace
Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -18,6 +18,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/ScopedPrinter.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
 #include 
 
@@ -86,7 +87,8 @@
 return L.R.start < R.R.start;
   }));
 
-  std::string Result;
+  std::string Buf;
+  llvm::raw_string_ostream OS(Buf);
   unsigned NextChar = 0;
   for (auto &T : Tokens) {
 unsigned StartOffset = llvm::cantFail(positionToOffset(Input, T.R.start));
@@ -94,14 +96,18 @@
 assert(StartOffset <= EndOffset);
 assert(NextChar <= StartOffset);
 
-Result += Input.substr(NextChar, StartOffset - NextChar);
-Result += std::string(
-llvm::formatv("${0}[[{1}]]", T.Kind,
-  Input.substr(StartOffset, EndOffset - StartOffset)));
+OS << Input.substr(NextChar, StartOffset - NextChar);
+OS << '$' << T.Kind;
+for (unsigned I = 0;
+ I < static_cast(HighlightingModifier::LastModifier); ++I) {
+  if (T.Modifiers & (1 << I))
+OS << '_' << static_cast(I);
+}
+OS << "[[" << Input.substr(StartOffset, EndOffset - StartOffset) << "]]";
 NextChar = EndOffset;
   }
-  Result += Input.substr(NextChar);
-  return Result;
+  OS << Input.substr(NextChar);
+  return std::move(OS.str());
 }
 
 void checkHighlightings(llvm::StringRef Code,
@@ -160,337 +166,340 @@
 TEST(SemanticHighlighting, GetsCorrectTokens) {
   const char *TestCases[] = {
   R"cpp(
-  struct $Class[[AS]] {
-double $Field[[SomeMember]];
+  struct $Class_decl[[AS]] {
+double $Field_decl[[SomeMember]];
   };
   struct {
-  } $Variable[[S]];
-  void $Function[[foo]](int $Parameter[[A]], $Class[[AS]] $Parameter[[As]]) {
-$Primitive[[auto]] $LocalVariable[[VeryLongVariableName]] = 12312;
-$Class[[AS]] $LocalVariable[[AA]];
-$Primitive[[auto]] $LocalVariable[[L]] = $LocalVariable[[AA]].$Field[[SomeMember]] + $Parameter[[A]];
-auto $LocalVariable[[FN]] = [ $LocalVariable[[AA]]](int $Parameter[[A]]) -> void {};
+  } $Variable_decl[[S]];
+  void $Function_decl[[foo]](int $Parameter_decl[[A]], $Class[[AS]] $Parameter_decl[[As]]) {
+$Primitive_deduced[[auto]] $Lo

[PATCH] D95538: [clang][Format] Evaluate FallbackStyle only if needed

2021-01-27 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added reviewers: MyDeveloperDay, curdeius.
kadircet requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Currently getStyle() fails immediately if FallbackStyle is not a
predefined style, even when it is not needed. This patch moves that evaluation
and bail-out to fallback-case, enabling getStyle() to succeed in cases where
FallbackStyle is malformed but not needed.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95538

Files:
  clang/lib/Format/Format.cpp


Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2901,10 +2901,6 @@
   }
   FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
 
-  FormatStyle FallbackStyle = getNoStyle();
-  if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
-return make_string_error("Invalid fallback style \"" + FallbackStyleName);
-
   if (StyleName.startswith("{")) {
 // Parse YAML/JSON style from the command line.
 if (std::error_code ec = parseConfiguration(
@@ -2974,6 +2970,10 @@
 return make_string_error("Configuration file(s) do(es) not support " +
  getLanguageName(Style.Language) + ": " +
  UnsuitableConfigFiles);
+
+  FormatStyle FallbackStyle = getNoStyle();
+  if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
+return make_string_error("Invalid fallback style \"" + FallbackStyleName);
   return FallbackStyle;
 }
 


Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2901,10 +2901,6 @@
   }
   FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
 
-  FormatStyle FallbackStyle = getNoStyle();
-  if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
-return make_string_error("Invalid fallback style \"" + FallbackStyleName);
-
   if (StyleName.startswith("{")) {
 // Parse YAML/JSON style from the command line.
 if (std::error_code ec = parseConfiguration(
@@ -2974,6 +2970,10 @@
 return make_string_error("Configuration file(s) do(es) not support " +
  getLanguageName(Style.Language) + ": " +
  UnsuitableConfigFiles);
+
+  FormatStyle FallbackStyle = getNoStyle();
+  if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
+return make_string_error("Invalid fallback style \"" + FallbackStyleName);
   return FallbackStyle;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95031: [clangd] Log warning when using legacy (theia) semantic highlighting.

2021-01-27 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D95031#2509896 , @nridge wrote:

> Thanks for the heads up! It would be nice to get D77702 
>  landed before the removal of 
> `TheiaSemanticHighlighting`. I'll try to find some time to rebase it.

Good point!
I've revived D77811 , as I'd prefer not to 
start adding modifiers before can make them independent of kinds. (Moving 
features to different infrastructure tends to involve some 
backward-compatibility/testing toil...)

From there I think it should be easy to get the rest of this merged:

- scope modifiers make a lot of sense and should be straightforward to add
- dependent type vs name: maybe we should consider making dependent a modifier 
instead? but otherwise LG
- the "member" issue I think has been resolved for the most part, by clarifying 
the spec


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95031

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


[PATCH] D95526: [Syntax] Add syntax-tree-dump in clang-check.

2021-01-27 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/tools/clang-check/ClangCheck.cpp:141
 
+class BuildSyntaxTree : public clang::ASTFrontendAction {
+public:

DumpSyntaxTree since this is used for its side-effect?



Comment at: clang/tools/clang-check/ClangCheck.cpp:152
+clang::syntax::Arena A(AST.getSourceManager(), AST.getLangOpts(), TB);
+llvm::outs() << clang::syntax::buildSyntaxTree(A, AST)->dump(
+AST.getSourceManager());

ooh, we should consider colorizing this one day :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95526

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


[PATCH] D94952: [clangd] Take into account what is in the index (symbols, references, etc.) at indexes merge

2021-01-27 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX updated this revision to Diff 319602.
ArcsinX added a comment.

- Set `IdxContents` at `FileSymbols` object breation instead of at 
`FileSymbols::buildIndex()` call.
- Revert change of the preamble index key scheme
- Add comment for `IndexContents`
- `IndexDataKind` => `IndexContents`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94952

Files:
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/FileIndex.cpp
  clang-tools-extra/clangd/index/FileIndex.h
  clang-tools-extra/clangd/index/Index.cpp
  clang-tools-extra/clangd/index/Index.h
  clang-tools-extra/clangd/index/MemIndex.cpp
  clang-tools-extra/clangd/index/MemIndex.h
  clang-tools-extra/clangd/index/Merge.cpp
  clang-tools-extra/clangd/index/Merge.h
  clang-tools-extra/clangd/index/ProjectAware.cpp
  clang-tools-extra/clangd/index/dex/Dex.cpp
  clang-tools-extra/clangd/index/dex/Dex.h
  clang-tools-extra/clangd/index/remote/Client.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/DexTests.cpp
  clang-tools-extra/clangd/unittests/IndexTests.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1244,9 +1244,9 @@
llvm::function_ref
Callback) const override {}
 
-llvm::unique_function
+llvm::unique_function
 indexedFiles() const override {
-  return [](llvm::StringRef) { return false; };
+  return [](llvm::StringRef) { return IndexContents::None; };
 }
 
 size_t estimateMemoryUsage() const override { return 0; }
@@ -1298,9 +1298,9 @@
llvm::function_ref)
 const override {}
 
-llvm::unique_function
+llvm::unique_function
 indexedFiles() const override {
-  return [](llvm::StringRef) { return false; };
+  return [](llvm::StringRef) { return IndexContents::None; };
 }
 
 size_t estimateMemoryUsage() const override { return 0; }
Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -231,11 +231,11 @@
   auto Data = std::make_pair(std::move(Symbols), std::move(Refs));
   llvm::StringSet<> Files = {testPath("foo.cc"), testPath("bar.cc")};
   MemIndex I(std::move(Data.first), std::move(Data.second), RelationSlab(),
- std::move(Files), std::move(Data), Size);
+ std::move(Files), IndexContents::All, std::move(Data), Size);
   auto ContainsFile = I.indexedFiles();
-  EXPECT_TRUE(ContainsFile("unittest:///foo.cc"));
-  EXPECT_TRUE(ContainsFile("unittest:///bar.cc"));
-  EXPECT_FALSE(ContainsFile("unittest:///foobar.cc"));
+  EXPECT_EQ(ContainsFile("unittest:///foo.cc"), IndexContents::All);
+  EXPECT_EQ(ContainsFile("unittest:///bar.cc"), IndexContents::All);
+  EXPECT_EQ(ContainsFile("unittest:///foobar.cc"), IndexContents::None);
 }
 
 TEST(MemIndexTest, TemplateSpecialization) {
@@ -508,23 +508,24 @@
   auto DynData = std::make_pair(std::move(DynSymbols), std::move(DynRefs));
   llvm::StringSet<> DynFiles = {testPath("foo.cc")};
   MemIndex DynIndex(std::move(DynData.first), std::move(DynData.second),
-RelationSlab(), std::move(DynFiles), std::move(DynData),
-DynSize);
+RelationSlab(), std::move(DynFiles), IndexContents::Symbols,
+std::move(DynData), DynSize);
   SymbolSlab StaticSymbols;
   RefSlab StaticRefs;
   auto StaticData =
   std::make_pair(std::move(StaticSymbols), std::move(StaticRefs));
-  llvm::StringSet<> StaticFiles = {testPath("bar.cc")};
-  MemIndex StaticIndex(std::move(StaticData.first),
-   std::move(StaticData.second), RelationSlab(),
-   std::move(StaticFiles), std::move(StaticData),
-   StaticSymbols.bytes() + StaticRefs.bytes());
+  llvm::StringSet<> StaticFiles = {testPath("foo.cc"), testPath("bar.cc")};
+  MemIndex StaticIndex(
+  std::move(StaticData.first), std::move(StaticData.second), RelationSlab(),
+  std::move(StaticFiles), IndexContents::References, std::move(StaticData),
+  StaticSymbols.bytes() + StaticRefs.bytes());
   MergedIndex Merge(&DynIndex, &StaticIndex);
 
   auto ContainsFile = Merge.indexedFiles();
-  EXPECT_TRUE(ContainsFile("unittest:///foo.cc"));
-  EXPECT_TRUE(ContainsFile("unittest:///bar.cc"));
-  EXPECT_FALSE(ContainsFile("unittest:///foobar.cc"));
+  EXPECT_EQ(ContainsFile("unittest:///foo.cc"),
+IndexContents::Symbols | IndexContents::References);
+  EXPECT_EQ(ContainsFile("unittest:///bar.cc"), IndexConte

[PATCH] D94952: [clangd] Take into account what is in the index (symbols, references, etc.) at indexes merge

2021-01-27 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX marked 4 inline comments as done.
ArcsinX added inline comments.



Comment at: clang-tools-extra/clangd/index/FileIndex.cpp:433
 PreambleSymbols.update(
-Uri, std::make_unique(std::move(*IF->Symbols)),
+FilePath ? *FilePath : (consumeError(FilePath.takeError()), Uri),
+std::make_unique(std::move(*IF->Symbols)),

sammccall wrote:
> ArcsinX wrote:
> > ArcsinX wrote:
> > > sammccall wrote:
> > > > ArcsinX wrote:
> > > > > sammccall wrote:
> > > > > > Is this change related? It changes the key scheme for the preamble 
> > > > > > index from URIs to paths, but I'm not sure why.
> > > > > > 
> > > > > > Do we have multiple URIs pointing to the same path? What are they 
> > > > > > concretely?
> > > > > This is the main thing in this patch. I will try to explain.
> > > > > We use these keys to create the file list, which is used by 
> > > > > `indexedFiles()`.
> > > > > Currently, the preamble index contains URI's instead of paths (as a 
> > > > > file list), that leads to the function returned by 
> > > > > `PreambleIndex::indexedFiles()` always return `false` (because we 
> > > > > pass to this function paths, not URI's). So, we always take data from 
> > > > > the preamble index (but maybe we should not in some cases).
> > > > > 
> > > > Oooh... I'm not sure how I misunderstood the original so much :-( And I 
> > > > missed it in this patch description as well, apologies.
> > > > 
> > > > My impression was that the file list was derived from the index data, 
> > > > rather than from the keys, which were always intended to be 
> > > > opaque/arbitrary.
> > > > (At various times, these have been filenames, URIs, and other things 
> > > > IIRC. And until relatively recently, the preamble index keys were the 
> > > > file the preamble was built from, not the file containing the symbol!)
> > > > 
> > > > It feels like using URIs extracted from symbols might not be 
> > > > *completely* robust. Because having CanonicalDeclaration etc set to a 
> > > > file might not line up exactly with the idea that we indexed the file. 
> > > > But we do use this partitioning for FileShardedIndex, so it has to work 
> > > > well enough.
> > > > 
> > > > The advantage of using the extracted URIs would be: also works for 
> > > > non-file-sharded indexes like --index-file, avoid a bunch of conversion 
> > > > between URI and path, and we get to keep the simpler/flexible design 
> > > > for FileSymbols where the key is opaque.
> > > > 
> > > > Does this seem feasible to you?
> > > > that leads to the function returned by `PreambleIndex::indexedFiles()` 
> > > > always return `false` (because we pass to this function paths, not 
> > > > URI's)
> > > 
> > > This is a bit incorrect.
> > > We pass to this function URI, but this URI is converted to path. i.e. 
> > > `MemIndex::indexedFiles()`, `Dex::indexedFiles()` expect that `Files` are 
> > > paths, but they are URI's for the preamble index. That's why 
> > > `PreambleIndex::indexedFiles()` always return `false`.
> > I also do not like these path <=> URI conversions. But what about empty 
> > files?, e.g.:
> > - open a file
> > - remove everything from this file
> > - the dynamic index has no symbols with definition/declaration from this 
> > file, so we do not have this file in the dynamic index file list.
> > - the static index has symbols with definition/declaration from this file, 
> > so we have this file in the static index file list.
> > - we will show stale results from the static index for this file.
> > 
> > 
> > Unsure, maybe it's ok to ignore the problem with empty files, seems this is 
> > the only case when the file was indexed, but we have no symbols located 
> > there.
> > 
> > Overall, I like the idea to use URI's instead of paths. I think we could 
> > implement it first as a separate patch and after that return to this one.
> > 
> > What do you think?
> Right, completely empty files are going to be mishandled., in the same way 
> that before your changes we mishandled files that had no results from the 
> query.
> 
> I do still think this is the way to go though, because:
>  - completely empty files are much rarer
>  - again this is a peer to an FileShardedIndex issue where empty files get no 
> shards. Therefore *within* the dynamic index, we'll never clear out the 
> symbols for a file while the file is emptied
>  - having SymbolCollector explicitly the files indexed is the principled 
> solution to both problems, and that seems feasible for us to do at some point.
> 
> > Overall, I like the idea to use URI's instead of paths. I think we could 
> > implement it first as a separate patch and after that return to this one.
> 
> That sounds great if you don't mind!
> (Is there a reason we can't land the rest of this patch as-is already?)
> (Is there a reason we can't land the rest of this patch as-is already?)
Seems we have no reason =)



Comment at: clang-tools-extra/clangd/index/In

[PATCH] D95307: [StaticAnalyzer] Add checking for degenerate base class in MemRegion

2021-01-27 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 319607.
RedDocMD added a comment.

Removing duplication of CXXBaseSpecifiers when they are created for 
PointerToMember
Removed hackish weakening of assert


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95307

Files:
  clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp
  clang/test/Analysis/pointer-to-member.cpp

Index: clang/test/Analysis/pointer-to-member.cpp
===
--- clang/test/Analysis/pointer-to-member.cpp
+++ clang/test/Analysis/pointer-to-member.cpp
@@ -231,6 +231,23 @@
 }
 } // end of testPointerToMemberDiamond namespace
 
+namespace testPointerToMemberViaStaticCast {
+// From bug #48739
+struct Base {
+  int field;
+};
+
+struct Derived : public Base {};
+
+void static_cast_test() {
+  int Derived::*derived_field = &Derived::field;
+  Base base;
+  base.field = 5;
+  int Base::*base_field = static_cast(derived_field);
+  clang_analyzer_eval(base.*base_field == 5); // expected-warning {{TRUE}}
+}
+} // namespace testPointerToMemberViaStaticCast
+
 namespace testAnonymousMember {
 struct A {
   int a;
Index: clang/lib/StaticAnalyzer/Core/MemRegion.cpp
===
--- clang/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ clang/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -63,7 +63,7 @@
 //===--===//
 
 template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
   RegionTy::ProfileRegion(ID, arg1, superRegion);
@@ -80,7 +80,7 @@
 }
 
 template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
   RegionTy::ProfileRegion(ID, arg1, arg2, superRegion);
@@ -96,9 +96,9 @@
   return R;
 }
 
-template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
+template 
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
  const Arg3Ty arg3,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
@@ -129,8 +129,8 @@
 // Basic methods.
 //===--===//
 
-bool SubRegion::isSubRegionOf(const MemRegion* R) const {
-  const MemRegion* r = this;
+bool SubRegion::isSubRegionOf(const MemRegion *R) const {
+  const MemRegion *r = this;
   do {
 if (r == R)
   return true;
@@ -143,7 +143,7 @@
 }
 
 MemRegionManager &SubRegion::getMemRegionManager() const {
-  const SubRegion* r = this;
+  const SubRegion *r = this;
   do {
 const MemRegion *superRegion = r->getSuperRegion();
 if (const auto *sr = dyn_cast(superRegion)) {
@@ -164,9 +164,7 @@
 
 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
 
-QualType ObjCIvarRegion::getValueType() const {
-  return getDecl()->getType();
-}
+QualType ObjCIvarRegion::getValueType() const { return getDecl()->getType(); }
 
 QualType CXXBaseObjectRegion::getValueType() const {
   return QualType(getDecl()->getTypeForDecl(), 0);
@@ -237,26 +235,25 @@
   ID.AddPointer(superRegion);
 }
 
-void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
- const Expr *Ex, unsigned cnt,
- const MemRegion *superRegion) {
+void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, const Expr *Ex,
+ unsigned cnt, const MemRegion *superRegion) {
   ID.AddInteger(static_cast(AllocaRegionKind));
   ID.AddPointer(Ex);
   ID.AddInteger(cnt);
   ID.AddPointer(superRegion);
 }
 
-void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
+void AllocaRegion::Profile(llvm::FoldingSetNodeID &ID) const {
   ProfileRegion(ID, Ex, Cnt, superRegion);
 }
 
-void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
+void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID &ID) const {
   CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
 }
 
-void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
+void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
   const CompoundLiteralExpr *CL,
-  const MemRegion* superRegion) {
+  const MemRegion *superRegion) {
   ID.AddInteger(static_cast(CompoundLiteralRegionKind));
   ID.AddPointer(CL);
   ID.AddPointer(superRegion);
@@ -278,9 +275,9 @@
   Pro

[PATCH] D94500: Rework Whitesmiths mode to use line-level values in UnwrappedLineParser

2021-01-27 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius requested changes to this revision.
curdeius added inline comments.
This revision now requires changes to proceed.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:613
+  // settings. This allows the format to back up one level in those cases.
+  if (!AddLevel && NamespaceBlock &&
+  Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)

HazardyKnusperkeks wrote:
> Maybe give `!AddLevel && Style.BreakBeforeBraces == 
> FormatStyle::BS_Whitesmiths` a name? You check it three times.
Agree on this.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2159
+
+// If we're in whitesmiths mode, indent the brace.
+if (!AddLevel && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)

Nit: please write consistently Whitesmiths with a capital W.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2163
+
+parseBlock(/*MustBeDeclaration=*/true, AddLevel, true, true);
 // Munch the semicolon after a namespace. This is more common than one 
would

3*true? Please add comments a minima.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2259
+  // If in Whitesmiths mode, the line with the while() needs to be indented
+  // to the same level as the block
+  if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)

Nit: full stop at the end of the phrase.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2967
+  // needs to be indented.
+  bool ClosesBlock =
+  Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&

Please move below to the place of use. Also, just naming it `ClosesBlock` is a 
bit misleading as it is only for Whitesmiths style.



Comment at: clang/unittests/Format/FormatTest.cpp:13688
 
-  WhitesmithsBraceStyle.IndentCaseBlocks = true;
+  WhitesmithsBraceStyle.IndentCaseLabels = true;
   verifyFormat("void switchTest1(int a)\n"

Hmm, you don't test the same thing anymore...



Comment at: clang/unittests/Format/FormatTest.cpp:13696
"  }\n"
-   "break;\n"
+   "  break;\n"
"}\n"

MyDeveloperDay wrote:
> whilst I don't really like changing the indentation I don't think there was 
> anything that says it was correct before.
That is really strange that `case` is indented differently than `break`. Is it 
intended? Is the style really like this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94500

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


[PATCH] D94827: [SimplifyCFG] If provided, preserve Dominator Tree

2021-01-27 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 319624.
lebedev.ri retitled this revision from "[SimplifyCFG] Require and preserve 
dominator tree" to "[SimplifyCFG] If provided, preserve Dominator Tree".
lebedev.ri edited the summary of this revision.
lebedev.ri added a comment.

Let me resell this. This patch is fully NFC,
it just signifies that SimplifyCFG is now DomTree-aware,
and preserves it **if** it is provided.

Here, i'm only looking for a congratulatory LGTM.
I'm sure some edgecases will pop up


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94827

Files:
  llvm/lib/Transforms/Utils/SimplifyCFG.cpp


Index: llvm/lib/Transforms/Utils/SimplifyCFG.cpp
===
--- llvm/lib/Transforms/Utils/SimplifyCFG.cpp
+++ llvm/lib/Transforms/Utils/SimplifyCFG.cpp
@@ -6561,20 +6561,10 @@
 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
   bool Changed = simplifyOnceImpl(BB);
 
-  assert((!RequireAndPreserveDomTree ||
-  (DTU &&
-   DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full))) 
&&
- "Failed to maintain validity of domtree!");
-
   return Changed;
 }
 
 bool SimplifyCFGOpt::run(BasicBlock *BB) {
-  assert((!RequireAndPreserveDomTree ||
-  (DTU &&
-   DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full))) 
&&
- "Original domtree is invalid?");
-
   bool Changed = false;
 
   // Repeated simplify BB as long as resimplification is requested.
@@ -6592,7 +6582,7 @@
 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
DomTreeUpdater *DTU, const SimplifyCFGOptions &Options,
ArrayRef LoopHeaders) {
-  return SimplifyCFGOpt(TTI, RequireAndPreserveDomTree ? DTU : nullptr,
-BB->getModule()->getDataLayout(), LoopHeaders, Options)
+  return SimplifyCFGOpt(TTI, DTU, BB->getModule()->getDataLayout(), 
LoopHeaders,
+Options)
   .run(BB);
 }


Index: llvm/lib/Transforms/Utils/SimplifyCFG.cpp
===
--- llvm/lib/Transforms/Utils/SimplifyCFG.cpp
+++ llvm/lib/Transforms/Utils/SimplifyCFG.cpp
@@ -6561,20 +6561,10 @@
 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
   bool Changed = simplifyOnceImpl(BB);
 
-  assert((!RequireAndPreserveDomTree ||
-  (DTU &&
-   DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full))) &&
- "Failed to maintain validity of domtree!");
-
   return Changed;
 }
 
 bool SimplifyCFGOpt::run(BasicBlock *BB) {
-  assert((!RequireAndPreserveDomTree ||
-  (DTU &&
-   DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full))) &&
- "Original domtree is invalid?");
-
   bool Changed = false;
 
   // Repeated simplify BB as long as resimplification is requested.
@@ -6592,7 +6582,7 @@
 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
DomTreeUpdater *DTU, const SimplifyCFGOptions &Options,
ArrayRef LoopHeaders) {
-  return SimplifyCFGOpt(TTI, RequireAndPreserveDomTree ? DTU : nullptr,
-BB->getModule()->getDataLayout(), LoopHeaders, Options)
+  return SimplifyCFGOpt(TTI, DTU, BB->getModule()->getDataLayout(), LoopHeaders,
+Options)
   .run(BB);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D93688: [ASTMatchers] Ensure that we can match inside lambdas

2021-01-27 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

This patch causes practically infinite traversal times on code that contains 
deeply nested lambdas. I'll try to get a suitable repro, but could you maybe 
revert this in the meantime?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93688

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


[PATCH] D69560: [clang-tidy] Add 'bugprone-easily-swappable-parameters' check

2021-01-27 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-easily-swappable-parameters-len2.cpp:10
+
+void declaration(int Param, int Other); // NO-WARN: No chance to change this 
function.
+

aaron.ballman wrote:
> I think this is a case where we could warn when the declaration is outside of 
> a system header (perhaps as an option).
> 
> Thinking about it a bit more, declarations and definitions provide a novel 
> way to get another kind of swap:
> ```
> void func(int x, int y);
> void func(int y, int x) {} // Oops, the swap was probably not intentional
> ```
> which may or may not be interesting for a check (or its heuristics).
I gave this some thought. It is a very good idea, but I believe not for 
//this// check, but D20689. What do you think of that? Maybe simply saying 
"call site v. function node that was called" could be extended with a 
completely analogous, string distance function based "function definition node 
v. redecl chain" case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69560

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


[PATCH] D91913: Suppress non-conforming GNU paste extension in all standard-conforming modes

2021-01-27 Thread Harald van Dijk via Phabricator via cfe-commits
hvdijk added a comment.

@rnk Taking it upon yourself to revert this without approval and without 
communication on all branches, especially given the earlier suggestion by 
@rsmith to only revert this on the LLVM 12 branch, is an abuse of your commit 
privileges as far as I am concerned.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91913

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


[PATCH] D94827: [SimplifyCFG] If provided, preserve Dominator Tree

2021-01-27 Thread Nikita Popov via Phabricator via cfe-commits
nikic accepted this revision.
nikic added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94827

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


[PATCH] D95119: Prefer /usr/bin/env xxx over /usr/bin/xxx where xxx = perl, python, awk

2021-01-27 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

`#!/usr/bin/env perl -w` (2 arguments) unfortunately does not work on Linux and 
many other systems.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95119

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


[PATCH] D95119: Prefer /usr/bin/env xxx over /usr/bin/xxx where xxx = perl, python, awk

2021-01-27 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

Several `llvm/utils/` scripts can probably just be removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95119

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


[PATCH] D95534: clang-cl: Invent a /winsysroot concept

2021-01-27 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

> "Windows Kits/10" has the drawback that it contains a space and yet another 
> number. Ideally the contents of that directory would be available under some 
> short name, so I went with /winsdkdir /win_sdk. I'm not married to this 
> though. Maybe /WinSdk looks move like VC/Tools/MSVC?

FWIW, for my own cross-MSVC setups, I use /vc/tools/msvc and /kits/10 
- kinda preserving the "Windows Kits" directory, but in a friendlier form - but 
this proposal is clearly workable too.


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

https://reviews.llvm.org/D95534

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


[PATCH] D95514: [clang][cli] Teach CompilerInvocation to allocate strings on its own

2021-01-27 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.

In D95514#2525517 , @jansvoboda11 
wrote:

> In D95514#2525255 , @dexonsmith 
> wrote:
>
>> Can you include the use in the patch?
>> I also wonder what command-line option is forcing this.
>
> The use-case that requires it is here: 
> https://github.com/llvm/llvm-project/blob/f3449ed6073cac58efd9b62d0eb285affa650238/clang/lib/Frontend/CompilerInvocation.cpp#L734.
> Clang accepts analyzer arguments in form of `-analyzer-config key=value`. 
> Reference to the `key` sub-string is stored as an index in a `StringMap` 
> (`AnalyzerOptions::Config`) and values are held by `std::string`. More 
> entries get stored into the map in `parseAnalyzerConfigs`.
>
>> String arguments could reuse the original char*.
>
> Interesting idea. We could avoid allocation (and the need for owning strings) 
> by grabbing the map key substring, scanning past its end until we hit `\0` 
> and putting the whole thing into generated arguments. Keys in the `StringMap` 
> that are not followed by `=value` most likely only come from 
> `parseAnalyzerConfigs`, but we don't need to generate those.
> This could work, but I'm worried it's somewhat brittle.

I think (?) running the tests with ASan on would catch any bugs, and there are 
bots that do that. Might be worth double-checking though.

You'd also want to `assert(!Arg.end()[0] && "reused command-line arg not 
null-terminated?")`...

>> It seems better to drop frivolous `=` than carrying this around.
>
> Cool, this could save us allocations in some cases. Not sure dropping `=` 
> between key-value pairs would result in good user experience though.

Well, the compiler developers are the users, since `-cc1` isn't for end-users. 
I acknowledge it's a tradeoff. IMO, without actually seeing it in practice, it 
seems a bit nicer to design this away entirely. But maybe having a `=` is more 
valuable than I think.

Here's another option. Assume we have a broken-up version of 
`UniqueStringSaver` that let's us pre-load the existing strings and move away 
the new ones for later storage, something like:

  BumpPtrAllocator Storage;
  DenseSet ExistingStrings;
  StringSaver NewStrings(Storage);
  
  auto saveString = [&](const Twine &T) {
SmallVector Storage;
StringRef S = T.toStringRef(Storage);
auto I = ExistingStrings.find(S);
if (I != ExistingStrings.end())
  return *I;
S = NewStrings.save(S);
ExistingStrings.insert(S);
return S;
  };
  
  Strings.ExistingStrings.reserve(CommandLineArgs.size());
  for (StringRef Arg : CommandLineArgs)
Strings.ExistingStrings.insert(Arg);

For string options:

- If `-cc1` accepts only `-opt string`, no need for allocation.
- If `-cc1` accepts only `-opt=string`, the fully-spelled option is on the 
original command-line. `ExistingStrings.find()` should turn it up when calling 
`Strings.save()`.
- If `-cc1` accepts both `-opt=string` and `-opt string` canonicalize to `-opt 
string` when generating. No need for allocation.

For numeric / enum options we'll need to allocate, but the allocation doesn't 
have to live past running the parser.

The only problem would be if `string` gets canonicalized / rewritten somehow 
during parse + generate, or if an enum value is additionally saved as a string 
value.

>> I’m not sure having the AllocateString API totally makes sense, vs moving in 
>> a string pool that was independently used during generation, but maybe in 
>> context?
>
> What exactly do you mean here?

The intent in this patch seemed to be to call 
`CompilerInvocation::AllocateString` when generating arguments. My intuition 
would be to continue using the StringMap we have now (or `StringSaver`, or 
whatever), and then `std::move()` that into a `CompilerInvocation` that's 
parsed from it. In which case there's no need for 
`CompilerInvocation::AllocateString`.

In fact, it might be even better if it was type-erased, just a payload that had 
to be kept alive...

  class CompilerInvocation {
class RoundTrippedCommandLineStorage {
  std::shared_ptr Storage;
public:
  void store(BumpPtrAllocator &&Strings) {
assert(!Storage);
Storage = std::make_shared(std::move(Strings));
  }
} RoundTrip;
  };



>> Consider that some callers may parse the full command-line and then drop 
>> everything but one options class. That pattern wouldn’t work anymore since 
>> the StringRefs won’t be valid.
>
> Ah, that's right. So if we don't go with the allocation-less approach, we'd 
> need to take `StringAllocator` from the client that also ensures proper 
> lifetimes.

Maybe it wouldn't be terrible to have a `RoundTrip` arg on each options class. 
When you assign to the CompilerInvocation, it copies the shared ptr into each 
of the options classes, so that the pool stays alive as long as one of them has 
it.




Comment at: clang/include/clang/Frontend/CompilerInvocation.h:144
+  /// Cont

[PATCH] D94827: [SimplifyCFG] If provided, preserve Dominator Tree

2021-01-27 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

@kuhar @mkazantsev wanna get in on the hype train?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94827

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


[PATCH] D94827: [SimplifyCFG] If provided, preserve Dominator Tree

2021-01-27 Thread Jakub Kuderski via Phabricator via cfe-commits
kuhar accepted this revision.
kuhar added a comment.

Choo choo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94827

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


[PATCH] D95487: Itanium Mangling: Fix handling of in .

2021-01-27 Thread James Y Knight via Phabricator via cfe-commits
jyknight added inline comments.



Comment at: clang/lib/AST/ItaniumMangle.cpp:3912
+IsPrimaryExpr = false;
+  };
+

jyknight wrote:
> rjmccall wrote:
> > I think it might be more reasonable to just check for the relatively small 
> > number of primary-expression cases in `mangleTemplateArgExpr` and skip the 
> > `X...E` there rather than pushing it down into this function.
> I started out writing it that way, but it's more complex than it first seems.
> 
> First you have the 9 expression types that always fit into  -- 
> those are simple enough, but that's already a lot more than one might think. 
> But, then you also need to handle recusing on all the cases with no output 
> (ParenExprClass etc. -- 10 cases of this). And, finally, you have complex 
> cases like DeclRefExpr, CXXConstructExprClass, and 
> UnaryExprOrTypeTraitExprClass, which sometimes emit a primary expression and 
> sometimes do not.
> 
> Putting all of that together, the number of cases to handle with a separate 
> function was large enough -- and duplicative enough -- that it seemed more 
> confusing to have such an implementation split than it was helpful.
Ultimately, we'd end up with a second large switch in a second function -- but 
it must be carefully kept in sync with any changes to the switch in 
mangleExpression. I think that'd just end up more likely to cause problems in 
the future, when new expression types are added.

Additionally, the NotPrimaryExpr idiom is already in use in 
mangleValueInTemplateArg, and doing the same thing for both cases is helpful 
for understandability, IMO.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95487

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


[PATCH] D91913: Suppress non-conforming GNU paste extension in all standard-conforming modes

2021-01-27 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In D91913#2525993 , @hvdijk wrote:

> @rnk Taking it upon yourself to revert this without approval and without 
> communication on all branches, especially given the earlier suggestion by 
> @rsmith to only revert this on the LLVM 12 branch, is an abuse of your commit 
> privileges as far as I am concerned. This is not a Google project. Google 
> does not get to unilaterally dictate its direction. I do not intend to get 
> into a revert-the-revert war and will not revert your revert myself. I do 
> expect you to do so.

I think @rnk's observation that `__VA_OPT__` isn't actually available in any 
compilation mode other than C++20 (which I hadn't previously realized) is 
important here: we'd left longstanding users of this functionality with no path 
forward, and that is, I think, sufficient motivation for a revert. I'm working 
on a patch to make `__VA_OPT__` available across all language modes. Once 
that's landed, the next step should be adding the warning to trunk and the 
Clang 12 branch, and then we can decide how long we want the warning in trunk 
before we make the conformance change -- while we're not beholden to the needs 
of any particular Clang user, Clang doesn't exist in a vacuum, and giving our 
live-at-head users a little time to adapt to this change seems reasonable, 
especially given that there doesn't seem to be any particular urgency in this 
fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91913

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


[PATCH] D94500: Rework Whitesmiths mode to use line-level values in UnwrappedLineParser

2021-01-27 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:13696
"  }\n"
-   "break;\n"
+   "  break;\n"
"}\n"

curdeius wrote:
> MyDeveloperDay wrote:
> > whilst I don't really like changing the indentation I don't think there was 
> > anything that says it was correct before.
> That is really strange that `case` is indented differently than `break`. Is 
> it intended? Is the style really like this?
Forget it. I was thinking about something else.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94500

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


[PATCH] D94987: DR39: Perform ambiguous subobject checks for class member access as part of object argument conversion, not as part of name lookup.

2021-01-27 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/include/clang/AST/CXXInheritance.h:77
 
-  CXXBasePath() = default;
+  /// Additional data stashed on the base path by its consumers.
+  union {

rjmccall wrote:
> rsmith wrote:
> > rjmccall wrote:
> > > rsmith wrote:
> > > > rjmccall wrote:
> > > > > Is there a way to know which case we're in, or do different consumers 
> > > > > do different things?
> > > > We could use a discriminated union here. Ultimately, I think what we 
> > > > really want is to provide some opaque storage for the consumer to use, 
> > > > rather than to have some hard-coded list here. I haven't thought of a 
> > > > good way to expose that; I don't think it's worth templating the entire 
> > > > base path finding mechanism to add such storage, and a single pointer 
> > > > isn't large enough for a `DeclContext::lookup_result`.
> > > > 
> > > > Vassil's https://reviews.llvm.org/D91524 will make the `lookup_result` 
> > > > case fit into a single pointer; once we adopt that, perhaps we can 
> > > > switch to holding an opaque `void*` here?
> > > Yeah, that might be cleaner, assuming we really need this.  What are the 
> > > clients that need to store something specifically in the `CXXBasePath` 
> > > object and can't just keep it separate?
> > The main users of this are in name lookup proper (where we store the lookup 
> > results on the path to avoid redoing the class scope hash table lookup) and 
> > now in access checking (where we store the most-accessible declaration). I 
> > think there's a couple of other name-lookup-like clients that also store a 
> > lookup result here.
> > 
> > In all cases the side storage is just a convenience. But it's probably an 
> > important convenience; it's awkward for a client to maintain a mapping on 
> > the side, because the key for that map would end up being the entire base 
> > path. 
> > 
> > We could just number the paths as we find them, and let the consumers build 
> > a `SmallVector` on the side rather than storing data in the `CXXBasePath`s. 
> > We'd need to be careful about the post-processing pass in `lookupInBases` 
> > that removes virtual base paths that are shadowed by non-virtual 
> > inheritance from the vbase, but that seems feasible. Worthwhile?
> I see what you're saying.  We have places that compute all the base paths in 
> an array, and it's convenient to be able to stash things into the elements of 
> that array instead of having a second data structure that's parallel to it.  
> I guess there are three options:
> 
> - Tell clients to just make a parallel structure.
> 
> - Have this sort of intrusive storage and just accept that clients that want 
> to use it will have some awkward casting to do.
> 
> - Get rid of the initial array dependence by making it a callback API instead 
> of an array-building API, and then clients that want to build an array can 
> build an array with the type they actually want.
> 
> I guess the third might be awkward?
Yes, the problem with the third option is its interaction with the 
post-processing step in `CXXRecordDecl::lookupInBases`. We're not supposed to 
consider virtual bases if they're shadowed along any path. The way that 
`lookupInBases` handles this is by first finding all paths to subobjects, and 
then removing any path containing an edge to a virtual base for which some 
other path ends in a class deriving from that vbase. So we end up with the 
callback being called spuriously in some cases, and `lookupInBases` ends up 
producing only a subset of the paths that were followed.

I'm pretty sure we could rearchitect the lookup process so that this doesn't 
happen -- so that we never visit a virtual base until we've finished traversing 
all subobjects that virtually inherit from it -- but that's not what the 
`lookupInBases` algorithm is doing right now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94987

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


  1   2   3   >