[PATCH] D124611: [RISCV][Clang] add more tests for clang driver. (NFC)

2022-05-04 Thread Zakk Chen via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6c10014f1de6: [RISCV][Clang] add more tests for clang 
driver. (NFC) (authored by khchen).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124611

Files:
  clang/test/Driver/riscv-arch.c


Index: clang/test/Driver/riscv-arch.c
===
--- clang/test/Driver/riscv-arch.c
+++ clang/test/Driver/riscv-arch.c
@@ -412,6 +412,26 @@
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZFHMIN %s
 // RV32-ZFHMIN: "-target-feature" "+zfhmin"
 
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izbt -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-EXPERIMENTAL-NOFLAG 
%s
+// RV32-EXPERIMENTAL-NOFLAG: error: invalid arch name 'rv32izbt'
+// RV32-EXPERIMENTAL-NOFLAG: requires '-menable-experimental-extensions'
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izbt 
-menable-experimental-extensions -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-EXPERIMENTAL-NOVERS 
%s
+// RV32-EXPERIMENTAL-NOVERS: error: invalid arch name 'rv32izbt'
+// RV32-EXPERIMENTAL-NOVERS: experimental extension requires explicit version 
number
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izbt0p1 
-menable-experimental-extensions -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-EXPERIMENTAL-BADVERS 
%s
+// RV32-EXPERIMENTAL-BADVERS: error: invalid arch name 'rv32izbt0p1'
+// RV32-EXPERIMENTAL-BADVERS: unsupported version number 0.1 for experimental 
extension
+// RV32-EXPERIMENTAL-BADVERS: 'zbt'(this compiler supports 0.93)
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izbt0p93 
-menable-experimental-extensions -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck 
-check-prefix=RV32-EXPERIMENTAL-GOODVERS %s
+// RV32-EXPERIMENTAL-GOODVERS: "-target-feature" "+experimental-zbt"
+
 // RUN: %clang --target=riscv32-unknown-elf -march=rv32izbb1p0 -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZBB %s
 // RUN: %clang --target=riscv32-unknown-elf -march=rv32izbb -### %s \
@@ -494,3 +514,48 @@
 // RUN: %clang --target=riscv32-unknown-elf -march=rv32izk1p0 -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZK %s
 // RV32-ZK: "-target-feature" "+zk"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izfh1p0 -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=CHECK-RV32-ZFH %s
+// CHECK-RV32-ZFH: "-target-feature" "+zfh"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izfhmin1p0 -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=CHECK-RV32-ZFHMIN %s
+// CHECK-RV32-ZFHMIN: "-target-feature" "+zfhmin"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve32x0p1 -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE32X-BADVERS %s
+// RV32-ZVE32X-BADVERS: error: invalid arch name 'rv32izve32x0p1'
+// RV32-ZVE32X-BADVERS: unsupported version number 0.1 for extension 'zve32x'
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve32x -### %s -c 2>&1 
| \
+// RUN:   FileCheck -check-prefix=RV32-ZVE32X-GOODVERS %s
+// RV32-ZVE32X-GOODVERS: "-target-feature" "+zve32x"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve32f -### %s -c 2>&1 
| \
+// RUN:   FileCheck -check-prefix=RV32-ZVE32F-REQUIRE-F %s
+// RV32-ZVE32F-REQUIRE-F: error: invalid arch name 'rv32izve32f', zve32f 
requires f or zfinx extension to also be specified
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32ifzve32f -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE32F-GOOD %s
+// RV32-ZVE32F-GOOD: "-target-feature" "+zve32f"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve64x -### %s -c 2>&1 
| \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64X %s
+// RV32-ZVE64X: "-target-feature" "+zve64x"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve64f -### %s -c 2>&1 
| \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64F-REQUIRE-F %s
+// RV32-ZVE64F-REQUIRE-F: error: invalid arch name 'rv32izve64f', zve32f 
requires f or zfinx extension to also be specified
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32ifzve64f -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64F-GOOD %s
+// RV32-ZVE64F-GOOD: "-target-feature" "+zve64f"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32ifzve64d -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64D-REQUIRE-D %s
+// RV32-ZVE64D-REQUIRE-D: error: invalid arch name 'rv32ifzve64d', zve64d 
requires d or zdinx extension to also be specified
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32ifdzve64d -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64D-GOOD %s
+// RV32-ZVE64D-GOOD: "-target-feature" "+zve64d"


Index: clang/test/Driver/riscv-arch.c
===
--- 

[clang] 6c10014 - [RISCV][Clang] add more tests for clang driver. (NFC)

2022-05-04 Thread Zakk Chen via cfe-commits

Author: Zakk Chen
Date: 2022-05-04T23:55:52-07:00
New Revision: 6c10014f1de6bf5533a7fb51dc21790cd5f16d28

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

LOG: [RISCV][Clang] add more tests for clang driver. (NFC)

Test experimental arch, Zfh, Zfmin and Zve arch.

Reviewed By: craig.topper

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

Added: 


Modified: 
clang/test/Driver/riscv-arch.c

Removed: 




diff  --git a/clang/test/Driver/riscv-arch.c b/clang/test/Driver/riscv-arch.c
index 46cab6384ab97..824e85eeb55fc 100644
--- a/clang/test/Driver/riscv-arch.c
+++ b/clang/test/Driver/riscv-arch.c
@@ -412,6 +412,26 @@
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZFHMIN %s
 // RV32-ZFHMIN: "-target-feature" "+zfhmin"
 
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izbt -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-EXPERIMENTAL-NOFLAG 
%s
+// RV32-EXPERIMENTAL-NOFLAG: error: invalid arch name 'rv32izbt'
+// RV32-EXPERIMENTAL-NOFLAG: requires '-menable-experimental-extensions'
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izbt 
-menable-experimental-extensions -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-EXPERIMENTAL-NOVERS 
%s
+// RV32-EXPERIMENTAL-NOVERS: error: invalid arch name 'rv32izbt'
+// RV32-EXPERIMENTAL-NOVERS: experimental extension requires explicit version 
number
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izbt0p1 
-menable-experimental-extensions -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-EXPERIMENTAL-BADVERS 
%s
+// RV32-EXPERIMENTAL-BADVERS: error: invalid arch name 'rv32izbt0p1'
+// RV32-EXPERIMENTAL-BADVERS: unsupported version number 0.1 for experimental 
extension
+// RV32-EXPERIMENTAL-BADVERS: 'zbt'(this compiler supports 0.93)
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izbt0p93 
-menable-experimental-extensions -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck 
-check-prefix=RV32-EXPERIMENTAL-GOODVERS %s
+// RV32-EXPERIMENTAL-GOODVERS: "-target-feature" "+experimental-zbt"
+
 // RUN: %clang --target=riscv32-unknown-elf -march=rv32izbb1p0 -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZBB %s
 // RUN: %clang --target=riscv32-unknown-elf -march=rv32izbb -### %s \
@@ -494,3 +514,48 @@
 // RUN: %clang --target=riscv32-unknown-elf -march=rv32izk1p0 -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZK %s
 // RV32-ZK: "-target-feature" "+zk"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izfh1p0 -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=CHECK-RV32-ZFH %s
+// CHECK-RV32-ZFH: "-target-feature" "+zfh"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izfhmin1p0 -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=CHECK-RV32-ZFHMIN %s
+// CHECK-RV32-ZFHMIN: "-target-feature" "+zfhmin"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve32x0p1 -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE32X-BADVERS %s
+// RV32-ZVE32X-BADVERS: error: invalid arch name 'rv32izve32x0p1'
+// RV32-ZVE32X-BADVERS: unsupported version number 0.1 for extension 'zve32x'
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve32x -### %s -c 2>&1 
| \
+// RUN:   FileCheck -check-prefix=RV32-ZVE32X-GOODVERS %s
+// RV32-ZVE32X-GOODVERS: "-target-feature" "+zve32x"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve32f -### %s -c 2>&1 
| \
+// RUN:   FileCheck -check-prefix=RV32-ZVE32F-REQUIRE-F %s
+// RV32-ZVE32F-REQUIRE-F: error: invalid arch name 'rv32izve32f', zve32f 
requires f or zfinx extension to also be specified
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32ifzve32f -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE32F-GOOD %s
+// RV32-ZVE32F-GOOD: "-target-feature" "+zve32f"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve64x -### %s -c 2>&1 
| \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64X %s
+// RV32-ZVE64X: "-target-feature" "+zve64x"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve64f -### %s -c 2>&1 
| \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64F-REQUIRE-F %s
+// RV32-ZVE64F-REQUIRE-F: error: invalid arch name 'rv32izve64f', zve32f 
requires f or zfinx extension to also be specified
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32ifzve64f -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64F-GOOD %s
+// RV32-ZVE64F-GOOD: "-target-feature" "+zve64f"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32ifzve64d -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64D-REQUIRE-D %s
+// RV32-ZVE64D-REQUIRE-D: error: invalid arch name 'rv32ifzve64d', zve64d 
requires d or zdinx extension to also be specified
+
+// 

[PATCH] D124813: [HLSL] Add clang builtin for HLSL.

2022-05-04 Thread Sameer Sahasrabuddhe via Phabricator via cfe-commits
sameerds resigned from this revision.
sameerds added a comment.

I am not much familiar with DirectX and HLSL, so unable to review this patch. 
It might help to post on the Discourse under Clang Frontend:

https://discourse.llvm.org/c/clang/6


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124813

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


[PATCH] D124690: [clangd] add inlay hints for std::forward-ed parameter packs

2022-05-04 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj planned changes to this revision.
upsj added a comment.

I will take a different approach to the matchers: For each CallExpr involving 
parameter packs, record the arguments (if they are a ParmVarDecl or 
stdForward(ParmVarDecl)) and the matching ParmVarDecl of the FunctionDecl in a 
map. Then I will compact that map to skip intermediate forwarding functions 
like emplace_back -> allocator::construct -> constructor and in a second pass 
resolve all previously unresolved forwarded parameters.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

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


[PATCH] D124983: [HLSL} add -fcgl option flag.

2022-05-04 Thread Xiang Li via Phabricator via cfe-commits
python3kgae created this revision.
python3kgae added reviewers: amccarth, craig.topper, hans, rnk, 
stefan_reinalter, beanz, pow2clk.
Herald added subscribers: Anastasia, StephenFan.
Herald added a project: All.
python3kgae requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

fcgl option will make compilation stop after clang codeGen and output the llvm 
ir.
It is added to check clang codeGen output for HLSL.

It will be translated into -S -emit-llvm and -disable-llvm-passes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124983

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/HLSL.cpp
  clang/unittests/Driver/ToolChainTest.cpp

Index: clang/unittests/Driver/ToolChainTest.cpp
===
--- clang/unittests/Driver/ToolChainTest.cpp
+++ clang/unittests/Driver/ToolChainTest.cpp
@@ -610,4 +610,45 @@
   DiagConsumer->clear();
 }
 
+TEST(DxcModeTest, ValidatorFCGL) {
+  IntrusiveRefCntPtr DiagID(new DiagnosticIDs());
+
+  IntrusiveRefCntPtr InMemoryFileSystem(
+  new llvm::vfs::InMemoryFileSystem);
+
+  InMemoryFileSystem->addFile("foo.hlsl", 0,
+  llvm::MemoryBuffer::getMemBuffer("\n"));
+
+  auto *DiagConsumer = new SimpleDiagnosticConsumer;
+  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
+  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagConsumer);
+  Driver TheDriver("/bin/clang", "", Diags, "", InMemoryFileSystem);
+  std::unique_ptr C(TheDriver.BuildCompilation(
+  {"clang", "--driver-mode=dxc", "-fcgl", "foo.hlsl"}));
+  EXPECT_TRUE(C);
+  EXPECT_TRUE(!C->containsError());
+  auto &Jobs = C->getJobs();
+  EXPECT_EQ(Jobs.size(), 1);
+  if (Jobs.size() == 1) {
+auto &Job = *Jobs.begin();
+auto &Args = Job.getArguments();
+// Make sure fcgl translated into -S -emit-llvm and -disable-llvm-passes.
+bool HasS = false;
+bool HasEmitLLVM = false;
+bool HasDisableLLVMPasses = false;
+for (auto *Arg : Args) {
+  StringRef Str(Arg);
+  if (Str == "-S")
+HasS = true;
+  else if (Str == "-emit-llvm")
+HasEmitLLVM = true;
+  else if (Str == "-disable-llvm-passes")
+HasDisableLLVMPasses = true;
+}
+EXPECT_TRUE(HasS);
+EXPECT_TRUE(HasEmitLLVM);
+EXPECT_TRUE(HasDisableLLVMPasses);
+  }
+}
+
 } // end anonymous namespace.
Index: clang/lib/Driver/ToolChains/HLSL.cpp
===
--- clang/lib/Driver/ToolChains/HLSL.cpp
+++ clang/lib/Driver/ToolChains/HLSL.cpp
@@ -169,6 +169,15 @@
   if (!isLegalValidatorVersion(ValVerStr, getDriver()))
 continue;
 }
+if (A->getOption().getID() == options::OPT_fcgl) {
+  // Translate fcgl into -S -emit-llvm and -disable-llvm-passes.
+  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_S));
+  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_emit_llvm));
+  DAL->AddFlagArg(nullptr,
+  Opts.getOption(options::OPT_disable_llvm_passes));
+  A->claim();
+  continue;
+}
 DAL->append(A);
   }
   // Add default validator version if not set.
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -3470,7 +3470,9 @@
 
 static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
   types::ID InputType) {
-  const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version};
+  const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
+ options::OPT_S, options::OPT_emit_llvm,
+ options::OPT_disable_llvm_passes};
 
   for (const auto &Arg : ForwardedArguments)
 if (const auto *A = Args.getLastArg(Arg))
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -6736,6 +6736,8 @@
 
 def dxc_Group : OptionGroup<"">, Flags<[DXCOption]>,
   HelpText<"dxc compatibility options">;
+class DXCFlag : Option<["/", "-"], name, KIND_FLAG>,
+  Group, Flags<[DXCOption, NoXarchOption]>;
 class DXCJoinedOrSeparate : Option<["/", "-"], name,
   KIND_JOINED_OR_SEPARATE>, Group, Flags<[DXCOption, NoXarchOption]>;
 
@@ -6760,3 +6762,5 @@
  "lib_6_3, lib_6_4, lib_6_5, lib_6_6, lib_6_7, lib_6_x,"
  "ms_6_5, ms_6_6, ms_6_7,"
  "as_6_5, as_6_6, as_6_7">;
+def fcgl : DXCFlag<"fcgl">,
+  HelpText<"Generate high-level code only. Without any dxil related passes.">;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-

[PATCH] D124982: [clang][OpenMP][DebugInfo] Debug support for variables in containing scope of OMP constructs

2022-05-04 Thread Alok Kumar Sharma via Phabricator via cfe-commits
alok created this revision.
alok added reviewers: aprantl, djtodoro, jmorse, jini.susan.
alok added a project: debug-info.
Herald added subscribers: guansong, hiraditya, yaxunl.
Herald added a project: All.
alok requested review of this revision.
Herald added a reviewer: jdoerfert.
Herald added subscribers: llvm-commits, cfe-commits, sstefan1.
Herald added projects: clang, LLVM.

In case of OpenMP, compilers generate encapsulates code present in
OpenMP construct to artificial functions. This is done to apply parallelism
to block of code. In context of these blocks, currently containing scope
variables are not accessible. This is due to new artificial function DIE being
in global scope.
As from user point of view, containing scope is same lexical scope, there
must be correct DIE hierarchy for artificial functions, which should be child
of containing scope.
Please consider below testcase.

   1  #include 
   2  #include 
   3
   4  int global_var1;
   5  int global_var2 = 99;
   6  int foo(int n) {
   7int same_var = 5;
   8int other_var = 21;
   9int share = 9, priv, i;
  10global_var1 = 99;
  11
  12if (n < 2)
  13  return n;
  14else {
  15  int same_var = rand() % 5;
  16  int local_var = 31;
  17  #pragma omp parallel for
  18  for (i = 0; i < n; i++) {
  19share += i;  // <-- (A)
  20  }
  21  return share;
  22}
  23  }
  24
  25  int main() {
  26int n = 10;
  27printf("foo(%d) = %d\n", n, foo(n));
  28return 0;
  29  }

Please consider the line# 19, user expects variables "same_var", "local_var", 
"other_var" to be
accessible inside debugger but which is not possible.

  (gdb) p same_var
  No symbol "same_var" in current context.
  (gdb) p other_var
  No symbol "other_var" in current context.
  (gdb) p local_var
  No symbol "local_var" in current context.

After current patch.

  (gdb) thr 1
  [Switching to thread 1 (Thread 0x77c1c400 (LWP 17992))]
  #0  .omp_outlined._debug__ (.global_tid.=0x7fffdad0, 
.bound_tid.=0x7fffdac8, n=@0x7fffdf18: 10, share=@0x7fffdf0c: 9) at 
1.c:19
  19share += i;
  (gdb) p same_var
  $1 = 3
  (gdb) p local_var
  $2 = 31
  (gdb) p other_var
  $3 = 21


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124982

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.h
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/test/OpenMP/debug_containing_scope.c
  llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp
  llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
  llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h

Index: llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h
===
--- llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h
+++ llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h
@@ -237,6 +237,7 @@
   DIE *getOrCreateNameSpace(const DINamespace *NS);
   DIE *getOrCreateModule(const DIModule *M);
   DIE *getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal = false);
+  DIE *getOrCreateLexicalScopeDIE(const DILexicalBlock *LS);
 
   void applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
  bool SkipSPAttributes = false);
Index: llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
+++ llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
@@ -554,6 +554,8 @@
 return getOrCreateSubprogramDIE(SP);
   if (auto *M = dyn_cast(Context))
 return getOrCreateModule(M);
+  if (auto *LS = dyn_cast(Context))
+return getOrCreateLexicalScopeDIE(LS);
   return getDIE(Context);
 }
 
@@ -1181,6 +1183,17 @@
   return &SPDie;
 }
 
+DIE *DwarfUnit::getOrCreateLexicalScopeDIE(const DILexicalBlock *LS) {
+  DIE *ContextDIE = getOrCreateContextDIE(LS->getScope());
+
+  if (DIE *LSDie = getDIE(LS))
+return LSDie;
+
+  DIE &LSDie = createAndAddDIE(dwarf::DW_TAG_lexical_block, *ContextDIE, LS);
+
+  return &LSDie;
+}
+
 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
 DIE &SPDie, bool Minimal) {
   DIE *DeclDie = nullptr;
Index: llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp
+++ llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp
@@ -686,6 +686,7 @@
 return nullptr;
 
   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
+  insertDIE(Scope->getScopeNode(), ScopeDIE);
   if (Scope->isAbstractScope())
 return ScopeDIE;
 
Index: clang/test/OpenMP/debug_containing_scope.c
===
--- /dev/null
+++ clang/test/OpenMP

[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-04 Thread Wang Yihan via Phabricator via cfe-commits
yihanaa added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:433
+
+  llvm::StringRef getFormatSpecifier(QualType T) {
+if (auto *BT = T->getAs()) {

yihanaa wrote:
> erichkeane wrote:
> > rsmith wrote:
> > > yihanaa wrote:
> > > > rsmith wrote:
> > > > > rsmith wrote:
> > > > > > aaron.ballman wrote:
> > > > > > > yihanaa wrote:
> > > > > > > > I think this is better maintained in 
> > > > > > > > "clang/AST/FormatString.h". For example 
> > > > > > > > analyze_printf::PrintfSpecifier can get format specifier, what 
> > > > > > > > do you all think about?
> > > > > > > +1 to this suggestion -- my hope is that we could generalize it 
> > > > > > > more then as I notice there are missing specifiers for things 
> > > > > > > like intmax_t, size_t, ptrdiff_t, _Decimal types, etc. Plus, that 
> > > > > > > will hopefully make it easier for __builtin_dump_struct to 
> > > > > > > benefit when new format specifiers are added, such as ones for 
> > > > > > > printing a _BitInt.
> > > > > > I am somewhat uncertain: every one of these is making arbitrary 
> > > > > > choices about how to format the value, so it's not clear to me that 
> > > > > > this is general logic rather than something specific to 
> > > > > > `__builtin_dump_struct`. For example, using `%f` rather than one of 
> > > > > > the myriad other ways of formatting `double` is somewhat arbitrary. 
> > > > > > Using `%s` for any `const char*` is *extremely* arbitrary and will 
> > > > > > be wrong and will cause crashes in some cases, but it may be the 
> > > > > > pragmatically correct choice for a dumping utility. A 
> > > > > > general-purpose mechanism would use `%p` for all kinds of pointer.
> > > > > > 
> > > > > > We could perhaps factor out the formatting for cases where there is 
> > > > > > a clear canonical default formatting, such as for integer types and 
> > > > > > probably `%p` for pointers, then call that from here with some 
> > > > > > special-casing, but without a second consumer for that 
> > > > > > functionality it's really not clear to me what form it should take.
> > > > > I went ahead and did this, mostly to match concurrent changes to the 
> > > > > old implementation. There are a few cases where our existing "guess a 
> > > > > format specifier" logic does the wrong thing for dumping purposes, 
> > > > > which I've explicitly handled -- things like wanting to dump a `char` 
> > > > > / `signed char` / `unsigned char` member as a number rather than as a 
> > > > > (potentially non-printable or whitespace) character.
> > > >  When I was patching that old implementation, I found that for uint8_t, 
> > > > int8_t, Clang's existing "guess a format specifier" logic would treat 
> > > > the value as an integer, but for unsigned char, signed char, char 
> > > > types, it would Treat it as a character, please look at this example ( 
> > > > https://godbolt.org/z/ooqn4468T ), I guess this existing logic may have 
> > > > made some special judgment.
> > > Yeah. I think in the case where we see some random call to `printf`, `%c` 
> > > is probably the right thing to guess here, but it doesn't seem 
> > > appropriate to me to use this in a dumping routine. If we could dump as 
> > > `'x'` for printable characters and as `'\xAB'` for everything else, 
> > > that'd be great, but `printf` can't do that itself and I'm not sure we 
> > > want to be injecting calls to `isprint` or whatever to make that work. 
> > > Dumping as an integer always seems like it's probably the least-bad 
> > > option.
> > > 
> > > Somewhat related: I wonder if we should use `"\"%s\""` instead of simply 
> > > `"%s"` when dumping a `const char*`. That's not ideal but probably 
> > > clearer than the current dump output.
> > I see value to having strings with SOME level of delimiter, if at least to 
> > handle cases when the string itself has a newline in it.
> This looks good, but the string may need to be escaped (if there are some 
> special characters in the original string)
Maybe users should wrap the printf function, and then pass the wrapper function 
as a parameter, so that they can do some custom things


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-04 Thread Wang Yihan via Phabricator via cfe-commits
yihanaa added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:433
+
+  llvm::StringRef getFormatSpecifier(QualType T) {
+if (auto *BT = T->getAs()) {

erichkeane wrote:
> rsmith wrote:
> > yihanaa wrote:
> > > rsmith wrote:
> > > > rsmith wrote:
> > > > > aaron.ballman wrote:
> > > > > > yihanaa wrote:
> > > > > > > I think this is better maintained in "clang/AST/FormatString.h". 
> > > > > > > For example analyze_printf::PrintfSpecifier can get format 
> > > > > > > specifier, what do you all think about?
> > > > > > +1 to this suggestion -- my hope is that we could generalize it 
> > > > > > more then as I notice there are missing specifiers for things like 
> > > > > > intmax_t, size_t, ptrdiff_t, _Decimal types, etc. Plus, that will 
> > > > > > hopefully make it easier for __builtin_dump_struct to benefit when 
> > > > > > new format specifiers are added, such as ones for printing a 
> > > > > > _BitInt.
> > > > > I am somewhat uncertain: every one of these is making arbitrary 
> > > > > choices about how to format the value, so it's not clear to me that 
> > > > > this is general logic rather than something specific to 
> > > > > `__builtin_dump_struct`. For example, using `%f` rather than one of 
> > > > > the myriad other ways of formatting `double` is somewhat arbitrary. 
> > > > > Using `%s` for any `const char*` is *extremely* arbitrary and will be 
> > > > > wrong and will cause crashes in some cases, but it may be the 
> > > > > pragmatically correct choice for a dumping utility. A general-purpose 
> > > > > mechanism would use `%p` for all kinds of pointer.
> > > > > 
> > > > > We could perhaps factor out the formatting for cases where there is a 
> > > > > clear canonical default formatting, such as for integer types and 
> > > > > probably `%p` for pointers, then call that from here with some 
> > > > > special-casing, but without a second consumer for that functionality 
> > > > > it's really not clear to me what form it should take.
> > > > I went ahead and did this, mostly to match concurrent changes to the 
> > > > old implementation. There are a few cases where our existing "guess a 
> > > > format specifier" logic does the wrong thing for dumping purposes, 
> > > > which I've explicitly handled -- things like wanting to dump a `char` / 
> > > > `signed char` / `unsigned char` member as a number rather than as a 
> > > > (potentially non-printable or whitespace) character.
> > >  When I was patching that old implementation, I found that for uint8_t, 
> > > int8_t, Clang's existing "guess a format specifier" logic would treat the 
> > > value as an integer, but for unsigned char, signed char, char types, it 
> > > would Treat it as a character, please look at this example ( 
> > > https://godbolt.org/z/ooqn4468T ), I guess this existing logic may have 
> > > made some special judgment.
> > Yeah. I think in the case where we see some random call to `printf`, `%c` 
> > is probably the right thing to guess here, but it doesn't seem appropriate 
> > to me to use this in a dumping routine. If we could dump as `'x'` for 
> > printable characters and as `'\xAB'` for everything else, that'd be great, 
> > but `printf` can't do that itself and I'm not sure we want to be injecting 
> > calls to `isprint` or whatever to make that work. Dumping as an integer 
> > always seems like it's probably the least-bad option.
> > 
> > Somewhat related: I wonder if we should use `"\"%s\""` instead of simply 
> > `"%s"` when dumping a `const char*`. That's not ideal but probably clearer 
> > than the current dump output.
> I see value to having strings with SOME level of delimiter, if at least to 
> handle cases when the string itself has a newline in it.
This looks good, but the string may need to be escaped (if there are some 
special characters in the original string)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D124977: [NFC][Clang] Modify expect of fail test or XFAIL because CSKY align is different

2022-05-04 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu created this revision.
zixuan-wu added reviewers: majnemer, kparzysz, ddunbar.
Herald added a project: All.
zixuan-wu requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

CSKY is always in 4-byte align, no matter it's long long type. For aggregate 
type,  it's 4-byte align if its size is bigger than or equal to 4 bytes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124977

Files:
  clang/test/CodeGen/c-strings.c
  clang/test/Sema/builtin-alloca-with-align.c


Index: clang/test/Sema/builtin-alloca-with-align.c
===
--- clang/test/Sema/builtin-alloca-with-align.c
+++ clang/test/Sema/builtin-alloca-with-align.c
@@ -29,5 +29,10 @@
 }
 
 void test8(void) {
+#if defined(__csky__)
   __builtin_alloca_with_align(sizeof(__INT64_TYPE__), 
__alignof__(__INT64_TYPE__)); // expected-warning {{second argument to 
__builtin_alloca_with_align is supposed to be in bits}}
+   
 // expected-error@-1 {{requested alignment must be 8 or greater}}
+#else
+  __builtin_alloca_with_align(sizeof(__INT64_TYPE__), 
__alignof__(__INT64_TYPE__)); // expected-warning {{second argument to 
__builtin_alloca_with_align is supposed to be in bits}}
+#endif
 }
Index: clang/test/CodeGen/c-strings.c
===
--- clang/test/CodeGen/c-strings.c
+++ clang/test/CodeGen/c-strings.c
@@ -20,6 +20,11 @@
 // fails the check for "@f3.x = ... align [ALIGN]", since ALIGN is derived
 // from the alignment of a single i8, which is still 1.
 
+// XFAIL: csky
+// CSKY aligns arrays of size 4+ bytes to a 32-bit boundary, which
+// fails the check for "@f2.x = ... align [ALIGN]", since ALIGN is derived
+// from the alignment of a single i8, which is still 1.
+
 #if defined(__s390x__)
 unsigned char align = 2;
 #else
@@ -69,4 +74,3 @@
 }
 
 char x[3] = "ola";
-


Index: clang/test/Sema/builtin-alloca-with-align.c
===
--- clang/test/Sema/builtin-alloca-with-align.c
+++ clang/test/Sema/builtin-alloca-with-align.c
@@ -29,5 +29,10 @@
 }
 
 void test8(void) {
+#if defined(__csky__)
   __builtin_alloca_with_align(sizeof(__INT64_TYPE__), __alignof__(__INT64_TYPE__)); // expected-warning {{second argument to __builtin_alloca_with_align is supposed to be in bits}}
+// expected-error@-1 {{requested alignment must be 8 or greater}}
+#else
+  __builtin_alloca_with_align(sizeof(__INT64_TYPE__), __alignof__(__INT64_TYPE__)); // expected-warning {{second argument to __builtin_alloca_with_align is supposed to be in bits}}
+#endif
 }
Index: clang/test/CodeGen/c-strings.c
===
--- clang/test/CodeGen/c-strings.c
+++ clang/test/CodeGen/c-strings.c
@@ -20,6 +20,11 @@
 // fails the check for "@f3.x = ... align [ALIGN]", since ALIGN is derived
 // from the alignment of a single i8, which is still 1.
 
+// XFAIL: csky
+// CSKY aligns arrays of size 4+ bytes to a 32-bit boundary, which
+// fails the check for "@f2.x = ... align [ALIGN]", since ALIGN is derived
+// from the alignment of a single i8, which is still 1.
+
 #if defined(__s390x__)
 unsigned char align = 2;
 #else
@@ -69,4 +74,3 @@
 }
 
 char x[3] = "ola";
-
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124857: [AIX][PGO] Enable linux style PGO on AIX

2022-05-04 Thread wael yehia 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 rG2407c13aa4a4: [AIX][PGO] Enable linux style PGO on AIX 
(authored by w2yehia).
Herald added projects: clang, Sanitizers.
Herald added subscribers: Sanitizers, cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124857

Files:
  clang/lib/Driver/ToolChains/AIX.cpp
  clang/test/Driver/aix-ld.c
  compiler-rt/lib/profile/InstrProfilingPlatformLinux.c
  compiler-rt/lib/profile/InstrProfilingPlatformOther.c
  llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
  llvm/test/Instrumentation/InstrProfiling/platform.ll
  llvm/test/Instrumentation/InstrProfiling/profiling.ll

Index: llvm/test/Instrumentation/InstrProfiling/profiling.ll
===
--- llvm/test/Instrumentation/InstrProfiling/profiling.ll
+++ llvm/test/Instrumentation/InstrProfiling/profiling.ll
@@ -119,9 +119,4 @@
 ; ELF_GENERIC-NEXT:   ret void
 ; ELF_GENERIC-NEXT: }
 
-; XCOFF:  define internal void @__llvm_profile_register_functions() unnamed_addr {
-; XCOFF-NEXT:   call void @__llvm_profile_register_function(i8* bitcast ({ i64, i64, i64, i8*, i8*, i32, [{{.*}} x i16] }* @__profd_foo to i8*))
-; XCOFF-NEXT:   call void @__llvm_profile_register_function(i8* bitcast ({ i64, i64, i64, i8*, i8*, i32, [{{.*}} x i16] }* @__profd_foo_weak to i8*))
-; XCOFF:   call void @__llvm_profile_register_names_function(i8* getelementptr inbounds {{.*}} @__llvm_prf_nm
-; XCOFF-NEXT:   ret void
-; XCOFF-NEXT: }
+; XCOFF-NOT:  internal void @__llvm_profile_register_functions() 
Index: llvm/test/Instrumentation/InstrProfiling/platform.ll
===
--- llvm/test/Instrumentation/InstrProfiling/platform.ll
+++ llvm/test/Instrumentation/InstrProfiling/platform.ll
@@ -50,7 +50,7 @@
 ; SOLARIS-NOT: define internal void @__llvm_profile_register_functions
 ; PS4-NOT: define internal void @__llvm_profile_register_functions
 ; WINDOWS-NOT: define internal void @__llvm_profile_register_functions
-; AIX: define internal void @__llvm_profile_register_functions
+; AIX-NOT: define internal void @__llvm_profile_register_functions
 
 ;; PR38340: When dynamic registration is used, we had a bug where we'd register
 ;; something that's not a __profd_* variable.
@@ -61,4 +61,4 @@
 ; SOLARIS-NOT: define internal void @__llvm_profile_init
 ; PS4-NOT: define internal void @__llvm_profile_init
 ; WINDOWS-NOT: define internal void @__llvm_profile_init
-; AIX: define internal void @__llvm_profile_init
+; AIX-NOT: define internal void @__llvm_profile_init
Index: llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
===
--- llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
+++ llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
@@ -855,7 +855,7 @@
   if (TT.isOSDarwin())
 return false;
   // Use linker script magic to get data/cnts/name start/end.
-  if (TT.isOSLinux() || TT.isOSFreeBSD() || TT.isOSNetBSD() ||
+  if (TT.isOSAIX() || TT.isOSLinux() || TT.isOSFreeBSD() || TT.isOSNetBSD() ||
   TT.isOSSolaris() || TT.isOSFuchsia() || TT.isPS4() || TT.isOSWindows())
 return false;
 
Index: compiler-rt/lib/profile/InstrProfilingPlatformOther.c
===
--- compiler-rt/lib/profile/InstrProfilingPlatformOther.c
+++ compiler-rt/lib/profile/InstrProfilingPlatformOther.c
@@ -8,7 +8,7 @@
 
 #if !defined(__APPLE__) && !defined(__linux__) && !defined(__FreeBSD__) && \
 !defined(__Fuchsia__) && !(defined(__sun__) && defined(__svr4__)) &&   \
-!defined(__NetBSD__) && !defined(_WIN32)
+!defined(__NetBSD__) && !defined(_WIN32) && !defined(_AIX)
 
 #include 
 #include 
Index: compiler-rt/lib/profile/InstrProfilingPlatformLinux.c
===
--- compiler-rt/lib/profile/InstrProfilingPlatformLinux.c
+++ compiler-rt/lib/profile/InstrProfilingPlatformLinux.c
@@ -7,10 +7,13 @@
 \*===--===*/
 
 #if defined(__linux__) || defined(__FreeBSD__) || defined(__Fuchsia__) || \
-(defined(__sun__) && defined(__svr4__)) || defined(__NetBSD__)
+(defined(__sun__) && defined(__svr4__)) || defined(__NetBSD__) || \
+defined(_AIX)
 
+#if !defined(_AIX)
 #include 
 #include 
+#endif
 #include 
 #include 
 
@@ -227,4 +230,43 @@
 }
 #endif
 
+#if defined(_AIX)
+// Empty stubs to allow linking object files using the registration-based scheme
+COMPILER_RT_VISIBILITY
+void __llvm_profile_register_function(void *Data_) {}
+
+COMPILER_RT_VISIBILITY
+void __llvm_profile_register_names_function(void *NamesStart,
+uint64_t NamesSize) {}
+
+// The __start_

[clang] 2407c13 - [AIX][PGO] Enable linux style PGO on AIX

2022-05-04 Thread Wael Yehia via cfe-commits

Author: Wael Yehia
Date: 2022-05-05T04:10:39Z
New Revision: 2407c13aa4a42f3a3438ae2d03fa38df0a5fd30b

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

LOG: [AIX][PGO] Enable linux style PGO on AIX

This patch switches the PGO implementation on AIX from using the runtime
registration-based section tracking to the __start_SECNAME/__stop_SECNAME
based. In order to enable the recognition of __start_SECNAME/__stop_SECNAME
symbols in the AIX linker, the -bdbg:namedsects:ss needs to be used.

Reviewed By: jsji, MaskRay, davidxl

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/AIX.cpp
clang/test/Driver/aix-ld.c
compiler-rt/lib/profile/InstrProfilingPlatformLinux.c
compiler-rt/lib/profile/InstrProfilingPlatformOther.c
llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
llvm/test/Instrumentation/InstrProfiling/platform.ll
llvm/test/Instrumentation/InstrProfiling/profiling.ll

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/AIX.cpp 
b/clang/lib/Driver/ToolChains/AIX.cpp
index 37316a792f6d12..878b84a777027c 100644
--- a/clang/lib/Driver/ToolChains/AIX.cpp
+++ b/clang/lib/Driver/ToolChains/AIX.cpp
@@ -117,7 +117,7 @@ void aix::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 options::OPT_fno_profile_generate, false) ||
Args.hasArg(options::OPT_fcreate_profile) ||
Args.hasArg(options::OPT_coverage))
-CmdArgs.push_back("-bdbg:namedsects");
+CmdArgs.push_back("-bdbg:namedsects:ss");
 
   // Specify linker output file.
   assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");

diff  --git a/clang/test/Driver/aix-ld.c b/clang/test/Driver/aix-ld.c
index eccae132763d5e..3f4784daa1e3eb 100644
--- a/clang/test/Driver/aix-ld.c
+++ b/clang/test/Driver/aix-ld.c
@@ -664,7 +664,7 @@
 // CHECK-PGO-NON-LTO: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-PGO-NON-LTO: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-PGO-NON-LTO: "{{.*}}ld{{(.exe)?}}"
-// CHECK-PGO-NON-LTO: "-bdbg:namedsects"
+// CHECK-PGO-NON-LTO: "-bdbg:namedsects:ss"
 // CHECK-PGO-NON-LTO: "-b32"
 // CHECK-PGO-NON-LTO: "-bpT:0x1000" "-bpD:0x2000"
 // CHECK-PGO-NON-LTO: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
@@ -692,7 +692,7 @@
 // CHECK-PGO-LTO: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-PGO-LTO: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-PGO-LTO: "{{.*}}ld{{(.exe)?}}"
-// CHECK-PGO-LTO: "-bdbg:namedsects"
+// CHECK-PGO-LTO: "-bdbg:namedsects:ss"
 // CHECK-PGO-LTO: "-b32"
 // CHECK-PGO-LTO: "-bpT:0x1000" "-bpD:0x2000"
 // CHECK-PGO-LTO: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"

diff  --git a/compiler-rt/lib/profile/InstrProfilingPlatformLinux.c 
b/compiler-rt/lib/profile/InstrProfilingPlatformLinux.c
index 592c09b49d4b15..3af61d24948e7c 100644
--- a/compiler-rt/lib/profile/InstrProfilingPlatformLinux.c
+++ b/compiler-rt/lib/profile/InstrProfilingPlatformLinux.c
@@ -7,10 +7,13 @@
 
\*===--===*/
 
 #if defined(__linux__) || defined(__FreeBSD__) || defined(__Fuchsia__) || \
-(defined(__sun__) && defined(__svr4__)) || defined(__NetBSD__)
+(defined(__sun__) && defined(__svr4__)) || defined(__NetBSD__) || \
+defined(_AIX)
 
+#if !defined(_AIX)
 #include 
 #include 
+#endif
 #include 
 #include 
 
@@ -227,4 +230,43 @@ COMPILER_RT_VISIBILITY int 
__llvm_write_binary_ids(ProfDataWriter *Writer) {
 }
 #endif
 
+#if defined(_AIX)
+// Empty stubs to allow linking object files using the registration-based 
scheme
+COMPILER_RT_VISIBILITY
+void __llvm_profile_register_function(void *Data_) {}
+
+COMPILER_RT_VISIBILITY
+void __llvm_profile_register_names_function(void *NamesStart,
+uint64_t NamesSize) {}
+
+// The __start_SECNAME and __stop_SECNAME symbols (for SECNAME \in
+// {"__llvm_prf_cnts", "__llvm_prf_data", "__llvm_prf_name", 
"__llvm_prf_vnds"})
+// are always live when linking on AIX, regardless if the .o's being linked
+// reference symbols from the profile library (for example when no files were
+// compiled with -fprofile-generate). That's because these symbols are kept
+// alive through references in constructor functions that are always live in 
the
+// default linking model on AIX (-bcdtors:all). The __start_SECNAME and
+// __stop_SECNAME symbols are only resolved by the linker when the SECNAME
+// section exists. So for the scenario where the user objects have no such
+// section (i.e. when they are compiled with -fno-profile-generate), we always
+// define these zero length variables in each of the above 4 sections.
+COMPILER_RT_VISIBILITY int dummy_cnts[0] COMPILER_RT_SECT

[PATCH] D124813: [HLSL] Add clang builtin for HLSL.

2022-05-04 Thread Yonghong Song via Phabricator via cfe-commits
yonghong-song resigned from this revision.
yonghong-song added a comment.

please having proper reviewers. Me, @anakryiko  @ast are not the right persons 
to review this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124813

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


[PATCH] D124943: [clang][dataflow] Add flowConditionIsTautology function

2022-05-04 Thread Eric Li 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 rG58abe36ae765: [clang][dataflow] Add flowConditionIsTautology 
function (authored by li.zhe.hua).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124943

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp


Index: clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
@@ -140,4 +140,33 @@
   EXPECT_TRUE(Context.flowConditionImplies(FC3, C3));
 }
 
+TEST_F(DataflowAnalysisContextTest, FlowConditionTautologies) {
+  // Fresh flow condition with empty/no constraints is always true.
+  auto &FC1 = Context.makeFlowConditionToken();
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC1));
+
+  // Literal `true` is always true.
+  auto &FC2 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC2, Context.getBoolLiteralValue(true));
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC2));
+
+  // Literal `false` is never true.
+  auto &FC3 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC3, Context.getBoolLiteralValue(false));
+  EXPECT_FALSE(Context.flowConditionIsTautology(FC3));
+
+  // We can't prove that an arbitrary bool A is always true...
+  auto &C1 = Context.createAtomicBoolValue();
+  auto &FC4 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC4, C1);
+  EXPECT_FALSE(Context.flowConditionIsTautology(FC4));
+
+  // ... but we can prove A || !A is true.
+  auto &FC5 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(
+  FC5, Context.getOrCreateDisjunctionValue(
+   C1, Context.getOrCreateNegationValue(C1)));
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC5));
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
@@ -117,6 +117,19 @@
   return S->solve(std::move(Constraints)) == Solver::Result::Unsatisfiable;
 }
 
+bool DataflowAnalysisContext::flowConditionIsTautology(AtomicBoolValue &Token) 
{
+  // Returns true if and only if we cannot prove that the flow condition can
+  // ever be false.
+  llvm::DenseSet Constraints = {
+  &getBoolLiteralValue(true),
+  &getOrCreateNegationValue(getBoolLiteralValue(false)),
+  &getOrCreateNegationValue(Token),
+  };
+  llvm::DenseSet VisitedTokens;
+  addTransitiveFlowConditionConstraints(Token, Constraints, VisitedTokens);
+  return S->solve(std::move(Constraints)) == Solver::Result::Unsatisfiable;
+}
+
 void DataflowAnalysisContext::addTransitiveFlowConditionConstraints(
 AtomicBoolValue &Token, llvm::DenseSet &Constraints,
 llvm::DenseSet &VisitedTokens) const {
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
@@ -173,6 +173,10 @@
   /// identified by `Token` imply that `Val` is true.
   bool flowConditionImplies(AtomicBoolValue &Token, BoolValue &Val);
 
+  /// Returns true if and only if the constraints of the flow condition
+  /// identified by `Token` are always true.
+  bool flowConditionIsTautology(AtomicBoolValue &Token);
+
 private:
   /// Adds all constraints of the flow condition identified by `Token` and all
   /// of its transitive dependencies to `Constraints`. `VisitedTokens` is used


Index: clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
@@ -140,4 +140,33 @@
   EXPECT_TRUE(Context.flowConditionImplies(FC3, C3));
 }
 
+TEST_F(DataflowAnalysisContextTest, FlowConditionTautologies) {
+  // Fresh flow condition with empty/no constraints is always true.
+  auto &FC1 = Context.makeFlowConditionToken();
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC1));
+
+  // Literal `true` is always true.
+  auto &FC2 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC2, Context.getBoolLiteralValue(true));
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC2));
+
+  // Literal `false` is neve

[clang] 58abe36 - [clang][dataflow] Add flowConditionIsTautology function

2022-05-04 Thread Eric Li via cfe-commits

Author: Eric Li
Date: 2022-05-05T03:57:43Z
New Revision: 58abe36ae7654987f5af793e3e261ac0b43c870b

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

LOG: [clang][dataflow] Add flowConditionIsTautology function

Provide a way for users to check if a flow condition is
unconditionally true.

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp

Removed: 




diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
index 5cf681e4e489c..a762cb9de48bd 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
@@ -173,6 +173,10 @@ class DataflowAnalysisContext {
   /// identified by `Token` imply that `Val` is true.
   bool flowConditionImplies(AtomicBoolValue &Token, BoolValue &Val);
 
+  /// Returns true if and only if the constraints of the flow condition
+  /// identified by `Token` are always true.
+  bool flowConditionIsTautology(AtomicBoolValue &Token);
+
 private:
   /// Adds all constraints of the flow condition identified by `Token` and all
   /// of its transitive dependencies to `Constraints`. `VisitedTokens` is used

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
index 4274fca4e3c14..b29983eed79f9 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
@@ -117,6 +117,19 @@ bool 
DataflowAnalysisContext::flowConditionImplies(AtomicBoolValue &Token,
   return S->solve(std::move(Constraints)) == Solver::Result::Unsatisfiable;
 }
 
+bool DataflowAnalysisContext::flowConditionIsTautology(AtomicBoolValue &Token) 
{
+  // Returns true if and only if we cannot prove that the flow condition can
+  // ever be false.
+  llvm::DenseSet Constraints = {
+  &getBoolLiteralValue(true),
+  &getOrCreateNegationValue(getBoolLiteralValue(false)),
+  &getOrCreateNegationValue(Token),
+  };
+  llvm::DenseSet VisitedTokens;
+  addTransitiveFlowConditionConstraints(Token, Constraints, VisitedTokens);
+  return S->solve(std::move(Constraints)) == Solver::Result::Unsatisfiable;
+}
+
 void DataflowAnalysisContext::addTransitiveFlowConditionConstraints(
 AtomicBoolValue &Token, llvm::DenseSet &Constraints,
 llvm::DenseSet &VisitedTokens) const {

diff  --git 
a/clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
index b4b9b169f440e..b8a9ef52504af 100644
--- a/clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
@@ -140,4 +140,33 @@ TEST_F(DataflowAnalysisContextTest, JoinFlowConditions) {
   EXPECT_TRUE(Context.flowConditionImplies(FC3, C3));
 }
 
+TEST_F(DataflowAnalysisContextTest, FlowConditionTautologies) {
+  // Fresh flow condition with empty/no constraints is always true.
+  auto &FC1 = Context.makeFlowConditionToken();
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC1));
+
+  // Literal `true` is always true.
+  auto &FC2 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC2, Context.getBoolLiteralValue(true));
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC2));
+
+  // Literal `false` is never true.
+  auto &FC3 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC3, Context.getBoolLiteralValue(false));
+  EXPECT_FALSE(Context.flowConditionIsTautology(FC3));
+
+  // We can't prove that an arbitrary bool A is always true...
+  auto &C1 = Context.createAtomicBoolValue();
+  auto &FC4 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC4, C1);
+  EXPECT_FALSE(Context.flowConditionIsTautology(FC4));
+
+  // ... but we can prove A || !A is true.
+  auto &FC5 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(
+  FC5, Context.getOrCreateDisjunctionValue(
+   C1, Context.getOrCreateNegationValue(C1)));
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC5));
+}
+
 } // namespace



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


[PATCH] D124943: [clang][dataflow] Add flowConditionIsTautology function

2022-05-04 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua marked 4 inline comments as done.
li.zhe.hua added a comment.

Ah, good catch regarding the flow condition deps not being tracked. Thanks for 
the review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124943

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


[PATCH] D124943: [clang][dataflow] Add flowConditionIsTautology function

2022-05-04 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua updated this revision to Diff 427183.
li.zhe.hua added a comment.

Address reviewer comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124943

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp


Index: clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
@@ -140,4 +140,33 @@
   EXPECT_TRUE(Context.flowConditionImplies(FC3, C3));
 }
 
+TEST_F(DataflowAnalysisContextTest, FlowConditionTautologies) {
+  // Fresh flow condition with empty/no constraints is always true.
+  auto &FC1 = Context.makeFlowConditionToken();
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC1));
+
+  // Literal `true` is always true.
+  auto &FC2 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC2, Context.getBoolLiteralValue(true));
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC2));
+
+  // Literal `false` is never true.
+  auto &FC3 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC3, Context.getBoolLiteralValue(false));
+  EXPECT_FALSE(Context.flowConditionIsTautology(FC3));
+
+  // We can't prove that an arbitrary bool A is always true...
+  auto &C1 = Context.createAtomicBoolValue();
+  auto &FC4 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC4, C1);
+  EXPECT_FALSE(Context.flowConditionIsTautology(FC4));
+
+  // ... but we can prove A || !A is true.
+  auto &FC5 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(
+  FC5, Context.getOrCreateDisjunctionValue(
+   C1, Context.getOrCreateNegationValue(C1)));
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC5));
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
@@ -117,6 +117,19 @@
   return S->solve(std::move(Constraints)) == Solver::Result::Unsatisfiable;
 }
 
+bool DataflowAnalysisContext::flowConditionIsTautology(AtomicBoolValue &Token) 
{
+  // Returns true if and only if we cannot prove that the flow condition can
+  // ever be false.
+  llvm::DenseSet Constraints = {
+  &getBoolLiteralValue(true),
+  &getOrCreateNegationValue(getBoolLiteralValue(false)),
+  &getOrCreateNegationValue(Token),
+  };
+  llvm::DenseSet VisitedTokens;
+  addTransitiveFlowConditionConstraints(Token, Constraints, VisitedTokens);
+  return S->solve(std::move(Constraints)) == Solver::Result::Unsatisfiable;
+}
+
 void DataflowAnalysisContext::addTransitiveFlowConditionConstraints(
 AtomicBoolValue &Token, llvm::DenseSet &Constraints,
 llvm::DenseSet &VisitedTokens) const {
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
@@ -173,6 +173,10 @@
   /// identified by `Token` imply that `Val` is true.
   bool flowConditionImplies(AtomicBoolValue &Token, BoolValue &Val);
 
+  /// Returns true if and only if the constraints of the flow condition
+  /// identified by `Token` are always true.
+  bool flowConditionIsTautology(AtomicBoolValue &Token);
+
 private:
   /// Adds all constraints of the flow condition identified by `Token` and all
   /// of its transitive dependencies to `Constraints`. `VisitedTokens` is used


Index: clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
@@ -140,4 +140,33 @@
   EXPECT_TRUE(Context.flowConditionImplies(FC3, C3));
 }
 
+TEST_F(DataflowAnalysisContextTest, FlowConditionTautologies) {
+  // Fresh flow condition with empty/no constraints is always true.
+  auto &FC1 = Context.makeFlowConditionToken();
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC1));
+
+  // Literal `true` is always true.
+  auto &FC2 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC2, Context.getBoolLiteralValue(true));
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC2));
+
+  // Literal `false` is never true.
+  auto &FC3 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC3, Context.getBoolLiteralValue(false));
+  

[PATCH] D124943: [clang][dataflow] Add flowConditionIsTautology function

2022-05-04 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua added a comment.

I'm playing around with a tool to take raw pointers and add a non-null 
annotation or convert them to references, for code that is assumed to be 
correct. So in this case, "interesting expression" is anything that would be UB 
if the pointer was null, e.g. dereferencing the pointer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124943

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


[PATCH] D124943: [clang][dataflow] Add flowConditionIsTautology function

2022-05-04 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev accepted this revision.
sgatev added inline comments.



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:176-177
 
+  /// Returns true if the constraints of the flow condition identified by
+  /// `Token` is always true.
+  bool flowConditionIsTautology(AtomicBoolValue &Token);





Comment at: 
clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp:144
+TEST_F(DataflowAnalysisContextTest, FlowConditionTautologies) {
+  // Default flow condition with empty/no constraints is always true.
+  auto &FC1 = Context.makeFlowConditionToken();





Comment at: 
clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp:151
+  Context.addFlowConditionConstraint(FC2,
+ Context.getOrCreateNegationValue(FC1));
+  EXPECT_FALSE(Context.flowConditionIsTautology(FC2));

I don't think this is doing what the comment above it says. We probably 
shouldn't add flow conditions directly as constraints because this isn't 
tracking flow condition dependencies. I suggest removing this case and keeping 
the one with `FC5`.



Comment at: 
clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp:154
+
+  // FC1 || !FC1 is always true.
+  EXPECT_TRUE(

Again, I suggest removing this case. The one with `FC6` should suffice.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124943

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


[PATCH] D120290: [Clang][OpenMP] Add the codegen support for `atomic compare capture`

2022-05-04 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 updated this revision to Diff 427182.
tianshilei1992 added a comment.

fix comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120290

Files:
  clang/include/clang/AST/StmtOpenMP.h
  clang/lib/AST/StmtOpenMP.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/test/OpenMP/atomic_compare_codegen.cpp

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


[PATCH] D104975: Implement P1949

2022-05-04 Thread Ade Durcov via Phabricator via cfe-commits
intractabilis added a comment.

I checked the latest GCC 12. Despite P1949 <https://reviews.llvm.org/P1949> 
support, I can use math symbols like 𝜕 and 𝛻 without any problem with any 
combination of `-std=c++xx`, xx ≠ 98, xx ≠ 03. Thanks, God, there are 
reasonable people in the GCC team.

test.cpp:

  #include 
  
  int main(int argc, char* argv[]) {
  auto 𝜕Ω = 4;
  std::cout << "𝜕Ω = " << 𝜕Ω << std::endl;
  }



  $ g++ --version
  g++ (GCC) 12.0.1 20220504 (prerelease)
  Copyright (C) 2022 Free Software Foundation, Inc.
  This is free software; see the source for copying conditions.  There is NO
  warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  $ g++ -std=c++23 -o test test.cpp
  $ ./test
  𝜕Ω = 4


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104975

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


[PATCH] D124916: [X86] Fix uninitialized variable warnings in cetintrin.h reported by #55224

2022-05-04 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei marked an inline comment as done.
pengfei added inline comments.



Comment at: clang/lib/Headers/cetintrin.h:45
 
 static __inline__ unsigned int __DEFAULT_FN_ATTRS _rdsspd_i32() {
+#pragma clang diagnostic push

craig.topper wrote:
> The argument should also be `(void)`.
Thanks! Done by rGaa25b55bde87.



Comment at: clang/lib/Headers/cetintrin.h:48
+#pragma clang diagnostic ignored "-Wuninitialized"
   unsigned int t;
   return __builtin_ia32_rdsspd(t);

craig.topper wrote:
> So if CET isn't enabled this intrinsic returns a random value instead of 0 
> like _get_ssp?
Exactly! These intrinsics are used to reflect the exact instructions behavior, 
i.e., a nop operation. They are used for performance.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124916

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


[clang] aa25b55 - [X86] Add `void` to void function. NFC

2022-05-04 Thread Phoebe Wang via cfe-commits

Author: Phoebe Wang
Date: 2022-05-05T10:58:46+08:00
New Revision: aa25b55bde87501f72346704136951834140bda8

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

LOG: [X86] Add `void` to void function. NFC

Added: 


Modified: 
clang/lib/Headers/cetintrin.h

Removed: 




diff  --git a/clang/lib/Headers/cetintrin.h b/clang/lib/Headers/cetintrin.h
index 55670a0a9dba6..fbb6bfb00972c 100644
--- a/clang/lib/Headers/cetintrin.h
+++ b/clang/lib/Headers/cetintrin.h
@@ -42,7 +42,7 @@ static __inline__ unsigned int __DEFAULT_FN_ATTRS 
_rdsspd(unsigned int __a) {
   return __builtin_ia32_rdsspd(__a);
 }
 
-static __inline__ unsigned int __DEFAULT_FN_ATTRS _rdsspd_i32() {
+static __inline__ unsigned int __DEFAULT_FN_ATTRS _rdsspd_i32(void) {
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wuninitialized"
   unsigned int t;
@@ -55,7 +55,7 @@ static __inline__ unsigned long long __DEFAULT_FN_ATTRS 
_rdsspq(unsigned long lo
   return __builtin_ia32_rdsspq(__a);
 }
 
-static __inline__ unsigned long long __DEFAULT_FN_ATTRS _rdsspq_i64() {
+static __inline__ unsigned long long __DEFAULT_FN_ATTRS _rdsspq_i64(void) {
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wuninitialized"
   unsigned long long t;
@@ -74,7 +74,7 @@ static __inline__ unsigned int __DEFAULT_FN_ATTRS 
_get_ssp(void) {
 }
 #endif /* __x86_64__ */
 
-static __inline__ void __DEFAULT_FN_ATTRS _saveprevssp() {
+static __inline__ void __DEFAULT_FN_ATTRS _saveprevssp(void) {
   __builtin_ia32_saveprevssp();
 }
 
@@ -102,7 +102,7 @@ static __inline__ void __DEFAULT_FN_ATTRS _wrussq(unsigned 
long long __a, void *
 }
 #endif /* __x86_64__ */
 
-static __inline__ void __DEFAULT_FN_ATTRS _setssbsy() {
+static __inline__ void __DEFAULT_FN_ATTRS _setssbsy(void) {
   __builtin_ia32_setssbsy();
 }
 



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


[PATCH] D124708: Fix "the the" typo in documentation and user facing strings

2022-05-04 Thread Brian Tracy via Phabricator via cfe-commits
briantracy marked an inline comment as done.
briantracy added a comment.

Thank you Mark and Gabor. At your discretion, could you commit this on my 
behalf? My email is "brian.trac...@gmail.com" and full name is "Brian Tracy". 
Thanks again.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124708

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


[PATCH] D124974: [clang] Include clang config.h in LangStandards.cpp

2022-05-04 Thread Cassie Jones via Phabricator via cfe-commits
porglezomp created this revision.
porglezomp added reviewers: hokein, sammccall, dexonsmith.
Herald added a project: All.
porglezomp requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is necessary in order to pick up the default C/C++ standard from
the CLANG_DEFAULT_STD_C(XX) defines. This fixes a bug that was
introduced when this default language standard code was moved from
Frontend to Basic, making compilers ignore the configured default
language version override.

Fixes a bug introduced by D121375 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124974

Files:
  clang/lib/Basic/LangStandards.cpp


Index: clang/lib/Basic/LangStandards.cpp
===
--- clang/lib/Basic/LangStandards.cpp
+++ clang/lib/Basic/LangStandards.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "clang/Basic/LangStandard.h"
+#include "clang/Config/config.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Support/ErrorHandling.h"


Index: clang/lib/Basic/LangStandards.cpp
===
--- clang/lib/Basic/LangStandards.cpp
+++ clang/lib/Basic/LangStandards.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang/Basic/LangStandard.h"
+#include "clang/Config/config.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Support/ErrorHandling.h"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124534: [clang] Add a diagnostic for line directive of a gnu extension

2022-05-04 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui added a comment.

In D124534#3490732 , @aaron.ballman 
wrote:

> The tests run in -cc1 mode and don't #include anything, so I don't think the 
> issue is an internally included SDK. I think the issue could be from this: 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/Frontend/InitPreprocessor.cpp#L1355
>  and 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/Frontend/InitPreprocessor.cpp#L1368.
>  You may have to hook up to a debugger to see why we're issuing those 
> surprising warnings. If it turns out that it's these inserted directives, you 
> may have to look at the source location of the digit token to see if 
> `isWrittenInBuiltinFile()` is true or not (and we may need to also check 
> `isWrittenInScratchSpace()` as well, perhaps).

Thank you for the information! I'm going to look into the source code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

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


[PATCH] D124149: [NFC] follow up code cleanup after D123837

2022-05-04 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

@iains ping!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124149

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


[PATCH] D124726: Suggest typoed directives in preprocessor conditionals

2022-05-04 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui added a comment.

Thank you so much for your clear review!




Comment at: clang/include/clang/Basic/DiagnosticGroups.td:1023-1024
 
+// Typoed directive warnings
+def TypoedDirective : DiagGroup<"typoed-directive">;
+

aaron.ballman wrote:
> We don't typically use "typo" in the user-facing part of diagnostics and this 
> group doesn't seem likely to be reused, so I would remove it (another comment 
> on this elsewhere).
Ah, I see. Thank you!



Comment at: clang/include/clang/Basic/DiagnosticLexKinds.td:362-365
 
+def warn_pp_typo_directive : Warning<
+  "'#%0' directive not found, did you mean '#%1'?">,
+  InGroup;

aaron.ballman wrote:
> Rather than adding a warning over the top of an existing error, I think we 
> should modify `err_pp_invalid_directive` to have an optional "did you mean?" 
> when we find a plausible typo to correct.
> 
> However, we do not issue that diagnostic when it's inside of a skipped 
> conditional block, and that's what the crux of 
> https://github.com/llvm/llvm-project/issues/51598 is about. As @rsmith 
> pointed out in that issue (and I agree), compilers are free to support custom 
> directives and those will validly appear inside of a conditional block that 
> is skipped. We need to be careful not to diagnose those kinds of situations 
> as an error. However, we still want to diagnose when the unknown directive is 
> "sufficiently close" to another one which can control the conditional chain. 
> e.g.,
> ```
> #fi FOO // error unknown directive, did you mean #if?
> #endfi // error unknown directive, did you mean #endif?
> 
> #if FOO
> #esle // diag: unknown directive, did you mean #else?
> #elfi // diag: unknown directive, did you mean #elif?
> #elfidef // diag: unknown directive, did you mean #elifdef
> #elinfdef // diag: unknown directive, did you mean #elifndef
> 
> #frobble // No diagnostic, not close enough to a conditional directive to 
> warrant diagnosing
> #eerp // No diagnostic, not close enough to a conditional directive to 
> warrant diagnosing
> 
> #endif
> ```
> Today, if `FOO` is defined to a nonzero value, you'll get diagnostics for all 
> of those, but if `FOO` is not defined or is defined to 0, then there's no 
> diagnostics. I think we want to consider directives that are *very likely* to 
> be a typo (edit distance of 1, maybe 2?) for a conditional directive as a 
> special case.
> 
> Currently, we only diagnose unknown directives as an error. I think for these 
> special cased conditional directive diagnostics, we'll want to use a warning 
> rather than an error in this circumstance (just in case it turns out to be a 
> valid directive in a skipped conditional block). If we do go that route and 
> make it a warning, I think the warning group should be `-Wunknown-directives` 
> to mirror `-Wunknown-pragmas`, `-Wunknown-attributes`, etc and it should be 
> defined to have the same text as the error case. e.g., 
> ```
> def err_pp_invalid_directive : Error<
>   "invalid preprocessing directive%select{|; did you mean '#%1'?}0"
> >;
> def warn_pp_invalid_directive : Warning<
>   err_pp_invalid_directive.Text>, InGroup>;
> ```
> WDYT?
> 
> (These were my thoughts before seeing the rest of the patch. After reading 
> the patch, it looks like we have pretty similar ideas here, which is great, 
> but leaving the comment anyway in case you have further opinions.)
> Currently, we only diagnose unknown directives as an error. I think for these 
> special cased conditional directive diagnostics, we'll want to use a warning 
> rather than an error in this circumstance (just in case it turns out to be a 
> valid directive in a skipped conditional block). If we do go that route and 
> make it a warning, I think the warning group should be `-Wunknown-directives` 
> to mirror `-Wunknown-pragmas`, `-Wunknown-attributes`, etc and it should be 
> defined to have the same text as the error case. e.g., 
> ```
> def err_pp_invalid_directive : Error<
>   "invalid preprocessing directive%select{|; did you mean '#%1'?}0"
> >;
> def warn_pp_invalid_directive : Warning<
>   err_pp_invalid_directive.Text>, InGroup>;
> ```
> WDYT?
> 
> (These were my thoughts before seeing the rest of the patch. After reading 
> the patch, it looks like we have pretty similar ideas here, which is great, 
> but leaving the comment anyway in case you have further opinions.)

For now, I totally agree with deriving a new warning from 
`err_pp_invalid_directive`.

However, for future scalability, I think it would be great if we could split 
those diagnostics into Error & Warning and Help, for example. Rustc does split 
the diagnostics like the following, and I think this is quite clear. So, a bit 
apart from this patch, I speculate creating a diagnostic system that can split 
them would bring Clang diagnostics much more readable.

https://github.com/rust-lang/rust/blob/598d89bf142823b5d84e2eb0f0f9e418ee966a4b/src/test/ui/suggestions

[PATCH] D123924: [clang-apply-replacements] Added an option to ignore insert conflict.

2022-05-04 Thread liushuai wang via Phabricator via cfe-commits
MTC added a comment.

In D123924#3482342 , @aaron.ballman 
wrote:

> I don't know enough about this code base to feel comfortable signing off on 
> it, but the changes look reasonable to me FWIW.

Thanks, Aaron! I will find another guy to review the change.


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

https://reviews.llvm.org/D123924

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


[PATCH] D124956: [clang-format] Fix another bug in AlignConsecutiveAssignments

2022-05-04 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

No, because the first part of that test case would cause non-consecutive 
assignments to be aligned. (See 
https://github.com/llvm/llvm-project/issues/55265.) Only then would the `if` 
block be treated as a braced list and get misindented. We should definitely use 
test cases with PP directives when fixing #55265 though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124956

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


[PATCH] D124611: [RISCV][Clang] add more tests for clang driver. (NFC)

2022-05-04 Thread Craig Topper via Phabricator via cfe-commits
craig.topper accepted this revision.
craig.topper 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/D124611/new/

https://reviews.llvm.org/D124611

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


[PATCH] D124971: [Frontend] give createInvocationFromCommandLine an options struct

2022-05-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added subscribers: usaxena95, arphaman.
Herald added a project: All.
sammccall requested review of this revision.
Herald added projects: clang, clang-tools-extra.
Herald added a subscriber: cfe-commits.

It's accumulating way too many optional params (see D124970 
)

While here, improve the name and the documentation.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124971

Files:
  clang-tools-extra/clangd/Compiler.cpp
  clang/include/clang/Frontend/Utils.h
  clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
  clang/unittests/Frontend/UtilsTest.cpp

Index: clang/unittests/Frontend/UtilsTest.cpp
===
--- clang/unittests/Frontend/UtilsTest.cpp
+++ clang/unittests/Frontend/UtilsTest.cpp
@@ -23,12 +23,12 @@
   std::vector Args = {"clang", "--target=macho", "-arch",  "i386",
 "-arch", "x86_64", "foo.cpp"};
   clang::IgnoringDiagConsumer D;
-  llvm::IntrusiveRefCntPtr CommandLineDiagsEngine =
-  clang::CompilerInstance::createDiagnostics(new DiagnosticOptions, &D,
- false);
-  std::unique_ptr CI = createInvocationFromCommandLine(
-  Args, CommandLineDiagsEngine, new llvm::vfs::InMemoryFileSystem(),
-  /*ShouldRecoverOnErrors=*/true);
+  CreateInvocationOptions Opts;
+  Opts.RecoverOnError = true;
+  Opts.Diags = clang::CompilerInstance::createDiagnostics(new DiagnosticOptions,
+  &D, false);
+  Opts.VFS = new llvm::vfs::InMemoryFileSystem();
+  std::unique_ptr CI = createInvocation(Args, Opts);
   ASSERT_TRUE(CI);
   EXPECT_THAT(CI->TargetOpts->Triple, testing::StartsWith("i386-"));
 }
Index: clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
===
--- clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
+++ clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
@@ -26,16 +26,13 @@
 using namespace clang;
 using namespace llvm::opt;
 
-std::unique_ptr clang::createInvocationFromCommandLine(
-ArrayRef ArgList, IntrusiveRefCntPtr Diags,
-IntrusiveRefCntPtr VFS, bool ShouldRecoverOnErorrs,
-std::vector *CC1Args) {
+std::unique_ptr
+clang::createInvocation(ArrayRef ArgList,
+CreateInvocationOptions Opts) {
   assert(!ArgList.empty());
-  if (!Diags.get()) {
-// No diagnostics engine was provided, so create our own diagnostics object
-// with the default options.
-Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions);
-  }
+  auto Diags = Opts.Diags
+   ? std::move(Opts.Diags)
+   : CompilerInstance::createDiagnostics(new DiagnosticOptions);
 
   SmallVector Args(ArgList.begin(), ArgList.end());
 
@@ -47,7 +44,7 @@
 
   // FIXME: We shouldn't have to pass in the path info.
   driver::Driver TheDriver(Args[0], llvm::sys::getDefaultTargetTriple(), *Diags,
-   "clang LLVM compiler", VFS);
+   "clang LLVM compiler", Opts.VFS);
 
   // Don't check that inputs exist, they may have been remapped.
   TheDriver.setCheckInputsExist(false);
@@ -81,7 +78,7 @@
 }
   }
 
-  bool PickFirstOfMany = OffloadCompilation || ShouldRecoverOnErorrs;
+  bool PickFirstOfMany = OffloadCompilation || Opts.RecoverOnError;
   if (Jobs.size() == 0 || (Jobs.size() > 1 && !PickFirstOfMany)) {
 SmallString<256> Msg;
 llvm::raw_svector_ostream OS(Msg);
@@ -98,11 +95,20 @@
   }
 
   const ArgStringList &CCArgs = Cmd->getArguments();
-  if (CC1Args)
-*CC1Args = {CCArgs.begin(), CCArgs.end()};
+  if (Opts.CC1Args)
+*Opts.CC1Args = {CCArgs.begin(), CCArgs.end()};
   auto CI = std::make_unique();
   if (!CompilerInvocation::CreateFromArgs(*CI, CCArgs, *Diags, Args[0]) &&
-  !ShouldRecoverOnErorrs)
+  !Opts.RecoverOnError)
 return nullptr;
   return CI;
 }
+
+std::unique_ptr clang::createInvocationFromCommandLine(
+ArrayRef Args, IntrusiveRefCntPtr Diags,
+IntrusiveRefCntPtr VFS, bool ShouldRecoverOnErrors,
+std::vector *CC1Args) {
+  return createInvocation(
+  Args,
+  CreateInvocationOptions{Diags, VFS, ShouldRecoverOnErrors, CC1Args});
+}
Index: clang/include/clang/Frontend/Utils.h
===
--- clang/include/clang/Frontend/Utils.h
+++ clang/include/clang/Frontend/Utils.h
@@ -22,7 +22,6 @@
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSet.h"
-#include "llvm/Option/OptSpecifier.h"
 #include "llvm/Support/FileCollector.h"
 #include "llvm/Support/VirtualFileSystem.h"
 #include 
@@ -190,18 +189,47 @@
 createChainedIncludesSource(CompilerInstance &CI,
 IntrusiveRefCntPtr &Reader);
 
-/// createInvocationFromCommandLine 

[PATCH] D124970: [Driver] Make "upgrade" of -include to include-pch optional; disable in clangd

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

Kadir, sending this your way as it looks like you investigated #856.

I do plan to flip the global default, but not for libclang and friends :-( I 
feel like a coward.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124970

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


[PATCH] D124970: [Driver] Make "upgrade" of -include to include-pch optional; disable in clangd

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

If clang is passed "-include foo.h", it will rewrite to "-include-pch foo.h.pch"
before passing it to cc1, if foo.h.pch exists.

Existence is checked, but validity is not. This is probably a reasonable
assumption for the compiler itself, but not for clang-based tools where the
actual compiler may be a different version of clang, or even GCC.
In the end, we lose our -include, we gain a -include-pch that can't be used,
and the file often fails to parse.

I would like to turn this off for all non-clang invocations (i.e.
createInvocationFromCommandLine), but we have explicit tests of this behavior
for libclang and I can't work out the implications of changing it.

Instead this patch:

- makes it optional in the driver, default on (no change)
- makes it optional in createInvocationFromCommandLine, default on (no change)
- changes driver to do IO through the VFS so it can be tested
- tests the option
- turns the option off in clangd where the problem was reported

Subsequent patches should make libclang opt in explicitly and flip the default
for all other tools. It's probably also time to extract an options struct
for createInvocationFromCommandLine.

Fixes https://github.com/clangd/clangd/issues/856
Fixes https://github.com/clangd/vscode-clangd/issues/324


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124970

Files:
  clang-tools-extra/clangd/Compiler.cpp
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Frontend/Utils.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
  clang/unittests/Frontend/UtilsTest.cpp

Index: clang/unittests/Frontend/UtilsTest.cpp
===
--- clang/unittests/Frontend/UtilsTest.cpp
+++ clang/unittests/Frontend/UtilsTest.cpp
@@ -11,12 +11,15 @@
 #include "clang/Basic/TargetOptions.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/Support/VirtualFileSystem.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace clang {
 namespace {
+using testing::ElementsAre;
 
 TEST(BuildCompilerInvocationTest, RecoverMultipleJobs) {
   // This generates multiple jobs and we recover by using the first.
@@ -33,5 +36,31 @@
   EXPECT_THAT(CI->TargetOpts->Triple, testing::StartsWith("i386-"));
 }
 
+// buildInvocationFromCommandLine should not translate -include to -include-pch,
+// even if the PCH file exists.
+TEST(BuildCompilerInvocationTest, ProbePrecompiled) {
+  std::vector Args = {"clang", "-include", "foo.h", "foo.cpp"};
+  auto FS = llvm::makeIntrusiveRefCnt();
+  FS->addFile("foo.h", 0, llvm::MemoryBuffer::getMemBuffer(""));
+  FS->addFile("foo.h.pch", 0, llvm::MemoryBuffer::getMemBuffer(""));
+
+  clang::IgnoringDiagConsumer D;
+  llvm::IntrusiveRefCntPtr CommandLineDiagsEngine =
+  clang::CompilerInstance::createDiagnostics(new DiagnosticOptions, &D,
+ false);
+  // Default: ProbePrecompiled is true.
+  std::unique_ptr CI = createInvocationFromCommandLine(
+  Args, CommandLineDiagsEngine, FS, false, nullptr);
+  ASSERT_TRUE(CI);
+  EXPECT_THAT(CI->getPreprocessorOpts().Includes, ElementsAre());
+  EXPECT_EQ(CI->getPreprocessorOpts().ImplicitPCHInclude, "foo.h.pch");
+
+  CI = createInvocationFromCommandLine(Args, CommandLineDiagsEngine, FS, false,
+   nullptr, /*ProbePrecompiled=*/false);
+  ASSERT_TRUE(CI);
+  EXPECT_THAT(CI->getPreprocessorOpts().Includes, ElementsAre("foo.h"));
+  EXPECT_EQ(CI->getPreprocessorOpts().ImplicitPCHInclude, "");
+}
+
 } // namespace
 } // namespace clang
Index: clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
===
--- clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
+++ clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
@@ -29,7 +29,7 @@
 std::unique_ptr clang::createInvocationFromCommandLine(
 ArrayRef ArgList, IntrusiveRefCntPtr Diags,
 IntrusiveRefCntPtr VFS, bool ShouldRecoverOnErorrs,
-std::vector *CC1Args) {
+std::vector *CC1Args, bool ProbePrecompiled) {
   assert(!ArgList.empty());
   if (!Diags.get()) {
 // No diagnostics engine was provided, so create our own diagnostics object
@@ -51,6 +51,9 @@
 
   // Don't check that inputs exist, they may have been remapped.
   TheDriver.setCheckInputsExist(false);
+  // Don't probe on the filesystem for PCHes of -include'd headers - we may have
+  // a VFS, they may be misversioned, etc.
+  TheDriver.setProb

[PATCH] D104975: Implement P1949

2022-05-04 Thread Ade Durcov via Phabricator via cfe-commits
intractabilis added a comment.

In D104975#3492099 , @tahonermann 
wrote:

> I am quite sure that gcc will also be implementing P1949 
>  as adopted for C++23.

Yes, you are right, it is available in GCC 12 
(https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100977).

Since it is a C++23 feature, can we at least have it only if the user requests 
C++23 standard compliance? Isn't it strange to force it upon users if they 
specify `-std=c++20`? I am going to check how GCC 12 behaves with this regard.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104975

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


[PATCH] D124943: [clang][dataflow] Add flowConditionIsTautology function

2022-05-04 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added a comment.
This revision is now accepted and ready to land.

The code looks good to me too. I was also wondering what sort of check will 
need this info.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124943

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


[PATCH] D124836: [AArch64] Add support for -fzero-call-used-regs

2022-05-04 Thread Bill Wendling via Phabricator via cfe-commits
void added inline comments.



Comment at: llvm/lib/Target/AArch64/AArch64RegisterInfo.td:1398
+ (sequence "W%u", 0, 7))>;
+def FPR8_ARG : RegisterClass<"AArch64", [untyped], 8, (trunc FPR8, 7)> {
+  let Size = 8;

sdesmalen wrote:
> Should this feature/attribute work with other calling conventions? If so, 
> then it's probably best not to hard-code these values here, but rather to get 
> them from the chosen calling convention for that particular function. The 
> supported calling conventions are defined in AArch64CallingConvention.td.
> 
> For example, you could iterate all registers in GPR64/FPR128/ZPR/PPR register 
> classes and zero their values if they are not marked as callee saved. You can 
> query this information from the call by looking at it's callee-saved regmask 
> (see for example `CSR_AArch64_AAPCS_RegMask` to see how those are defined 
> defined).
Ideally it could be retrieved from the `*CallingConvention.td` files, but in 
reality it's difficult because those files have a lot of `CCIf...<>` constructs 
in them, making a simple query complex.

I don't know about the `*_RegMask` thing. Could you explain what it is and how 
it works?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124836

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


[PATCH] D124932: [clang][dataflow] Track `optional` contents in `optional` model.

2022-05-04 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

Overall looks good to me. I am curious what will the strategy be to properly 
support construction. Do you plan to introduce a customization point to 
`Env.createValue` to give checks/models a way to set properties up? Or do you 
have something else in mind?




Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:219
+/// its location. Returns nullptr if the value can't be represented.
+StorageLocation *initializeUnwrappedValue(const Expr &Expr,
+  StructValue &OptionalVal,

I recall some problems with convergence due to creating fresh locations lazily 
in multiple branches. I wonder if doubling down before finding a proper 
solution could make it harder to fix this in the near future. If this is just a 
temporary solution until construction is better supported, it might be fine.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:286
   // Record that this unwrap is *not* provably safe.
   State.Lattice.getSourceLocations().insert(ObjectExpr->getBeginLoc());
 }

I wonder how well this strategy works in practice. If we have many `unwrap` 
calls to the same `optional`, we might end up emitting lots of diagnostics. An 
alternative approach is to assume that the `optional` has a value after the 
first unwrap. This would ensure that we only report a particular problem once 
and can reduce the noise.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124932

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


[PATCH] D124966: Thread safety analysis: Handle compound assignment and ->* overloads

2022-05-04 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a subscriber: rupprecht.
aaronpuchert added a comment.

@rupprecht, do you still do integration at Google? This patch might be 
interesting to try out, since it strengthens some warnings.




Comment at: clang/test/SemaCXX/warn-thread-safety-analysis.cpp:85-86
 
+template
+U& operator->*(const SmartPtr& ptr, U T::*p) { return ptr->*p; }
+

In case you're wondering, making this a member function prevents instantiating 
the class with non-class types:

```
error: member pointer refers into non-class type 'int'
  U& operator->*(U T::*p) const { return ptr_->*p; }
  ^
note: in instantiation of template class 'SmartPtr' requested here
SmartPtr p;
  ^
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124966

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


[PATCH] D124964: Revert "Revert "[clang][extract-api] Use relative includes""

2022-05-04 Thread Zixu Wang 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 rGcb5bb28511f2: Revert "Revert "[clang][extract-api] 
Use relative includes"" (authored by zixuw).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124964

Files:
  clang/include/clang/ExtractAPI/FrontendActions.h
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/test/ExtractAPI/known_files_only_hmap.c
  clang/test/ExtractAPI/relative_include.m

Index: clang/test/ExtractAPI/relative_include.m
===
--- /dev/null
+++ clang/test/ExtractAPI/relative_include.m
@@ -0,0 +1,193 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// Setup framework root
+// RUN: mkdir -p %t/Frameworks/MyFramework.framework/Headers
+// RUN: cp %t/MyFramework.h %t/Frameworks/MyFramework.framework/Headers/
+// RUN: cp %t/MyHeader.h %t/Frameworks/MyFramework.framework/Headers/
+
+// RUN: sed -e "s@SRCROOT@%{/t:regex_replacement}@g" \
+// RUN: %t/reference.output.json.in >> %t/reference.output.json
+
+// Headermap maps headers to the source root SRCROOT
+// RUN: sed -e "s@SRCROOT@%{/t:regex_replacement}@g" \
+// RUN: %t/headermap.hmap.json.in >> %t/headermap.hmap.json
+// RUN: %hmaptool write %t/headermap.hmap.json %t/headermap.hmap
+
+// Input headers use paths to the framework root/DSTROOT
+// RUN: %clang_cc1 -extract-api -v --product-name=MyFramework \
+// RUN: -triple arm64-apple-macosx \
+// RUN: -iquote%t -I%t/headermap.hmap -F%t/Frameworks \
+// RUN: -x objective-c-header \
+// RUN: %t/Frameworks/MyFramework.framework/Headers/MyFramework.h \
+// RUN: %t/Frameworks/MyFramework.framework/Headers/MyHeader.h \
+// RUN: %t/QuotedHeader.h \
+// RUN: -o %t/output.json 2>&1 -verify | FileCheck -allow-empty %s
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+// CHECK:  :
+// CHECK-NEXT: #import 
+// CHECK-NEXT: #import 
+// CHECK-NEXT: #import "QuotedHeader.h"
+
+//--- headermap.hmap.json.in
+{
+  "mappings" :
+{
+ "MyFramework/MyHeader.h" : "SRCROOT/MyHeader.h"
+}
+}
+
+//--- MyFramework.h
+// Umbrella for MyFramework
+#import 
+// expected-no-diagnostics
+
+//--- MyHeader.h
+#import 
+int MyInt;
+// expected-no-diagnostics
+
+//--- QuotedHeader.h
+char MyChar;
+// expected-no-diagnostics
+
+//--- Frameworks/OtherFramework.framework/Headers/OtherHeader.h
+int OtherInt;
+// expected-no-diagnostics
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "MyFramework",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationships": [],
+  "symbols": [
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:I",
+  "spelling": "int"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "MyInt"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:@MyInt"
+  },
+  "kind": {
+"displayName": "Global Variable",
+"identifier": "objective-c.var"
+  },
+  "location": {
+"position": {
+  "character": 5,
+  "line": 2
+},
+"uri": "file://SRCROOT/MyHeader.h"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "MyInt"
+  }
+],
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "MyInt"
+  }
+],
+"title": "MyInt"
+  },
+  "pathComponents": [
+"MyInt"
+  ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:C",
+  "spelling": "char"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "MyChar"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:@MyChar"
+  },
+  "kind": {
+"displayName": "Global Variable",
+"identifier": "objective-c.var"
+  },
+  "location": {
+

[clang] cb5bb28 - Revert "Revert "[clang][extract-api] Use relative includes""

2022-05-04 Thread Zixu Wang via cfe-commits

Author: Zixu Wang
Date: 2022-05-04T14:52:45-07:00
New Revision: cb5bb28511f2c7530806af7ef53696deed453ca1

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

LOG: Revert "Revert "[clang][extract-api] Use relative includes""

Reapply the change after fixing sanitizer errors.
The original problem was that `StringRef`s in `Matches` are pointing to
temporary local `std::string`s created by `path::convert_to_slash` in
the regex match call. This patch does the conversion up front in
container `FilePath`.

This reverts commit 2966f0fa505266735dbc8324b8821b7f0aa901ff.

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

Added: 
clang/test/ExtractAPI/relative_include.m

Modified: 
clang/include/clang/ExtractAPI/FrontendActions.h
clang/lib/ExtractAPI/ExtractAPIConsumer.cpp

Removed: 
clang/test/ExtractAPI/known_files_only_hmap.c



diff  --git a/clang/include/clang/ExtractAPI/FrontendActions.h 
b/clang/include/clang/ExtractAPI/FrontendActions.h
index dec3b5ca93d18d..2cb8ef130fdd77 100644
--- a/clang/include/clang/ExtractAPI/FrontendActions.h
+++ b/clang/include/clang/ExtractAPI/FrontendActions.h
@@ -40,7 +40,10 @@ class ExtractAPIAction : public ASTFrontendAction {
   std::unique_ptr Buffer;
 
   /// The input file originally provided on the command line.
-  std::vector KnownInputFiles;
+  ///
+  /// This captures the spelling used to include the file and whether the
+  /// include is quoted or not.
+  SmallVector, bool>> KnownInputFiles;
 
   /// Prepare to execute the action on the given CompilerInstance.
   ///

diff  --git a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp 
b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
index b1de2674b622b1..70c8bac59ce978 100644
--- a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
+++ b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
@@ -38,7 +38,10 @@
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Regex.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -55,10 +58,125 @@ StringRef getTypedefName(const TagDecl *Decl) {
   return {};
 }
 
+Optional getRelativeIncludeName(const CompilerInstance &CI,
+ StringRef File,
+ bool *IsQuoted = nullptr) {
+  assert(CI.hasFileManager() &&
+ "CompilerInstance does not have a FileNamager!");
+
+  using namespace llvm::sys;
+  // Matches framework include patterns
+  const llvm::Regex Rule("/(.+)\\.framework/(.+)?Headers/(.+)");
+
+  const auto &FS = CI.getVirtualFileSystem();
+
+  SmallString<128> FilePath(File.begin(), File.end());
+  FS.makeAbsolute(FilePath);
+  path::remove_dots(FilePath, true);
+  FilePath = path::convert_to_slash(FilePath);
+  File = FilePath;
+
+  // Checks whether `Dir` is a strict path prefix of `File`. If so returns
+  // the prefix length. Otherwise return 0.
+  auto CheckDir = [&](llvm::StringRef Dir) -> unsigned {
+llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
+FS.makeAbsolute(DirPath);
+path::remove_dots(DirPath, true);
+Dir = DirPath;
+for (auto NI = path::begin(File), NE = path::end(File),
+  DI = path::begin(Dir), DE = path::end(Dir);
+ /*termination condition in loop*/; ++NI, ++DI) {
+  // '.' components in File are ignored.
+  while (NI != NE && *NI == ".")
+++NI;
+  if (NI == NE)
+break;
+
+  // '.' components in Dir are ignored.
+  while (DI != DE && *DI == ".")
+++DI;
+
+  // Dir is a prefix of File, up to '.' components and choice of path
+  // separators.
+  if (DI == DE)
+return NI - path::begin(File);
+
+  // Consider all path separators equal.
+  if (NI->size() == 1 && DI->size() == 1 &&
+  path::is_separator(NI->front()) && path::is_separator(DI->front()))
+continue;
+
+  // Special case Apple .sdk folders since the search path is typically a
+  // symlink like `iPhoneSimulator14.5.sdk` while the file is instead
+  // located in `iPhoneSimulator.sdk` (the real folder).
+  if (NI->endswith(".sdk") && DI->endswith(".sdk")) {
+StringRef NBasename = path::stem(*NI);
+StringRef DBasename = path::stem(*DI);
+if (DBasename.startswith(NBasename))
+  continue;
+  }
+
+  if (*NI != *DI)
+break;
+}
+return 0;
+  };
+
+  unsigned PrefixLength = 0;
+
+  // Go through the search paths and find the first one that is a prefix of
+  // the header.
+  for (const auto &Entry : CI.getHeaderSearchOpts().UserEntries) {
+// Note whether the match is found in a quoted entry.
+if (IsQuoted)
+  

[PATCH] D124964: Revert "Revert "[clang][extract-api] Use relative includes""

2022-05-04 Thread Zixu Wang via Phabricator via cfe-commits
zixuw added a comment.

In D124964#3492423 , @dang wrote:

> LGTM! If I understand the issue correctly we gave `llvm::Regex::match` a 
> string temporary to match against before and now we store it for long enough 
> to process the match results?

Yup, exactly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124964

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


[PATCH] D124964: Revert "Revert "[clang][extract-api] Use relative includes""

2022-05-04 Thread Daniel Grumberg via Phabricator via cfe-commits
dang accepted this revision.
dang added a comment.
This revision is now accepted and ready to land.

LGTM! If I understand the issue correctly we gave `llvm::Regex::match` a string 
temporary to match against before and now we store it for long enough to 
process the match results?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124964

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


[PATCH] D124966: Thread safety analysis: Handle compound assignment and ->* overloads

2022-05-04 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert created this revision.
aaronpuchert added reviewers: aaron.ballman, delesley.
Herald added a project: All.
aaronpuchert requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Like regular assignment, compound assignment operators can be assumed to
write to their left-hand side operand. So we strengthen the requirements
there. (Previously only the default read access had been required.)

Just like operator->, operator->* can also be assumed to dereference the
left-hand side argument, so we require read access to the pointee. This
will generate new warnings if the left-hand side has a pt_guarded_by
attribute. This overload is rarely used, but it was trivial to add, so
why not. (Supporting the builtin operator requires changes to the TIL.)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124966

Files:
  clang/lib/Analysis/ThreadSafety.cpp
  clang/test/SemaCXX/warn-thread-safety-analysis.cpp


Index: clang/test/SemaCXX/warn-thread-safety-analysis.cpp
===
--- clang/test/SemaCXX/warn-thread-safety-analysis.cpp
+++ clang/test/SemaCXX/warn-thread-safety-analysis.cpp
@@ -82,6 +82,9 @@
   T* ptr_;
 };
 
+template
+U& operator->*(const SmartPtr& ptr, U T::*p) { return ptr->*p; }
+
 
 // For testing destructor calls and cleanup.
 class MyString {
@@ -4338,6 +4341,8 @@
 
   void operator()() { }
 
+  Data& operator+=(int);
+
 private:
   int dat;
 };
@@ -4404,6 +4409,7 @@
   // expected-warning {{reading variable 'datap1_' 
requires holding mutex 'mu_'}}
 data_ = *datap2_; // expected-warning {{writing variable 'data_' 
requires holding mutex 'mu_' exclusively}} \
   // expected-warning {{reading the value pointed to 
by 'datap2_' requires holding mutex 'mu_'}}
+data_ += 0;   // expected-warning {{writing variable 'data_' 
requires holding mutex 'mu_' exclusively}}
 
 data_[0] = 0; // expected-warning {{reading variable 'data_' 
requires holding mutex 'mu_'}}
 (*datap2_)[0] = 0;// expected-warning {{reading the value pointed to 
by 'datap2_' requires holding mutex 'mu_'}}
@@ -4923,6 +4929,8 @@
   SmartPtr  sp GUARDED_BY(mu1) PT_GUARDED_BY(mu2);
   SmartPtr sq GUARDED_BY(mu1) PT_GUARDED_BY(mu2);
 
+  static constexpr int Cell::*pa = &Cell::a;
+
   void test1() {
 mu1.ReaderLock();
 mu2.Lock();
@@ -4931,6 +4939,7 @@
 if (*sp == 0) doSomething();
 *sp = 0;
 sq->a = 0;
+sq->*pa = 0;
 
 if (sp[0] == 0) doSomething();
 sp[0] = 0;
@@ -4946,6 +4955,7 @@
 if (*sp == 0) doSomething();   // expected-warning {{reading variable 'sp' 
requires holding mutex 'mu1'}}
 *sp = 0;   // expected-warning {{reading variable 'sp' 
requires holding mutex 'mu1'}}
 sq->a = 0; // expected-warning {{reading variable 'sq' 
requires holding mutex 'mu1'}}
+sq->*pa = 0;   // expected-warning {{reading variable 'sq' 
requires holding mutex 'mu1'}}
 
 if (sp[0] == 0) doSomething();   // expected-warning {{reading variable 
'sp' requires holding mutex 'mu1'}}
 sp[0] = 0;   // expected-warning {{reading variable 
'sp' requires holding mutex 'mu1'}}
@@ -4962,6 +4972,7 @@
 if (*sp == 0) doSomething();   // expected-warning {{reading the value 
pointed to by 'sp' requires holding mutex 'mu2'}}
 *sp = 0;   // expected-warning {{reading the value 
pointed to by 'sp' requires holding mutex 'mu2'}}
 sq->a = 0; // expected-warning {{reading the value 
pointed to by 'sq' requires holding mutex 'mu2'}}
+sq->*pa = 0;   // expected-warning {{reading the value 
pointed to by 'sq' requires holding mutex 'mu2'}}
 
 if (sp[0] == 0) doSomething();   // expected-warning {{reading the value 
pointed to by 'sp' requires holding mutex 'mu2'}}
 sp[0] = 0;   // expected-warning {{reading the value 
pointed to by 'sp' requires holding mutex 'mu2'}}
Index: clang/lib/Analysis/ThreadSafety.cpp
===
--- clang/lib/Analysis/ThreadSafety.cpp
+++ clang/lib/Analysis/ThreadSafety.cpp
@@ -1990,7 +1990,17 @@
   } else if (const auto *OE = dyn_cast(Exp)) {
 auto OEop = OE->getOperator();
 switch (OEop) {
-  case OO_Equal: {
+  case OO_Equal:
+  case OO_PlusEqual:
+  case OO_MinusEqual:
+  case OO_StarEqual:
+  case OO_SlashEqual:
+  case OO_PercentEqual:
+  case OO_CaretEqual:
+  case OO_AmpEqual:
+  case OO_PipeEqual:
+  case OO_LessLessEqual:
+  case OO_GreaterGreaterEqual: {
 const Expr *Target = OE->getArg(0);
 const Expr *Source = OE->getArg(1);
 checkAccess(Target, AK_Written);
@@ -1998,6 +2008,7 @@
 break;
   }
   case OO_Star:
+  case OO_ArrowStar:
   case OO_A

[PATCH] D124965: [clang][dataflow] Centralize expression skipping logic

2022-05-04 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua created this revision.
li.zhe.hua added reviewers: sgatev, ymandel.
Herald added subscribers: tschuett, steakhal.
Herald added a project: All.
li.zhe.hua requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

A follow-up to 62b2a47 
 to 
centralize the logic that skips expressions
that the CFG does not emit. This allows client code to avoid
sprinkling this logic everywhere.

Add redirects in the transfer function to similarly skip such
expressions by forwarding the visit to the sub-expression.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124965

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/Transfer.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -46,7 +46,7 @@
   : CFCtx(CFCtx), BlockToState(BlockToState) {}
 
   const Environment *getEnvironment(const Stmt &S) const override {
-auto BlockIT = CFCtx.getStmtToBlock().find(&S);
+auto BlockIT = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));
 assert(BlockIT != CFCtx.getStmtToBlock().end());
 const auto &State = BlockToState[BlockIT->getSecond()->getBlockID()];
 assert(State.hasValue());
@@ -77,26 +77,26 @@
   : StmtToEnv(StmtToEnv), Env(Env), BlockSuccIdx(BlockSuccIdx) {}
 
   void VisitIfStmt(const IfStmt *S) {
-auto *Cond = ignoreExprWithCleanups(S->getCond())->IgnoreParens();
+auto *Cond = S->getCond();
 assert(Cond != nullptr);
 extendFlowCondition(*Cond);
   }
 
   void VisitWhileStmt(const WhileStmt *S) {
-auto *Cond = ignoreExprWithCleanups(S->getCond())->IgnoreParens();
+auto *Cond = S->getCond();
 assert(Cond != nullptr);
 extendFlowCondition(*Cond);
   }
 
   void VisitBinaryOperator(const BinaryOperator *S) {
 assert(S->getOpcode() == BO_LAnd || S->getOpcode() == BO_LOr);
-auto *LHS = ignoreExprWithCleanups(S->getLHS())->IgnoreParens();
+auto *LHS = S->getLHS();
 assert(LHS != nullptr);
 extendFlowCondition(*LHS);
   }
 
   void VisitConditionalOperator(const ConditionalOperator *S) {
-auto *Cond = ignoreExprWithCleanups(S->getCond())->IgnoreParens();
+auto *Cond = S->getCond();
 assert(Cond != nullptr);
 extendFlowCondition(*Cond);
   }
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -33,27 +33,12 @@
 namespace clang {
 namespace dataflow {
 
-const Expr *ignoreExprWithCleanups(const Expr *E) {
-  if (auto *C = dyn_cast_or_null(E))
-return C->getSubExpr();
-  return E;
-}
-
 static BoolValue &evaluateBooleanEquality(const Expr &LHS, const Expr &RHS,
   Environment &Env) {
-  // Equality of booleans involves implicit integral casts. Ignore these casts
-  // for now and focus on the values associated with the wrapped expressions.
-  // FIXME: Consider changing this once the framework offers better support for
-  // integral casts.
-  const Expr *LHSNorm = LHS.IgnoreCasts();
-  const Expr *RHSNorm = RHS.IgnoreCasts();
-  assert(LHSNorm != nullptr);
-  assert(RHSNorm != nullptr);
-
-  if (auto *LHSValue = dyn_cast_or_null(
-  Env.getValue(*LHSNorm, SkipPast::Reference)))
-if (auto *RHSValue = dyn_cast_or_null(
-Env.getValue(*RHSNorm, SkipPast::Reference)))
+  if (auto *LHSValue =
+  dyn_cast_or_null(Env.getValue(LHS, SkipPast::Reference)))
+if (auto *RHSValue =
+dyn_cast_or_null(Env.getValue(RHS, SkipPast::Reference)))
   return Env.makeIff(*LHSValue, *RHSValue);
 
   return Env.makeAtomicBoolValue();
@@ -65,14 +50,10 @@
   : StmtToEnv(StmtToEnv), Env(Env) {}
 
   void VisitBinaryOperator(const BinaryOperator *S) {
-// The CFG does not contain `ParenExpr` as top-level statements in basic
-// blocks, however sub-expressions can still be of that type.
-assert(S->getLHS() != nullptr);
-const Expr *LHS = S->getLHS()->IgnoreParens();
+const Expr *LHS = S->getLHS();
 assert(LHS != nullptr);
 
-assert(S->getRHS() != nullptr);
-const Expr *RHS = S->getRHS()->IgnoreParens();
+const Expr *RHS = S->getRHS();
 assert(RHS != nullptr);
 
 switch (S->getOpcode()) {
@@ -155,7 +136,7 @@
   retur

[PATCH] D124964: Revert "Revert "[clang][extract-api] Use relative includes""

2022-05-04 Thread Zixu Wang via Phabricator via cfe-commits
zixuw updated this revision to Diff 427140.
zixuw added a comment.

Whitespace change: clang-format removed an empty line


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124964

Files:
  clang/include/clang/ExtractAPI/FrontendActions.h
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/test/ExtractAPI/known_files_only_hmap.c
  clang/test/ExtractAPI/relative_include.m

Index: clang/test/ExtractAPI/relative_include.m
===
--- /dev/null
+++ clang/test/ExtractAPI/relative_include.m
@@ -0,0 +1,193 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// Setup framework root
+// RUN: mkdir -p %t/Frameworks/MyFramework.framework/Headers
+// RUN: cp %t/MyFramework.h %t/Frameworks/MyFramework.framework/Headers/
+// RUN: cp %t/MyHeader.h %t/Frameworks/MyFramework.framework/Headers/
+
+// RUN: sed -e "s@SRCROOT@%{/t:regex_replacement}@g" \
+// RUN: %t/reference.output.json.in >> %t/reference.output.json
+
+// Headermap maps headers to the source root SRCROOT
+// RUN: sed -e "s@SRCROOT@%{/t:regex_replacement}@g" \
+// RUN: %t/headermap.hmap.json.in >> %t/headermap.hmap.json
+// RUN: %hmaptool write %t/headermap.hmap.json %t/headermap.hmap
+
+// Input headers use paths to the framework root/DSTROOT
+// RUN: %clang_cc1 -extract-api -v --product-name=MyFramework \
+// RUN: -triple arm64-apple-macosx \
+// RUN: -iquote%t -I%t/headermap.hmap -F%t/Frameworks \
+// RUN: -x objective-c-header \
+// RUN: %t/Frameworks/MyFramework.framework/Headers/MyFramework.h \
+// RUN: %t/Frameworks/MyFramework.framework/Headers/MyHeader.h \
+// RUN: %t/QuotedHeader.h \
+// RUN: -o %t/output.json 2>&1 -verify | FileCheck -allow-empty %s
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+// CHECK:  :
+// CHECK-NEXT: #import 
+// CHECK-NEXT: #import 
+// CHECK-NEXT: #import "QuotedHeader.h"
+
+//--- headermap.hmap.json.in
+{
+  "mappings" :
+{
+ "MyFramework/MyHeader.h" : "SRCROOT/MyHeader.h"
+}
+}
+
+//--- MyFramework.h
+// Umbrella for MyFramework
+#import 
+// expected-no-diagnostics
+
+//--- MyHeader.h
+#import 
+int MyInt;
+// expected-no-diagnostics
+
+//--- QuotedHeader.h
+char MyChar;
+// expected-no-diagnostics
+
+//--- Frameworks/OtherFramework.framework/Headers/OtherHeader.h
+int OtherInt;
+// expected-no-diagnostics
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "MyFramework",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationships": [],
+  "symbols": [
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:I",
+  "spelling": "int"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "MyInt"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:@MyInt"
+  },
+  "kind": {
+"displayName": "Global Variable",
+"identifier": "objective-c.var"
+  },
+  "location": {
+"position": {
+  "character": 5,
+  "line": 2
+},
+"uri": "file://SRCROOT/MyHeader.h"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "MyInt"
+  }
+],
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "MyInt"
+  }
+],
+"title": "MyInt"
+  },
+  "pathComponents": [
+"MyInt"
+  ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:C",
+  "spelling": "char"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "MyChar"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:@MyChar"
+  },
+  "kind": {
+"displayName": "Global Variable",
+"identifier": "objective-c.var"
+  },
+  "location": {
+"position": {
+  "character": 6,
+  "line": 1
+},
+"uri": "file://SRCROOT/QuotedHeader.h"
+

[PATCH] D124964: Revert "Revert "[clang][extract-api] Use relative includes""

2022-05-04 Thread Zixu Wang via Phabricator via cfe-commits
zixuw created this revision.
zixuw added reviewers: ributzka, dang, cishida.
Herald added a project: All.
zixuw requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Reapply the change after fixing sanitizer errors.
The original problem was that `StringRef`s in `Matches` are pointing to
temporary local `std::string`s created by `path::convert_to_slash` in
the regex match call. This patch does the conversion up front in
container `FilePath`.

This reverts commit 2966f0fa505266735dbc8324b8821b7f0aa901ff 
.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124964

Files:
  clang/include/clang/ExtractAPI/FrontendActions.h
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/test/ExtractAPI/known_files_only_hmap.c
  clang/test/ExtractAPI/relative_include.m

Index: clang/test/ExtractAPI/relative_include.m
===
--- /dev/null
+++ clang/test/ExtractAPI/relative_include.m
@@ -0,0 +1,193 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// Setup framework root
+// RUN: mkdir -p %t/Frameworks/MyFramework.framework/Headers
+// RUN: cp %t/MyFramework.h %t/Frameworks/MyFramework.framework/Headers/
+// RUN: cp %t/MyHeader.h %t/Frameworks/MyFramework.framework/Headers/
+
+// RUN: sed -e "s@SRCROOT@%{/t:regex_replacement}@g" \
+// RUN: %t/reference.output.json.in >> %t/reference.output.json
+
+// Headermap maps headers to the source root SRCROOT
+// RUN: sed -e "s@SRCROOT@%{/t:regex_replacement}@g" \
+// RUN: %t/headermap.hmap.json.in >> %t/headermap.hmap.json
+// RUN: %hmaptool write %t/headermap.hmap.json %t/headermap.hmap
+
+// Input headers use paths to the framework root/DSTROOT
+// RUN: %clang_cc1 -extract-api -v --product-name=MyFramework \
+// RUN: -triple arm64-apple-macosx \
+// RUN: -iquote%t -I%t/headermap.hmap -F%t/Frameworks \
+// RUN: -x objective-c-header \
+// RUN: %t/Frameworks/MyFramework.framework/Headers/MyFramework.h \
+// RUN: %t/Frameworks/MyFramework.framework/Headers/MyHeader.h \
+// RUN: %t/QuotedHeader.h \
+// RUN: -o %t/output.json 2>&1 -verify | FileCheck -allow-empty %s
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+// CHECK:  :
+// CHECK-NEXT: #import 
+// CHECK-NEXT: #import 
+// CHECK-NEXT: #import "QuotedHeader.h"
+
+//--- headermap.hmap.json.in
+{
+  "mappings" :
+{
+ "MyFramework/MyHeader.h" : "SRCROOT/MyHeader.h"
+}
+}
+
+//--- MyFramework.h
+// Umbrella for MyFramework
+#import 
+// expected-no-diagnostics
+
+//--- MyHeader.h
+#import 
+int MyInt;
+// expected-no-diagnostics
+
+//--- QuotedHeader.h
+char MyChar;
+// expected-no-diagnostics
+
+//--- Frameworks/OtherFramework.framework/Headers/OtherHeader.h
+int OtherInt;
+// expected-no-diagnostics
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "MyFramework",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationships": [],
+  "symbols": [
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:I",
+  "spelling": "int"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "MyInt"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:@MyInt"
+  },
+  "kind": {
+"displayName": "Global Variable",
+"identifier": "objective-c.var"
+  },
+  "location": {
+"position": {
+  "character": 5,
+  "line": 2
+},
+"uri": "file://SRCROOT/MyHeader.h"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "MyInt"
+  }
+],
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "MyInt"
+  }
+],
+"title": "MyInt"
+  },
+  "pathComponents": [
+"MyInt"
+  ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:C",
+  "spelling": "char"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind"

[PATCH] D124956: [clang-format] Fix another bug in AlignConsecutiveAssignments

2022-05-04 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

Just one last thought, shouldn't we have a test case close to what was reported 
in the issue? I.e. with PP directives.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124956

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


[PATCH] D124956: [clang-format] Fix another bug in AlignConsecutiveAssignments

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

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124956

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


[PATCH] D124952: [clang-tidy] Escape diagnostic messages before passing to `diag` in Transformer.

2022-05-04 Thread Yitzhak Mandelbaum 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 rG9a8d33dbd8a8: [clang-tidy] Escape diagnostic messages before 
passing to `diag` in Transformer. (authored by ymandel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124952

Files:
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp


Index: clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -90,6 +90,27 @@
   EXPECT_EQ(Errors[0].Message.FileOffset, 10U);
 }
 
+TEST(TransformerClangTidyCheckTest, DiagnosticMessageEscaped) {
+  class GiveDiagWithPercentSymbol : public TransformerClangTidyCheck {
+  public:
+GiveDiagWithPercentSymbol(StringRef Name, ClangTidyContext *Context)
+: TransformerClangTidyCheck(makeRule(returnStmt(),
+ noopEdit(node(RootID)),
+ cat("bad code: x % y % z")),
+Name, Context) {}
+  };
+  std::string Input = "int somecode() { return 0; }";
+  std::vector Errors;
+  EXPECT_EQ(Input,
+test::runCheckOnCode(Input, &Errors));
+  ASSERT_EQ(Errors.size(), 1U);
+  // The message stored in this field shouldn't include escaped percent signs,
+  // because the diagnostic printer should have _unescaped_ them when 
processing
+  // the diagnostic. The only behavior observable/verifiable by the test is 
that
+  // the presence of the '%' doesn't crash Clang.
+  EXPECT_EQ(Errors[0].Message.Message, "bad code: x % y % z");
+}
+
 class IntLitCheck : public TransformerClangTidyCheck {
 public:
   IntLitCheck(StringRef Name, ClangTidyContext *Context)
Index: clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
@@ -27,6 +27,33 @@
  " explicitly provide an empty explanation if none is desired");
 }
 
+// If a string unintentionally containing '%' is passed as a diagnostic, Clang
+// will claim the string is ill-formed and assert-fail. This function escapes
+// such strings so they can be safely used in diagnostics.
+std::string escapeForDiagnostic(std::string ToEscape) {
+  // Optimize for the common case that the string does not contain `%` at the
+  // cost of an extra scan over the string in the slow case.
+  auto Pos = ToEscape.find('%');
+  if (Pos == ToEscape.npos)
+return ToEscape;
+
+  std::string Result;
+  Result.reserve(ToEscape.size());
+  // Convert position to a count.
+  ++Pos;
+  Result.append(ToEscape, 0, Pos);
+  Result += '%';
+
+  for (auto N = ToEscape.size(); Pos < N; ++Pos) {
+const char C = ToEscape.at(Pos);
+Result += C;
+if (C == '%')
+  Result += '%';
+  }
+
+  return Result;
+}
+
 TransformerClangTidyCheck::TransformerClangTidyCheck(StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
@@ -99,7 +126,8 @@
   }
 
   // Associate the diagnostic with the location of the first change.
-  DiagnosticBuilder Diag = diag((*Edits)[0].Range.getBegin(), *Explanation);
+  DiagnosticBuilder Diag =
+  diag((*Edits)[0].Range.getBegin(), escapeForDiagnostic(*Explanation));
   for (const auto &T : *Edits)
 switch (T.Kind) {
 case transformer::EditKind::Range:


Index: clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -90,6 +90,27 @@
   EXPECT_EQ(Errors[0].Message.FileOffset, 10U);
 }
 
+TEST(TransformerClangTidyCheckTest, DiagnosticMessageEscaped) {
+  class GiveDiagWithPercentSymbol : public TransformerClangTidyCheck {
+  public:
+GiveDiagWithPercentSymbol(StringRef Name, ClangTidyContext *Context)
+: TransformerClangTidyCheck(makeRule(returnStmt(),
+ noopEdit(node(RootID)),
+ cat("bad code: x % y % z")),
+Name, Context) {}
+  };
+  std::string Input = "int somecode() { return 0; }";
+  std::vector Errors;
+  EXPECT_EQ(Input,
+test::runCheckOnCode(Input, &Errors));
+  ASSERT_EQ(Errors.size(), 1U);
+  // The message stored in this field shouldn't include escaped percent 

[clang-tools-extra] 9a8d33d - [clang-tidy] Escape diagnostic messages before passing to `diag` in Transformer.

2022-05-04 Thread Yitzhak Mandelbaum via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2022-05-04T20:56:56Z
New Revision: 9a8d33dbd8a851ccb9821d5d1346aa225398cadc

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

LOG: [clang-tidy] Escape diagnostic messages before passing to `diag` in 
Transformer.

Messages generated by Transformer rules may have `%` in them, which
needs to be escaped before being passed to `diag`, which interprets them
specially (and crashes if they are misused).

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
index b8b2c253aa4920..bd76e67f12c85d 100644
--- a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
@@ -27,6 +27,33 @@ static void verifyRule(const RewriteRuleWith 
&Rule) {
  " explicitly provide an empty explanation if none is desired");
 }
 
+// If a string unintentionally containing '%' is passed as a diagnostic, Clang
+// will claim the string is ill-formed and assert-fail. This function escapes
+// such strings so they can be safely used in diagnostics.
+std::string escapeForDiagnostic(std::string ToEscape) {
+  // Optimize for the common case that the string does not contain `%` at the
+  // cost of an extra scan over the string in the slow case.
+  auto Pos = ToEscape.find('%');
+  if (Pos == ToEscape.npos)
+return ToEscape;
+
+  std::string Result;
+  Result.reserve(ToEscape.size());
+  // Convert position to a count.
+  ++Pos;
+  Result.append(ToEscape, 0, Pos);
+  Result += '%';
+
+  for (auto N = ToEscape.size(); Pos < N; ++Pos) {
+const char C = ToEscape.at(Pos);
+Result += C;
+if (C == '%')
+  Result += '%';
+  }
+
+  return Result;
+}
+
 TransformerClangTidyCheck::TransformerClangTidyCheck(StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
@@ -99,7 +126,8 @@ void TransformerClangTidyCheck::check(
   }
 
   // Associate the diagnostic with the location of the first change.
-  DiagnosticBuilder Diag = diag((*Edits)[0].Range.getBegin(), *Explanation);
+  DiagnosticBuilder Diag =
+  diag((*Edits)[0].Range.getBegin(), escapeForDiagnostic(*Explanation));
   for (const auto &T : *Edits)
 switch (T.Kind) {
 case transformer::EditKind::Range:

diff  --git 
a/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp 
b/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
index 832b8b86e12669..a3600ab58ff3fe 100644
--- a/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -90,6 +90,27 @@ TEST(TransformerClangTidyCheckTest, 
DiagnosticsCorrectlyGenerated) {
   EXPECT_EQ(Errors[0].Message.FileOffset, 10U);
 }
 
+TEST(TransformerClangTidyCheckTest, DiagnosticMessageEscaped) {
+  class GiveDiagWithPercentSymbol : public TransformerClangTidyCheck {
+  public:
+GiveDiagWithPercentSymbol(StringRef Name, ClangTidyContext *Context)
+: TransformerClangTidyCheck(makeRule(returnStmt(),
+ noopEdit(node(RootID)),
+ cat("bad code: x % y % z")),
+Name, Context) {}
+  };
+  std::string Input = "int somecode() { return 0; }";
+  std::vector Errors;
+  EXPECT_EQ(Input,
+test::runCheckOnCode(Input, &Errors));
+  ASSERT_EQ(Errors.size(), 1U);
+  // The message stored in this field shouldn't include escaped percent signs,
+  // because the diagnostic printer should have _unescaped_ them when 
processing
+  // the diagnostic. The only behavior observable/verifiable by the test is 
that
+  // the presence of the '%' doesn't crash Clang.
+  EXPECT_EQ(Errors[0].Message.Message, "bad code: x % y % z");
+}
+
 class IntLitCheck : public TransformerClangTidyCheck {
 public:
   IntLitCheck(StringRef Name, ClangTidyContext *Context)



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


[PATCH] D124702: [MSVC] Add support for pragma function

2022-05-04 Thread Stephen Long via Phabricator via cfe-commits
steplong updated this revision to Diff 427127.
steplong added a comment.

Error if pragma function/intrinsic is used inside a function


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124702

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/CodeGen/pragma-ms-function-intrinsic.c

Index: clang/test/CodeGen/pragma-ms-function-intrinsic.c
===
--- /dev/null
+++ clang/test/CodeGen/pragma-ms-function-intrinsic.c
@@ -0,0 +1,78 @@
+// RUN: %clang_cc1 -emit-llvm -fms-extensions -o - %s | FileCheck %s
+
+typedef typeof(sizeof(0)) size_t;
+
+void bar(char *s);
+void *memset(void *s, int c, size_t n);
+void *memcpy(void *d, const void *s, size_t n);
+
+// CHECK: define{{.*}} void @foo1({{.*}}) #[[NO_NOBUILTIN:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   call void @llvm.memset
+// CHECK:   call void @llvm.memcpy
+void foo1(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 0, n);
+memcpy(d, s, n);
+}
+
+#pragma function(strlen, memset)
+
+// CHECK: define{{.*}} void @foo2({{.*}}) #[[NOBUILTIN_MEMSET:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call {{.*}} @memset
+// CHECK:   call void @llvm.memcpy
+void foo2(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 1, n);
+memcpy(d, s, n);
+}
+
+#pragma function(memcpy)
+
+// CHECK: define{{.*}} void @foo3({{.*}}) #[[NOBUILTIN_MEMSET_MEMCPY:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call {{.*}} @memset
+// CHECK:   {{.*}}call {{.*}} @memcpy
+void foo3(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 2, n);
+memcpy(d, s, n);
+}
+
+#pragma intrinsic(memset, strlen)
+
+// CHECK: define{{.*}} void @foo4({{.*}}) #[[NOBUILTIN_MEMCPY:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   call void @llvm.memset
+// CHECK:   {{.*}}call {{.*}} @memcpy
+void foo4(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 3, n);
+memcpy(d, s, n);
+}
+
+#pragma intrinsic(memcpy)
+
+// CHECK: define{{.*}} void @foo5({{.*}}) #[[NO_NOBUILTIN]]
+// CHECK:   call void @bar
+// CHECK:   call void @llvm.memset
+// CHECK:   call void @llvm.memcpy
+void foo5(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 4, n);
+memcpy(d, s, n);
+}
+
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK-NOT: attributes #[[NOBUILTIN_MEMSET]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET_MEMCPY]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMCPY]] = {{{.*}}"no-builtin-memcpy"{{.*}}}
+// CHECK-NOT: attributes #[[NOBUILTIN_MEMCPY]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -10218,10 +10218,12 @@
   // marking the function.
   AddCFAuditedAttribute(NewFD);
 
-  // If this is a function definition, check if we have to apply optnone due to
-  // a pragma.
-  if(D.isFunctionDefinition())
+  // If this is a function definition, check if we have to apply any
+  // attributes (i.e. optnone and no_builtin) due to a pragma.
+  if(D.isFunctionDefinition()) {
 AddRangeBasedOptnone(NewFD);
+AddRangeBasedNoBuiltin(NewFD);
+  }
 
   // If this is the first declaration of an extern C variable, update
   // the map of such variables.
Index: clang/lib/Sema/SemaAttr.cpp
===
--- clang/lib/Sema/SemaAttr.cpp
+++ clang/lib/Sema/SemaAttr.cpp
@@ -1065,6 +1065,31 @@
 OptimizeOffPragmaLocation = PragmaLoc;
 }
 
+void Sema::ActOnPragmaMSIntrinsic(
+SourceLocation Loc, const SmallVectorImpl &Intrinsics) {
+  if (!CurContext->getRedeclContext()->isFileContext()) {
+Diag(Loc, diag::err_pragma_intrinsic_function_scope);
+return;
+  }
+
+  for (auto &Intrinsic : Intrinsics)
+MSFunctionNoBuiltins.erase(std::remove(MSFunctionNoBuiltins.begin(),
+   MSFunctionNoBuiltins.end(),
+   Intrinsic),
+   MSFunctionNoBuiltins.end());
+}
+
+void Sema::ActOnPragmaMSFunction(SourceLocation Loc,
+ const SmallVectorImpl &NoBuiltins) {
+  if (!CurContext->getRedeclContext()->isFileContext()) {
+Diag(Loc, diag::err_pragma_intrinsic_function_scope);
+return;
+  }
+
+  MSFunctionNoBuiltins.insert(MSFun

[PATCH] D124952: [clang-tidy] Escape diagnostic messages before passing to `diag` in Transformer.

2022-05-04 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked an inline comment as done.
ymandel added a comment.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124952

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


[PATCH] D124952: [clang-tidy] Escape diagnostic messages before passing to `diag` in Transformer.

2022-05-04 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 427126.
ymandel added a comment.

address reviewer comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124952

Files:
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp


Index: clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -90,6 +90,27 @@
   EXPECT_EQ(Errors[0].Message.FileOffset, 10U);
 }
 
+TEST(TransformerClangTidyCheckTest, DiagnosticMessageEscaped) {
+  class GiveDiagWithPercentSymbol : public TransformerClangTidyCheck {
+  public:
+GiveDiagWithPercentSymbol(StringRef Name, ClangTidyContext *Context)
+: TransformerClangTidyCheck(makeRule(returnStmt(),
+ noopEdit(node(RootID)),
+ cat("bad code: x % y % z")),
+Name, Context) {}
+  };
+  std::string Input = "int somecode() { return 0; }";
+  std::vector Errors;
+  EXPECT_EQ(Input,
+test::runCheckOnCode(Input, &Errors));
+  ASSERT_EQ(Errors.size(), 1U);
+  // The message stored in this field shouldn't include escaped percent signs,
+  // because the diagnostic printer should have _unescaped_ them when 
processing
+  // the diagnostic. The only behavior observable/verifiable by the test is 
that
+  // the presence of the '%' doesn't crash Clang.
+  EXPECT_EQ(Errors[0].Message.Message, "bad code: x % y % z");
+}
+
 class IntLitCheck : public TransformerClangTidyCheck {
 public:
   IntLitCheck(StringRef Name, ClangTidyContext *Context)
Index: clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
@@ -27,6 +27,33 @@
  " explicitly provide an empty explanation if none is desired");
 }
 
+// If a string unintentionally containing '%' is passed as a diagnostic, Clang
+// will claim the string is ill-formed and assert-fail. This function escapes
+// such strings so they can be safely used in diagnostics.
+std::string escapeForDiagnostic(std::string ToEscape) {
+  // Optimize for the common case that the string does not contain `%` at the
+  // cost of an extra scan over the string in the slow case.
+  auto Pos = ToEscape.find('%');
+  if (Pos == ToEscape.npos)
+return ToEscape;
+
+  std::string Result;
+  Result.reserve(ToEscape.size());
+  // Convert position to a count.
+  ++Pos;
+  Result.append(ToEscape, 0, Pos);
+  Result += '%';
+
+  for (auto N = ToEscape.size(); Pos < N; ++Pos) {
+const char C = ToEscape.at(Pos);
+Result += C;
+if (C == '%')
+  Result += '%';
+  }
+
+  return Result;
+}
+
 TransformerClangTidyCheck::TransformerClangTidyCheck(StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
@@ -99,7 +126,8 @@
   }
 
   // Associate the diagnostic with the location of the first change.
-  DiagnosticBuilder Diag = diag((*Edits)[0].Range.getBegin(), *Explanation);
+  DiagnosticBuilder Diag =
+  diag((*Edits)[0].Range.getBegin(), escapeForDiagnostic(*Explanation));
   for (const auto &T : *Edits)
 switch (T.Kind) {
 case transformer::EditKind::Range:


Index: clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -90,6 +90,27 @@
   EXPECT_EQ(Errors[0].Message.FileOffset, 10U);
 }
 
+TEST(TransformerClangTidyCheckTest, DiagnosticMessageEscaped) {
+  class GiveDiagWithPercentSymbol : public TransformerClangTidyCheck {
+  public:
+GiveDiagWithPercentSymbol(StringRef Name, ClangTidyContext *Context)
+: TransformerClangTidyCheck(makeRule(returnStmt(),
+ noopEdit(node(RootID)),
+ cat("bad code: x % y % z")),
+Name, Context) {}
+  };
+  std::string Input = "int somecode() { return 0; }";
+  std::vector Errors;
+  EXPECT_EQ(Input,
+test::runCheckOnCode(Input, &Errors));
+  ASSERT_EQ(Errors.size(), 1U);
+  // The message stored in this field shouldn't include escaped percent signs,
+  // because the diagnostic printer should have _unescaped_ them when processing
+  // the diagnostic. The only behavior observable/verifiable by the test is th

[PATCH] D124719: [docs] PCH usage documentation update

2022-05-04 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann reopened this revision.
tahonermann added a comment.
This revision is now accepted and ready to land.

Reopening for further discussion or clarification.

The changes appear to suggest that a PCH file won't be implicitly used when an 
explicit include for the corresponding header is made via the `-include` 
option, but that is not correct.

  $ cat t.h
  const int i = 0;
  $ cat t.c
  int g = i;
  $ clang t.h
  $ ls -1
  t.c
  t.h
  t.h.gch
  $ clang -c -I. -include t.h t.c
  $ touch t.h
  $ clang -c -I. -include t.h t.c
  fatal error: file '/iusers/thonerma/tmp/pch/t.h' has been modified since the 
precompiled header 't.h.gch' was built: mtime changed
  note: please rebuild precompiled header 't.h.gch'
  1 error generated.

If the ability to include a PCH file via `-include` is intentional behavior (as 
I have always believed it to be), then I think the documentation should 
demonstrate both the `-include` and `-include-pch` methods of using a PCH file.

Please note that gcc also supports implicit use of a PCH file via its -include 
option .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124719

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


[clang] b1a55d0 - Fix a crash on targets where __bf16 isn't supported

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

Author: Aaron Ballman
Date: 2022-05-04T16:45:59-04:00
New Revision: b1a55d0895249a493da5a442e44ee0a846410e88

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

LOG: Fix a crash on targets where __bf16 isn't supported

We'd nondeterministically assert (and later crash) when calculating the size or
alignment of a __bf16 type when the type isn't supported on a target because of
reading uninitialized values. Now we check whether the type is supported first.

Fixes #50171

Added: 
clang/test/Sema/vector-decl-crash.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/ASTContext.cpp
clang/lib/Sema/SemaType.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3187dad2b729e..04418633ec248 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -136,6 +136,9 @@ Bug Fixes
   floating-point vector type when the width of the initialization is exactly
   the same as the elements of the vector being initialized.
   Fixes `Issue 50216 `_.
+- Fixed a crash when the ``__bf16`` type is used such that its size or
+  alignment is calculated on a target which does not support that type. This
+  fixes `Issue 50171 `_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 838669107b04c..1ee18f913b914 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -2118,8 +2118,10 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) 
const {
   Align = Target->getLongFractAlign();
   break;
 case BuiltinType::BFloat16:
-  Width = Target->getBFloat16Width();
-  Align = Target->getBFloat16Align();
+  if (Target->hasBFloat16Type()) {
+Width = Target->getBFloat16Width();
+Align = Target->getBFloat16Align();
+  }
   break;
 case BuiltinType::Float16:
 case BuiltinType::Half:

diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 631a53263431c..15f7d36840bad 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -2630,7 +2630,7 @@ QualType Sema::BuildVectorType(QualType CurType, Expr 
*SizeExpr,
 return QualType();
   }
 
-  if (VectorSizeBits % TypeSize) {
+  if (!TypeSize || VectorSizeBits % TypeSize) {
 Diag(AttrLoc, diag::err_attribute_invalid_size)
 << SizeExpr->getSourceRange();
 return QualType();

diff  --git a/clang/test/Sema/vector-decl-crash.c 
b/clang/test/Sema/vector-decl-crash.c
new file mode 100644
index 0..5e4b098fee2d3
--- /dev/null
+++ b/clang/test/Sema/vector-decl-crash.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 %s -fsyntax-only -verify -triple x86_64-unknown-unknown
+
+// GH50171
+// This would previously crash when __bf16 was not a supported type.
+__bf16 v64bf __attribute__((vector_size(128))); // expected-error {{__bf16 is 
not supported on this target}} \
+   expected-error {{vector 
size not an integral multiple of component size}}
+



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


[PATCH] D124952: [clang-tidy] Escape diagnostic messages before passing to `diag` in Transformer.

2022-05-04 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added inline comments.
This revision is now accepted and ready to land.



Comment at: 
clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp:107
+  ASSERT_EQ(Errors.size(), 1U);
+  // This should match the input; this test only verifies that the presence of
+  // '%' doesn't crash Clang.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124952

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


[PATCH] D124701: [clang] Honor __attribute__((no_builtin("foo"))) on functions

2022-05-04 Thread Stephen Long via Phabricator via cfe-commits
steplong added inline comments.



Comment at: clang/lib/CodeGen/CGExpr.cpp:5219
+// function.
+else if (!CGF.CurFn->getAttributes().hasFnAttr(AttributeNoBuiltin))
   return CGCallee::forBuiltin(builtinID, FD);

hans wrote:
> What if CurFn has the "wildcard" no-builtins attribute?
Hmmm, good question. Currently, "*" generates a warning. I was able to get "*" 
to add the attribute no-builtins to the function, but if I try making it affect 
the calls in the function, I see a compiler crash when compiling compiler-rt. 
It looks like some builtins must be generated even if -fno-builtins is called 
such as __sync_lock_test_and_set_1. I'm not sure how to check for that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124701

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


[PATCH] D104975: Implement P1949

2022-05-04 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added a comment.

> I hope at least GCC will not implement this arbitrary restriction on math 
> symbols. I would argue a partial derivative symbol in C++ has more sense than 
> a skull emoji.

I am quite sure that gcc will also be implementing P1949 
 as adopted for C++23.

Thank you to Aaron and Steve for their excellent analysis and responses!

@intractabilis, please note that this is not the end of the identifier story. A 
new Unicode work group recently started meeting as a result of the Trojan 
Source  reporting. Some members of that work group 
also maintain code bases that were negatively impacted by the changes in P1949 
. That group is expected to eventually produce 
guidance to better help language designers determine what should and should not 
be allowed in identifiers. The concerns are complicated; see Unicode UAX#31 
, UAX#36 
, and UAX#39 
 for detailed analysis of most of the 
concerns. I think it is unlikely that WG21 or any of the major compiler 
implementors will deviate from P1949  until new 
guidance emerges from the Unicode Technical Committee. With luck, that guidance 
will help to establish conventions that will be followed by most/all 
programming languages. But don't hold your breath; this will likely take quite 
a while.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104975

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


[libunwind] 6123e9c - [libunwind] Silence warnings about unused variables. NFC.

2022-05-04 Thread Martin Storsjö via cfe-commits

Author: Martin Storsjö
Date: 2022-05-04T22:55:02+03:00
New Revision: 6123e9c0d03bf1e3f43c3851f4122a7267b33c28

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

LOG: [libunwind] Silence warnings about unused variables. NFC.

This variable was considered unused when NDEBUG was defined.

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

Added: 


Modified: 
libunwind/src/AddressSpace.hpp

Removed: 




diff  --git a/libunwind/src/AddressSpace.hpp b/libunwind/src/AddressSpace.hpp
index 5fc9ee3fe6c38..36c9f5a9e36f9 100644
--- a/libunwind/src/AddressSpace.hpp
+++ b/libunwind/src/AddressSpace.hpp
@@ -551,6 +551,7 @@ inline bool LocalAddressSpace::findUnwindSections(pint_t 
targetAddr,
 DWORD err = GetLastError();
 _LIBUNWIND_TRACE_UNWINDING("findUnwindSections: EnumProcessModules failed, 
"
"returned error %d", (int)err);
+(void)err;
 return false;
   }
 



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


[libunwind] f1f8899 - [libunwind] [CMake] Handle the RelWithDebInfo configuration similarly to Release

2022-05-04 Thread Martin Storsjö via cfe-commits

Author: Martin Storsjö
Date: 2022-05-04T22:55:01+03:00
New Revision: f1f8899a18822ede04d8f90cbdae29d66333d7dc

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

LOG: [libunwind] [CMake] Handle the RelWithDebInfo configuration similarly to 
Release

This makes sure to include libunwind log messages in the build if
LIBUNWIND_ENABLE_ASSERTIONS is set (which it is by default), when
building in RelWithDebInfo configurations.

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

Added: 


Modified: 
libunwind/CMakeLists.txt

Removed: 




diff  --git a/libunwind/CMakeLists.txt b/libunwind/CMakeLists.txt
index 6a76917ae91b9..632316bc5065c 100644
--- a/libunwind/CMakeLists.txt
+++ b/libunwind/CMakeLists.txt
@@ -295,11 +295,11 @@ if (LIBUNWIND_ENABLE_ASSERTIONS)
 
   # On Release builds cmake automatically defines NDEBUG, so we
   # explicitly undefine it:
-  if (uppercase_CMAKE_BUILD_TYPE STREQUAL "RELEASE")
+  if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
 add_compile_flags(-UNDEBUG)
   endif()
 else()
-  if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "RELEASE")
+  if (uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
 add_compile_flags(-DNDEBUG)
   endif()
 endif()



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


[PATCH] D124956: [clang-format] Fix another bug in AlignConsecutiveAssignments

2022-05-04 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
owenpan added reviewers: curdeius, HazardyKnusperkeks, MyDeveloperDay.
owenpan added a project: clang-format.
Herald added a project: All.
owenpan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Similar to D124868 .

The `ShouldShiftBeAdded` lambda checks if extra space should be
added before the wrapped part of a braced list. If the first
element of the list is wrapped, no extra space should be added.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124956

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -18023,6 +18023,12 @@
"}",
Style);
 
+  verifyFormat("unsigned i = 0;\n"
+   "int a[]= {\n"
+   "1234567890,\n"
+   "-1234567890};",
+   Style);
+
   Style.ColumnLimit = 120;
 
   // clang-format off
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -398,6 +398,8 @@
 Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace))
   return false;
   }
+  if (Changes[ScopeStart].NewlinesBefore > 0)
+return false;
   return true;
 }
 


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -18023,6 +18023,12 @@
"}",
Style);
 
+  verifyFormat("unsigned i = 0;\n"
+   "int a[]= {\n"
+   "1234567890,\n"
+   "-1234567890};",
+   Style);
+
   Style.ColumnLimit = 120;
 
   // clang-format off
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -398,6 +398,8 @@
 Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace))
   return false;
   }
+  if (Changes[ScopeStart].NewlinesBefore > 0)
+return false;
   return true;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124687: [Tooling/DependencyScanning & Preprocessor] Refactor dependency scanning to record and use pre-lexed preprocessor directive tokens, instead of minimized sources

2022-05-04 Thread Argyrios Kyrtzidis via Phabricator via cfe-commits
akyrtzi added a comment.

In D124687#3486473 , @akyrtzi wrote:

> In D124687#3485710 , @tschuett 
> wrote:
>
>> Is there overhead in the non dependency scanning mode?
>
> Good suggestion, I'll do some measurements and get back to you.

I took measurements for preprocessing the clang sources, with a 
release+thin-LTO build, and differences are within the noise level.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124687

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


[PATCH] D124955: [clang-tidy] Make header-guard check a little looser on comment whitespace

2022-05-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: hokein.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a project: All.
sammccall requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Currently it rejects "//  FOO_BAR_H" as an endif comment due to the extra space.
A user complained that this is too picky, which seems fair enough.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124955

Files:
  clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
  clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp


Index: clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
@@ -204,6 +204,14 @@
 "include/llvm/ADT/foo.h",
 StringRef("header guard does not follow preferred style")));
 
+  // An extra space inside the comment is OK.
+  llvm::StringRef WithExtraSpace = "#ifndef LLVM_ADT_FOO_H\n"
+   "#define LLVM_ADT_FOO_H\n"
+   "#endif //  LLVM_ADT_FOO_H\n";
+  EXPECT_EQ(WithExtraSpace,
+runHeaderGuardCheckWithEndif(WithExtraSpace,
+ "include/llvm/ADT/foo.h", None));
+
   EXPECT_EQ("#ifndef LLVM_ADT_FOO_H\n"
 "#define LLVM_ADT_FOO_H\n"
 "#endif \\ \n"
Index: clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
===
--- clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
+++ clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
@@ -145,13 +145,13 @@
 EndIfStr[FindEscapedNewline] == '\\')
   return false;
 
-if (!Check->shouldSuggestEndifComment(FileName) &&
-!(EndIfStr.startswith("//") ||
-  (EndIfStr.startswith("/*") && EndIfStr.endswith("*/"
-  return false;
+bool IsLineComment =
+EndIfStr.consume_front("//") ||
+(EndIfStr.consume_front("/*") && EndIfStr.consume_back("*/"));
+if (!IsLineComment)
+  return Check->shouldSuggestEndifComment(FileName);
 
-return (EndIfStr != "// " + HeaderGuard.str()) &&
-   (EndIfStr != "/* " + HeaderGuard.str() + " */");
+return EndIfStr.trim() != HeaderGuard;
   }
 
   /// Look for header guards that don't match the preferred style. Emit


Index: clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
@@ -204,6 +204,14 @@
 "include/llvm/ADT/foo.h",
 StringRef("header guard does not follow preferred style")));
 
+  // An extra space inside the comment is OK.
+  llvm::StringRef WithExtraSpace = "#ifndef LLVM_ADT_FOO_H\n"
+   "#define LLVM_ADT_FOO_H\n"
+   "#endif //  LLVM_ADT_FOO_H\n";
+  EXPECT_EQ(WithExtraSpace,
+runHeaderGuardCheckWithEndif(WithExtraSpace,
+ "include/llvm/ADT/foo.h", None));
+
   EXPECT_EQ("#ifndef LLVM_ADT_FOO_H\n"
 "#define LLVM_ADT_FOO_H\n"
 "#endif \\ \n"
Index: clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
===
--- clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
+++ clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
@@ -145,13 +145,13 @@
 EndIfStr[FindEscapedNewline] == '\\')
   return false;
 
-if (!Check->shouldSuggestEndifComment(FileName) &&
-!(EndIfStr.startswith("//") ||
-  (EndIfStr.startswith("/*") && EndIfStr.endswith("*/"
-  return false;
+bool IsLineComment =
+EndIfStr.consume_front("//") ||
+(EndIfStr.consume_front("/*") && EndIfStr.consume_back("*/"));
+if (!IsLineComment)
+  return Check->shouldSuggestEndifComment(FileName);
 
-return (EndIfStr != "// " + HeaderGuard.str()) &&
-   (EndIfStr != "/* " + HeaderGuard.str() + " */");
+return EndIfStr.trim() != HeaderGuard;
   }
 
   /// Look for header guards that don't match the preferred style. Emit
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124349: [analyzer] Get direct binding for specific punned case

2022-05-04 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers updated this revision to Diff 427106.
vabridgers added a comment.

Address comments from @martong


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124349

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/array-punned-region.c


Index: clang/test/Analysis/array-punned-region.c
===
--- /dev/null
+++ clang/test/Analysis/array-punned-region.c
@@ -0,0 +1,39 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core,debug.ExprInspection -verify -analyzer-config 
eagerly-assume=false -triple x86_64-pc-linux-gnu %s
+
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core,debug.ExprInspection -verify -analyzer-config 
eagerly-assume=false -triple i386-pc-linux-gnu  %s
+
+int clang_analyzer_eval(int);
+
+typedef struct {
+  int a : 1;
+  int b[2];
+} BITFIELD_CAST;
+
+void array_struct_bitfield_1() {
+  BITFIELD_CAST ff = {0};
+  BITFIELD_CAST *pff = &ff;
+  clang_analyzer_eval(*((int *)pff + 1) == 0); // expected-warning{{TRUE}}
+  ff.b[0] = 3;
+  clang_analyzer_eval(*((int *)pff + 1) == 3); // expected-warning{{TRUE}}
+}
+
+int array_struct_bitfield_2() {
+  BITFIELD_CAST ff = {0};
+  BITFIELD_CAST *pff = &ff;
+  int a = *((int *)pff + 2); // expected-warning{{Assigned value is garbage or 
undefined [core.uninitialized.Assign]}}
+  return a;
+}
+
+typedef struct {
+  unsigned int a : 1;
+  unsigned int x : 31;
+  unsigned int c : 1;
+  int b[2];
+} mystruct;
+
+void array_struct_bitfield_3() {
+  mystruct ff;
+  mystruct *pff = &ff;
+  ff.b[0] = 3;
+  clang_analyzer_eval(*((int *)pff + 2) == 3); // expected-warning{{TRUE}}  // 
Or should this be `pff + 3` ???
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2147,8 +2147,13 @@
   return UnknownVal();
 
 // Additionally allow introspection of a block's internal layout.
-if (!hasPartialLazyBinding && !isa(R->getBaseRegion()))
+// Try to get direct binding if all other attempts failed thus far.
+// Else, return UndefinedVal()
+if (!hasPartialLazyBinding && !isa(R->getBaseRegion())) {
+  if (const Optional &V = B.getDefaultBinding(R))
+return *V;
   return UndefinedVal();
+}
   }
 
   // All other values are symbolic.


Index: clang/test/Analysis/array-punned-region.c
===
--- /dev/null
+++ clang/test/Analysis/array-punned-region.c
@@ -0,0 +1,39 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core,debug.ExprInspection -verify -analyzer-config eagerly-assume=false -triple x86_64-pc-linux-gnu %s
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core,debug.ExprInspection -verify -analyzer-config eagerly-assume=false -triple i386-pc-linux-gnu  %s
+
+int clang_analyzer_eval(int);
+
+typedef struct {
+  int a : 1;
+  int b[2];
+} BITFIELD_CAST;
+
+void array_struct_bitfield_1() {
+  BITFIELD_CAST ff = {0};
+  BITFIELD_CAST *pff = &ff;
+  clang_analyzer_eval(*((int *)pff + 1) == 0); // expected-warning{{TRUE}}
+  ff.b[0] = 3;
+  clang_analyzer_eval(*((int *)pff + 1) == 3); // expected-warning{{TRUE}}
+}
+
+int array_struct_bitfield_2() {
+  BITFIELD_CAST ff = {0};
+  BITFIELD_CAST *pff = &ff;
+  int a = *((int *)pff + 2); // expected-warning{{Assigned value is garbage or undefined [core.uninitialized.Assign]}}
+  return a;
+}
+
+typedef struct {
+  unsigned int a : 1;
+  unsigned int x : 31;
+  unsigned int c : 1;
+  int b[2];
+} mystruct;
+
+void array_struct_bitfield_3() {
+  mystruct ff;
+  mystruct *pff = &ff;
+  ff.b[0] = 3;
+  clang_analyzer_eval(*((int *)pff + 2) == 3); // expected-warning{{TRUE}}  // Or should this be `pff + 3` ???
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2147,8 +2147,13 @@
   return UnknownVal();
 
 // Additionally allow introspection of a block's internal layout.
-if (!hasPartialLazyBinding && !isa(R->getBaseRegion()))
+// Try to get direct binding if all other attempts failed thus far.
+// Else, return UndefinedVal()
+if (!hasPartialLazyBinding && !isa(R->getBaseRegion())) {
+  if (const Optional &V = B.getDefaultBinding(R))
+return *V;
   return UndefinedVal();
+}
   }
 
   // All other values are symbolic.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119147: [AIX][clang][driver] Check the command string to the linker for exportlist opts and

2022-05-04 Thread Steven Wan via Phabricator via cfe-commits
stevewan added inline comments.



Comment at: clang/test/Driver/aix-ld.c:675-676
+// CHECK-LD32-SHARED-EXPORTS-NOT: "{{.*}}llvm-nm"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "-X"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "32"
+// CHECK-LD32-SHARED-EXPORTS: "{{.*}}ld{{(.exe)?}}"

DiggerLin wrote:
> stevewan wrote:
> > And please keep this consistent across the tests.
> using:
> // CHECK-LD32-SHARED-EXPORTS-NOT: "-X"
> // CHECK-LD32-SHARED-EXPORTS-NOT: "32"
> 
> will be fail on the -X 64 too.
> 
> using  // CHECK-LD32-SHARED-EXPORTS-NOT: "-X" "32"
>  will be success on the -X 64. 
> So I am prefer use the
>  CHECK-LD32-SHARED-EXPORTS-NOT: "-X"
>  CHECK-LD32-SHARED-EXPORTS-NOT: "32" 
> 
If this is meant to check also for `-X 64`. I suggest using proper regex 
instead of relying solely on the `-X` check.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119147

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


[clang] 2966f0f - Revert "[clang][extract-api] Use relative includes"

2022-05-04 Thread Zixu Wang via cfe-commits

Author: Zixu Wang
Date: 2022-05-04T12:27:20-07:00
New Revision: 2966f0fa505266735dbc8324b8821b7f0aa901ff

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

LOG: Revert "[clang][extract-api] Use relative includes"

This reverts commit 4c262fee08b5383c96857d77eefe80d61c41d2b0.
Revert to fix Msan and Asan errors.

Added: 
clang/test/ExtractAPI/known_files_only_hmap.c

Modified: 
clang/include/clang/ExtractAPI/FrontendActions.h
clang/lib/ExtractAPI/ExtractAPIConsumer.cpp

Removed: 
clang/test/ExtractAPI/relative_include.m



diff  --git a/clang/include/clang/ExtractAPI/FrontendActions.h 
b/clang/include/clang/ExtractAPI/FrontendActions.h
index 2cb8ef130fdd7..dec3b5ca93d18 100644
--- a/clang/include/clang/ExtractAPI/FrontendActions.h
+++ b/clang/include/clang/ExtractAPI/FrontendActions.h
@@ -40,10 +40,7 @@ class ExtractAPIAction : public ASTFrontendAction {
   std::unique_ptr Buffer;
 
   /// The input file originally provided on the command line.
-  ///
-  /// This captures the spelling used to include the file and whether the
-  /// include is quoted or not.
-  SmallVector, bool>> KnownInputFiles;
+  std::vector KnownInputFiles;
 
   /// Prepare to execute the action on the given CompilerInstance.
   ///

diff  --git a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp 
b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
index 317bcd1be8256..b1de2674b622b 100644
--- a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
+++ b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
@@ -38,10 +38,7 @@
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
-#include "llvm/Support/Path.h"
-#include "llvm/Support/Regex.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -58,128 +55,10 @@ StringRef getTypedefName(const TagDecl *Decl) {
   return {};
 }
 
-Optional getRelativeIncludeName(const CompilerInstance &CI,
- StringRef File,
- bool *IsQuoted = nullptr) {
-  assert(CI.hasFileManager() &&
- "CompilerInstance does not have a FileNamager!");
-
-  using namespace llvm::sys;
-  // Matches framework include patterns
-  const llvm::Regex Rule("/(.+)\\.framework/(.+)?Headers/(.+)");
-
-  const auto &FS = CI.getVirtualFileSystem();
-
-  SmallString<128> FilePath(File.begin(), File.end());
-  FS.makeAbsolute(FilePath);
-  path::remove_dots(FilePath, true);
-  File = FilePath;
-
-  // Checks whether `Dir` is a strict path prefix of `File`. If so returns
-  // the prefix length. Otherwise return 0.
-  auto CheckDir = [&](llvm::StringRef Dir) -> unsigned {
-llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
-FS.makeAbsolute(DirPath);
-path::remove_dots(DirPath, true);
-Dir = DirPath;
-for (auto NI = path::begin(File), NE = path::end(File),
-  DI = path::begin(Dir), DE = path::end(Dir);
- /*termination condition in loop*/; ++NI, ++DI) {
-  // '.' components in File are ignored.
-  while (NI != NE && *NI == ".")
-++NI;
-  if (NI == NE)
-break;
-
-  // '.' components in Dir are ignored.
-  while (DI != DE && *DI == ".")
-++DI;
-
-  // Dir is a prefix of File, up to '.' components and choice of path
-  // separators.
-  if (DI == DE)
-return NI - path::begin(File);
-
-  // Consider all path separators equal.
-  if (NI->size() == 1 && DI->size() == 1 &&
-  path::is_separator(NI->front()) && path::is_separator(DI->front()))
-continue;
-
-  // Special case Apple .sdk folders since the search path is typically a
-  // symlink like `iPhoneSimulator14.5.sdk` while the file is instead
-  // located in `iPhoneSimulator.sdk` (the real folder).
-  if (NI->endswith(".sdk") && DI->endswith(".sdk")) {
-StringRef NBasename = path::stem(*NI);
-StringRef DBasename = path::stem(*DI);
-if (DBasename.startswith(NBasename))
-  continue;
-  }
-
-  if (*NI != *DI)
-break;
-}
-return 0;
-  };
-
-  unsigned PrefixLength = 0;
-
-  // Go through the search paths and find the first one that is a prefix of
-  // the header.
-  for (const auto &Entry : CI.getHeaderSearchOpts().UserEntries) {
-// Note whether the match is found in a quoted entry.
-if (IsQuoted)
-  *IsQuoted = Entry.Group == frontend::Quoted;
-
-if (auto EntryFile = CI.getFileManager().getOptionalFileRef(Entry.Path)) {
-  if (auto HMap = HeaderMap::Create(*EntryFile, CI.getFileManager())) {
-// If this is a headermap entry, try to reverse lookup the full path
-// for a spelled name before mapping.
-StringRef SpelledFil

[PATCH] D111548: [Clang] Add the `annotate_type` attribute

2022-05-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a subscriber: rjmccall.
aaron.ballman added inline comments.



Comment at: clang/test/SemaCXX/annotate-type.cpp:2
+// RUN: %clang_cc1 %s -std=c++17 -fsyntax-only -verify
+
+struct S1 {

mboehme wrote:
> aaron.ballman wrote:
> > mboehme wrote:
> > > aaron.ballman wrote:
> > > > mboehme wrote:
> > > > > aaron.ballman wrote:
> > > > > > mboehme wrote:
> > > > > > > aaron.ballman wrote:
> > > > > > > > mboehme wrote:
> > > > > > > > > aaron.ballman wrote:
> > > > > > > > > > Can you also add some test coverage for applying the 
> > > > > > > > > > attribute to a declaration instead of a type or not giving 
> > > > > > > > > > it any arguments? Also, should test arguments which are not 
> > > > > > > > > > a constant expression.
> > > > > > > > > I've added tests as you suggested, though I put most of them 
> > > > > > > > > in Sema/annotate-type.c, as they're not specific to C++.
> > > > > > > > > 
> > > > > > > > > Thanks for prompting me to do this -- the tests caused me to 
> > > > > > > > > notice and fix a number of bugs.
> > > > > > > > > 
> > > > > > > > > I haven't managed to diagnose the case when the attribute 
> > > > > > > > > appears at the beginning of the declaration. It seems to me 
> > > > > > > > > that, at the point where I've added the check, this case is 
> > > > > > > > > indistinguishable from an attribute that appears on the type. 
> > > > > > > > > In both cases, the `TAL` is `TAL_DeclSpec`, and the attribute 
> > > > > > > > > is contained in `DeclSpec::getAttributes()`. This is because 
> > > > > > > > > `Parser::ParseSimpleDeclaration` forwards the declaration 
> > > > > > > > > attributes to the `DeclSpec`:
> > > > > > > > > 
> > > > > > > > > https://github.com/llvm/llvm-project/blob/main/clang/lib/Parse/ParseDecl.cpp#L1851
> > > > > > > > > 
> > > > > > > > > I believe if I wanted to prohibit this case, I would need to 
> > > > > > > > > add a check to `Parser::ParseStatementOrDeclaration` and 
> > > > > > > > > prohibit any occurrences of `annotate_type` there. However, 
> > > > > > > > > this seems the wrong place to do this because it doesn't 
> > > > > > > > > contain any specific processing for other attributes.
> > > > > > > > > 
> > > > > > > > > I've noticed that Clang also doesn't prohibit other type 
> > > > > > > > > attributes (even ones with C++ 11 syntax) from being applied 
> > > > > > > > > to declarations. For example: https://godbolt.org/z/Yj1zWY7nn
> > > > > > > > > 
> > > > > > > > > How do you think I should proceed here? I think the 
> > > > > > > > > underlying issue is that Clang doesn't always distinguish 
> > > > > > > > > cleanly between declaration attributes and type attributes, 
> > > > > > > > > and fixing this might be nontrivial.
> > > > > > > > > How do you think I should proceed here? I think the 
> > > > > > > > > underlying issue is that Clang doesn't always distinguish 
> > > > > > > > > cleanly between declaration attributes and type attributes, 
> > > > > > > > > and fixing this might be nontrivial.
> > > > > > > > 
> > > > > > > > This is a general issue with attribute processing. I would 
> > > > > > > > imagine that SemaDeclAttr.cpp should be able to diagnose that 
> > > > > > > > case when the attribute only applies to types and not 
> > > > > > > > declarations, but it'd take some investigation for me to be 
> > > > > > > > sure.
> > > > > > > > 
> > > > > > > > Because this issue isn't new to your situation, I'd recommend 
> > > > > > > > filing an issue about the general problem and then we can solve 
> > > > > > > > that later.
> > > > > > > I've done some more investigation myself, and I think I've come 
> > > > > > > up with a solution; actually, two potential solutions. I have 
> > > > > > > draft patches for both of these; I wanted to run these by you 
> > > > > > > here first, so I haven't opened a bug yet.
> > > > > > > 
> > > > > > > I'd appreciate your input on how you'd prefer me to proceed with 
> > > > > > > this. I do think it makes sense to do this work now because 
> > > > > > > otherwise, people will start putting `annotate_type` in places 
> > > > > > > where it doesn't belong, and then we'll have to keep supporting 
> > > > > > > that in the future.
> > > > > > > 
> > > > > > > **My preferred solution**
> > > > > > > 
> > > > > > > https://reviews.llvm.org/D124081
> > > > > > > 
> > > > > > > This adds a function `DiagnoseCXX11NonDeclAttrs()` and calls it 
> > > > > > > in all places where we should reject attributes that can't be put 
> > > > > > > on declarations. (As part of this work, I noticed that 
> > > > > > > `gsl::suppress` should be a `DeclOrStmtAttr`, not just a 
> > > > > > > `StmtAttr`.)
> > > > > > > 
> > > > > > > Advantages:
> > > > > > > - Not very invasive.
> > > > > > > Disadvantages:
> > > > > > > - Need to make sure we call `DiagnoseCXX11NonDeclAttrs()` 
> > > > > > > everywhere that non-declaration attributes should be rejected. 
> > > > > >

[PATCH] D124715: Use QoS class Utility for ThreadPriority::Low on Mac

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

OK, so wanting this to be utility makes sense, and maybe/probably it should be 
the default.

I'm still concerned some users will find this a large regression and we won't 
have a good workaround:

- it'll use a lot more battery than before
- not everyone will see the background index as so critical
- I think our only advice can be to disable background indexing entirely

What do you think about keeping `Background` in the enum along with `Low`, and 
switching clangd to `Low`?
I'm happy to do the plumbing to add a flag to clangd, and to implement `Low` 
for other OSes.
(Digging into windows, it looks like the background mode there is also much 
slower).

@kadircet any opinion here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124715

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


[clang] 342e1c7 - [clang-format] Fix a bug in AlignConsecutiveAssignments

2022-05-04 Thread via cfe-commits

Author: owenca
Date: 2022-05-04T12:04:43-07:00
New Revision: 342e1c77c360e745fc6457037e6c1e37b84f2791

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

LOG: [clang-format] Fix a bug in AlignConsecutiveAssignments

Fixes #55113.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 2dcc4fd62c5e8..cf4ef6338f1bd 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -369,6 +369,8 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
   if (Changes[i].Tok->MatchingParen &&
   Changes[i].Tok->MatchingParen->is(TT_LambdaLBrace))
 return false;
+  if (Changes[ScopeStart].NewlinesBefore > 0)
+return false;
   return Style.BinPackArguments;
 }
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 37f32691a1d36..78a3c21c33009 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -18010,11 +18010,21 @@ TEST_F(FormatTest, AlignWithLineBreaks) {
Style);
   // clang-format on
 
-  Style = getLLVMStyleWithColumns(120);
+  Style = getLLVMStyleWithColumns(20);
   Style.AlignConsecutiveAssignments.Enabled = true;
-  Style.ContinuationIndentWidth = 4;
   Style.IndentWidth = 4;
 
+  verifyFormat("void foo() {\n"
+   "int i1 = 1;\n"
+   "int j  = 0;\n"
+   "int k  = bar(\n"
+   "argument1,\n"
+   "argument2);\n"
+   "}",
+   Style);
+
+  Style.ColumnLimit = 120;
+
   // clang-format off
   verifyFormat("void SomeFunc() {\n"
"newWatcher.maxAgeUsec = 
ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp(monitorFrequencyUsec),\n"



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


[PATCH] D124868: [clang-format] Fix a bug in AlignConsecutiveAssignments

2022-05-04 Thread Owen Pan 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 rG342e1c77c360: [clang-format] Fix a bug in 
AlignConsecutiveAssignments (authored by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124868

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -18010,11 +18010,21 @@
Style);
   // clang-format on
 
-  Style = getLLVMStyleWithColumns(120);
+  Style = getLLVMStyleWithColumns(20);
   Style.AlignConsecutiveAssignments.Enabled = true;
-  Style.ContinuationIndentWidth = 4;
   Style.IndentWidth = 4;
 
+  verifyFormat("void foo() {\n"
+   "int i1 = 1;\n"
+   "int j  = 0;\n"
+   "int k  = bar(\n"
+   "argument1,\n"
+   "argument2);\n"
+   "}",
+   Style);
+
+  Style.ColumnLimit = 120;
+
   // clang-format off
   verifyFormat("void SomeFunc() {\n"
"newWatcher.maxAgeUsec = 
ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp(monitorFrequencyUsec),\n"
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -369,6 +369,8 @@
   if (Changes[i].Tok->MatchingParen &&
   Changes[i].Tok->MatchingParen->is(TT_LambdaLBrace))
 return false;
+  if (Changes[ScopeStart].NewlinesBefore > 0)
+return false;
   return Style.BinPackArguments;
 }
 


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -18010,11 +18010,21 @@
Style);
   // clang-format on
 
-  Style = getLLVMStyleWithColumns(120);
+  Style = getLLVMStyleWithColumns(20);
   Style.AlignConsecutiveAssignments.Enabled = true;
-  Style.ContinuationIndentWidth = 4;
   Style.IndentWidth = 4;
 
+  verifyFormat("void foo() {\n"
+   "int i1 = 1;\n"
+   "int j  = 0;\n"
+   "int k  = bar(\n"
+   "argument1,\n"
+   "argument2);\n"
+   "}",
+   Style);
+
+  Style.ColumnLimit = 120;
+
   // clang-format off
   verifyFormat("void SomeFunc() {\n"
"newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp(monitorFrequencyUsec),\n"
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -369,6 +369,8 @@
   if (Changes[i].Tok->MatchingParen &&
   Changes[i].Tok->MatchingParen->is(TT_LambdaLBrace))
 return false;
+  if (Changes[ScopeStart].NewlinesBefore > 0)
+return false;
   return Style.BinPackArguments;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105564: Fix for DWARF parsing to better handle auto return type for member functions

2022-05-04 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik updated this revision to Diff 427081.
shafik removed reviewers: teemperor, jingham, jasonmolenda.
shafik added a comment.
Herald added a project: All.

- Expanded test
- applied clang-format


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

https://reviews.llvm.org/D105564

Files:
  lldb/source/Plugins/ExpressionParser/Clang/ASTResultSynthesizer.cpp
  lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp
  lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp
  lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h
  lldb/test/API/lang/cpp/auto_return/Makefile
  lldb/test/API/lang/cpp/auto_return/TestCppAutoReturn.py
  lldb/test/API/lang/cpp/auto_return/main.cpp
  lldb/test/API/lang/cpp/auto_return/other.cpp
  lldb/test/Shell/SymbolFile/DWARF/x86/auto_return_symtab.s

Index: lldb/test/Shell/SymbolFile/DWARF/x86/auto_return_symtab.s
===
--- /dev/null
+++ lldb/test/Shell/SymbolFile/DWARF/x86/auto_return_symtab.s
@@ -0,0 +1,257 @@
+# This tests that lldb when using symbol table we are able to find the definition
+# for an auto return function.
+
+# RUN: llvm-mc -triple x86_64-apple-macosx10.15.0 %s -filetype=obj > %t.o
+# RUN: lldb-test symbols --dump-clang-ast %t.o | FileCheck %s
+
+# CHECK: CXXMethodDecl {{.*}} <>  f 'int ()'
+
+# This was compiled from the following code:
+#
+# struct A {
+# auto f();
+# };
+#
+# auto A::f() {
+# return 0;
+# }
+#
+# Compiled using:
+#
+#  -target x86_64-apple-macosx10.15.0
+#
+# and edited to remove some uneeded sections.
+
+	.section	__TEXT,__text,regular,pure_instructions
+	.globl	__ZN1A1fEv  ## -- Begin function _ZN1A1fEv
+	.p2align	4, 0x90
+__ZN1A1fEv: ## @_ZN1A1fEv
+Lfunc_begin0:
+	.cfi_startproc
+## %bb.0:   ## %entry
+	pushq	%rbp
+	.cfi_def_cfa_offset 16
+	.cfi_offset %rbp, -16
+	movq	%rsp, %rbp
+	.cfi_def_cfa_register %rbp
+	movq	%rdi, -8(%rbp)
+Ltmp0:
+	xorl	%eax, %eax
+	popq	%rbp
+	retq
+Ltmp1:
+Lfunc_end0:
+	.cfi_endproc
+## -- End function
+	.section	__DWARF,__debug_abbrev,regular,debug
+Lsection_abbrev:
+	.byte	1   ## Abbreviation Code
+	.byte	17  ## DW_TAG_compile_unit
+	.byte	1   ## DW_CHILDREN_yes
+	.byte	37  ## DW_AT_producer
+	.byte	14  ## DW_FORM_strp
+	.byte	19  ## DW_AT_language
+	.byte	5   ## DW_FORM_data2
+	.byte	3   ## DW_AT_name
+	.byte	14  ## DW_FORM_strp
+	.ascii	"\202|" ## DW_AT_LLVM_sysroot
+	.byte	14  ## DW_FORM_strp
+	.ascii	"\357\177"  ## DW_AT_APPLE_sdk
+	.byte	14  ## DW_FORM_strp
+	.byte	16  ## DW_AT_stmt_list
+	.byte	23  ## DW_FORM_sec_offset
+	.byte	27  ## DW_AT_comp_dir
+	.byte	14  ## DW_FORM_strp
+	.byte	17  ## DW_AT_low_pc
+	.byte	1   ## DW_FORM_addr
+	.byte	18  ## DW_AT_high_pc
+	.byte	6   ## DW_FORM_data4
+	.byte	0   ## EOM(1)
+	.byte	0   ## EOM(2)
+	.byte	2   ## Abbreviation Code
+	.byte	19  ## DW_TAG_structure_type
+	.byte	1   ## DW_CHILDREN_yes
+	.byte	54  ## DW_AT_calling_convention
+	.byte	11  ## DW_FORM_data1
+	.byte	3   ## DW_AT_name
+	.byte	14  ## DW_FORM_strp
+	.byte	11  ## DW_AT_byte_size
+	.byte	11  ## DW_FORM_data1
+	.byte	58  ## DW_AT_decl_file
+	.byte	11  ## DW_FORM_data1
+	.byte	59  ## DW_AT_decl_line
+	.byte	11  ## DW_FORM_data1
+	.byte	0   ## EOM(1)
+	.byte	0   ## EOM(2)
+	.byte	3   ## Abbreviation Code
+	.byte	46  ## DW_TAG_subprogram
+	.byte	1   ## DW_CHILDREN_yes
+	.byte	110 ## DW_AT_linkage_name
+	.byte	14  ## DW_FORM_strp
+	.byte	3   ## DW_AT_name
+	.byte	14  ## DW_FORM_strp
+	.byte	58  ## DW_AT_decl_file
+	.byte	11  ## DW_FORM_data1
+	.byte	59  ## DW_AT_decl_line
+	.byte	11  

[PATCH] D124952: [clang-tidy] Escape diagnostic messages before passing to `diag` in Transformer.

2022-05-04 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added a reviewer: gribozavr2.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a project: All.
ymandel requested review of this revision.
Herald added a project: clang-tools-extra.

Messages generated by Transformer rules may have `%` in them, which
needs to be escaped before being passed to `diag`, which interprets them
specially (and crashes if they are misused).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124952

Files:
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp


Index: clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -90,6 +90,25 @@
   EXPECT_EQ(Errors[0].Message.FileOffset, 10U);
 }
 
+TEST(TransformerClangTidyCheckTest, DiagnosticMessageEscaped) {
+  class GiveDiagWithPercentSymbol : public TransformerClangTidyCheck {
+  public:
+GiveDiagWithPercentSymbol(StringRef Name, ClangTidyContext *Context)
+: TransformerClangTidyCheck(makeRule(returnStmt(),
+ noopEdit(node(RootID)),
+ cat("bad code: x % y % z")),
+Name, Context) {}
+  };
+  std::string Input = "int somecode() { return 0; }";
+  std::vector Errors;
+  EXPECT_EQ(Input,
+test::runCheckOnCode(Input, &Errors));
+  ASSERT_EQ(Errors.size(), 1U);
+  // This should match the input; this test only verifies that the presence of
+  // '%' doesn't crash Clang.
+  EXPECT_EQ(Errors[0].Message.Message, "bad code: x % y % z");
+}
+
 class IntLitCheck : public TransformerClangTidyCheck {
 public:
   IntLitCheck(StringRef Name, ClangTidyContext *Context)
Index: clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
@@ -27,6 +27,33 @@
  " explicitly provide an empty explanation if none is desired");
 }
 
+// If a string unintentionally containing '%' is passed as a diagnostic, Clang
+// will claim the string is ill-formed and assert-fail. This function escapes
+// such strings so they can be safely used in diagnostics.
+std::string escapeForDiagnostic(std::string ToEscape) {
+  // Optimize for the common case that the string does not contain `%` at the
+  // cost of an extra scan over the string in the slow case.
+  auto Pos = ToEscape.find('%');
+  if (Pos == ToEscape.npos)
+return ToEscape;
+
+  std::string Result;
+  Result.reserve(ToEscape.size());
+  // Convert position to a count.
+  ++Pos;
+  Result.append(ToEscape, 0, Pos);
+  Result += '%';
+
+  for (auto N = ToEscape.size(); Pos < N; ++Pos) {
+const char C = ToEscape.at(Pos);
+Result += C;
+if (C == '%')
+  Result += '%';
+  }
+
+  return Result;
+}
+
 TransformerClangTidyCheck::TransformerClangTidyCheck(StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
@@ -99,7 +126,8 @@
   }
 
   // Associate the diagnostic with the location of the first change.
-  DiagnosticBuilder Diag = diag((*Edits)[0].Range.getBegin(), *Explanation);
+  DiagnosticBuilder Diag =
+  diag((*Edits)[0].Range.getBegin(), escapeForDiagnostic(*Explanation));
   for (const auto &T : *Edits)
 switch (T.Kind) {
 case transformer::EditKind::Range:


Index: clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -90,6 +90,25 @@
   EXPECT_EQ(Errors[0].Message.FileOffset, 10U);
 }
 
+TEST(TransformerClangTidyCheckTest, DiagnosticMessageEscaped) {
+  class GiveDiagWithPercentSymbol : public TransformerClangTidyCheck {
+  public:
+GiveDiagWithPercentSymbol(StringRef Name, ClangTidyContext *Context)
+: TransformerClangTidyCheck(makeRule(returnStmt(),
+ noopEdit(node(RootID)),
+ cat("bad code: x % y % z")),
+Name, Context) {}
+  };
+  std::string Input = "int somecode() { return 0; }";
+  std::vector Errors;
+  EXPECT_EQ(Input,
+test::runCheckOnCode(Input, &Errors));
+  ASSERT_EQ(Errors.size(), 1U);
+  // This should match the input; this test only verifies that the presence of
+  // '%' doesn't crash Clang.
+  EXPECT_EQ(Errors[0].Message.Message, "bad code: x % y % 

[PATCH] D124715: Use QoS class Utility for ThreadPriority::Low on Mac

2022-05-04 Thread Stefan Haller via Phabricator via cfe-commits
stefanhaller added a comment.

In D124715#3491782 , @akyrtzi wrote:

> That said, you may want to consider dynamically switching to background if 
> running on laptop with battery, or other heuristics,

My take on this is that it would be Apple's responsibility to add a QoS class 
that has this behavior. I don't think it makes sense for every application to 
implement this logic client-side.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124715

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


[PATCH] D124666: In MSVC compatibility mode, handle unqualified templated base class initialization

2022-05-04 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.
This revision is now accepted and ready to land.

lgtm, thanks!

In D124666#3490871 , 
@frederic-tingaud-sonarsource wrote:

> By the way, in the current state of the code, there is no risk of such 
> conflict between typo correction and UnqualifiedBase, because when an 
> unqualified base exists the lookup result will not be empty.
> That's why the test was not failing even without moving the compatibility 
> first.

Yep, that's exactly it, but with the reordering it's somewhat clearer that, if 
we make this work for MS compat purposes, typo correction will not occur.


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

https://reviews.llvm.org/D124666

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


[PATCH] D124806: [clang-tidy] add support for Demorgan conversions to readability-simplify-bool-expr

2022-05-04 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 427087.
njames93 added a comment.

Added release notes.
Fix build issues with previous push.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124806

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-demorgan.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-demorgan.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-demorgan.cpp
@@ -0,0 +1,67 @@
+// RUN: %check_clang_tidy %s readability-simplify-boolean-expr %t
+
+void foo(bool A1, bool A2, bool A3, bool A4) {
+  bool X;
+  X = !(!A1 || A2);
+  X = !(A1 || !A2);
+  X = !(!A1 || !A2);
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (A1 && !A2);
+  // CHECK-FIXES-NEXT: X = (!A1 && A2);
+  // CHECK-FIXES-NEXT: X = (A1 && A2);
+
+  X = !(!A1 && A2);
+  X = !(A1 && !A2);
+  X = !(!A1 && !A2);
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (A1 || !A2);
+  // CHECK-FIXES-NEXT: X = (!A1 || A2);
+  // CHECK-FIXES-NEXT: X = (A1 || A2);
+
+  X = !(!A1 && !A2 && !A3);
+  X = !(!A1 && (!A2 && !A3));
+  X = !(!A1 && (A2 && A3));
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (A1 || A2 || A3);
+  // CHECK-FIXES-NEXT: X = (A1 || A2 || A3);
+  // CHECK-FIXES-NEXT: X = (A1 || !A2 || !A3);
+
+  X = !(A1 && A2 == A3);
+  X = !(!A1 && A2 > A3);
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (!A1 || A2 != A3);
+  // CHECK-FIXES-NEXT: X = (A1 || A2 <= A3);
+
+  // Ensure the check doesn't try to combine fixes for the inner and outer demorgan simplification.
+  X = !(!A1 && !(!A2 && !A3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-2]]:16: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (A1 || (!A2 && !A3));
+
+  // Testing to see how it handles parens
+  X = !(A1 && !A2 && !A3);
+  X = !(A1 && !A2 || !A3);
+  X = !(!A1 || A2 && !A3);
+  X = !((A1 || !A2) && !A3);
+  X = !((A1 || !A2) || !A3);
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (!A1 || A2 || A3);
+  // CHECK-FIXES-NEXT: X = ((!A1 || A2) && A3);
+  // CHECK-FIXES-NEXT: X = (A1 && (!A2 || A3));
+  // CHECK-FIXES-NEXT: X = (!A1 && A2 || A3);
+  // CHECK-FIXES-NEXT: X = (!A1 && A2 && A3);
+  X = !((A1 || A2) && (!A3 || A4));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (!A1 && !A2 || A3 && !A4);
+}
Index: clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
@@ -4,7 +4,8 @@
 =
 
 Looks for boolean expressions involving boolean constants and simplifies
-them to use the appropriate boolean expression directly.
+them

[PATCH] D124349: [analyzer] Get direct binding for specific punned case

2022-05-04 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers added a comment.

Thanks for the comments! Per our discussion, I'll create a different test case 
with a pinned target and add the additional test case to be sure we see 
expected behavior. Best!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124349

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


[PATCH] D124806: [clang-tidy] add support for Demorgan conversions to readability-simplify-bool-expr

2022-05-04 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 427082.
njames93 added a comment.

Reimplement matchers as an ASTVisitor instead.
This massively simplifies the tracking of nested cases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124806

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
  clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-demorgan.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-demorgan.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-demorgan.cpp
@@ -0,0 +1,67 @@
+// RUN: %check_clang_tidy %s readability-simplify-boolean-expr %t
+
+void foo(bool A1, bool A2, bool A3, bool A4) {
+  bool X;
+  X = !(!A1 || A2);
+  X = !(A1 || !A2);
+  X = !(!A1 || !A2);
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (A1 && !A2);
+  // CHECK-FIXES-NEXT: X = (!A1 && A2);
+  // CHECK-FIXES-NEXT: X = (A1 && A2);
+
+  X = !(!A1 && A2);
+  X = !(A1 && !A2);
+  X = !(!A1 && !A2);
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (A1 || !A2);
+  // CHECK-FIXES-NEXT: X = (!A1 || A2);
+  // CHECK-FIXES-NEXT: X = (A1 || A2);
+
+  X = !(!A1 && !A2 && !A3);
+  X = !(!A1 && (!A2 && !A3));
+  X = !(!A1 && (A2 && A3));
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-3]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (A1 || A2 || A3);
+  // CHECK-FIXES-NEXT: X = (A1 || A2 || A3);
+  // CHECK-FIXES-NEXT: X = (A1 || !A2 || !A3);
+
+  X = !(A1 && A2 == A3);
+  X = !(!A1 && A2 > A3);
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (!A1 || A2 != A3);
+  // CHECK-FIXES-NEXT: X = (A1 || A2 <= A3);
+
+  // Ensure the check doesn't try to combine fixes for the inner and outer demorgan simplification.
+  X = !(!A1 && !(!A2 && !A3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-2]]:16: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (A1 || (!A2 && !A3));
+
+  // Testing to see how it handles parens
+  X = !(A1 && !A2 && !A3);
+  X = !(A1 && !A2 || !A3);
+  X = !(!A1 || A2 && !A3);
+  X = !((A1 || !A2) && !A3);
+  X = !((A1 || !A2) || !A3);
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (!A1 || A2 || A3);
+  // CHECK-FIXES-NEXT: X = ((!A1 || A2) && A3);
+  // CHECK-FIXES-NEXT: X = (A1 && (!A2 || A3));
+  // CHECK-FIXES-NEXT: X = (!A1 && A2 || A3);
+  // CHECK-FIXES-NEXT: X = (!A1 && A2 && A3);
+  X = !((A1 || A2) && (!A3 || A4));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: boolean expression can be simplified by DeMorgan's theorem
+  // CHECK-FIXES: X = (!A1 && !A2 || A3 && !A4);
+}
Index: clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
@@ -4,7 +4,8 @@
 =
 
 Looks for boolean expressions involving boolean constants and simplifies
-them to use the appropriate boolean expression directly.
+t

[PATCH] D124715: Use QoS class Utility for ThreadPriority::Low on Mac

2022-05-04 Thread Argyrios Kyrtzidis via Phabricator via cfe-commits
akyrtzi added a comment.

My recommendation is that indexing belongs to 'utility', as @stefanhaller 
mentioned the user is actively depending on functionality coming from the index.
That said, you may want to consider dynamically switching to background if 
running on laptop with battery, or other heuristics, but that could be a 
follow-up enhancement, I don't think always using 'background' is appropriate.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124715

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


[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

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



Comment at: clang/lib/Sema/SemaChecking.cpp:433
+
+  llvm::StringRef getFormatSpecifier(QualType T) {
+if (auto *BT = T->getAs()) {

rsmith wrote:
> yihanaa wrote:
> > rsmith wrote:
> > > rsmith wrote:
> > > > aaron.ballman wrote:
> > > > > yihanaa wrote:
> > > > > > I think this is better maintained in "clang/AST/FormatString.h". 
> > > > > > For example analyze_printf::PrintfSpecifier can get format 
> > > > > > specifier, what do you all think about?
> > > > > +1 to this suggestion -- my hope is that we could generalize it more 
> > > > > then as I notice there are missing specifiers for things like 
> > > > > intmax_t, size_t, ptrdiff_t, _Decimal types, etc. Plus, that will 
> > > > > hopefully make it easier for __builtin_dump_struct to benefit when 
> > > > > new format specifiers are added, such as ones for printing a _BitInt.
> > > > I am somewhat uncertain: every one of these is making arbitrary choices 
> > > > about how to format the value, so it's not clear to me that this is 
> > > > general logic rather than something specific to 
> > > > `__builtin_dump_struct`. For example, using `%f` rather than one of the 
> > > > myriad other ways of formatting `double` is somewhat arbitrary. Using 
> > > > `%s` for any `const char*` is *extremely* arbitrary and will be wrong 
> > > > and will cause crashes in some cases, but it may be the pragmatically 
> > > > correct choice for a dumping utility. A general-purpose mechanism would 
> > > > use `%p` for all kinds of pointer.
> > > > 
> > > > We could perhaps factor out the formatting for cases where there is a 
> > > > clear canonical default formatting, such as for integer types and 
> > > > probably `%p` for pointers, then call that from here with some 
> > > > special-casing, but without a second consumer for that functionality 
> > > > it's really not clear to me what form it should take.
> > > I went ahead and did this, mostly to match concurrent changes to the old 
> > > implementation. There are a few cases where our existing "guess a format 
> > > specifier" logic does the wrong thing for dumping purposes, which I've 
> > > explicitly handled -- things like wanting to dump a `char` / `signed 
> > > char` / `unsigned char` member as a number rather than as a (potentially 
> > > non-printable or whitespace) character.
> >  When I was patching that old implementation, I found that for uint8_t, 
> > int8_t, Clang's existing "guess a format specifier" logic would treat the 
> > value as an integer, but for unsigned char, signed char, char types, it 
> > would Treat it as a character, please look at this example ( 
> > https://godbolt.org/z/ooqn4468T ), I guess this existing logic may have 
> > made some special judgment.
> Yeah. I think in the case where we see some random call to `printf`, `%c` is 
> probably the right thing to guess here, but it doesn't seem appropriate to me 
> to use this in a dumping routine. If we could dump as `'x'` for printable 
> characters and as `'\xAB'` for everything else, that'd be great, but `printf` 
> can't do that itself and I'm not sure we want to be injecting calls to 
> `isprint` or whatever to make that work. Dumping as an integer always seems 
> like it's probably the least-bad option.
> 
> Somewhat related: I wonder if we should use `"\"%s\""` instead of simply 
> `"%s"` when dumping a `const char*`. That's not ideal but probably clearer 
> than the current dump output.
I see value to having strings with SOME level of delimiter, if at least to 
handle cases when the string itself has a newline in it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-04 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:433
+
+  llvm::StringRef getFormatSpecifier(QualType T) {
+if (auto *BT = T->getAs()) {

yihanaa wrote:
> rsmith wrote:
> > rsmith wrote:
> > > aaron.ballman wrote:
> > > > yihanaa wrote:
> > > > > I think this is better maintained in "clang/AST/FormatString.h". For 
> > > > > example analyze_printf::PrintfSpecifier can get format specifier, 
> > > > > what do you all think about?
> > > > +1 to this suggestion -- my hope is that we could generalize it more 
> > > > then as I notice there are missing specifiers for things like intmax_t, 
> > > > size_t, ptrdiff_t, _Decimal types, etc. Plus, that will hopefully make 
> > > > it easier for __builtin_dump_struct to benefit when new format 
> > > > specifiers are added, such as ones for printing a _BitInt.
> > > I am somewhat uncertain: every one of these is making arbitrary choices 
> > > about how to format the value, so it's not clear to me that this is 
> > > general logic rather than something specific to `__builtin_dump_struct`. 
> > > For example, using `%f` rather than one of the myriad other ways of 
> > > formatting `double` is somewhat arbitrary. Using `%s` for any `const 
> > > char*` is *extremely* arbitrary and will be wrong and will cause crashes 
> > > in some cases, but it may be the pragmatically correct choice for a 
> > > dumping utility. A general-purpose mechanism would use `%p` for all kinds 
> > > of pointer.
> > > 
> > > We could perhaps factor out the formatting for cases where there is a 
> > > clear canonical default formatting, such as for integer types and 
> > > probably `%p` for pointers, then call that from here with some 
> > > special-casing, but without a second consumer for that functionality it's 
> > > really not clear to me what form it should take.
> > I went ahead and did this, mostly to match concurrent changes to the old 
> > implementation. There are a few cases where our existing "guess a format 
> > specifier" logic does the wrong thing for dumping purposes, which I've 
> > explicitly handled -- things like wanting to dump a `char` / `signed char` 
> > / `unsigned char` member as a number rather than as a (potentially 
> > non-printable or whitespace) character.
>  When I was patching that old implementation, I found that for uint8_t, 
> int8_t, Clang's existing "guess a format specifier" logic would treat the 
> value as an integer, but for unsigned char, signed char, char types, it would 
> Treat it as a character, please look at this example ( 
> https://godbolt.org/z/ooqn4468T ), I guess this existing logic may have made 
> some special judgment.
Yeah. I think in the case where we see some random call to `printf`, `%c` is 
probably the right thing to guess here, but it doesn't seem appropriate to me 
to use this in a dumping routine. If we could dump as `'x'` for printable 
characters and as `'\xAB'` for everything else, that'd be great, but `printf` 
can't do that itself and I'm not sure we want to be injecting calls to 
`isprint` or whatever to make that work. Dumping as an integer always seems 
like it's probably the least-bad option.

Somewhat related: I wonder if we should use `"\"%s\""` instead of simply `"%s"` 
when dumping a `const char*`. That's not ideal but probably clearer than the 
current dump output.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D124715: Use QoS class Utility for ThreadPriority::Low on Mac

2022-05-04 Thread David Goldman via Phabricator via cfe-commits
dgoldman added a comment.

In D124715#3490364 , @stefanhaller 
wrote:

> In D124715#3488447 , @sammccall 
> wrote:
>
>> (How) does this interact with battery vs mains power on laptops?
>> It seems like there's a common scenario where:
>>
>> - the user is on a relatively slow laptop, running off battery
>> - the codebase is large, and indexing is unlikely to finish within an 
>> editing session
>>
>> In this case, it seems like only using efficiency cores is what you'd want, 
>> and that people are likely to be upset if clangd 15 keeps their performance 
>> cores running at all times.
>
> I can only speak for myself here: I'm a laptop user myself, and I work on 
> battery the majority of the day; but I still wouldn't trade indexing speed 
> for saving battery. The clangd index is so essential for my work that I 
> always want it to be available as quickly as possible.
>
>> Reading the docs 
>> 
>>  it seems like background is the intended QoS for this type of work ("such 
>> as indexing"..."minutes or hours").
>
> How long it takes is only one aspect of it. Other clues from the 
> documentation:
>
> Utility: "typically have a progress bar that is visible to the user. Focuses 
> on providing a balance between responsiveness, performance, and energy 
> efficiency."
> Background: "isn't visible to the user. Focuses on energy efficiency."
>
> The way I read it, Background is intended for tasks that don't make a 
> significant difference to the functionality of the software. An example might 
> be face detection in the Photos app; as long as it is not finished, it only 
> affects a small part of the functionality, the rest of the app is perfectly 
> usable. That's not the case for clangd, the software is pretty much not 
> usable without an index.

See also Argyrios's comment 
 - I 
think the main problem is it competes with Spotlight indexing and disk backups. 
Maybe we'd want to keep this customizable though e.g. via a clangd flag?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124715

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


[PATCH] D119147: [AIX][clang][driver] Check the command string to the linker for exportlist opts and

2022-05-04 Thread Digger Lin via Phabricator via cfe-commits
DiggerLin marked 8 inline comments as done.
DiggerLin added inline comments.



Comment at: clang/test/Driver/aix-ld.c:985
+// CHECK-LD64-SHARED-EXPFULL: "-bM:SRE"
+// CHECK-LD64-SHARED-EXPFULL: "-bnoentry"
+// CHECK-LD64-SHARED-EXPFULL: "-b64"

MaskRay wrote:
> If these options are actually adjacent, check them on the same line to make 
> the test more strict: you can catch issues if new options are somehow 
> inserted in between.
yes, the options are actually adjacent now, if we put these option in the same 
line,  there maybe a failure when the driver change the options(for example 
adding a option) later.  and it will have different style on the existing test 
options


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119147

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


[PATCH] D123831: [clang][extract-api] Use relative includes

2022-05-04 Thread Zixu Wang via Phabricator via cfe-commits
zixuw added a comment.

Accidentally added another test case in my local workspace. Removed in 
5f841c71fc2cc77c92f526791cd7a938bcac69aa 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123831

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


[clang] 5f841c7 - [NFC] Remove unfinished test case

2022-05-04 Thread Zixu Wang via cfe-commits

Author: Zixu Wang
Date: 2022-05-04T10:40:25-07:00
New Revision: 5f841c71fc2cc77c92f526791cd7a938bcac69aa

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

LOG: [NFC] Remove unfinished test case

4c262fee08b5383c96857d77eefe80d61c41d2b0 accidentally added local
unfinished test case clang/test/Index/annotate-comments-enum-constant.c
This patch removes it.

Added: 


Modified: 


Removed: 
clang/test/Index/annotate-comments-enum-constant.c



diff  --git a/clang/test/Index/annotate-comments-enum-constant.c 
b/clang/test/Index/annotate-comments-enum-constant.c
deleted file mode 100644
index f86eaf4742d30..0
--- a/clang/test/Index/annotate-comments-enum-constant.c
+++ /dev/null
@@ -1,17 +0,0 @@
-// RUN: rm -rf %t
-// RUN: mkdir %t
-// RUN: c-index-test -test-load-source all 
-comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng %s > %t/out
-// RUN: FileCheck %s --dump-input always < %t/out
-
-enum {
-  /// Documentation for Foo
-  Foo,
-  Bar, // No documentation for Bar
-  /// Documentation for Baz
-  Baz,
-};
-// CHECK: EnumConstantDecl=Foo:[[@LINE-5]]:3 (Definition) {{.*}} 
BriefComment=[Documentation for Foo] FullCommentAsHTML=[ 
Documentation for Foo] FullCommentAsXML=[Fooc:@Ea@Foo@FooFoo
 Documentation for Foo]
-// CHECK: EnumConstantDecl=Bar:[[@LINE-5]]:3 (Definition)
-// CHECK-NOT: BriefComment=[Documentation for Foo]
-// CHECK: EnumConstantDecl=Baz:[[@LINE-5]]:3 (Definition) {{.*}} 
BriefComment=[Documentation for Baz] FullCommentAsHTML=[ 
Documentation for Baz] FullCommentAsXML=[Bazc:@Ea@Foo@BazBaz
 Documentation for Baz]
-



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


[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-05-04 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Yes, we've discussed this before, and I'm very much in favor of this change. 
This is assertion removal, and the assertion has been really useful back in the 
day, but the assertion doesn't seem to be realistic to maintain with all the 
new logic in the constraint solver coming in in recent years.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h:88
   GenericDataMap   GDM;  // Custom data stored by a client of this class.
+  bool Infeasible = false;
   unsigned refCount;

The reader deserves a massive amount of explanation here. Normally infeasible 
states are just null states. We need to explain how these new infeasible states 
are different.

Maybe a longer name? `IsPostOverconstrained` or something like that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

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


[PATCH] D124943: [clang][dataflow] Add flowConditionIsTautology function

2022-05-04 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua added a comment.

This allows me to query when an expression is always encountered/executed. 
Alternatively, if I have a set of interesting expressions, I can note the flow 
condition at every expression, compute the disjunction of the set of flow 
conditions, and determine if execution will always encounter an interesting 
expression.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124943

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


[PATCH] D124874: [clang] add -fmodule-file-home-is-cwd

2022-05-04 Thread Richard Howell via Phabricator via cfe-commits
rmaz updated this revision to Diff 427065.
rmaz added a comment.

fix windows paths attempt #2


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124874

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Lex/HeaderSearchOptions.h
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/Modules/module-file-home-is-cwd.m


Index: clang/test/Modules/module-file-home-is-cwd.m
===
--- /dev/null
+++ clang/test/Modules/module-file-home-is-cwd.m
@@ -0,0 +1,8 @@
+// RUN: cd %S
+// RUN: %clang_cc1 -fmodules -fno-implicit-modules -fmodule-file-home-is-cwd 
-fmodule-name=libA -emit-module Inputs/normal-module-map/module.map -o 
%t/mod.pcm
+// RUN: llvm-bcanalyzer --dump --disable-histogram %t/mod.pcm | FileCheck %s
+
+// CHECK:  blob data = 
'Inputs{{/|\\}}normal-module-map{{/|\\}}a1.h'
+// CHECK:  blob data = 
'Inputs{{/|\\}}normal-module-map{{/|\\}}a2.h'
+// CHECK:  blob data = 
'Inputs{{/|\\}}normal-module-map{{/|\\}}module.map'
+// CHECK-NOT: MODULE_DIRECTORY
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -1223,7 +1223,15 @@
 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
   }
 
-  if (WritingModule && WritingModule->Directory) {
+  if (WritingModule &&
+  PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd) {
+// Use the current working directory as the base path for all inputs.
+auto *CWD =
+Context.getSourceManager().getFileManager().getDirectory(".").get();
+SmallString<128> BaseDir(CWD->getName());
+cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
+BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
+  } else if (WritingModule && WritingModule->Directory) {
 SmallString<128> BaseDir(WritingModule->Directory->getName());
 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
 
Index: clang/include/clang/Lex/HeaderSearchOptions.h
===
--- clang/include/clang/Lex/HeaderSearchOptions.h
+++ clang/include/clang/Lex/HeaderSearchOptions.h
@@ -143,6 +143,12 @@
   /// file.
   unsigned ModuleMapFileHomeIsCwd : 1;
 
+  /// Set the base path of a built module file to be the current working
+  /// directory. This is useful for sharing module files across machines
+  /// that build with different paths without having to rewrite all
+  /// modulemap files to have working directory relative paths.
+  unsigned ModuleFileHomeIsCwd : 1;
+
   /// Also search for prebuilt implicit modules in the prebuilt module cache
   /// path.
   unsigned EnablePrebuiltImplicitModules : 1;
@@ -222,9 +228,9 @@
   HeaderSearchOptions(StringRef _Sysroot = "/")
   : Sysroot(_Sysroot), ModuleFormat("raw"), DisableModuleHash(false),
 ImplicitModuleMaps(false), ModuleMapFileHomeIsCwd(false),
-EnablePrebuiltImplicitModules(false), UseBuiltinIncludes(true),
-UseStandardSystemIncludes(true), UseStandardCXXIncludes(true),
-UseLibcxx(false), Verbose(false),
+ModuleFileHomeIsCwd(false), EnablePrebuiltImplicitModules(false),
+UseBuiltinIncludes(true), UseStandardSystemIncludes(true),
+UseStandardCXXIncludes(true), UseLibcxx(false), Verbose(false),
 ModulesValidateOncePerBuildSession(false),
 ModulesValidateSystemHeaders(false),
 ValidateASTInputFilesContent(false), UseDebugInfo(false),
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -5609,6 +5609,10 @@
   HelpText<"Use the current working directory as the home directory of "
"module maps specified by -fmodule-map-file=">,
   MarshallingInfoFlag>;
+def fmodule_file_home_is_cwd : Flag<["-"], "fmodule-file-home-is-cwd">,
+  HelpText<"Use the current working directory as the base directory of "
+   "compiled module files.">,
+  MarshallingInfoFlag>;
 def fmodule_feature : Separate<["-"], "fmodule-feature">,
   MetaVarName<"">,
   HelpText<"Enable  in module map requires declarations">,


Index: clang/test/Modules/module-file-home-is-cwd.m
===
--- /dev/null
+++ clang/test/Modules/module-file-home-is-cwd.m
@@ -0,0 +1,8 @@
+// RUN: cd %S
+// RUN: %clang_cc1 -fmodules -fno-implicit-modules -fmodule-file-home-is-cwd -fmodule-name=libA -emit-module Inputs/normal-module-map/module.map -o %t/mod.pcm
+// RUN: llvm-bcanalyzer --dump --disable-histogram %t/mod.pcm | FileCheck %s
+
+// CHECK:  blob data = 'Inputs{{/|\\}}normal-module-map{{/|\\}}a1.h'
+// CHECK:  blob data = 'Inputs{{/|\\}}normal-module-map{{/|\\}}

[PATCH] D124946: [clang] serialize ORIGINAL_PCH_DIR relative to BaseDirectory

2022-05-04 Thread Richard Howell via Phabricator via cfe-commits
rmaz created this revision.
Herald added a project: All.
rmaz requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This diff changes the serialization of the `ORIGINAL_PCH_DIR`
entry in module files to be serialized relative to the module's
`BaseDirectory`. This will allow for the module to be relocatable
across machines.

The path is restored relative to the module's BaseDirectory on
deserialization.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124946

Files:
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/Modules/relative-original-dir.m


Index: clang/test/Modules/relative-original-dir.m
===
--- /dev/null
+++ clang/test/Modules/relative-original-dir.m
@@ -0,0 +1,6 @@
+// RUN: rm -rf %t/normal-module-map
+// RUN: cp -R %S/Inputs/normal-module-map %t
+// RUN: %clang_cc1 -fmodules -fno-implicit-modules -fmodule-name=libA 
-emit-module %t/normal-module-map/module.map -o 
%t/normal-module-map/outdir/mod.pcm
+// RUN: llvm-bcanalyzer --dump --disable-histogram 
%t/normal-module-map/outdir/mod.pcm | FileCheck %s
+
+// CHECK:  blob data = 'outdir'
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -1461,8 +1461,7 @@
 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
 
 SmallString<128> OutputPath(OutputFile);
-
-SM.getFileManager().makeAbsolutePath(OutputPath);
+PreparePathForOutput(OutputPath);
 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
 
 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -2898,6 +2898,7 @@
 
 case ORIGINAL_PCH_DIR:
   F.OriginalDir = std::string(Blob);
+  ResolveImportedPath(F, F.OriginalDir);
   break;
 
 case MODULE_NAME:


Index: clang/test/Modules/relative-original-dir.m
===
--- /dev/null
+++ clang/test/Modules/relative-original-dir.m
@@ -0,0 +1,6 @@
+// RUN: rm -rf %t/normal-module-map
+// RUN: cp -R %S/Inputs/normal-module-map %t
+// RUN: %clang_cc1 -fmodules -fno-implicit-modules -fmodule-name=libA -emit-module %t/normal-module-map/module.map -o %t/normal-module-map/outdir/mod.pcm
+// RUN: llvm-bcanalyzer --dump --disable-histogram %t/normal-module-map/outdir/mod.pcm | FileCheck %s
+
+// CHECK:  blob data = 'outdir'
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -1461,8 +1461,7 @@
 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
 
 SmallString<128> OutputPath(OutputFile);
-
-SM.getFileManager().makeAbsolutePath(OutputPath);
+PreparePathForOutput(OutputPath);
 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
 
 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -2898,6 +2898,7 @@
 
 case ORIGINAL_PCH_DIR:
   F.OriginalDir = std::string(Blob);
+  ResolveImportedPath(F, F.OriginalDir);
   break;
 
 case MODULE_NAME:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123831: [clang][extract-api] Use relative includes

2022-05-04 Thread Zixu Wang 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 rG4c262fee08b5: [clang][extract-api] Use relative includes 
(authored by zixuw).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123831

Files:
  clang/include/clang/ExtractAPI/FrontendActions.h
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/test/ExtractAPI/known_files_only_hmap.c
  clang/test/ExtractAPI/relative_include.m
  clang/test/Index/annotate-comments-enum-constant.c

Index: clang/test/Index/annotate-comments-enum-constant.c
===
--- /dev/null
+++ clang/test/Index/annotate-comments-enum-constant.c
@@ -0,0 +1,17 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: c-index-test -test-load-source all -comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng %s > %t/out
+// RUN: FileCheck %s --dump-input always < %t/out
+
+enum {
+  /// Documentation for Foo
+  Foo,
+  Bar, // No documentation for Bar
+  /// Documentation for Baz
+  Baz,
+};
+// CHECK: EnumConstantDecl=Foo:[[@LINE-5]]:3 (Definition) {{.*}} BriefComment=[Documentation for Foo] FullCommentAsHTML=[ Documentation for Foo] FullCommentAsXML=[Fooc:@Ea@Foo@FooFoo Documentation for Foo]
+// CHECK: EnumConstantDecl=Bar:[[@LINE-5]]:3 (Definition)
+// CHECK-NOT: BriefComment=[Documentation for Foo]
+// CHECK: EnumConstantDecl=Baz:[[@LINE-5]]:3 (Definition) {{.*}} BriefComment=[Documentation for Baz] FullCommentAsHTML=[ Documentation for Baz] FullCommentAsXML=[Bazc:@Ea@Foo@BazBaz Documentation for Baz]
+
Index: clang/test/ExtractAPI/relative_include.m
===
--- /dev/null
+++ clang/test/ExtractAPI/relative_include.m
@@ -0,0 +1,193 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// Setup framework root
+// RUN: mkdir -p %t/Frameworks/MyFramework.framework/Headers
+// RUN: cp %t/MyFramework.h %t/Frameworks/MyFramework.framework/Headers/
+// RUN: cp %t/MyHeader.h %t/Frameworks/MyFramework.framework/Headers/
+
+// RUN: sed -e "s@SRCROOT@%{/t:regex_replacement}@g" \
+// RUN: %t/reference.output.json.in >> %t/reference.output.json
+
+// Headermap maps headers to the source root SRCROOT
+// RUN: sed -e "s@SRCROOT@%{/t:regex_replacement}@g" \
+// RUN: %t/headermap.hmap.json.in >> %t/headermap.hmap.json
+// RUN: %hmaptool write %t/headermap.hmap.json %t/headermap.hmap
+
+// Input headers use paths to the framework root/DSTROOT
+// RUN: %clang_cc1 -extract-api -v --product-name=MyFramework \
+// RUN: -triple arm64-apple-macosx \
+// RUN: -iquote%t -I%t/headermap.hmap -F%t/Frameworks \
+// RUN: -x objective-c-header \
+// RUN: %t/Frameworks/MyFramework.framework/Headers/MyFramework.h \
+// RUN: %t/Frameworks/MyFramework.framework/Headers/MyHeader.h \
+// RUN: %t/QuotedHeader.h \
+// RUN: -o %t/output.json 2>&1 -verify | FileCheck -allow-empty %s
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+// CHECK:  :
+// CHECK-NEXT: #import 
+// CHECK-NEXT: #import 
+// CHECK-NEXT: #import "QuotedHeader.h"
+
+//--- headermap.hmap.json.in
+{
+  "mappings" :
+{
+ "MyFramework/MyHeader.h" : "SRCROOT/MyHeader.h"
+}
+}
+
+//--- MyFramework.h
+// Umbrella for MyFramework
+#import 
+// expected-no-diagnostics
+
+//--- MyHeader.h
+#import 
+int MyInt;
+// expected-no-diagnostics
+
+//--- QuotedHeader.h
+char MyChar;
+// expected-no-diagnostics
+
+//--- Frameworks/OtherFramework.framework/Headers/OtherHeader.h
+int OtherInt;
+// expected-no-diagnostics
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "MyFramework",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationships": [],
+  "symbols": [
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:I",
+  "spelling": "int"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "MyInt"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:@MyInt"
+  },
+  "kind": {
+"displayName": "Global Variable",
+"identifier": "objective-c.var"
+  },
+  "location": {
+"position": {
+   

[clang] 4c262fe - [clang][extract-api] Use relative includes

2022-05-04 Thread Zixu Wang via cfe-commits

Author: Zixu Wang
Date: 2022-05-04T10:28:01-07:00
New Revision: 4c262fee08b5383c96857d77eefe80d61c41d2b0

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

LOG: [clang][extract-api] Use relative includes

This patch transforms the given input headers to relative include names
using header search entries and some heuritics.
For example: `/Path/To/Header.h` will be included as `` with a
search path of `-I /Path/To/`; and
`/Path/To/Framework.framework/Headers/Header.h` will be included as
``, given a search path of `-F /Path/To`.
Headermaps will also be queried in reverse to find a spelled name to
include headers.

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

Added: 
clang/test/ExtractAPI/relative_include.m
clang/test/Index/annotate-comments-enum-constant.c

Modified: 
clang/include/clang/ExtractAPI/FrontendActions.h
clang/lib/ExtractAPI/ExtractAPIConsumer.cpp

Removed: 
clang/test/ExtractAPI/known_files_only_hmap.c



diff  --git a/clang/include/clang/ExtractAPI/FrontendActions.h 
b/clang/include/clang/ExtractAPI/FrontendActions.h
index dec3b5ca93d18..2cb8ef130fdd7 100644
--- a/clang/include/clang/ExtractAPI/FrontendActions.h
+++ b/clang/include/clang/ExtractAPI/FrontendActions.h
@@ -40,7 +40,10 @@ class ExtractAPIAction : public ASTFrontendAction {
   std::unique_ptr Buffer;
 
   /// The input file originally provided on the command line.
-  std::vector KnownInputFiles;
+  ///
+  /// This captures the spelling used to include the file and whether the
+  /// include is quoted or not.
+  SmallVector, bool>> KnownInputFiles;
 
   /// Prepare to execute the action on the given CompilerInstance.
   ///

diff  --git a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp 
b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
index b1de2674b622b..317bcd1be8256 100644
--- a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
+++ b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
@@ -38,7 +38,10 @@
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Regex.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -55,10 +58,128 @@ StringRef getTypedefName(const TagDecl *Decl) {
   return {};
 }
 
+Optional getRelativeIncludeName(const CompilerInstance &CI,
+ StringRef File,
+ bool *IsQuoted = nullptr) {
+  assert(CI.hasFileManager() &&
+ "CompilerInstance does not have a FileNamager!");
+
+  using namespace llvm::sys;
+  // Matches framework include patterns
+  const llvm::Regex Rule("/(.+)\\.framework/(.+)?Headers/(.+)");
+
+  const auto &FS = CI.getVirtualFileSystem();
+
+  SmallString<128> FilePath(File.begin(), File.end());
+  FS.makeAbsolute(FilePath);
+  path::remove_dots(FilePath, true);
+  File = FilePath;
+
+  // Checks whether `Dir` is a strict path prefix of `File`. If so returns
+  // the prefix length. Otherwise return 0.
+  auto CheckDir = [&](llvm::StringRef Dir) -> unsigned {
+llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
+FS.makeAbsolute(DirPath);
+path::remove_dots(DirPath, true);
+Dir = DirPath;
+for (auto NI = path::begin(File), NE = path::end(File),
+  DI = path::begin(Dir), DE = path::end(Dir);
+ /*termination condition in loop*/; ++NI, ++DI) {
+  // '.' components in File are ignored.
+  while (NI != NE && *NI == ".")
+++NI;
+  if (NI == NE)
+break;
+
+  // '.' components in Dir are ignored.
+  while (DI != DE && *DI == ".")
+++DI;
+
+  // Dir is a prefix of File, up to '.' components and choice of path
+  // separators.
+  if (DI == DE)
+return NI - path::begin(File);
+
+  // Consider all path separators equal.
+  if (NI->size() == 1 && DI->size() == 1 &&
+  path::is_separator(NI->front()) && path::is_separator(DI->front()))
+continue;
+
+  // Special case Apple .sdk folders since the search path is typically a
+  // symlink like `iPhoneSimulator14.5.sdk` while the file is instead
+  // located in `iPhoneSimulator.sdk` (the real folder).
+  if (NI->endswith(".sdk") && DI->endswith(".sdk")) {
+StringRef NBasename = path::stem(*NI);
+StringRef DBasename = path::stem(*DI);
+if (DBasename.startswith(NBasename))
+  continue;
+  }
+
+  if (*NI != *DI)
+break;
+}
+return 0;
+  };
+
+  unsigned PrefixLength = 0;
+
+  // Go through the search paths and find the first one that is a prefix of
+  // the header.
+  for (const auto &Entry : CI.getHeaderSearchOpts().UserEntries) {
+// Note whether the

[PATCH] D123831: [clang][extract-api] Use relative includes

2022-05-04 Thread Zixu Wang via Phabricator via cfe-commits
zixuw updated this revision to Diff 427061.
zixuw added a comment.
Herald added a subscriber: arphaman.

Update test case to use cc1 instead of driver


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123831

Files:
  clang/include/clang/ExtractAPI/FrontendActions.h
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/test/ExtractAPI/known_files_only_hmap.c
  clang/test/ExtractAPI/relative_include.m
  clang/test/Index/annotate-comments-enum-constant.c

Index: clang/test/Index/annotate-comments-enum-constant.c
===
--- /dev/null
+++ clang/test/Index/annotate-comments-enum-constant.c
@@ -0,0 +1,17 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: c-index-test -test-load-source all -comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng %s > %t/out
+// RUN: FileCheck %s --dump-input always < %t/out
+
+enum {
+  /// Documentation for Foo
+  Foo,
+  Bar, // No documentation for Bar
+  /// Documentation for Baz
+  Baz,
+};
+// CHECK: EnumConstantDecl=Foo:[[@LINE-5]]:3 (Definition) {{.*}} BriefComment=[Documentation for Foo] FullCommentAsHTML=[ Documentation for Foo] FullCommentAsXML=[Fooc:@Ea@Foo@FooFoo Documentation for Foo]
+// CHECK: EnumConstantDecl=Bar:[[@LINE-5]]:3 (Definition)
+// CHECK-NOT: BriefComment=[Documentation for Foo]
+// CHECK: EnumConstantDecl=Baz:[[@LINE-5]]:3 (Definition) {{.*}} BriefComment=[Documentation for Baz] FullCommentAsHTML=[ Documentation for Baz] FullCommentAsXML=[Bazc:@Ea@Foo@BazBaz Documentation for Baz]
+
Index: clang/test/ExtractAPI/relative_include.m
===
--- /dev/null
+++ clang/test/ExtractAPI/relative_include.m
@@ -0,0 +1,193 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// Setup framework root
+// RUN: mkdir -p %t/Frameworks/MyFramework.framework/Headers
+// RUN: cp %t/MyFramework.h %t/Frameworks/MyFramework.framework/Headers/
+// RUN: cp %t/MyHeader.h %t/Frameworks/MyFramework.framework/Headers/
+
+// RUN: sed -e "s@SRCROOT@%{/t:regex_replacement}@g" \
+// RUN: %t/reference.output.json.in >> %t/reference.output.json
+
+// Headermap maps headers to the source root SRCROOT
+// RUN: sed -e "s@SRCROOT@%{/t:regex_replacement}@g" \
+// RUN: %t/headermap.hmap.json.in >> %t/headermap.hmap.json
+// RUN: %hmaptool write %t/headermap.hmap.json %t/headermap.hmap
+
+// Input headers use paths to the framework root/DSTROOT
+// RUN: %clang_cc1 -extract-api -v --product-name=MyFramework \
+// RUN: -triple arm64-apple-macosx \
+// RUN: -iquote%t -I%t/headermap.hmap -F%t/Frameworks \
+// RUN: -x objective-c-header \
+// RUN: %t/Frameworks/MyFramework.framework/Headers/MyFramework.h \
+// RUN: %t/Frameworks/MyFramework.framework/Headers/MyHeader.h \
+// RUN: %t/QuotedHeader.h \
+// RUN: -o %t/output.json 2>&1 -verify | FileCheck -allow-empty %s
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+// CHECK:  :
+// CHECK-NEXT: #import 
+// CHECK-NEXT: #import 
+// CHECK-NEXT: #import "QuotedHeader.h"
+
+//--- headermap.hmap.json.in
+{
+  "mappings" :
+{
+ "MyFramework/MyHeader.h" : "SRCROOT/MyHeader.h"
+}
+}
+
+//--- MyFramework.h
+// Umbrella for MyFramework
+#import 
+// expected-no-diagnostics
+
+//--- MyHeader.h
+#import 
+int MyInt;
+// expected-no-diagnostics
+
+//--- QuotedHeader.h
+char MyChar;
+// expected-no-diagnostics
+
+//--- Frameworks/OtherFramework.framework/Headers/OtherHeader.h
+int OtherInt;
+// expected-no-diagnostics
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "MyFramework",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationships": [],
+  "symbols": [
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:I",
+  "spelling": "int"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "MyInt"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "objective-c",
+"precise": "c:@MyInt"
+  },
+  "kind": {
+"displayName": "Global Variable",
+"identifier": "objective-c.var"
+  },
+  "location": {
+"position": {
+  "character": 5,
+  "line": 2
+},
+"uri": "file://

[PATCH] D124943: [clang][dataflow] Add flowConditionIsTautology function

2022-05-04 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

The code looks good, but what is the intended application?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124943

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


[clang] 859d923 - Fix a failing assertion with vector type initialization

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

Author: Aaron Ballman
Date: 2022-05-04T13:25:21-04:00
New Revision: 859d92394812c0e5e650ab337717719b9687e5ce

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

LOG: Fix a failing assertion with vector type initialization

When constant evaluating the initializer for an object of vector type,
we would call APInt::trunc() but truncate to the same bit-width the
object already had, which would cause an assertion. Instead, use
APInt::truncOrSelf() so that we no longer assert in this situation.

Fix #50216

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/ExprConstant.cpp
clang/test/Sema/vector-init.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 079523a07361e..3187dad2b729e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -132,6 +132,10 @@ Bug Fixes
   argument to a generic selection expression has side effects in the case where
   the expression is result dependent. This fixes
   `Issue 50227 `_.
+- Fixed an assertion when constant evaluating an initializer for a GCC/Clang
+  floating-point vector type when the width of the initialization is exactly
+  the same as the elements of the vector being initialized.
+  Fixes `Issue 50216 `_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 70a1e0bbd91aa..650ba305c48b1 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -10353,9 +10353,9 @@ bool VectorExprEvaluator::VisitCastExpr(const CastExpr 
*E) {
   for (unsigned i = 0; i < NElts; i++) {
 llvm::APInt Elt;
 if (BigEndian)
-  Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
+  Elt = SValInt.rotl(i*EltSize+FloatEltSize).truncOrSelf(FloatEltSize);
 else
-  Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
+  Elt = SValInt.rotr(i*EltSize).truncOrSelf(FloatEltSize);
 Elts.push_back(APValue(APFloat(Sem, Elt)));
   }
 } else if (EltTy->isIntegerType()) {

diff  --git a/clang/test/Sema/vector-init.c b/clang/test/Sema/vector-init.c
index c7c278f96368f..554e976892636 100644
--- a/clang/test/Sema/vector-init.c
+++ b/clang/test/Sema/vector-init.c
@@ -42,3 +42,11 @@ void test3(void) {
   longlong2 arr1[2] = { test3_helper(), test3_helper() };
   short4 arr2[2] = { test3_helper(), test3_helper() }; // expected-error 2 
{{initializing 'short4' (vector of 4 'short' values) with an expression of 
incompatible type 'short8' (vector of 8 'short' values)}}
 }
+
+// GH50216
+// These would previously crash when constant evaluating the initializers.
+typedef double float64x1_t __attribute__((vector_size(8)));
+float64x1_t arg1 = (float64x1_t)0x3fedf9d4343c7c80; // okay
+
+typedef float float32x1_t __attribute__((vector_size(4)));
+float32x1_t arg2 = (float32x1_t)0x3fedf9d4; // okay



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


[PATCH] D124923: [Sema] Simplify CheckConstraintSatisfaction. NFC

2022-05-04 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clang/lib/Sema/SemaConcept.cpp:335
+  auto Satisfaction =
+  std::make_unique(Template, TemplateArgs);
   if (::CheckConstraintSatisfaction(*this, Template, ConstraintExprs,

ilya-biryukov wrote:
> sammccall wrote:
> > ilya-biryukov wrote:
> > > I also wonder if this could be allocated in the AST arena, maybe worth 
> > > exploring.
> > > Definitely outside this change, though, would like to keep this one an 
> > > NFC.
> > not just could, but must - FoldingSet doesn't own its objects, so this 
> > object is leaked once the FoldingSet is destroyed! Allocating it on the 
> > ASTContext would fix this because they have the same lifetime.
> > 
> > Agree with not mixing it into this patch, but please add a FIXME and do 
> > follow up on it if you don't mind.
> > (and at that point, should we really be passing it back by value?)
> Oh, wow, good catch, thanks. I'll send a separate fix for the memory leak.
So there's no memory leak actually.
`Sema`'s destructor calls `delete` for all nodes inside `SatisfactionCache`. 
Allocating them in `ASTContext` is not trivial as they store a `SmallVector`, 
which may dynamically allocate itself. Hence, we must call destructor and 
`ASTContext` does not do that. 
The `SmallVector` itself gets built recursively when calling 
`CheckConstraintSatisfaction`.

Cleaning it up is probably possible, but a bit more work than I planned for 
this. I'll replace the fixme with a comment mentioning `Sema` destructor cleans 
up for us.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124923

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


[PATCH] D124943: [clang][dataflow] Add flowConditionIsTautology function

2022-05-04 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua created this revision.
li.zhe.hua added reviewers: ymandel, sgatev, xazax.hun.
Herald added subscribers: tschuett, steakhal, rnkovacs.
Herald added a project: All.
li.zhe.hua requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Provide a way for users to check if a flow condition is
unconditionally true.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124943

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp


Index: clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
@@ -140,4 +140,43 @@
   EXPECT_TRUE(Context.flowConditionImplies(FC3, C3));
 }
 
+TEST_F(DataflowAnalysisContextTest, FlowConditionTautologies) {
+  // Default flow condition with empty/no constraints is always true.
+  auto &FC1 = Context.makeFlowConditionToken();
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC1));
+
+  // Negation of empty constraints is never true.
+  auto &FC2 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC2,
+ Context.getOrCreateNegationValue(FC1));
+  EXPECT_FALSE(Context.flowConditionIsTautology(FC2));
+
+  // FC1 || !FC1 is always true.
+  EXPECT_TRUE(
+  Context.flowConditionIsTautology(Context.joinFlowConditions(FC1, FC2)));
+
+  // Literal `true` is always true.
+  auto &FC3 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC3, Context.getBoolLiteralValue(true));
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC3));
+
+  // Literal `false` is never true.
+  auto &FC4 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC4, Context.getBoolLiteralValue(false));
+  EXPECT_FALSE(Context.flowConditionIsTautology(FC4));
+
+  // We can't prove that an arbitrary bool A is always true...
+  auto &C1 = Context.createAtomicBoolValue();
+  auto &FC5 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC5, C1);
+  EXPECT_FALSE(Context.flowConditionIsTautology(FC5));
+
+  // ... but we can prove A || !A is true.
+  auto &FC6 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(
+  FC6, Context.getOrCreateDisjunctionValue(
+   C1, Context.getOrCreateNegationValue(C1)));
+  EXPECT_TRUE(Context.flowConditionIsTautology(FC6));
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
@@ -117,6 +117,19 @@
   return S->solve(std::move(Constraints)) == Solver::Result::Unsatisfiable;
 }
 
+bool DataflowAnalysisContext::flowConditionIsTautology(AtomicBoolValue &Token) 
{
+  // Returns true if and only if we cannot prove that the flow condition can
+  // ever be false.
+  llvm::DenseSet Constraints = {
+  &getBoolLiteralValue(true),
+  &getOrCreateNegationValue(getBoolLiteralValue(false)),
+  &getOrCreateNegationValue(Token),
+  };
+  llvm::DenseSet VisitedTokens;
+  addTransitiveFlowConditionConstraints(Token, Constraints, VisitedTokens);
+  return S->solve(std::move(Constraints)) == Solver::Result::Unsatisfiable;
+}
+
 void DataflowAnalysisContext::addTransitiveFlowConditionConstraints(
 AtomicBoolValue &Token, llvm::DenseSet &Constraints,
 llvm::DenseSet &VisitedTokens) const {
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
@@ -173,6 +173,10 @@
   /// identified by `Token` imply that `Val` is true.
   bool flowConditionImplies(AtomicBoolValue &Token, BoolValue &Val);
 
+  /// Returns true if the constraints of the flow condition identified by
+  /// `Token` is always true.
+  bool flowConditionIsTautology(AtomicBoolValue &Token);
+
 private:
   /// Adds all constraints of the flow condition identified by `Token` and all
   /// of its transitive dependencies to `Constraints`. `VisitedTokens` is used


Index: clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
@@ -140,4 +140,43 @@
   EXPECT_TRUE(Context.flowConditionImplies(FC3, C3));
 }
 
+TEST_F(DataflowAnalysisContextT

[PATCH] D124842: [NFC][CUDA][HIP] rework mangling number for aux target

2022-05-04 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
yaxunl marked an inline comment as done.
Closed by commit rG62501bc45a2f: [NFC][CUDA][HIP] rework mangling number for 
aux target (authored by yaxunl).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D124842?vs=426650&id=427053#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124842

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/Mangle.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/MicrosoftMangle.cpp
  clang/lib/CodeGen/CGCUDANV.cpp

Index: clang/lib/CodeGen/CGCUDANV.cpp
===
--- clang/lib/CodeGen/CGCUDANV.cpp
+++ clang/lib/CodeGen/CGCUDANV.cpp
@@ -24,7 +24,6 @@
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/ReplaceConstant.h"
 #include "llvm/Support/Format.h"
-#include "llvm/Support/SaveAndRestore.h"
 
 using namespace clang;
 using namespace CodeGen;
@@ -261,8 +260,6 @@
 }
 
 std::string CGNVCUDARuntime::getDeviceSideName(const NamedDecl *ND) {
-  llvm::SaveAndRestore MangleAsDevice(
-  CGM.getContext().CUDAMangleDeviceNameInHostCompilation, true);
   GlobalDecl GD;
   // D could be either a kernel or a variable.
   if (auto *FD = dyn_cast(ND))
Index: clang/lib/AST/MicrosoftMangle.cpp
===
--- clang/lib/AST/MicrosoftMangle.cpp
+++ clang/lib/AST/MicrosoftMangle.cpp
@@ -147,7 +147,8 @@
   SmallString<16> AnonymousNamespaceHash;
 
 public:
-  MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags);
+  MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags,
+ bool IsAux = false);
   bool shouldMangleCXXName(const NamedDecl *D) override;
   bool shouldMangleStringLiteral(const StringLiteral *SL) override;
   void mangleCXXName(GlobalDecl GD, raw_ostream &Out) override;
@@ -221,7 +222,7 @@
 
 // Use the canonical number for externally visible decls.
 if (ND->isExternallyVisible()) {
-  disc = getASTContext().getManglingNumber(ND);
+  disc = getASTContext().getManglingNumber(ND, isAux());
   return true;
 }
 
@@ -459,8 +460,9 @@
 }
 
 MicrosoftMangleContextImpl::MicrosoftMangleContextImpl(ASTContext &Context,
-   DiagnosticsEngine &Diags)
-: MicrosoftMangleContext(Context, Diags) {
+   DiagnosticsEngine &Diags,
+   bool IsAux)
+: MicrosoftMangleContext(Context, Diags, IsAux) {
   // To mangle anonymous namespaces, hash the path to the main source file. The
   // path should be whatever (probably relative) path was passed on the command
   // line. The goal is for the compiler to produce the same output regardless of
@@ -3944,7 +3946,8 @@
   Mangler.getStream() << '@';
 }
 
-MicrosoftMangleContext *
-MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
-  return new MicrosoftMangleContextImpl(Context, Diags);
+MicrosoftMangleContext *MicrosoftMangleContext::create(ASTContext &Context,
+   DiagnosticsEngine &Diags,
+   bool IsAux) {
+  return new MicrosoftMangleContextImpl(Context, Diags, IsAux);
 }
Index: clang/lib/AST/ItaniumMangle.cpp
===
--- clang/lib/AST/ItaniumMangle.cpp
+++ clang/lib/AST/ItaniumMangle.cpp
@@ -78,8 +78,8 @@
 public:
   explicit ItaniumMangleContextImpl(
   ASTContext &Context, DiagnosticsEngine &Diags,
-  DiscriminatorOverrideTy DiscriminatorOverride)
-  : ItaniumMangleContext(Context, Diags),
+  DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)
+  : ItaniumMangleContext(Context, Diags, IsAux),
 DiscriminatorOverride(DiscriminatorOverride) {}
 
   /// @name Mangler Entry Points
@@ -143,7 +143,7 @@
 
 // Use the canonical number for externally visible decls.
 if (ND->isExternallyVisible()) {
-  unsigned discriminator = getASTContext().getManglingNumber(ND);
+  unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
   if (discriminator == 1)
 return false;
   disc = discriminator - 2;
@@ -1570,7 +1570,8 @@
 }
 
 if (TD->isExternallyVisible()) {
-  unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
+  unsigned UnnamedMangle =
+  getASTContext().getManglingNumber(TD, Context.isAux());
   Out << "Ut";
   if (UnnamedMangle > 1)
 Out << UnnamedMangle - 2;
@@ -6531,16 +6532,20 @@
 }
 
 ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context,
-   DiagnosticsEngine

[clang] 62501bc - [NFC][CUDA][HIP] rework mangling number for aux target

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

Author: Yaxun (Sam) Liu
Date: 2022-05-04T13:05:33-04:00
New Revision: 62501bc45a2fb4980725baccf48576cf9b45cd4d

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

LOG: [NFC][CUDA][HIP] rework mangling number for aux target

CUDA/HIP needs to mangle for aux target. When mangling for aux target,
the mangler should use mangling number for aux target. Previously
in https://reviews.llvm.org/D122734 a state was introduced in
ASTContext to let the mangler get mangling number for aux target
from ASTContext. This patch removes that state from ASTConext
and add an IsAux member to MangleContext to indicate that
the mangle context is for aux target. This reflects the reality that
the mangle context is created for mangling aux target and makes
ASTContext cleaner.

Reviewed by: Artem Belevich, Reid Kleckner

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

Added: 


Modified: 
clang/include/clang/AST/ASTContext.h
clang/include/clang/AST/Mangle.h
clang/lib/AST/ASTContext.cpp
clang/lib/AST/ItaniumMangle.cpp
clang/lib/AST/MicrosoftMangle.cpp
clang/lib/CodeGen/CGCUDANV.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index e04766f93d69e..fe22930e0fb11 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -677,9 +677,6 @@ class ASTContext : public RefCountedBase {
 ~CUDAConstantEvalContextRAII() { Ctx.CUDAConstantEvalCtx = SavedCtx; }
   };
 
-  /// Current CUDA name mangling is for device name in host compilation.
-  bool CUDAMangleDeviceNameInHostCompilation = false;
-
   /// Returns the dynamic AST node parent map context.
   ParentMapContext &getParentMapContext();
 
@@ -3044,7 +3041,8 @@ class ASTContext : public RefCountedBase {
   DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
 
   void setManglingNumber(const NamedDecl *ND, unsigned Number);
-  unsigned getManglingNumber(const NamedDecl *ND) const;
+  unsigned getManglingNumber(const NamedDecl *ND,
+ bool ForAuxTarget = false) const;
 
   void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
   unsigned getStaticLocalNumber(const VarDecl *VD) const;

diff  --git a/clang/include/clang/AST/Mangle.h 
b/clang/include/clang/AST/Mangle.h
index 7d02f08e0120c..9bca97a611d08 100644
--- a/clang/include/clang/AST/Mangle.h
+++ b/clang/include/clang/AST/Mangle.h
@@ -54,6 +54,9 @@ class MangleContext {
   ASTContext &Context;
   DiagnosticsEngine &Diags;
   const ManglerKind Kind;
+  /// For aux target. If true, uses mangling number for aux target from
+  /// ASTContext.
+  bool IsAux = false;
 
   llvm::DenseMap GlobalBlockIds;
   llvm::DenseMap LocalBlockIds;
@@ -62,10 +65,11 @@ class MangleContext {
 public:
   ManglerKind getKind() const { return Kind; }
 
-  explicit MangleContext(ASTContext &Context,
- DiagnosticsEngine &Diags,
- ManglerKind Kind)
-  : Context(Context), Diags(Diags), Kind(Kind) {}
+  bool isAux() const { return IsAux; }
+
+  explicit MangleContext(ASTContext &Context, DiagnosticsEngine &Diags,
+ ManglerKind Kind, bool IsAux = false)
+  : Context(Context), Diags(Diags), Kind(Kind), IsAux(IsAux) {}
 
   virtual ~MangleContext() { }
 
@@ -172,8 +176,9 @@ class ItaniumMangleContext : public MangleContext {
 public:
   using DiscriminatorOverrideTy =
   llvm::Optional (*)(ASTContext &, const NamedDecl *);
-  explicit ItaniumMangleContext(ASTContext &C, DiagnosticsEngine &D)
-  : MangleContext(C, D, MK_Itanium) {}
+  explicit ItaniumMangleContext(ASTContext &C, DiagnosticsEngine &D,
+bool IsAux = false)
+  : MangleContext(C, D, MK_Itanium, IsAux) {}
 
   virtual void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) = 0;
   virtual void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) = 0;
@@ -201,17 +206,19 @@ class ItaniumMangleContext : public MangleContext {
 return C->getKind() == MK_Itanium;
   }
 
-  static ItaniumMangleContext *create(ASTContext &Context,
-  DiagnosticsEngine &Diags);
+  static ItaniumMangleContext *
+  create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux = false);
   static ItaniumMangleContext *create(ASTContext &Context,
   DiagnosticsEngine &Diags,
-  DiscriminatorOverrideTy Discriminator);
+  DiscriminatorOverrideTy Discriminator,
+  bool IsAux = false);
 };
 
 class MicrosoftMangleContext : public MangleContext {
 public:
-  explicit MicrosoftMangleContext(ASTContext &C, DiagnosticsEngine &D)
- 

[PATCH] D123831: [clang][extract-api] Use relative includes

2022-05-04 Thread Zixu Wang via Phabricator via cfe-commits
zixuw added a comment.

In D123831#3490684 , @dang wrote:

> Since this is a new test can we use the approach in 
> https://reviews.llvm.org/D124634 to check for diagnostics output.

I used FileCheck to check the input buffer dump in this test, but I'll try to 
move to cc1 and fix the diagnostics check.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123831

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


[PATCH] D124638: [clang] Track how headers get included generally during lookup time

2022-05-04 Thread Cyndy Ishida via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb6c67c3c6789: [clang] Track how headers get included 
generally during lookup time (authored by cishida).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124638

Files:
  clang/include/clang/Lex/HeaderSearch.h
  clang/lib/Lex/HeaderSearch.cpp
  clang/unittests/Lex/HeaderSearchTest.cpp


Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -207,6 +207,7 @@
   EXPECT_TRUE(FI);
   EXPECT_TRUE(FI->IsValid);
   EXPECT_EQ(FI->Framework.str(), "Foo");
+  EXPECT_EQ(Search.getIncludeNameForHeader(FE), "Foo/Foo.h");
 }
 
 // Helper struct with null terminator character to make MemoryBuffer happy.
@@ -275,6 +276,7 @@
   EXPECT_TRUE(FI);
   EXPECT_TRUE(FI->IsValid);
   EXPECT_EQ(FI->Framework.str(), "Foo");
+  EXPECT_EQ(Search.getIncludeNameForHeader(FE), "Foo/Foo.h");
 }
 
 } // namespace
Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -1030,8 +1030,11 @@
 
 CurDir = It;
 
+const auto FE = &File->getFileEntry();
+IncludeNames[FE] = Filename;
+
 // This file is a system header or C++ unfriendly if the dir is.
-HeaderFileInfo &HFI = getFileInfo(&File->getFileEntry());
+HeaderFileInfo &HFI = getFileInfo(FE);
 HFI.DirInfo = CurDir->getDirCharacteristic();
 
 // If the directory characteristic is User but this framework was
@@ -1460,6 +1463,13 @@
   return FrameworkNames.insert(Framework).first->first();
 }
 
+StringRef HeaderSearch::getIncludeNameForHeader(const FileEntry *File) const {
+  auto It = IncludeNames.find(File);
+  if (It == IncludeNames.end())
+return {};
+  return It->second;
+}
+
 bool HeaderSearch::hasModuleMap(StringRef FileName,
 const DirectoryEntry *Root,
 bool IsSystem) {
Index: clang/include/clang/Lex/HeaderSearch.h
===
--- clang/include/clang/Lex/HeaderSearch.h
+++ clang/include/clang/Lex/HeaderSearch.h
@@ -20,6 +20,7 @@
 #include "clang/Lex/ModuleMap.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSet.h"
@@ -314,6 +315,9 @@
   /// whether they were valid or not.
   llvm::DenseMap LoadedModuleMaps;
 
+  // A map of discovered headers with their associated include file name.
+  llvm::DenseMap> IncludeNames;
+
   /// Uniqued set of framework names, which is used to track which
   /// headers were included as framework headers.
   llvm::StringSet FrameworkNames;
@@ -823,6 +827,13 @@
   /// Retrieve a uniqued framework name.
   StringRef getUniqueFrameworkName(StringRef Framework);
 
+  /// Retrieve the include name for the header.
+  ///
+  /// \param File The entry for a given header.
+  /// \returns The name of how the file was included when the header's location
+  /// was resolved.
+  StringRef getIncludeNameForHeader(const FileEntry *File) const;
+
   /// Suggest a path by which the specified file could be found, for use in
   /// diagnostics to suggest a #include. Returned path will only contain 
forward
   /// slashes as separators. MainFile is the absolute path of the file that we


Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -207,6 +207,7 @@
   EXPECT_TRUE(FI);
   EXPECT_TRUE(FI->IsValid);
   EXPECT_EQ(FI->Framework.str(), "Foo");
+  EXPECT_EQ(Search.getIncludeNameForHeader(FE), "Foo/Foo.h");
 }
 
 // Helper struct with null terminator character to make MemoryBuffer happy.
@@ -275,6 +276,7 @@
   EXPECT_TRUE(FI);
   EXPECT_TRUE(FI->IsValid);
   EXPECT_EQ(FI->Framework.str(), "Foo");
+  EXPECT_EQ(Search.getIncludeNameForHeader(FE), "Foo/Foo.h");
 }
 
 } // namespace
Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -1030,8 +1030,11 @@
 
 CurDir = It;
 
+const auto FE = &File->getFileEntry();
+IncludeNames[FE] = Filename;
+
 // This file is a system header or C++ unfriendly if the dir is.
-HeaderFileInfo &HFI = getFileInfo(&File->getFileEntry());
+HeaderFileInfo &HFI = getFileInfo(FE);
 HFI.DirInfo = CurDir->getDirCharacteristic();
 
 // If the directory characteristic is User but this framework was
@@ -1460,6 +1463,13 @@
   return FrameworkNames.insert(Framework).first->first();
 }
 
+StringRef HeaderSearch::getInc

[clang] b6c67c3 - [clang] Track how headers get included generally during lookup time

2022-05-04 Thread Cyndy Ishida via cfe-commits

Author: Cyndy Ishida
Date: 2022-05-04T09:52:31-07:00
New Revision: b6c67c3c67893d532fe741c508dfa2ac40fae1ad

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

LOG: [clang] Track how headers get included generally during lookup time

tapi & clang-extractapi both attempt to construct then check against
how a header was included to determine api information when working
against multiple search paths, headermap, and vfsoverlay mechanisms.
Validating this against what the preprocessor sees during lookup time
makes this check more reliable.

Reviewed By: zixuw, jansvoboda11

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

Added: 


Modified: 
clang/include/clang/Lex/HeaderSearch.h
clang/lib/Lex/HeaderSearch.cpp
clang/unittests/Lex/HeaderSearchTest.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/HeaderSearch.h 
b/clang/include/clang/Lex/HeaderSearch.h
index e88e600ba2b974..b523ad5ef9ff23 100644
--- a/clang/include/clang/Lex/HeaderSearch.h
+++ b/clang/include/clang/Lex/HeaderSearch.h
@@ -20,6 +20,7 @@
 #include "clang/Lex/ModuleMap.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSet.h"
@@ -314,6 +315,9 @@ class HeaderSearch {
   /// whether they were valid or not.
   llvm::DenseMap LoadedModuleMaps;
 
+  // A map of discovered headers with their associated include file name.
+  llvm::DenseMap> IncludeNames;
+
   /// Uniqued set of framework names, which is used to track which
   /// headers were included as framework headers.
   llvm::StringSet FrameworkNames;
@@ -823,6 +827,13 @@ class HeaderSearch {
   /// Retrieve a uniqued framework name.
   StringRef getUniqueFrameworkName(StringRef Framework);
 
+  /// Retrieve the include name for the header.
+  ///
+  /// \param File The entry for a given header.
+  /// \returns The name of how the file was included when the header's location
+  /// was resolved.
+  StringRef getIncludeNameForHeader(const FileEntry *File) const;
+
   /// Suggest a path by which the specified file could be found, for use in
   /// diagnostics to suggest a #include. Returned path will only contain 
forward
   /// slashes as separators. MainFile is the absolute path of the file that we

diff  --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index 14b9a1d7f68be1..5fd853541b6a21 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -1030,8 +1030,11 @@ Optional HeaderSearch::LookupFile(
 
 CurDir = It;
 
+const auto FE = &File->getFileEntry();
+IncludeNames[FE] = Filename;
+
 // This file is a system header or C++ unfriendly if the dir is.
-HeaderFileInfo &HFI = getFileInfo(&File->getFileEntry());
+HeaderFileInfo &HFI = getFileInfo(FE);
 HFI.DirInfo = CurDir->getDirCharacteristic();
 
 // If the directory characteristic is User but this framework was
@@ -1460,6 +1463,13 @@ StringRef HeaderSearch::getUniqueFrameworkName(StringRef 
Framework) {
   return FrameworkNames.insert(Framework).first->first();
 }
 
+StringRef HeaderSearch::getIncludeNameForHeader(const FileEntry *File) const {
+  auto It = IncludeNames.find(File);
+  if (It == IncludeNames.end())
+return {};
+  return It->second;
+}
+
 bool HeaderSearch::hasModuleMap(StringRef FileName,
 const DirectoryEntry *Root,
 bool IsSystem) {

diff  --git a/clang/unittests/Lex/HeaderSearchTest.cpp 
b/clang/unittests/Lex/HeaderSearchTest.cpp
index fbb5cb30754a79..87d1c01650987b 100644
--- a/clang/unittests/Lex/HeaderSearchTest.cpp
+++ b/clang/unittests/Lex/HeaderSearchTest.cpp
@@ -207,6 +207,7 @@ TEST_F(HeaderSearchTest, HeaderFrameworkLookup) {
   EXPECT_TRUE(FI);
   EXPECT_TRUE(FI->IsValid);
   EXPECT_EQ(FI->Framework.str(), "Foo");
+  EXPECT_EQ(Search.getIncludeNameForHeader(FE), "Foo/Foo.h");
 }
 
 // Helper struct with null terminator character to make MemoryBuffer happy.
@@ -275,6 +276,7 @@ TEST_F(HeaderSearchTest, HeaderMapFrameworkLookup) {
   EXPECT_TRUE(FI);
   EXPECT_TRUE(FI->IsValid);
   EXPECT_EQ(FI->Framework.str(), "Foo");
+  EXPECT_EQ(Search.getIncludeNameForHeader(FE), "Foo/Foo.h");
 }
 
 } // namespace



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


  1   2   >