[PATCH] D154091: [clang-format] Recognize escape sequences when breaking strings

2023-07-03 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

What would happen in a \r\n example




Comment at: clang/lib/Format/BreakableToken.cpp:207
+  case 't':
+  case 'v':
+AfterSpace = SplitPoint + 2;

Are you testing \r \v \f


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154091

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


[PATCH] D154397: [Driver] Default to -ftls-model=initial-exec on SerenityOS

2023-07-03 Thread Andrew Kaster via Phabricator via cfe-commits
ADKaster abandoned this revision.
ADKaster added a comment.

In D154397#4470094 , @jrtc27 wrote:

> This is pretty dodgy, I don't think it belongs upstream

Fair enough, the original patch had "probably don't upstream this" in the 
commit description. @BertalanD mentioned to me on discord that he had a WIP 
patch for proper TLS on x86_64 and aarch64 cooking already . I'll drop this one 
and by the time the series lands we'll most likely have the TLS support in 
serenity already (or we can add it to the default clang args we already use for 
setting --sysroot for Ports).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154397

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


[PATCH] D126694: [C++20][Modules] Implementation of GMF decl elision.

2023-07-03 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

Now I think the feature may be important for the performance of modules. And I 
feel we should work on the ASTWriter side instead of ASTReader side. Since the 
size of BMIs is a problem now also it shows that it is not free to load the 
large BMIs. So while it is semantical correct to work on the reader side, it is 
better for the performance to work on the writer side.

I'd like to finish the idea. And for the current patch, I'd like to refactor it 
a little bit:

1. Test it by unittest instead of by matching the dump result.
2. Remove the Serialization part. So it will be a NFC patch.
3. Some other trivial polishment.

Of course, I'll still mark you as the author.

How do you feel about this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126694

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


[PATCH] D146054: [RISCV] Add --print-supported-extensions support

2023-07-03 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat marked an inline comment as done.
4vtomat added inline comments.



Comment at: clang/test/Driver/print-supported-extensions.c:3
+
+// REQUIRES: riscv-registered-target
+

MaskRay wrote:
> If you remove `all` and `RISCV` from `LLVM_TARGETS_TO_BUILD`, you can test 
> whether this feature works without lib/Target/RISCV support. I suspect it 
> works, so you may need another build for verification.
No it cause an error if I use the command with the target without riscv such 
as: 
```
bin/clang --target=aarch64 --print-supported-extensions
or
bin/clang --target=x86 --print-supported-extensions
```



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146054

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


[PATCH] D146054: [RISCV] Add --print-supported-extensions support

2023-07-03 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat added inline comments.



Comment at: clang/test/Driver/print-supported-extensions.c:6
+// RUN: %clang --target=riscv64 --print-supported-extensions 2>&1 | \
+// RUN:   FileCheck %s --check-prefix=CHECK-RISCV
+

MaskRay wrote:
> MaskRay wrote:
> > Use `--implicit-check-not=warning:` instead of `// CHECK-NOT: warning: 
> > argument unused during compilation`.
> > 
> > We additionally check that there is no warning and the warning doesn't come 
> > after the output from `--print-supported-extensions`.
> For a file with just one prefix, conventionally we just use the default 
> `CHECK` and omit `--check-prefix`.
> 
> Have you ever checked that the test detects issues? `CHECK` below are ignored 
> with `--check-prefix=CHECK-RISCV`.
Oh, I missed it, CHECK-NEXT are all ignored...
thanks!!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146054

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


[PATCH] D146054: [RISCV] Add --print-supported-extensions support

2023-07-03 Thread Brandon Wu via Phabricator via cfe-commits
4vtomat updated this revision to Diff 536947.
4vtomat marked 27 inline comments as done.
4vtomat added a comment.
Herald added a subscriber: wangpc.

Sorry for late update.
Resolved MaskRay's comments, thanks for detailed review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146054

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/FrontendOptions.h
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/print-supported-extensions.c
  clang/tools/driver/cc1_main.cpp
  llvm/include/llvm/Support/RISCVISAInfo.h
  llvm/lib/Support/RISCVISAInfo.cpp

Index: llvm/lib/Support/RISCVISAInfo.cpp
===
--- llvm/lib/Support/RISCVISAInfo.cpp
+++ llvm/lib/Support/RISCVISAInfo.cpp
@@ -198,6 +198,29 @@
 #endif
 }
 
+void llvm::riscvExtensionsHelp() {
+  errs() << "All available -march extensions for RISC-V\n\n";
+  errs() << '\t' << left_justify("Name", 20) << "Version\n";
+
+  RISCVISAInfo::OrderedExtensionMap ExtMap;
+  for (const auto  : SupportedExtensions)
+ExtMap[E.Name] = { E.Version.Major, E.Version.Minor };
+  for (const auto  : ExtMap)
+errs() << format("\t%-20s%d.%d\n", E.first.c_str(), E.second.MajorVersion,
+ E.second.MinorVersion);
+
+  errs() << "\nExperimental extensions\n";
+  ExtMap.clear();
+  for (const auto  : SupportedExperimentalExtensions)
+ExtMap[E.Name] = { E.Version.Major, E.Version.Minor };
+  for (const auto  : ExtMap)
+errs() << format("\t%-20s%d.%d\n", E.first.c_str(), E.second.MajorVersion,
+ E.second.MinorVersion);
+
+  errs() << "\nUse -march to specify the target's extension.\n"
+"For example, clang -march=rv32i_v1p0\n";
+}
+
 static bool stripExperimentalPrefix(StringRef ) {
   return Ext.consume_front("experimental-");
 }
Index: llvm/include/llvm/Support/RISCVISAInfo.h
===
--- llvm/include/llvm/Support/RISCVISAInfo.h
+++ llvm/include/llvm/Support/RISCVISAInfo.h
@@ -22,6 +22,8 @@
   unsigned MinorVersion;
 };
 
+void riscvExtensionsHelp();
+
 class RISCVISAInfo {
 public:
   RISCVISAInfo(const RISCVISAInfo &) = delete;
Index: clang/tools/driver/cc1_main.cpp
===
--- clang/tools/driver/cc1_main.cpp
+++ clang/tools/driver/cc1_main.cpp
@@ -38,6 +38,7 @@
 #include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
+#include "llvm/Support/RISCVISAInfo.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/TimeProfiler.h"
@@ -182,6 +183,14 @@
   return 0;
 }
 
+/// Print supported extensions of the RISCV target.
+static int print_supported_extensions() {
+  llvm::riscvExtensionsHelp();
+
+  return 0;
+}
+
+
 int cc1_main(ArrayRef Argv, const char *Argv0, void *MainAddr) {
   ensureSufficientStack();
 
@@ -221,6 +230,10 @@
   if (Clang->getFrontendOpts().PrintSupportedCPUs)
 return PrintSupportedCPUs(Clang->getTargetOpts().Triple);
 
+  // --print-supported-extensions takes priority over the actual compilation.
+  if (Clang->getFrontendOpts().PrintSupportedExtensions)
+return print_supported_extensions();
+
   // Infer the builtin include path if unspecified.
   if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
   Clang->getHeaderSearchOpts().ResourceDir.empty())
Index: clang/test/Driver/print-supported-extensions.c
===
--- /dev/null
+++ clang/test/Driver/print-supported-extensions.c
@@ -0,0 +1,122 @@
+/// Test that --print-supported-extensions lists supported extensions.
+
+// REQUIRES: riscv-registered-target
+
+// RUN: %clang --target=riscv64 --print-supported-extensions 2>&1 | \
+// RUN:   FileCheck --implicit-check-not=warning --strict-whitespace --match-full-lines %s
+
+// CHECK:Target: riscv64
+// CHECK:All available -march extensions for RISC-V
+// CHECK:	NameVersion
+// CHECK-NEXT:	i   2.1
+// CHECK-NEXT:	e   2.0
+// CHECK-NEXT:	m   2.0
+// CHECK-NEXT:	a   2.1
+// CHECK-NEXT:	f   2.2
+// CHECK-NEXT:	d   2.2
+// CHECK-NEXT:	c   2.0
+// CHECK-NEXT:	v   1.0
+// CHECK-NEXT:	h   1.0
+// CHECK-NEXT:	zicbom  1.0
+// CHECK-NEXT:	zicbop  1.0
+// CHECK-NEXT:	zicboz  1.0
+// CHECK-NEXT:	zicntr  1.0
+// CHECK-NEXT:	zicsr   2.0
+// CHECK-NEXT:	zifencei2.0
+// CHECK-NEXT:	zihintpause 2.0
+// CHECK-NEXT:	zihpm   1.0
+// CHECK-NEXT:	zmmul   1.0
+// CHECK-NEXT:	zawrs   1.0
+// CHECK-NEXT:	zfh 1.0
+// CHECK-NEXT:	zfhmin  1.0
+// CHECK-NEXT:	zfinx   1.0
+// 

[PATCH] D154397: [Driver] Default to -ftls-model=initial-exec on SerenityOS

2023-07-03 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

This is pretty dodgy, I don't think it belongs upstream


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154397

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


[PATCH] D152021: [clang][AIX] Fix Overly Strict LTO Option Checking against `data-sections` when `mxcoff-roptr` is in Effect

2023-07-03 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast accepted this revision.
hubert.reinterpretcast added a comment.
This revision is now accepted and ready to land.

LGTM with minor comment.




Comment at: clang/lib/Driver/ToolChains/CommonArgs.cpp:732-735
UseSeparateSections))
 CmdArgs.push_back(
 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=1"));
+  else if (Args.hasArg(options::OPT_fno_data_sections)) {

Coding standards suggest that braces be used consistently for each part of an 
if/else chain.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152021

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


[PATCH] D143670: Stop claiming we support [[carries_dependency]]

2023-07-03 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

Updated patch limited to changing the feature test macro value would match 
Varna meeting outcome (changes to allow macro to be `0` accepted as DR).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143670

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


[PATCH] D153600: Implement -frecord-command-line for XCOFF

2023-07-03 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp:2338
   // Emit bytes for llvm.commandline metadata.
-  emitModuleCommandLines(M);
+  // The command line metadata waas emitted earlier on XCOFF.
+  if (!TM.getTargetTriple().isOSBinFormatXCOFF())

Minor nit: Typo.



Comment at: llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp:2974
+RSOS << "@(#)" << MDS->getString();
+RSOS.write('\0');
+  }

stephenpeckham wrote:
> I would use a newline here.  The AIX **what **command looks for @(#) and 
> echos subsequent bytes until it sees a double quote, a backslash, a > symbol, 
> newline, or null byte.  The @(#) is not echoed, nor is the terminating 
> character.  The **what **command prints a newline after it finds a 
> terminating character.  This means that if the command line contains any of 
> the special characters, the line will be truncated.
> 
> Exception:  If the @(#) is followed by "opt " or " opt ", the terminating 
> characters are only a newline or null byte. This allows any of the other 
> special characters to be part of the command line. It doesn't really matter 
> if you use a newline or a null byte, but the legacy XL compiler uses a 
> newline. The "opt" keyword should appear if the command line can contain a 
> double quote, a > or a backslash.
> 
> The legacy compiler also uses other keywords besides "opt", including 
> "version" and "cfg".  The **what** command doesn't do anything special with 
> these keywords.
As mentioned offline, newline on its own has potential of ambiguity because it 
can appear in command line options (null bytes cannot). If there is a 
preference for newline to be present, then having a null byte after could help.

Note that `@(#)opt ` can appear on the command line too. Using `what` will have 
limitations (but we should leave the possibility open for other tools/methods 
to work).



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

https://reviews.llvm.org/D153600

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


[PATCH] D151696: [x86] Remove CPU_SPECIFIC* MACROs and add getCPUDispatchMangling

2023-07-03 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe marked an inline comment as done.
FreddyYe added inline comments.



Comment at: clang/test/CodeGen/attr-cpuspecific-cpus.c:40
 ATTR(cpu_specific(knm)) void CPU(void){}
+ATTR(cpu_specific(cascadelake)) void CPU(void){}
+ATTR(cpu_specific(cooperlake)) void CPU(void){}

In this patch, I additionally supported some intel new CPU's _cpu_specific 
feature by creating a new mangling or copy some old ones (which means aliasing 
certain cpu). Maybe I should do this in a following patch?



Comment at: llvm/lib/TargetParser/X86TargetParser.cpp:378
+  { {"core_3rd_gen_avx"}, CK_IvyBridge, FEATURE_AVX, FeaturesIvyBridge, 'S', 
true },
+  { {"core-avx-i"}, CK_IvyBridge, FEATURE_AVX, FeaturesIvyBridge, '\0', false 
},
   // Haswell microarchitecture based processors.

RKSimon wrote:
> I'm still not clear on what determines the mangling mode and cpu dispatch 
> flag for cpu targets are supposedly the same? For example, none of these 
> ivybridge equivalent configs have the same values.
I assign them by following orders:
1. Copy the mangling from the original CPU_SPEICIFC MACRO.
2. If there's no way to copy, assign to '\0' by default, which means doesn't 
support __cpu_specific/dispatch feature.
3. If cpu name contain ''-', assign the mangling as '\0', too. Because '-' 
cannot be correctly identified in _cpu_specific/dispatch().
4. set OnlyForCPUDispatch flag as `true` if this cpu name was not listed here, 
which means it doesn't support -march, -mtune and so on. This flag makes this 
cpu name only support __cpu_dispatch/specific feature. E.g. core_3rd_gen_avx, 
core_4rd_gen_avx., ... And normally, these names are very old. So supporting 
them with -march=, -mtune= is not easy for now. And notice that new cpu names 
shouldn't set this flag as `true` since they should both support -march= and 
__cpu_specific/dispatch feature by default.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151696

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


[PATCH] D154401: [tools] Support building shared libLLVM and libClang for SerenityOS

2023-07-03 Thread Andrew Kaster via Phabricator via cfe-commits
ADKaster created this revision.
Herald added subscribers: mstorsjo, fedor.sergeev.
Herald added a project: All.
ADKaster requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

This patch tells CMake that the --whole-archive linker option should be
used for specifying the archives whose members will constitute these
shared libraries.

Symbol versioning is disabled, as the SerenityOS loader doesn't support
it, and the ELF sections that store version data would just waste space.

Depends on D154400 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154401

Files:
  clang/tools/libclang/CMakeLists.txt
  llvm/tools/llvm-shlib/CMakeLists.txt


Index: llvm/tools/llvm-shlib/CMakeLists.txt
===
--- llvm/tools/llvm-shlib/CMakeLists.txt
+++ llvm/tools/llvm-shlib/CMakeLists.txt
@@ -40,6 +40,7 @@
  OR ("${CMAKE_SYSTEM_NAME}" STREQUAL "Fuchsia")
  OR ("${CMAKE_SYSTEM_NAME}" STREQUAL "DragonFly")
  OR ("${CMAKE_SYSTEM_NAME}" STREQUAL "Android")
+ OR ("${CMAKE_SYSTEM_NAME}" STREQUAL "SerenityOS")
  OR ("${CMAKE_SYSTEM_NAME}" STREQUAL "SunOS")) # FIXME: It should be "GNU 
ld for elf"
 configure_file(
 ${CMAKE_CURRENT_SOURCE_DIR}/simple_version_script.map.in
@@ -47,7 +48,7 @@
 
 # GNU ld doesn't resolve symbols in the version script.
 set(LIB_NAMES -Wl,--whole-archive ${LIB_NAMES} -Wl,--no-whole-archive)
-if (NOT LLVM_LINKER_IS_SOLARISLD AND NOT MINGW)
+if (NOT LLVM_LINKER_IS_SOLARISLD AND NOT MINGW AND (NOT 
"${CMAKE_SYSTEM_NAME}" STREQUAL "SerenityOS"))
   # Solaris ld does not accept global: *; so there is no way to version 
*all* global symbols
   set(LIB_NAMES 
-Wl,--version-script,${LLVM_LIBRARY_DIR}/tools/llvm-shlib/simple_version_script.map
 ${LIB_NAMES})
 endif()
Index: clang/tools/libclang/CMakeLists.txt
===
--- clang/tools/libclang/CMakeLists.txt
+++ clang/tools/libclang/CMakeLists.txt
@@ -97,7 +97,7 @@
   set(LLVM_EXPORTED_SYMBOL_FILE)
 endif()
 
-if (UNIX AND NOT APPLE)
+if (UNIX AND NOT APPLE AND (NOT "${CMAKE_SYSTEM_NAME}" STREQUAL "SerenityOS"))
   set(LLVM_EXPORTED_SYMBOL_FILE)
   set(USE_VERSION_SCRIPT ${LLVM_HAVE_LINK_VERSION_SCRIPT})
 endif()


Index: llvm/tools/llvm-shlib/CMakeLists.txt
===
--- llvm/tools/llvm-shlib/CMakeLists.txt
+++ llvm/tools/llvm-shlib/CMakeLists.txt
@@ -40,6 +40,7 @@
  OR ("${CMAKE_SYSTEM_NAME}" STREQUAL "Fuchsia")
  OR ("${CMAKE_SYSTEM_NAME}" STREQUAL "DragonFly")
  OR ("${CMAKE_SYSTEM_NAME}" STREQUAL "Android")
+ OR ("${CMAKE_SYSTEM_NAME}" STREQUAL "SerenityOS")
  OR ("${CMAKE_SYSTEM_NAME}" STREQUAL "SunOS")) # FIXME: It should be "GNU ld for elf"
 configure_file(
 ${CMAKE_CURRENT_SOURCE_DIR}/simple_version_script.map.in
@@ -47,7 +48,7 @@
 
 # GNU ld doesn't resolve symbols in the version script.
 set(LIB_NAMES -Wl,--whole-archive ${LIB_NAMES} -Wl,--no-whole-archive)
-if (NOT LLVM_LINKER_IS_SOLARISLD AND NOT MINGW)
+if (NOT LLVM_LINKER_IS_SOLARISLD AND NOT MINGW AND (NOT "${CMAKE_SYSTEM_NAME}" STREQUAL "SerenityOS"))
   # Solaris ld does not accept global: *; so there is no way to version *all* global symbols
   set(LIB_NAMES -Wl,--version-script,${LLVM_LIBRARY_DIR}/tools/llvm-shlib/simple_version_script.map ${LIB_NAMES})
 endif()
Index: clang/tools/libclang/CMakeLists.txt
===
--- clang/tools/libclang/CMakeLists.txt
+++ clang/tools/libclang/CMakeLists.txt
@@ -97,7 +97,7 @@
   set(LLVM_EXPORTED_SYMBOL_FILE)
 endif()
 
-if (UNIX AND NOT APPLE)
+if (UNIX AND NOT APPLE AND (NOT "${CMAKE_SYSTEM_NAME}" STREQUAL "SerenityOS"))
   set(LLVM_EXPORTED_SYMBOL_FILE)
   set(USE_VERSION_SCRIPT ${LLVM_HAVE_LINK_VERSION_SCRIPT})
 endif()
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154397: [Driver] Default to -ftls-model=initial-exec on SerenityOS

2023-07-03 Thread Andrew Kaster via Phabricator via cfe-commits
ADKaster created this revision.
Herald added a project: All.
ADKaster requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

Force Clang use the initial-exec TLS model instead of the default
local-exec when building code for Serenity.

This patch should be removed when the SerenityOS program loader
implements proper TLS support.

Depends on D154396 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154397

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


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6170,7 +6170,13 @@
   Args.AddLastArg(CmdArgs, 
options::OPT_fvisibility_inlines_hidden_static_local_var,

options::OPT_fno_visibility_inlines_hidden_static_local_var);
   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
-  Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
+  if (Triple.isOSSerenity()) {
+StringRef tls_model =
+Args.getLastArgValue(options::OPT_ftlsmodel_EQ, "initial-exec");
+CmdArgs.push_back(Args.MakeArgString("-ftls-model=" + tls_model));
+  } else {
+Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
+  }
 
   if (Args.hasFlag(options::OPT_fnew_infallible,
options::OPT_fno_new_infallible, false))


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6170,7 +6170,13 @@
   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
options::OPT_fno_visibility_inlines_hidden_static_local_var);
   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
-  Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
+  if (Triple.isOSSerenity()) {
+StringRef tls_model =
+Args.getLastArgValue(options::OPT_ftlsmodel_EQ, "initial-exec");
+CmdArgs.push_back(Args.MakeArgString("-ftls-model=" + tls_model));
+  } else {
+Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
+  }
 
   if (Args.hasFlag(options::OPT_fnew_infallible,
options::OPT_fno_new_infallible, false))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154396: [clang] Add support for SerenityOS

2023-07-03 Thread Andrew Kaster via Phabricator via cfe-commits
ADKaster created this revision.
Herald added a project: All.
ADKaster requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

Adds support for the `$arch-pc-serenity` target to the Clang front end.
This makes the compiler look for libraries and headers in the right
places, and enables some security mitigations like stack-smashing
protection and position-independent code by default.

Depends on D154395 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154396

Files:
  clang/lib/Basic/Targets.cpp
  clang/lib/Basic/Targets/OSTargets.h
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Serenity.cpp
  clang/lib/Driver/ToolChains/Serenity.h

Index: clang/lib/Driver/ToolChains/Serenity.h
===
--- /dev/null
+++ clang/lib/Driver/ToolChains/Serenity.h
@@ -0,0 +1,100 @@
+//=== Serenity.h - SerenityOS ToolChain Implementation --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_SERENITY_H
+#define LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_SERENITY_H
+
+#include "clang/Basic/LangOptions.h"
+#include "clang/Driver/Tool.h"
+#include "clang/Driver/ToolChain.h"
+
+namespace clang {
+namespace driver {
+namespace tools {
+namespace serenity {
+
+class LLVM_LIBRARY_VISIBILITY Linker : public Tool {
+public:
+  Linker(const ToolChain ) : Tool("serenity::Linker", "linker", TC) {}
+
+  bool hasIntegratedCPP() const override { return false; }
+  bool isLinkJob() const override { return true; }
+
+  void ConstructJob(Compilation , const JobAction ,
+const InputInfo , const InputInfoList ,
+const llvm::opt::ArgList ,
+const char *LinkingOutput) const override;
+};
+} // end namespace serenity
+} // end namespace tools
+
+namespace toolchains {
+
+class LLVM_LIBRARY_VISIBILITY Serenity : public ToolChain {
+public:
+  Serenity(const Driver , const llvm::Triple ,
+   const llvm::opt::ArgList );
+
+  void
+  AddClangSystemIncludeArgs(const llvm::opt::ArgList ,
+llvm::opt::ArgStringList ) const override;
+
+  void AddClangCXXStdlibIncludeArgs(
+  const llvm::opt::ArgList ,
+  llvm::opt::ArgStringList ) const override;
+
+  RuntimeLibType GetDefaultRuntimeLibType() const override {
+return ToolChain::RLT_CompilerRT;
+  }
+
+  CXXStdlibType GetDefaultCXXStdlibType() const override {
+return ToolChain::CST_Libcxx;
+  }
+
+  UnwindLibType GetUnwindLibType(const llvm::opt::ArgList ) const override;
+
+  void
+  addClangTargetOptions(const llvm::opt::ArgList ,
+llvm::opt::ArgStringList ,
+Action::OffloadKind DeviceOffloadKind) const override;
+
+  const char *getDefaultLinker() const override { return "ld.lld"; }
+
+  bool HasNativeLLVMSupport() const override { return true; }
+
+  bool IsIntegratedAssemblerDefault() const override { return true; }
+
+  bool isPICDefault() const override { return true; }
+  bool isPIEDefault(const llvm::opt::ArgList &) const override { return false; }
+  bool isPICDefaultForced() const override { return false; }
+
+  bool IsMathErrnoDefault() const override { return false; }
+
+  UnwindTableLevel
+  getDefaultUnwindTableLevel(const llvm::opt::ArgList ) const override {
+return UnwindTableLevel::Asynchronous;
+  }
+
+  bool useRelaxRelocations() const override { return true; }
+
+  LangOptions::StackProtectorMode
+  GetDefaultStackProtectorLevel(bool KernelOrKext) const override {
+return LangOptions::SSPStrong;
+  }
+
+  unsigned GetDefaultDwarfVersion() const override { return 5; }
+
+protected:
+  Tool *buildLinker() const override;
+};
+
+} // end namespace toolchains
+} // end namespace driver
+} // end namespace clang
+
+#endif // LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_SERENITY_H
Index: clang/lib/Driver/ToolChains/Serenity.cpp
===
--- /dev/null
+++ clang/lib/Driver/ToolChains/Serenity.cpp
@@ -0,0 +1,336 @@
+//=== Serenity.cpp - SerenityOS ToolChain Implementation *- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "Serenity.h"
+#include "CommonArgs.h"
+#include "clang/Config/config.h"
+#include "clang/Driver/Compilation.h"
+#include "clang/Driver/Driver.h"
+#include 

[PATCH] D153600: Implement -frecord-command-line for XCOFF

2023-07-03 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan updated this revision to Diff 536920.
Jake-Egan edited the summary of this revision.
Jake-Egan added a comment.

Thanks for the review @stephenpeckham, I updated the patch with the requested 
changes.


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

https://reviews.llvm.org/D153600

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  llvm/include/llvm/CodeGen/AsmPrinter.h
  llvm/include/llvm/MC/MCStreamer.h
  llvm/include/llvm/MC/MCXCOFFStreamer.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/MC/MCAsmStreamer.cpp
  llvm/lib/MC/MCStreamer.cpp
  llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
  llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll

Index: llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll
@@ -0,0 +1,23 @@
+; RUN: llc -mtriple powerpc-ibm-aix-xcoff < %s | \
+; RUN: FileCheck --check-prefix=ASM %s
+; RUN: llc -mtriple powerpc64-ibm-aix-xcoff < %s | \
+; RUN: FileCheck --check-prefix=ASM %s
+
+; RUN: not --crash llc -mtriple powerpc-ibm-aix-xcoff -filetype=obj  < %s 2>&1 | \
+; RUN: FileCheck --check-prefix=OBJ %s
+; RUN: not --crash llc -mtriple powerpc64-ibm-aix-xcoff -filetype=obj  < %s 2>&1 | \
+; RUN: FileCheck --check-prefix=OBJ %s
+
+; Verify that llvm.commandline metadata is emitted to .info sections and that the
+; metadata is padded if necessary.
+
+; OBJ: LLVM ERROR: emitXCOFFCInfoSym is not implemented yet on object generation path
+
+; ASM: .info ".GCC.command.line", 0x0037, 
+; ASM: .info , 0x40282329, 0x6f707420, 0x636c616e, 0x67202d63, 0x6f6d6d61, 0x6e64202d
+; ASM: .info , 0x6c696e65, 0x0a402823, 0x296f7074, 0x20736f6d, 0x65746869, 0x6e672065
+; ASM: .info , 0x6c736531, 0x32330a00
+
+!llvm.commandline = !{!0, !1}
+!0 = !{!"clang -command -line"}
+!1 = !{!"something else123"}
Index: llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
===
--- llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
+++ llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
@@ -290,6 +290,8 @@
   bool doFinalization(Module ) override;
 
   void emitTTypeReference(const GlobalValue *GV, unsigned Encoding) override;
+
+  void emitModuleCommandLines(Module ) override;
 };
 
 } // end anonymous namespace
@@ -2954,6 +2956,25 @@
   return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
 }
 
+void PPCAIXAsmPrinter::emitModuleCommandLines(Module ) {
+  const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
+  if (!NMD || !NMD->getNumOperands())
+return;
+
+  std::string S;
+  raw_string_ostream RSOS(S);
+  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
+const MDNode *N = NMD->getOperand(i);
+assert(N->getNumOperands() == 1 &&
+   "llvm.commandline metadata entry can have only one operand");
+const MDString *MDS = cast(N->getOperand(0));
+// Add "@(#)" to support retrieving the command line information with the
+// AIX "what" command
+RSOS << "@(#)opt " << MDS->getString() << "\n";
+  }
+  OutStreamer->emitXCOFFCInfoSym(".GCC.command.line", RSOS.str());
+}
+
 // Force static initialization.
 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() {
   TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
Index: llvm/lib/MC/MCStreamer.cpp
===
--- llvm/lib/MC/MCStreamer.cpp
+++ llvm/lib/MC/MCStreamer.cpp
@@ -1208,6 +1208,11 @@
  "XCOFF targets");
 }
 
+void MCStreamer::emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) {
+  llvm_unreachable("emitXCOFFCInfoSym is only supported on"
+   "XCOFF targets");
+}
+
 void MCStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
 void MCStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
 StringRef Name, bool KeepOriginalSym) {}
Index: llvm/lib/MC/MCAsmStreamer.cpp
===
--- llvm/lib/MC/MCAsmStreamer.cpp
+++ llvm/lib/MC/MCAsmStreamer.cpp
@@ -37,6 +37,7 @@
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/Path.h"
 #include 
+#include 
 
 using namespace llvm;
 
@@ -200,6 +201,7 @@
 const MCSymbol *Trap,
 unsigned Lang, unsigned Reason,
 unsigned FunctionSize, bool hasDebug) override;
+  void emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) override;
 
   void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
   void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
@@ -966,6 +968,65 @@
   EmitEOL();
 }
 
+void MCAsmStreamer::emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) {
+  const char *InfoDirective = "\t.info ";
+  const char *Separator = ", ";
+  constexpr int WordSize = sizeof(uint32_t);
+
+  // Start by emitting the .info 

[clang] 3f3620e - [clang-format] Correctly annotate */&/&& in operator function calls

2023-07-03 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-07-03T17:49:10-07:00
New Revision: 3f3620e5c9ee0f7b64afc39e5a26c6f4cc5e7b37

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

LOG: [clang-format] Correctly annotate */&/&& in operator function calls

Reverts 4986f3f2f220 (but keeps its unit tests) and fixes #49973
differently.

Also fixes bugs that incorrectly annotate the operator keyword as
TT_FunctionDeclarationName in function calls and as TT_Unknown in function
declarations and definitions.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 735089f1ad9d7a..5536c89ae1067d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -310,14 +310,9 @@ class AnnotatingParser {
   // If faced with "a.operator*(argument)" or "a->operator*(argument)",
   // i.e. the operator is called as a member function,
   // then the argument must be an expression.
-  // If faced with "operator+(argument)", i.e. the operator is called as
-  // a free function, then the argument is an expression only if the 
current
-  // line can't be a declaration.
-  bool IsOperatorCallSite =
-  (Prev->Previous &&
-   Prev->Previous->isOneOf(tok::period, tok::arrow)) ||
-  (!Line.MustBeDeclaration && !Line.InMacroBody);
-  Contexts.back().IsExpression = IsOperatorCallSite;
+  bool OperatorCalledAsMemberFunction =
+  Prev->Previous && Prev->Previous->isOneOf(tok::period, tok::arrow);
+  Contexts.back().IsExpression = OperatorCalledAsMemberFunction;
 } else if (OpeningParen.is(TT_VerilogInstancePortLParen)) {
   Contexts.back().IsExpression = true;
   Contexts.back().ContextType = Context::VerilogInstancePortList;
@@ -3133,6 +3128,7 @@ void TokenAnnotator::annotate(AnnotatedLine ) {
 // function declaration.
 static bool isFunctionDeclarationName(bool IsCpp, const FormatToken ,
   const AnnotatedLine ) {
+  assert(Current.Previous);
   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
 for (; Next; Next = Next->Next) {
   if (Next->is(TT_OverloadedOperatorLParen))
@@ -3171,7 +3167,12 @@ static bool isFunctionDeclarationName(bool IsCpp, const 
FormatToken ,
   // Find parentheses of parameter list.
   const FormatToken *Next = Current.Next;
   if (Current.is(tok::kw_operator)) {
-if (Current.Previous && Current.Previous->is(tok::coloncolon))
+const auto *Previous = Current.Previous;
+if (Previous->Tok.getIdentifierInfo() &&
+!Previous->isOneOf(tok::kw_return, tok::kw_co_return)) {
+  return true;
+}
+if (!Previous->isOneOf(tok::star, tok::amp, tok::ampamp))
   return false;
 Next = skipOperatorName(Next);
   } else {
@@ -3302,9 +3303,11 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine ) const {
   if (AlignArrayOfStructures)
 calculateArrayInitializerColumnList(Line);
 
+  bool LineIsFunctionDeclaration = false;
   for (FormatToken *Tok = Current, *AfterLastAttribute = nullptr; Tok;
Tok = Tok->Next) {
 if (isFunctionDeclarationName(Style.isCpp(), *Tok, Line)) {
+  LineIsFunctionDeclaration = true;
   Tok->setType(TT_FunctionDeclarationName);
   if (AfterLastAttribute &&
   mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
@@ -3317,6 +3320,33 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine ) const {
   AfterLastAttribute = Tok;
   }
 
+  if (Style.isCpp() && !LineIsFunctionDeclaration) {
+// Annotate */&/&& in `operator` function calls as binary operators.
+for (const auto *Tok = Line.First; Tok; Tok = Tok->Next) {
+  if (Tok->isNot(tok::kw_operator))
+continue;
+  do {
+Tok = Tok->Next;
+  } while (Tok && Tok->isNot(TT_OverloadedOperatorLParen));
+  if (!Tok)
+break;
+  const auto *LeftParen = Tok;
+  for (Tok = Tok->Next; Tok && Tok != LeftParen->MatchingParen;
+   Tok = Tok->Next) {
+if (Tok->isNot(tok::identifier))
+  continue;
+auto *Next = Tok->Next;
+const bool NextIsBinaryOperator =
+Next && Next->isOneOf(tok::star, tok::amp, tok::ampamp) &&
+Next->Next && Next->Next->is(tok::identifier);
+if (!NextIsBinaryOperator)
+  continue;
+Next->setType(TT_BinaryOperator);
+Tok = Next;
+  }
+}
+  }
+
   while (Current) {
 const FormatToken *Prev = Current->Previous;
 if 

[PATCH] D154184: [clang-format] Correctly annotate */&/&& in operator function calls

2023-07-03 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 rG3f3620e5c9ee: [clang-format] Correctly annotate 
*// in operator function calls (authored by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154184

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp

Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -594,61 +594,59 @@
 TEST_F(TokenAnnotatorTest, UnderstandsOverloadedOperators) {
   auto Tokens = annotate("x.operator+()");
   ASSERT_EQ(Tokens.size(), 7u) << Tokens;
-  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_Unknown);
   EXPECT_TOKEN(Tokens[3], tok::plus, TT_OverloadedOperator);
   EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_OverloadedOperatorLParen);
   Tokens = annotate("x.operator=()");
   ASSERT_EQ(Tokens.size(), 7u) << Tokens;
-  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_Unknown);
   EXPECT_TOKEN(Tokens[3], tok::equal, TT_OverloadedOperator);
   EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_OverloadedOperatorLParen);
   Tokens = annotate("x.operator+=()");
   ASSERT_EQ(Tokens.size(), 7u) << Tokens;
-  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_Unknown);
   EXPECT_TOKEN(Tokens[3], tok::plusequal, TT_OverloadedOperator);
   EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_OverloadedOperatorLParen);
   Tokens = annotate("x.operator,()");
   ASSERT_EQ(Tokens.size(), 7u) << Tokens;
-  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_Unknown);
   EXPECT_TOKEN(Tokens[3], tok::comma, TT_OverloadedOperator);
   EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_OverloadedOperatorLParen);
   Tokens = annotate("x.operator()()");
   ASSERT_EQ(Tokens.size(), 8u) << Tokens;
-  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_Unknown);
   EXPECT_TOKEN(Tokens[3], tok::l_paren, TT_OverloadedOperator);
   EXPECT_TOKEN(Tokens[4], tok::r_paren, TT_OverloadedOperator);
   EXPECT_TOKEN(Tokens[5], tok::l_paren, TT_OverloadedOperatorLParen);
   Tokens = annotate("x.operator[]()");
   ASSERT_EQ(Tokens.size(), 8u) << Tokens;
-  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_Unknown);
   // EXPECT_TOKEN(Tokens[3], tok::l_square, TT_OverloadedOperator);
   // EXPECT_TOKEN(Tokens[4], tok::r_square, TT_OverloadedOperator);
   EXPECT_TOKEN(Tokens[5], tok::l_paren, TT_OverloadedOperatorLParen);
   Tokens = annotate("x.operator\"\"_a()");
   ASSERT_EQ(Tokens.size(), 7u) << Tokens;
-  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_Unknown);
   EXPECT_TOKEN(Tokens[3], tok::string_literal, TT_OverloadedOperator);
   EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_OverloadedOperatorLParen);
   Tokens = annotate("x.operator\"\" _a()");
   ASSERT_EQ(Tokens.size(), 8u) << Tokens;
-  // FIXME
-  // EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_Unknown);
   EXPECT_TOKEN(Tokens[3], tok::string_literal, TT_OverloadedOperator);
   EXPECT_TOKEN(Tokens[5], tok::l_paren, TT_OverloadedOperatorLParen);
   Tokens = annotate("x.operator\"\"if()");
   ASSERT_EQ(Tokens.size(), 7u) << Tokens;
-  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_Unknown);
   EXPECT_TOKEN(Tokens[3], tok::string_literal, TT_OverloadedOperator);
   EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_OverloadedOperatorLParen);
   Tokens = annotate("x.operator\"\"s()");
   ASSERT_EQ(Tokens.size(), 7u) << Tokens;
-  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_Unknown);
   EXPECT_TOKEN(Tokens[3], tok::string_literal, TT_OverloadedOperator);
   EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_OverloadedOperatorLParen);
   Tokens = annotate("x.operator\"\" s()");
   ASSERT_EQ(Tokens.size(), 8u) << Tokens;
-  // FIXME
-  // EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[2], tok::kw_operator, TT_Unknown);
   EXPECT_TOKEN(Tokens[3], tok::string_literal, TT_OverloadedOperator);
   EXPECT_TOKEN(Tokens[5], tok::l_paren, TT_OverloadedOperatorLParen);
 
@@ -678,20 +676,44 @@
   EXPECT_TOKEN(Tokens[6], tok::l_paren, 

[PATCH] D144347: [clang-tidy] Add readability-forward-usage check

2023-07-03 Thread Chris Cotter via Phabricator via cfe-commits
ccotter added a comment.

Great, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144347

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


[PATCH] D154251: Add a flag to disable "duplicate definition of category" warnings

2023-07-03 Thread Akira Hatanaka 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 rGcff99b76ac4f: Add a flag to disable duplicate 
definition of category warnings (authored by ahatanak).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154251

Files:
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/test/Misc/warning-flags.c
  clang/test/SemaObjC/check-dup-objc-decls-1.m


Index: clang/test/SemaObjC/check-dup-objc-decls-1.m
===
--- clang/test/SemaObjC/check-dup-objc-decls-1.m
+++ clang/test/SemaObjC/check-dup-objc-decls-1.m
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -Wno-objc-root-class %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Wno-objc-root-class 
-Wno-objc-duplicate-category-definition -DIGNORE_DUP_CAT %s
 
 @interface Foo // expected-note {{previous definition is here}}
 @end
@@ -41,8 +42,13 @@
 @protocol DP @end
 #pragma clang diagnostic pop
 
-@interface A(Cat) @end // expected-note {{previous definition is here}}
-@interface A(Cat) @end // expected-warning {{duplicate definition of 
category 'Cat' on interface 'A'}}
+@interface A(Cat) @end
+@interface A(Cat) @end
+
+#ifndef IGNORE_DUP_CAT
+// expected-note@-4 {{previous definition is here}}
+// expected-warning@-4 {{duplicate definition of category 'Cat' on interface 
'A'}}
+#endif
 
 // rdar 7626768
 @class NSString;
Index: clang/test/Misc/warning-flags.c
===
--- clang/test/Misc/warning-flags.c
+++ clang/test/Misc/warning-flags.c
@@ -18,7 +18,7 @@
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (66):
+CHECK: Warnings without flags (65):
 
 CHECK-NEXT:   ext_expected_semi_decl_list
 CHECK-NEXT:   ext_explicit_specialization_storage_class
@@ -46,7 +46,6 @@
 CHECK-NEXT:   warn_drv_assuming_mfloat_abi_is
 CHECK-NEXT:   warn_drv_clang_unsupported
 CHECK-NEXT:   warn_drv_pch_not_first_include
-CHECK-NEXT:   warn_dup_category_def
 CHECK-NEXT:   warn_enum_value_overflow
 CHECK-NEXT:   warn_expected_qualified_after_typename
 CHECK-NEXT:   warn_fe_backend_unsupported
Index: clang/include/clang/Basic/DiagnosticCommonKinds.td
===
--- clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -305,7 +305,8 @@
 
 // Sema && Serialization
 def warn_dup_category_def : Warning<
-  "duplicate definition of category %1 on interface %0">;
+  "duplicate definition of category %1 on interface %0">,
+  InGroup>;
 
 // Targets
 


Index: clang/test/SemaObjC/check-dup-objc-decls-1.m
===
--- clang/test/SemaObjC/check-dup-objc-decls-1.m
+++ clang/test/SemaObjC/check-dup-objc-decls-1.m
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -Wno-objc-root-class %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Wno-objc-root-class -Wno-objc-duplicate-category-definition -DIGNORE_DUP_CAT %s
 
 @interface Foo // expected-note {{previous definition is here}}
 @end
@@ -41,8 +42,13 @@
 @protocol DP @end
 #pragma clang diagnostic pop
 
-@interface A(Cat) @end // expected-note {{previous definition is here}}
-@interface A(Cat) @end // expected-warning {{duplicate definition of category 'Cat' on interface 'A'}}
+@interface A(Cat) @end
+@interface A(Cat) @end
+
+#ifndef IGNORE_DUP_CAT
+// expected-note@-4 {{previous definition is here}}
+// expected-warning@-4 {{duplicate definition of category 'Cat' on interface 'A'}}
+#endif
 
 // rdar 7626768
 @class NSString;
Index: clang/test/Misc/warning-flags.c
===
--- clang/test/Misc/warning-flags.c
+++ clang/test/Misc/warning-flags.c
@@ -18,7 +18,7 @@
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (66):
+CHECK: Warnings without flags (65):
 
 CHECK-NEXT:   ext_expected_semi_decl_list
 CHECK-NEXT:   ext_explicit_specialization_storage_class
@@ -46,7 +46,6 @@
 CHECK-NEXT:   warn_drv_assuming_mfloat_abi_is
 CHECK-NEXT:   warn_drv_clang_unsupported
 CHECK-NEXT:   warn_drv_pch_not_first_include
-CHECK-NEXT:   warn_dup_category_def
 CHECK-NEXT:   warn_enum_value_overflow
 CHECK-NEXT:   warn_expected_qualified_after_typename
 CHECK-NEXT:   warn_fe_backend_unsupported
Index: clang/include/clang/Basic/DiagnosticCommonKinds.td
===
--- clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -305,7 +305,8 @@
 
 // Sema && Serialization
 def warn_dup_category_def : Warning<
-  "duplicate definition of category %1 on interface %0">;
+  "duplicate definition of category %1 

[clang] cff99b7 - Add a flag to disable "duplicate definition of category" warnings

2023-07-03 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2023-07-03T16:25:22-07:00
New Revision: cff99b76ac4f502ceba897a62db658667f1237f3

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

LOG: Add a flag to disable "duplicate definition of category" warnings

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

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticCommonKinds.td
clang/test/Misc/warning-flags.c
clang/test/SemaObjC/check-dup-objc-decls-1.m

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticCommonKinds.td 
b/clang/include/clang/Basic/DiagnosticCommonKinds.td
index 3ccdaada1ee270..ee994e765e09a9 100644
--- a/clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -305,7 +305,8 @@ def warn_slh_does_not_support_asm_goto : Warning<
 
 // Sema && Serialization
 def warn_dup_category_def : Warning<
-  "duplicate definition of category %1 on interface %0">;
+  "duplicate definition of category %1 on interface %0">,
+  InGroup>;
 
 // Targets
 

diff  --git a/clang/test/Misc/warning-flags.c b/clang/test/Misc/warning-flags.c
index ac9a1f9f010c2e..c587337da5933a 100644
--- a/clang/test/Misc/warning-flags.c
+++ b/clang/test/Misc/warning-flags.c
@@ -18,7 +18,7 @@ This test serves two purposes:
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (66):
+CHECK: Warnings without flags (65):
 
 CHECK-NEXT:   ext_expected_semi_decl_list
 CHECK-NEXT:   ext_explicit_specialization_storage_class
@@ -46,7 +46,6 @@ CHECK-NEXT:   warn_double_const_requires_fp64
 CHECK-NEXT:   warn_drv_assuming_mfloat_abi_is
 CHECK-NEXT:   warn_drv_clang_unsupported
 CHECK-NEXT:   warn_drv_pch_not_first_include
-CHECK-NEXT:   warn_dup_category_def
 CHECK-NEXT:   warn_enum_value_overflow
 CHECK-NEXT:   warn_expected_qualified_after_typename
 CHECK-NEXT:   warn_fe_backend_unsupported

diff  --git a/clang/test/SemaObjC/check-dup-objc-decls-1.m 
b/clang/test/SemaObjC/check-dup-objc-decls-1.m
index 8867afef7159a9..94b33d5cfe801c 100644
--- a/clang/test/SemaObjC/check-dup-objc-decls-1.m
+++ b/clang/test/SemaObjC/check-dup-objc-decls-1.m
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -Wno-objc-root-class %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Wno-objc-root-class 
-Wno-objc-duplicate-category-definition -DIGNORE_DUP_CAT %s
 
 @interface Foo // expected-note {{previous definition is here}}
 @end
@@ -41,8 +42,13 @@ @protocol DP @end
 @protocol DP @end
 #pragma clang diagnostic pop
 
-@interface A(Cat) @end // expected-note {{previous definition is here}}
-@interface A(Cat) @end // expected-warning {{duplicate definition of 
category 'Cat' on interface 'A'}}
+@interface A(Cat) @end
+@interface A(Cat) @end
+
+#ifndef IGNORE_DUP_CAT
+// expected-note@-4 {{previous definition is here}}
+// expected-warning@-4 {{duplicate definition of category 'Cat' on interface 
'A'}}
+#endif
 
 // rdar 7626768
 @class NSString;



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


[PATCH] D144347: [clang-tidy] Add readability-forward-usage check

2023-07-03 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added a comment.

In D144347#4469770 , @ccotter wrote:

> @PiotrZSL - checking back, do you plan to revisit this change soon (I think 
> there are some pending feedback and you planned some changes)? I'd like to 
> see this in change merged in. Let me know if I can help.

I will try to re-visit this change this week. I need to split this check 
somehow. Probably extract casting between types into separate bugprone check 
and add some better support for template types.
Give me 2-3 days.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144347

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


[PATCH] D153600: Implement -frecord-command-line for XCOFF

2023-07-03 Thread Stephen Peckham via Phabricator via cfe-commits
stephenpeckham added inline comments.



Comment at: llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp:2338
   // Emit bytes for llvm.commandline metadata.
-  emitModuleCommandLines(M);
+  if (!TM.getTargetTriple().isOSBinFormatXCOFF())
+emitModuleCommandLines(M);

I would add a comment explaining that for XCOFF, the command line metadata was 
emitted earlier.



Comment at: llvm/lib/MC/MCAsmStreamer.cpp:981
+
+  // Metadata needs to be padded out to an even word size.
+  size_t MetadataSize = Metadata.size();

There's no requirement to pad the .info section. When you generate assembly 
language, the .info pseudo-op can only generate words of data, so the if the 
data length is not 0(mod 4), the last word will have to be padded with 
low-order 0s.  This means that the length of the .info section will be a 
multiple of 4. The length, on the other hand, should be exact. At link time, 
only "length" bytes will be copied to the output file.

If you emit object code directly, you will not need to emit any padding bytes.



Comment at: llvm/lib/MC/MCAsmStreamer.cpp:987
+  // If there's no metadata, the length is 0.
+  if (MetadataSize == 0) {
+OS << format_hex(uint32_t(0), 10) << ",";

Can this be moved up right after the computation of MetadataSize?  Can't you 
just emit "0,"?  Why call format_hex()? It seems odd to have a literal comma 
here instead of using Separator.



Comment at: llvm/lib/MC/MCAsmStreamer.cpp:994
+  // Emit length of the metadata with padding.
+  OS << format_hex(PaddedSize, 10) << ",";
+

You should use MetadataSize  and Separator here.  In fact, you could emit the 
length before checking for 0, expecially because a length of 0 is a rare case 
(and impossible for this patch).



Comment at: llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp:2974
+RSOS << "@(#)" << MDS->getString();
+RSOS.write('\0');
+  }

I would use a newline here.  The AIX **what **command looks for @(#) and echos 
subsequent bytes until it sees a double quote, a backslash, a > symbol, 
newline, or null byte.  The @(#) is not echoed, nor is the terminating 
character.  The **what **command prints a newline after it finds a terminating 
character.  This means that if the command line contains any of the special 
characters, the line will be truncated.

Exception:  If the @(#) is followed by "opt " or " opt ", the terminating 
characters are only a newline or null byte. This allows any of the other 
special characters to be part of the command line. It doesn't really matter if 
you use a newline or a null byte, but the legacy XL compiler uses a newline. 
The "opt" keyword should appear if the command line can contain a double quote, 
a > or a backslash.

The legacy compiler also uses other keywords besides "opt", including "version" 
and "cfg".  The **what** command doesn't do anything special with these 
keywords.



Comment at: llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll:16
+
+; ASM: .info ".GCC.command.line", 0x0030,
+; ASM: .info , 0x40282329, 0x636c616e, 0x67202d63, 0x6f6d6d61, 0x6e64202d, 
0x6c696e65

0x002e:  The actual length should be emitted.


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

https://reviews.llvm.org/D153600

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


[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Jennifer Yu 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 rG35041a435def: [OPENMP52] Codegen support for doacross 
clause. (authored by jyu2).

Changed prior to commit:
  https://reviews.llvm.org/D154180?vs=536838=536909#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/test/OpenMP/ordered_doacross_codegen.c

Index: clang/test/OpenMP/ordered_doacross_codegen.c
===
--- clang/test/OpenMP/ordered_doacross_codegen.c
+++ clang/test/OpenMP/ordered_doacross_codegen.c
@@ -2,13 +2,21 @@
 // RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-NORMAL
 
+// RUN: %clang_cc1 -verify -fopenmp -triple x86_64-unknown-unknown -emit-llvm %s -o - -fopenmp-version=52 | FileCheck %s --check-prefixes=CHECK,CHECK-NORMAL
 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -fopenmp-version=52 -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
 // RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
 
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
+
 // RUN: %clang_cc1 -verify -fopenmp-simd -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
+// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
 // RUN: %clang_cc1 -fopenmp-simd -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp-simd -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
+// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
 // SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
 // expected-no-diagnostics
 
@@ -51,7 +59,11 @@
 // CHECK-NORMAL-NEXT: call void @__kmpc_doacross_post(ptr [[IDENT]], i32 [[GTID]], ptr [[TMP]])
 // CHECK-IRBUILDER-NEXT: [[GTID1:%.+]] = call i32 @__kmpc_global_thread_num(ptr [[IDENT:@.+]])
 // CHECK-IRBUILDER-NEXT: call void @__kmpc_doacross_post(ptr [[IDENT]], i32 [[GTID1]], ptr [[TMP]])
+#if _OPENMP >= 202111
+#pragma omp ordered doacross(source:)
+#else
 #pragma omp ordered depend(source)
+#endif
 c[i] = c[i] + 1;
 foo();
 // CHECK: call void @foo()
@@ -66,7 +78,11 @@
 // CHECK-NORMAL-NEXT: call void @__kmpc_doacross_wait(ptr [[IDENT]], i32 [[GTID]], ptr [[TMP]])
 // CHECK-IRBUILDER-NEXT: [[GTID2:%.+]] = call i32 @__kmpc_global_thread_num(ptr [[IDENT:@.+]])
 // CHECK-IRBUILDER-NEXT: call void @__kmpc_doacross_wait(ptr [[IDENT]], i32 [[GTID2]], ptr [[TMP]])
+#if _OPENMP >= 202111
+#pragma omp ordered doacross(sink : i - 2)
+#else
 #pragma omp ordered depend(sink : i - 2)
+#endif
 d[i] = a[i - 2];
   }
   // CHECK: call void @__kmpc_for_static_fini(
Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -5839,37 +5839,46 @@
   return Fn;
 }
 
+template 
+static void emitRestoreIP(CodeGenFunction , const T *C,
+  llvm::OpenMPIRBuilder::InsertPointTy AllocaIP,
+  llvm::OpenMPIRBuilder ) {
+
+  unsigned NumLoops = C->getNumLoops();
+  QualType Int64Ty = CGF.CGM.getContext().getIntTypeForBitwidth(
+  /*DestWidth=*/64, /*Signed=*/1);
+  llvm::SmallVector StoreValues;
+  for (unsigned I = 0; I < NumLoops; I++) {
+const Expr *CounterVal = C->getLoopData(I);
+assert(CounterVal);
+llvm::Value *StoreValue = CGF.EmitScalarConversion(
+CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
+CounterVal->getExprLoc());
+

[clang] 35041a4 - [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Jennifer Yu via cfe-commits

Author: Jennifer Yu
Date: 2023-07-03T15:24:05-07:00
New Revision: 35041a435def860e2b1b99133b934632a9d634ac

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

LOG: [OPENMP52] Codegen support for doacross clause.

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

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntime.h
clang/lib/CodeGen/CGStmtOpenMP.cpp
clang/test/OpenMP/ordered_doacross_codegen.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 32964aa7d7e39e..188b21e3a88949 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -11381,8 +11381,10 @@ void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction 
,
  llvm::ArrayRef(FiniArgs));
 }
 
-void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction ,
-  const OMPDependClause *C) {
+template 
+static void EmitDoacrossOrdered(CodeGenFunction , CodeGenModule ,
+const T *C, llvm::Value *ULoc,
+llvm::Value *ThreadID) {
   QualType Int64Ty =
   CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
   llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
@@ -11399,21 +11401,35 @@ void 
CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction ,
   /*Volatile=*/false, Int64Ty);
   }
   llvm::Value *Args[] = {
-  emitUpdateLocation(CGF, C->getBeginLoc()),
-  getThreadID(CGF, C->getBeginLoc()),
-  CGF.Builder.CreateConstArrayGEP(CntAddr, 0).getPointer()};
+  ULoc, ThreadID, CGF.Builder.CreateConstArrayGEP(CntAddr, 
0).getPointer()};
   llvm::FunctionCallee RTLFn;
-  if (C->getDependencyKind() == OMPC_DEPEND_source) {
+  llvm::OpenMPIRBuilder  = CGM.getOpenMPRuntime().getOMPBuilder();
+  OMPDoacrossKind ODK;
+  if (ODK.isSource(C)) {
 RTLFn = OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
   OMPRTL___kmpc_doacross_post);
   } else {
-assert(C->getDependencyKind() == OMPC_DEPEND_sink);
+assert(ODK.isSink(C) && "Expect sink modifier.");
 RTLFn = OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
   OMPRTL___kmpc_doacross_wait);
   }
   CGF.EmitRuntimeCall(RTLFn, Args);
 }
 
+void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction ,
+  const OMPDependClause *C) {
+  return EmitDoacrossOrdered(
+  CGF, CGM, C, emitUpdateLocation(CGF, C->getBeginLoc()),
+  getThreadID(CGF, C->getBeginLoc()));
+}
+
+void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction ,
+  const OMPDoacrossClause *C) {
+  return EmitDoacrossOrdered(
+  CGF, CGM, C, emitUpdateLocation(CGF, C->getBeginLoc()),
+  getThreadID(CGF, C->getBeginLoc()));
+}
+
 void CGOpenMPRuntime::emitCall(CodeGenFunction , SourceLocation Loc,
llvm::FunctionCallee Callee,
ArrayRef Args) const {
@@ -12400,6 +12416,11 @@ void 
CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction ,
   llvm_unreachable("Not supported in SIMD-only mode");
 }
 
+void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction ,
+  const OMPDoacrossClause *C) {
+  llvm_unreachable("Not supported in SIMD-only mode");
+}
+
 const VarDecl *
 CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
 const VarDecl *NativeParam) const {

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.h 
b/clang/lib/CodeGen/CGOpenMPRuntime.h
index 4370c95e03feac..e346ef2b49a0ec 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.h
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.h
@@ -1487,6 +1487,11 @@ class CGOpenMPRuntime {
   virtual void emitDoacrossOrdered(CodeGenFunction ,
const OMPDependClause *C);
 
+  /// Emit code for doacross ordered directive with 'doacross' clause.
+  /// \param C 'doacross' clause with 'sink|source' dependence type.
+  virtual void emitDoacrossOrdered(CodeGenFunction ,
+   const OMPDoacrossClause *C);
+
   /// Translates the native parameter of outlined function if this is required
   /// for target.
   /// \param FD Field decl from captured record for the parameter.
@@ -2240,6 +2245,11 @@ class CGOpenMPSIMDRuntime final : public CGOpenMPRuntime 
{
   void emitDoacrossOrdered(CodeGenFunction ,
const OMPDependClause *C) override;
 
+  /// Emit code for doacross ordered directive with 'doacross' clause.
+ 

[PATCH] D144347: [clang-tidy] Add readability-forward-usage check

2023-07-03 Thread Chris Cotter via Phabricator via cfe-commits
ccotter added a comment.

@PiotrZSL - checking back, do you plan to revisit this change soon (I think 
there are some pending feedback and you planned some changes)? I'd like to see 
this in change merged in. Let me know if I can help.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144347

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


[PATCH] D153740: [llvm][Support] Deprecate llvm::writeFileAtomically API

2023-07-03 Thread Alexey Lapshin via Phabricator via cfe-commits
avl accepted this revision.
avl added a comment.
This revision is now accepted and ready to land.

this LGTM, assuming D154329  is landed. Thank 
you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153740

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


[PATCH] D154329: [lldb] Replace llvm::writeFileAtomically with llvm::writeToOutput API.

2023-07-03 Thread Jonas Devlieghere via Phabricator via cfe-commits
JDevlieghere accepted this revision.
JDevlieghere 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/D154329/new/

https://reviews.llvm.org/D154329

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


[PATCH] D153600: Implement -frecord-command-line for XCOFF

2023-07-03 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan updated this revision to Diff 536890.
Jake-Egan added a comment.

Fix formatting


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

https://reviews.llvm.org/D153600

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  llvm/include/llvm/CodeGen/AsmPrinter.h
  llvm/include/llvm/MC/MCStreamer.h
  llvm/include/llvm/MC/MCXCOFFStreamer.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/MC/MCAsmStreamer.cpp
  llvm/lib/MC/MCStreamer.cpp
  llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
  llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll

Index: llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll
@@ -0,0 +1,22 @@
+; RUN: llc -mtriple powerpc-ibm-aix-xcoff < %s | \
+; RUN: FileCheck --check-prefix=ASM %s
+; RUN: llc -mtriple powerpc64-ibm-aix-xcoff < %s | \
+; RUN: FileCheck --check-prefix=ASM %s
+
+; RUN: not --crash llc -mtriple powerpc-ibm-aix-xcoff -filetype=obj  < %s 2>&1 | \
+; RUN: FileCheck --check-prefix=OBJ %s
+; RUN: not --crash llc -mtriple powerpc64-ibm-aix-xcoff -filetype=obj  < %s 2>&1 | \
+; RUN: FileCheck --check-prefix=OBJ %s
+
+; Verify that llvm.commandline metadata is emitted to .info sections and that the
+; metadata is padded if necessary.
+
+; OBJ: LLVM ERROR: emitXCOFFCInfoSym is not implemented yet on object generation path
+
+; ASM: .info ".GCC.command.line", 0x0030,
+; ASM: .info , 0x40282329, 0x636c616e, 0x67202d63, 0x6f6d6d61, 0x6e64202d, 0x6c696e65
+; ASM: .info , 0x00402823, 0x29736f6d, 0x65746869, 0x6e672065, 0x6c736531, 0x3233
+
+!llvm.commandline = !{!0, !1}
+!0 = !{!"clang -command -line"}
+!1 = !{!"something else123"}
Index: llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
===
--- llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
+++ llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
@@ -290,6 +290,8 @@
   bool doFinalization(Module ) override;
 
   void emitTTypeReference(const GlobalValue *GV, unsigned Encoding) override;
+
+  void emitModuleCommandLines(Module ) override;
 };
 
 } // end anonymous namespace
@@ -2954,6 +2956,26 @@
   return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
 }
 
+void PPCAIXAsmPrinter::emitModuleCommandLines(Module ) {
+  const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
+  if (!NMD || !NMD->getNumOperands())
+return;
+
+  std::string S;
+  raw_string_ostream RSOS(S);
+  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
+const MDNode *N = NMD->getOperand(i);
+assert(N->getNumOperands() == 1 &&
+   "llvm.commandline metadata entry can have only one operand");
+const MDString *MDS = cast(N->getOperand(0));
+// Add "@(#)" to support retrieving the command line information with the
+// AIX "what" command
+RSOS << "@(#)" << MDS->getString();
+RSOS.write('\0');
+  }
+  OutStreamer->emitXCOFFCInfoSym(".GCC.command.line", RSOS.str());
+}
+
 // Force static initialization.
 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() {
   TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
Index: llvm/lib/MC/MCStreamer.cpp
===
--- llvm/lib/MC/MCStreamer.cpp
+++ llvm/lib/MC/MCStreamer.cpp
@@ -1208,6 +1208,11 @@
  "XCOFF targets");
 }
 
+void MCStreamer::emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) {
+  llvm_unreachable("emitXCOFFCInfoSym is only supported on"
+   "XCOFF targets");
+}
+
 void MCStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
 void MCStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
 StringRef Name, bool KeepOriginalSym) {}
Index: llvm/lib/MC/MCAsmStreamer.cpp
===
--- llvm/lib/MC/MCAsmStreamer.cpp
+++ llvm/lib/MC/MCAsmStreamer.cpp
@@ -36,6 +36,7 @@
 #include "llvm/Support/LEB128.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/Path.h"
+#include 
 #include 
 
 using namespace llvm;
@@ -200,6 +201,7 @@
 const MCSymbol *Trap,
 unsigned Lang, unsigned Reason,
 unsigned FunctionSize, bool hasDebug) override;
+  void emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) override;
 
   void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
   void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
@@ -966,6 +968,66 @@
   EmitEOL();
 }
 
+void MCAsmStreamer::emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) {
+  const char *InfoDirective = "\t.info ";
+  const char *Separator = ", ";
+  constexpr int WordSize = sizeof(uint32_t);
+
+  // Start by emitting the .info pseudo-op and C_INFO symbol name.
+  OS << InfoDirective;
+  PrintQuotedString(Name, OS);
+  OS << Separator;
+
+  // 

[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 added a comment.

In D154180#4469417 , @ABataev wrote:

> LG with a nit

Thank you so much!
Jennifer


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

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


[PATCH] D154133: [amdgpu] start documenting amdgpu support by clang

2023-07-03 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 536887.
yaxunl marked 2 inline comments as done.
yaxunl added a comment.

revised by comments


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

https://reviews.llvm.org/D154133

Files:
  clang/docs/AMDGPUSupport.rst


Index: clang/docs/AMDGPUSupport.rst
===
--- /dev/null
+++ clang/docs/AMDGPUSupport.rst
@@ -0,0 +1,63 @@
+.. raw:: html
+
+  
+.none { background-color: #FF }
+.part { background-color: #99 }
+.good { background-color: #CCFF99 }
+  
+
+.. role:: none
+.. role:: part
+.. role:: good
+
+.. contents::
+   :local:
+
+==
+AMDGPU Support
+==
+
+Clang supports OpenCL, HIP and OpenMP on AMD GPU targets.
+
+
+Predefined Macros
+=
+
+
+.. list-table::
+   :header-rows: 1
+
+   * - Macro
+ - Description
+   * - ``__AMDGPU__``
+ - Indicates that the code is being compiled for an AMD GPU.
+   * - ``__AMDGCN__``
+ - Defined if the GPU target is AMDGCN.
+   * - ``__R600__``
+ - Defined if the GPU target is R600.
+   * - ````
+ - Defined with the name of the architecture (e.g., ``__gfx906__`` for the 
gfx906 architecture).
+   * - ````
+ - Defines the GFX family (e.g., for gfx906, this macro would be 
``__GFX9__``).
+   * - ``__amdgcn_processor__``
+ - Defined with the processor name as a string (e.g., ``"gfx906"``).
+   * - ``__amdgcn_target_id__``
+ - Defined with the target ID as a string.
+   * - ``__amdgcn_feature___``
+ - Defined for each supported target feature. The value is 1 if the 
feature is enabled and 0 if it is disabled. Allowed feature names are sramecc 
and xnack.
+   * - ``__AMDGCN_CUMODE__``
+ - Defined as 1 if the CU mode is enabled and 0 if the WGP mode is enabled.
+   * - ``__AMDGCN_UNSAFE_FP_ATOMICS__``
+ - Defined if unsafe floating-point atomics are allowed.
+   * - ``__AMDGCN_WAVEFRONT_SIZE__``
+ - Defines the wavefront size. Allowed values are 32 and 64.
+   * - ``__AMDGCN_WAVEFRONT_SIZE``
+ - Alias to ``__AMDGCN_WAVEFRONT_SIZE__``. To be deprecated.
+   * - ``__HAS_FMAF__``
+ - Defined if FMAF instruction is available (deprecated).
+   * - ``__HAS_LDEXPF__``
+ - Defined if LDEXPF instruction is available (deprecated).
+   * - ``__HAS_FP64__``
+ - Defined if FP64 instruction is available (deprecated).
+
+Please note that the specific architecture and feature names will vary 
depending on the GPU. Also, some macros are deprecated and may be removed in 
future releases.


Index: clang/docs/AMDGPUSupport.rst
===
--- /dev/null
+++ clang/docs/AMDGPUSupport.rst
@@ -0,0 +1,63 @@
+.. raw:: html
+
+  
+.none { background-color: #FF }
+.part { background-color: #99 }
+.good { background-color: #CCFF99 }
+  
+
+.. role:: none
+.. role:: part
+.. role:: good
+
+.. contents::
+   :local:
+
+==
+AMDGPU Support
+==
+
+Clang supports OpenCL, HIP and OpenMP on AMD GPU targets.
+
+
+Predefined Macros
+=
+
+
+.. list-table::
+   :header-rows: 1
+
+   * - Macro
+ - Description
+   * - ``__AMDGPU__``
+ - Indicates that the code is being compiled for an AMD GPU.
+   * - ``__AMDGCN__``
+ - Defined if the GPU target is AMDGCN.
+   * - ``__R600__``
+ - Defined if the GPU target is R600.
+   * - ````
+ - Defined with the name of the architecture (e.g., ``__gfx906__`` for the gfx906 architecture).
+   * - ````
+ - Defines the GFX family (e.g., for gfx906, this macro would be ``__GFX9__``).
+   * - ``__amdgcn_processor__``
+ - Defined with the processor name as a string (e.g., ``"gfx906"``).
+   * - ``__amdgcn_target_id__``
+ - Defined with the target ID as a string.
+   * - ``__amdgcn_feature___``
+ - Defined for each supported target feature. The value is 1 if the feature is enabled and 0 if it is disabled. Allowed feature names are sramecc and xnack.
+   * - ``__AMDGCN_CUMODE__``
+ - Defined as 1 if the CU mode is enabled and 0 if the WGP mode is enabled.
+   * - ``__AMDGCN_UNSAFE_FP_ATOMICS__``
+ - Defined if unsafe floating-point atomics are allowed.
+   * - ``__AMDGCN_WAVEFRONT_SIZE__``
+ - Defines the wavefront size. Allowed values are 32 and 64.
+   * - ``__AMDGCN_WAVEFRONT_SIZE``
+ - Alias to ``__AMDGCN_WAVEFRONT_SIZE__``. To be deprecated.
+   * - ``__HAS_FMAF__``
+ - Defined if FMAF instruction is available (deprecated).
+   * - ``__HAS_LDEXPF__``
+ - Defined if LDEXPF instruction is available (deprecated).
+   * - ``__HAS_FP64__``
+ - Defined if FP64 instruction is available (deprecated).
+
+Please note that the specific architecture and feature names will vary depending on the GPU. Also, some macros are deprecated and may be removed in future releases.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D154133: [amdgpu] start documenting amdgpu support by clang

2023-07-03 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 3 inline comments as done.
yaxunl added inline comments.



Comment at: clang/docs/AMDGPUSupport.rst:20
+
+Clang supports OpenCL, HIP and OpenMP on amdgpu target.
+

lamb-j wrote:
> arsenm wrote:
> > "on amdgpu target" doesn't sound grammatical
> "for the //amdgpu// target"? or
> "on AMD GPU targets?"
> 
will use "on AMD GPU targets".



Comment at: clang/docs/AMDGPUSupport.rst:49
+   * - ``__AMDGCN_CUMODE__``
+ - Defines as 1 if the CU mode is enabled and 0 if the WGP mode is enabled.
+   * - ``__AMDGCN_UNSAFE_FP_ATOMICS__``

lamb-j wrote:
> Defined?
will fix


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

https://reviews.llvm.org/D154133

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


[PATCH] D154388: Don't pass -ibuiltininc, which is used only by the driver, to CC1

2023-07-03 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak created this revision.
ahatanak added reviewers: arphaman, fahad, MaskRay.
ahatanak added a project: clang.
Herald added a project: All.
ahatanak requested review of this revision.

This fixes a fallout from 5b77e752dcd073846b89559d6c0e1a7699e58615 
.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154388

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/darwin-header-search-system.cpp


Index: clang/test/Driver/darwin-header-search-system.cpp
===
--- clang/test/Driver/darwin-header-search-system.cpp
+++ clang/test/Driver/darwin-header-search-system.cpp
@@ -131,6 +131,7 @@
 // RUN:   -DRESOURCE=%S/Inputs/resource_dir \
 // RUN:   --check-prefix=CHECK-NOSTDINC-BUILTINC %s
 // CHECK-NOSTDINC-BUILTINC: "-cc1"
+// CHECK-NOSTDINC-BUILTINC-NOT: "-ibuiltininc"
 // CHECK-NOSTDINC-BUILTINC-NOT: "-internal-isystem" 
"[[SYSROOT]]/usr/local/include"
 // CHECK-NOSTDINC-BUILTINC: "-internal-isystem" "[[RESOURCE]]/include"
 // CHECK-NOSTDINC-BUILTINC-NOT: "-internal-externc-isystem" 
"[[SYSROOT]]/usr/include"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -1305,6 +1305,9 @@
 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
   // Translated to -internal-isystem by the driver, no need to pass to cc1.
   continue;
+} else if (A->getOption().matches(options::OPT_ibuiltininc)) {
+  // This is used only by the driver. No no need to pass to cc1.
+  continue;
 }
 
 // Not translated, render as usual.


Index: clang/test/Driver/darwin-header-search-system.cpp
===
--- clang/test/Driver/darwin-header-search-system.cpp
+++ clang/test/Driver/darwin-header-search-system.cpp
@@ -131,6 +131,7 @@
 // RUN:   -DRESOURCE=%S/Inputs/resource_dir \
 // RUN:   --check-prefix=CHECK-NOSTDINC-BUILTINC %s
 // CHECK-NOSTDINC-BUILTINC: "-cc1"
+// CHECK-NOSTDINC-BUILTINC-NOT: "-ibuiltininc"
 // CHECK-NOSTDINC-BUILTINC-NOT: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
 // CHECK-NOSTDINC-BUILTINC: "-internal-isystem" "[[RESOURCE]]/include"
 // CHECK-NOSTDINC-BUILTINC-NOT: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -1305,6 +1305,9 @@
 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
   // Translated to -internal-isystem by the driver, no need to pass to cc1.
   continue;
+} else if (A->getOption().matches(options::OPT_ibuiltininc)) {
+  // This is used only by the driver. No no need to pass to cc1.
+  continue;
 }
 
 // Not translated, render as usual.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 4eef528 - [HIP] Pass -fno-hip-fp32-correctly-rounded-divide-sqrt to clang -cc1

2023-07-03 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2023-07-03T16:19:25-04:00
New Revision: 4eef528853418fd72bffbb139d953520bb7b4c73

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

LOG: [HIP] Pass -fno-hip-fp32-correctly-rounded-divide-sqrt to clang -cc1

-fno-hip-fp32-correctly-rounded-divide-sqrt affects clang codegen
and should be passed to clang -cc1 by clang driver.

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

Reviewed by: Matt Arsenault

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/hip-options.hip

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 6f3d86b900edfb..f85584b3335e4b 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7223,6 +7223,11 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
 }
   }
 
+  if (IsHIPDevice)
+Args.addOptOutFlag(CmdArgs,
+   options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
+   
options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
+
   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
   // to specify the result of the compile phase on the host, so the meaningful
   // device declarations can be identified. Also, -fopenmp-is-device is passed

diff  --git a/clang/test/Driver/hip-options.hip 
b/clang/test/Driver/hip-options.hip
index 7a6965caf5e001..edbe4ff3acbedf 100644
--- a/clang/test/Driver/hip-options.hip
+++ b/clang/test/Driver/hip-options.hip
@@ -154,3 +154,18 @@
 // RUN: %clang -### -nogpuinc -nogpulib -mamdgpu-ieee -mno-amdgpu-ieee 
-ffast-math \
 // RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck 
-check-prefixes=IEEE-OFF-NEG %s
 // IEEE-OFF-NEG-NOT: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} 
"-mamdgpu-ieee"
+
+// Check -fno-hip-fp32-correctly-rounded-divide-sqrt is passed to -cc1 but
+// (default) -fhip-fp32-correctly-rounded-divide-sqrt is not.
+
+// RUN: %clang -### -nogpuinc -nogpulib 
-fno-hip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=NOCRDS %s
+// NOCRDS: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} 
"-fno-hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib 
-fhip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"



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


[PATCH] D154385: [HIP] Pass -fno-hip-fp32-correctly-rounded-divide-sqrt to clang -cc1

2023-07-03 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4eef52885341: [HIP] Pass 
-fno-hip-fp32-correctly-rounded-divide-sqrt to clang -cc1 (authored by yaxunl).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154385

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/hip-options.hip


Index: clang/test/Driver/hip-options.hip
===
--- clang/test/Driver/hip-options.hip
+++ clang/test/Driver/hip-options.hip
@@ -154,3 +154,18 @@
 // RUN: %clang -### -nogpuinc -nogpulib -mamdgpu-ieee -mno-amdgpu-ieee 
-ffast-math \
 // RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck 
-check-prefixes=IEEE-OFF-NEG %s
 // IEEE-OFF-NEG-NOT: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} 
"-mamdgpu-ieee"
+
+// Check -fno-hip-fp32-correctly-rounded-divide-sqrt is passed to -cc1 but
+// (default) -fhip-fp32-correctly-rounded-divide-sqrt is not.
+
+// RUN: %clang -### -nogpuinc -nogpulib 
-fno-hip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=NOCRDS %s
+// NOCRDS: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} 
"-fno-hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib 
-fhip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7223,6 +7223,11 @@
 }
   }
 
+  if (IsHIPDevice)
+Args.addOptOutFlag(CmdArgs,
+   options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
+   
options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
+
   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
   // to specify the result of the compile phase on the host, so the meaningful
   // device declarations can be identified. Also, -fopenmp-is-device is passed


Index: clang/test/Driver/hip-options.hip
===
--- clang/test/Driver/hip-options.hip
+++ clang/test/Driver/hip-options.hip
@@ -154,3 +154,18 @@
 // RUN: %clang -### -nogpuinc -nogpulib -mamdgpu-ieee -mno-amdgpu-ieee -ffast-math \
 // RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=IEEE-OFF-NEG %s
 // IEEE-OFF-NEG-NOT: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} "-mamdgpu-ieee"
+
+// Check -fno-hip-fp32-correctly-rounded-divide-sqrt is passed to -cc1 but
+// (default) -fhip-fp32-correctly-rounded-divide-sqrt is not.
+
+// RUN: %clang -### -nogpuinc -nogpulib -fno-hip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=NOCRDS %s
+// NOCRDS: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} "-fno-hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib -fhip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7223,6 +7223,11 @@
 }
   }
 
+  if (IsHIPDevice)
+Args.addOptOutFlag(CmdArgs,
+   options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
+   options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
+
   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
   // to specify the result of the compile phase on the host, so the meaningful
   // device declarations can be identified. Also, -fopenmp-is-device is passed
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154339: [clang][dataflow] Make `runDataflowReturnError()` a non-template function.

2023-07-03 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/unittests/Analysis/FlowSensitive/TestingSupport.h:389
 /// verify the results.
-template 
-llvm::Error
-runDataflowReturnError(llvm::StringRef Code, VerifyResultsT VerifyResults,
-   DataflowAnalysisOptions Options,
-   LangStandard::Kind Std = LangStandard::lang_cxx17,
-   llvm::StringRef TargetFun = "target") {
-  using ast_matchers::hasName;
-  llvm::SmallVector ASTBuildArgs = {
-  // -fnodelayed-template-parsing is the default everywhere but on Windows.
-  // Set it explicitly so that tests behave the same on Windows as on other
-  // platforms.
-  "-fsyntax-only", "-fno-delayed-template-parsing",
-  "-std=" +
-  std::string(LangStandard::getLangStandardForKind(Std).getName())};
-  AnalysisInputs AI(
-  Code, hasName(TargetFun),
-  [UseBuiltinModel = Options.BuiltinOpts.has_value()](ASTContext ,
-  Environment ) {
-return NoopAnalysis(
-C,
-DataflowAnalysisOptions{
-UseBuiltinModel ? Env.getDataflowAnalysisContext().getOptions()
-: std::optional()});
-  });
-  AI.ASTBuildArgs = ASTBuildArgs;
-  if (Options.BuiltinOpts)
-AI.BuiltinOptions = *Options.BuiltinOpts;
-  return checkDataflow(
-  std::move(AI),
-  /*VerifyResults=*/
-  [](
-  const llvm::StringMap> ,
-  const AnalysisOutputs ) { VerifyResults(Results, AO.ASTCtx); });
-}
+llvm::Error runDataflowReturnError(
+llvm::StringRef Code,

I don't quite understand your comment from the previous patch:

> This is really just moved from TransferTest.cpp -- and it's more closely 
> related to the `runDataflow()` functions there and in the newly added 
> RecordOps.cpp. (I can't call it `runDataflow()` because then it would differ 
> only in return type from one of the functions in the overload set.)

I don't see another `checkDataflow()` function with the same signature. 
Furthermore, `checkDataflow()` overloads above already return an `llvm::Error`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154339

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


[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added a comment.

Thank you or the quick fix!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154334

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


[PATCH] D61508: [clang-tidy] bugprone-header-guard : a simple version of llvm-header-guard

2023-07-03 Thread Gary Miguel via Phabricator via cfe-commits
garymm added a comment.
Herald added subscribers: carlosgalvezp, mgehre.
Herald added a project: All.

@aaron.ballman what's remaining for this to be mergeable?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D61508

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


[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG with a nit




Comment at: clang/lib/CodeGen/CGOpenMPRuntime.h:2285-2297
+return (C->getDependencyKind() == OMPC_DEPEND_sink);
+  }
+  bool isSource(const OMPDependClause *C) {
+return (C->getDependencyKind() == OMPC_DEPEND_source);
+  }
+};
+template <> class OMPDoacrossKind {

remove parens from the expressions, they are not needed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

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


[PATCH] D154385: [HIP] Pass -fno-hip-fp32-correctly-rounded-divide-sqrt to clang -cc1

2023-07-03 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added reviewers: tra, MaskRay, arsenm.
Herald added a project: All.
yaxunl requested review of this revision.
Herald added a subscriber: wdng.

`-fno-hip-fp32-correctly-rounded-divide-sqrt` affects clang codegen
and should be passed to clang -cc1 by clang driver.

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


https://reviews.llvm.org/D154385

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/hip-options.hip


Index: clang/test/Driver/hip-options.hip
===
--- clang/test/Driver/hip-options.hip
+++ clang/test/Driver/hip-options.hip
@@ -154,3 +154,18 @@
 // RUN: %clang -### -nogpuinc -nogpulib -mamdgpu-ieee -mno-amdgpu-ieee 
-ffast-math \
 // RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck 
-check-prefixes=IEEE-OFF-NEG %s
 // IEEE-OFF-NEG-NOT: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} 
"-mamdgpu-ieee"
+
+// Check -fno-hip-fp32-correctly-rounded-divide-sqrt is passed to -cc1 but
+// (default) -fhip-fp32-correctly-rounded-divide-sqrt is not.
+
+// RUN: %clang -### -nogpuinc -nogpulib 
-fno-hip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=NOCRDS %s
+// NOCRDS: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} 
"-fno-hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib 
-fhip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7223,6 +7223,11 @@
 }
   }
 
+  if (IsHIPDevice)
+Args.addOptOutFlag(CmdArgs,
+   options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
+   
options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
+
   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
   // to specify the result of the compile phase on the host, so the meaningful
   // device declarations can be identified. Also, -fopenmp-is-device is passed


Index: clang/test/Driver/hip-options.hip
===
--- clang/test/Driver/hip-options.hip
+++ clang/test/Driver/hip-options.hip
@@ -154,3 +154,18 @@
 // RUN: %clang -### -nogpuinc -nogpulib -mamdgpu-ieee -mno-amdgpu-ieee -ffast-math \
 // RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=IEEE-OFF-NEG %s
 // IEEE-OFF-NEG-NOT: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} "-mamdgpu-ieee"
+
+// Check -fno-hip-fp32-correctly-rounded-divide-sqrt is passed to -cc1 but
+// (default) -fhip-fp32-correctly-rounded-divide-sqrt is not.
+
+// RUN: %clang -### -nogpuinc -nogpulib -fno-hip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=NOCRDS %s
+// NOCRDS: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} "-fno-hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib -fhip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7223,6 +7223,11 @@
 }
   }
 
+  if (IsHIPDevice)
+Args.addOptOutFlag(CmdArgs,
+   options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
+   options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
+
   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
   // to specify the result of the compile phase on the host, so the meaningful
   // device declarations can be identified. Also, -fopenmp-is-device is passed
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D135849: [llvm] Return canonical virtual path from `RedirectingFileSystem`

2023-07-03 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir added a comment.

In D135849#4469347 , @jansvoboda11 
wrote:

> It'd be really nice to have DirectoryEntry::getDir() API, so that we can walk 
> up the directory hierarchy while preserving the virtual/real distinction 
> between directories in the overlay/on disk, never accidentally "bubbling up" 
> into the overlay again. What's your take on that?

Can you say more about how you would do this and preserve the real/virtual 
distinction? Currently FileManager is just filling in the directory based on 
the parent path with a lookup to the VFS, so isn't it the same issue? Or did 
you mean we would keep more info?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135849

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


[PATCH] D135849: [llvm] Return canonical virtual path from `RedirectingFileSystem`

2023-07-03 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

Okay, I'll try to figure out how expensive this would be. I'd like Clang to be 
stricter in situations like these, but if that's not feasible, I'll probably 
implement the first workaround.

For the second workaround, I don't think that moves us in better direction - we 
should be able to assign one canonical real path to each `DirectoryEntry`.

The unfortunate aspect of the `ModuleMap::canonicalizeModuleMapPath()` 
implementation is that it uses 
`FileManager.getDirectoryRef(llvm::sys::path::parent_path(ModuleMapFilePath))`. 
If the request for getting the module map file fell through the VFS into the 
underlying FS, parent `DirectoryEntry` of that file is different than the 
virtual directory made for the VFS. Chopping off the file name and going 
through the VFS again doesn't guarantee falling through the VFS again, which 
that code doesn't account for. It'd be really nice to have 
`DirectoryEntry::getDir()` API, so that we can walk up the directory hierarchy 
while preserving the virtual/real distinction between directories in the 
overlay/on disk, never accidentally "bubbling up" into the overlay again. 
What's your take on that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135849

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


[PATCH] D154382: [ClangRepl] support code completion at a REPL

2023-07-03 Thread Fred Fu via Phabricator via cfe-commits
capfredf created this revision.
capfredf added a reviewer: v.g.vassilev.
Herald added a project: All.
capfredf requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch enabled users to use code completion in a REPL session. The solution 
is based on LineEditor and Sema/CodeCompletion.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154382

Files:
  clang/include/clang/Interpreter/CodeCompletion.h
  clang/include/clang/Interpreter/Interpreter.h
  clang/lib/Interpreter/CMakeLists.txt
  clang/lib/Interpreter/CodeCompletion.cpp
  clang/lib/Interpreter/ExternalSource.cpp
  clang/lib/Interpreter/ExternalSource.h
  clang/lib/Interpreter/IncrementalParser.cpp
  clang/lib/Interpreter/IncrementalParser.h
  clang/lib/Interpreter/Interpreter.cpp
  clang/tools/clang-repl/ClangRepl.cpp
  clang/unittests/Interpreter/CMakeLists.txt
  clang/unittests/Interpreter/CodeCompletionTest.cpp

Index: clang/unittests/Interpreter/CodeCompletionTest.cpp
===
--- /dev/null
+++ clang/unittests/Interpreter/CodeCompletionTest.cpp
@@ -0,0 +1,61 @@
+#include "clang/Interpreter/CodeCompletion.h"
+#include "clang/Interpreter/Interpreter.h"
+
+#include "llvm/LineEditor/LineEditor.h"
+
+#include "clang/Frontend/CompilerInstance.h"
+#include "llvm/Support/Error.h"
+
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+namespace {
+auto CB = clang::IncrementalCompilerBuilder();
+
+static std::unique_ptr createInterpreter() {
+  auto CI = cantFail(CB.CreateCpp());
+  return cantFail(clang::Interpreter::create(std::move(CI)));
+}
+
+TEST(CodeCompletionTest, Sanity) {
+  auto Interp = createInterpreter();
+  if (auto R = Interp->ParseAndExecute("int foo = 12;")) {
+consumeError(std::move(R));
+return;
+  }
+  auto Completer = ReplListCompleter(CB, *Interp);
+  std::vector comps =
+  Completer(std::string("f"), 1);
+  EXPECT_EQ((size_t)2, comps.size()); // foo and float
+  EXPECT_EQ(comps[0].TypedText, std::string("oo"));
+}
+
+TEST(CodeCompletionTest, SanityNoneValid) {
+  auto Interp = createInterpreter();
+  if (auto R = Interp->ParseAndExecute("int foo = 12;")) {
+consumeError(std::move(R));
+return;
+  }
+  auto Completer = ReplListCompleter(CB, *Interp);
+  std::vector comps =
+  Completer(std::string("babanana"), 8);
+  EXPECT_EQ((size_t)0, comps.size()); // foo and float
+}
+
+TEST(CodeCompletionTest, TwoDecls) {
+  auto Interp = createInterpreter();
+  if (auto R = Interp->ParseAndExecute("int application = 12;")) {
+consumeError(std::move(R));
+return;
+  }
+  if (auto R = Interp->ParseAndExecute("int apple = 12;")) {
+consumeError(std::move(R));
+return;
+  }
+  auto Completer = ReplListCompleter(CB, *Interp);
+  std::vector comps =
+  Completer(std::string("app"), 3);
+  EXPECT_EQ((size_t)2, comps.size());
+}
+} // anonymous namespace
Index: clang/unittests/Interpreter/CMakeLists.txt
===
--- clang/unittests/Interpreter/CMakeLists.txt
+++ clang/unittests/Interpreter/CMakeLists.txt
@@ -9,6 +9,7 @@
 add_clang_unittest(ClangReplInterpreterTests
   IncrementalProcessingTest.cpp
   InterpreterTest.cpp
+  CodeCompletionTest.cpp
   )
 target_link_libraries(ClangReplInterpreterTests PUBLIC
   clangAST
Index: clang/tools/clang-repl/ClangRepl.cpp
===
--- clang/tools/clang-repl/ClangRepl.cpp
+++ clang/tools/clang-repl/ClangRepl.cpp
@@ -13,6 +13,7 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
+#include "clang/Interpreter/CodeCompletion.h"
 #include "clang/Interpreter/Interpreter.h"
 
 #include "llvm/ExecutionEngine/Orc/LLJIT.h"
@@ -155,8 +156,8 @@
 
   if (OptInputs.empty()) {
 llvm::LineEditor LE("clang-repl");
-// FIXME: Add LE.setListCompleter
 std::string Input;
+LE.setListCompleter(clang::ReplListCompleter(CB, *Interp));
 while (std::optional Line = LE.readLine()) {
   llvm::StringRef L = *Line;
   L = L.trim();
@@ -168,10 +169,10 @@
   }
 
   Input += L;
-
   if (Input == R"(%quit)") {
 break;
-  } else if (Input == R"(%undo)") {
+  }
+  if (Input == R"(%undo)") {
 if (auto Err = Interp->Undo()) {
   llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
   HasError = true;
Index: clang/lib/Interpreter/Interpreter.cpp
===
--- clang/lib/Interpreter/Interpreter.cpp
+++ clang/lib/Interpreter/Interpreter.cpp
@@ -14,6 +14,7 @@
 #include "clang/Interpreter/Interpreter.h"
 
 #include "DeviceOffload.h"
+#include "ExternalSource.h"
 #include "IncrementalExecutor.h"
 #include "IncrementalParser.h"
 
@@ -33,6 +34,7 @@
 #include "clang/Driver/Tool.h"
 #include 

[PATCH] D154357: [Driver] Recognize powerpc-unknown-eabi as a bare-metal toolchain

2023-07-03 Thread Jon Roelofs via Phabricator via cfe-commits
jroelofs added a comment.

> It seems to me that maybe anything with OS none (although that doesn’t seem 
> to be distinguished from unknown)

I considered splitting `none` from `unknown` in Triple, but never had the time 
to do it. I think this would be good for baremetal toolchains in light of the 
gcc installation detection machinery taking over whenever there isn't otherwise 
a match.

> or with environment eabi should be treated as bare-metal, but I don’t have a 
> lot of experience in this regard.

IIRC there are `arm-linux-eabi` toolchains in the wild, which are not baremetal.




Comment at: clang/lib/Driver/ToolChains/BareMetal.cpp:168
+
+  if (Triple.getVendor() != llvm::Triple::UnknownVendor)
+return false;

does this break your use cases re: having `indel` as the vendor? or will you 
have a downstream patch to exempt `indel` from this check?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154357

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


[PATCH] D154378: [LinkerWrapper] Set the GPU LTO job to be freestanding

2023-07-03 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: JonChesterfield, jdoerfert, yaxunl, tianshilei1992.
Herald added a subscriber: inglorion.
Herald added a project: All.
jhuber6 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The LTO config allows us to set whether or not the build is
freestanding. This pretty much prevents emission of library calls and
should cause them to be treated like normal functions. This is in
relation to D154364 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154378

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


Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -570,6 +570,10 @@
   Conf.CGFileType =
   (Triple.isNVPTX() || SaveTemps) ? CGFT_AssemblyFile : CGFT_ObjectFile;
 
+  // We consider the GPU to be a freestanding target so we shouldn't emit any
+  // builtin library calls.
+  Conf.Freestanding = true;
+
   // TODO: Handle remark files
   Conf.HasWholeProgramVisibility = Args.hasArg(OPT_whole_program);
 


Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -570,6 +570,10 @@
   Conf.CGFileType =
   (Triple.isNVPTX() || SaveTemps) ? CGFT_AssemblyFile : CGFT_ObjectFile;
 
+  // We consider the GPU to be a freestanding target so we shouldn't emit any
+  // builtin library calls.
+  Conf.Freestanding = true;
+
   // TODO: Handle remark files
   Conf.HasWholeProgramVisibility = Args.hasArg(OPT_whole_program);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:11410
   } else {
-assert(C->getDependencyKind() == OMPC_DEPEND_sink);
+assert(ODK.isSink(C));
 RTLFn = OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),

ABataev wrote:
> Add a message, please
Added.  Thanks for the review.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.h:2279
+public:
+  bool isSink(const T *) { return false; }
+};

ABataev wrote:
> Add isSOurce 
Opps..  Sorry.  Added.  Thanks!!!  Jennifer



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5860-5862
+  bool IsDependSource = false;
+  if (ODK.isSource(C))
+IsDependSource = true;

ABataev wrote:
> bool IsDependSource = ODK.isSource(C);
Thanks.  Changed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

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


[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 updated this revision to Diff 536838.
jyu2 added a comment.

Thanks  Alexey for the review!!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/test/OpenMP/ordered_doacross_codegen.c

Index: clang/test/OpenMP/ordered_doacross_codegen.c
===
--- clang/test/OpenMP/ordered_doacross_codegen.c
+++ clang/test/OpenMP/ordered_doacross_codegen.c
@@ -2,13 +2,21 @@
 // RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-NORMAL
 
+// RUN: %clang_cc1 -verify -fopenmp -triple x86_64-unknown-unknown -emit-llvm %s -o - -fopenmp-version=52 | FileCheck %s --check-prefixes=CHECK,CHECK-NORMAL
 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -fopenmp-version=52 -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
 // RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
 
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
+
 // RUN: %clang_cc1 -verify -fopenmp-simd -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
+// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
 // RUN: %clang_cc1 -fopenmp-simd -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp-simd -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
+// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
 // SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
 // expected-no-diagnostics
 
@@ -51,7 +59,11 @@
 // CHECK-NORMAL-NEXT: call void @__kmpc_doacross_post(ptr [[IDENT]], i32 [[GTID]], ptr [[TMP]])
 // CHECK-IRBUILDER-NEXT: [[GTID1:%.+]] = call i32 @__kmpc_global_thread_num(ptr [[IDENT:@.+]])
 // CHECK-IRBUILDER-NEXT: call void @__kmpc_doacross_post(ptr [[IDENT]], i32 [[GTID1]], ptr [[TMP]])
+#if _OPENMP >= 202111
+#pragma omp ordered doacross(source:)
+#else
 #pragma omp ordered depend(source)
+#endif
 c[i] = c[i] + 1;
 foo();
 // CHECK: call void @foo()
@@ -66,7 +78,11 @@
 // CHECK-NORMAL-NEXT: call void @__kmpc_doacross_wait(ptr [[IDENT]], i32 [[GTID]], ptr [[TMP]])
 // CHECK-IRBUILDER-NEXT: [[GTID2:%.+]] = call i32 @__kmpc_global_thread_num(ptr [[IDENT:@.+]])
 // CHECK-IRBUILDER-NEXT: call void @__kmpc_doacross_wait(ptr [[IDENT]], i32 [[GTID2]], ptr [[TMP]])
+#if _OPENMP >= 202111
+#pragma omp ordered doacross(sink : i - 2)
+#else
 #pragma omp ordered depend(sink : i - 2)
+#endif
 d[i] = a[i - 2];
   }
   // CHECK: call void @__kmpc_for_static_fini(
Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -5839,37 +5839,46 @@
   return Fn;
 }
 
+template 
+static void emitRestoreIP(CodeGenFunction , const T *C,
+  llvm::OpenMPIRBuilder::InsertPointTy AllocaIP,
+  llvm::OpenMPIRBuilder ) {
+
+  unsigned NumLoops = C->getNumLoops();
+  QualType Int64Ty = CGF.CGM.getContext().getIntTypeForBitwidth(
+  /*DestWidth=*/64, /*Signed=*/1);
+  llvm::SmallVector StoreValues;
+  for (unsigned I = 0; I < NumLoops; I++) {
+const Expr *CounterVal = C->getLoopData(I);
+assert(CounterVal);
+llvm::Value *StoreValue = CGF.EmitScalarConversion(
+CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
+CounterVal->getExprLoc());
+StoreValues.emplace_back(StoreValue);
+  }
+  OMPDoacrossKind ODK;
+  bool IsDependSource = ODK.isSource(C);
+  CGF.Builder.restoreIP(
+  OMPBuilder.createOrderedDepend(CGF.Builder, AllocaIP, NumLoops,
+ 

[PATCH] D154368: [Clang] Fix constraint checking of non-generic lambdas.

2023-07-03 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin created this revision.
Herald added a project: All.
cor3ntin requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

A lambda call operator can be a templated entity -
and therefore have constraints while not being a function template

  template void f() {
[]() requires false { }();
  }

In that case, we would check the constraints of the call operator
which is non-viable. However, we would find a viable candidate:
the conversion operator to function pointer, and use it to
perform a surrogate call.
These constraints were not checked because:

- We never check the constraints of surrogate functions
- The lambda conversion operator has non constraints.

>From the wording, it is not clear what the intent is but
it seems reasonable to expect the constraints of the lambda conversion
operator to be checked and it is consistent with GCC and MSVC.

This patch also improve the diagnostics for constraint failure
on surrogate calls.

Fixes #63181


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154368

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/SemaTemplate/concepts.cpp

Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -410,8 +410,8 @@
 
 template 
 void SingleDepthReferencesTopLambda(U &) {
-  []()
-requires IsInt
+  []() // #SDRTL_OP
+requires IsInt // #SDRTL_REQ
   {}();
 }
 
@@ -434,8 +434,8 @@
 
 template 
 void DoubleDepthReferencesTopLambda(U &) {
-  []() { []()
-   requires IsInt
+  []() { []() // #DDRTL_OP
+   requires IsInt // #DDRTL_REQ
  {}(); }();
 }
 
@@ -459,10 +459,11 @@
 
 template 
 void DoubleDepthReferencesAllLambda(U &) {
-  [](U &) {
-[](U && u3)
-  requires IsInt &&
-   IsInt && IsInt
+  [](U &) { // #DDRAL_OP1
+[](U && u3) // #DDRAL_OP2
+  requires IsInt // #DDRAL_REQ
+&& IsInt
+&& IsInt
 {}(u2);
   }(u);
 }
@@ -484,8 +485,8 @@
 template 
 void ChecksLocalVar(T x) {
   T Local;
-  []()
-requires(IsInt)
+  []() // #CLV_OP
+requires(IsInt) // #CLV_REQ
   {}();
 }
 
@@ -529,6 +530,11 @@
   SingleDepthReferencesTopLambda(v);
   // FIXME: This should error on constraint failure! (Lambda!)
   SingleDepthReferencesTopLambda(will_fail);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  // expected-error@#SDRTL_OP{{no matching function for call to object of type}}
+  // expected-note@#SDRTL_OP{{candidate function not viable: constraints not satisfied}}
+  // expected-note@#SDRTL_REQ{{because 'IsInt' evaluated to false}}
+
   DoubleDepthReferencesTop(v);
   DoubleDepthReferencesTop(will_fail);
   // expected-error@#DDRT_CALL{{no matching function for call to object of type 'lc2'}}
@@ -538,8 +544,12 @@
   // expected-note@#DDRT_REQ{{'IsInt' evaluated to false}}
 
   DoubleDepthReferencesTopLambda(v);
-  // FIXME: This should error on constraint failure! (Lambda!)
   DoubleDepthReferencesTopLambda(will_fail);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  // expected-error@#DDRTL_OP{{no matching function for call to object of type}}
+  // expected-note@#DDRTL_OP{{candidate function not viable: constraints not satisfied}}
+  // expected-note@#DDRTL_OP{{while substituting into a lambda expression here}}
+  // expected-note@#DDRTL_REQ{{because 'IsInt' evaluated to false}}
   DoubleDepthReferencesAll(v);
   DoubleDepthReferencesAll(will_fail);
   // expected-error@#DDRA_CALL{{no matching function for call to object of type 'lc2'}}
@@ -549,8 +559,12 @@
   // expected-note@#DDRA_REQ{{'IsInt' evaluated to false}}
 
   DoubleDepthReferencesAllLambda(v);
-  // FIXME: This should error on constraint failure! (Lambda!)
   DoubleDepthReferencesAllLambda(will_fail);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  // expected-note@#DDRAL_OP1{{while substituting into a lambda expression here}}
+  // expected-error@#DDRAL_OP2{{no matching function for call to object of type}}
+  // expected-note@#DDRAL_OP2{{candidate function not viable: constraints not satisfied}}
+  // expected-note@#DDRAL_REQ{{because 'IsInt' evaluated to false}}
 
   CausesFriendConstraint CFC;
   FriendFunc(CFC, 1);
@@ -565,6 +579,12 @@
   ChecksLocalVar(v);
   // FIXME: This should error on constraint failure! (Lambda!)
   ChecksLocalVar(will_fail);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  // expected-error@#CLV_OP{{no matching function for call to object of type}}
+  // expected-note@#CLV_OP{{candidate function not viable: constraints not satisfied}}
+  // expected-note@#CLV_REQ{{because 'IsInt' evaluated to false}}
+
+
 
   LocalStructMemberVar(v);
   

[PATCH] D154366: [clang][ExprConstant] Print template arguments when describing stack frame

2023-07-03 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet created this revision.
hazohelet added reviewers: aaron.ballman, tbaeder, cjdb, shafik.
Herald added a project: All.
hazohelet requested review of this revision.
Herald added a project: clang.

This patch adds additional printing of template argument list when the 
described function is a template specialization.
This can be useful when handling complex template functions in constexpr 
evaluator.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154366

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/AST/ExprConstant.cpp
  clang/test/AST/Interp/literals.cpp
  clang/test/SemaCXX/builtin-align-cxx.cpp
  clang/test/SemaCXX/constant-expression-cxx11.cpp
  clang/test/SemaCXX/constant-expression-cxx14.cpp
  clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
  clang/test/SemaCXX/cxx2b-consteval-propagate.cpp

Index: clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
===
--- clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
+++ clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
@@ -45,7 +45,7 @@
 }
 
 int i = hh(); // expected-error {{call to immediate function 'examples::hh' is not a constant expression}} \
-   // expected-note {{in call to 'hh()'}}
+   // expected-note {{in call to 'hh()'}}
 
 struct A {
   int x;
Index: clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
===
--- clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
+++ clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
@@ -117,11 +117,11 @@
 
   constexpr pad pir{4, 4};
   // expected-error@+2 {{constexpr variable 'piw' must be initialized by a constant expression}}
-  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
+  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
   constexpr int piw = bit_cast(pir).x;
 
   // expected-error@+2 {{constexpr variable 'bad' must be initialized by a constant expression}}
-  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
+  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
   constexpr no_pad bad = bit_cast(pir);
 
   constexpr pad fine = bit_cast(no_pad{1, 2, 3, 4, 5});
Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -1038,7 +1038,7 @@
 void foo() __attribute__((enable_if(sum(Cs) == 'a' + 'b', "")));
 void run() { foo(); }
 
-static_assert(sum(Cs) == 'a' + 'b', ""); // expected-error{{not an integral constant expression}} expected-note{{in call to 'sum(Cs)'}}
+static_assert(sum(Cs) == 'a' + 'b', ""); // expected-error{{not an integral constant expression}} expected-note{{in call to 'sum<2>(Cs)'}}
 constexpr int S = sum(Cs); // expected-error{{must be initialized by a constant expression}} expected-note{{in call}}
 }
 
Index: clang/test/SemaCXX/constant-expression-cxx11.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -1781,7 +1781,7 @@
   static_assert(get(arr, 1) == 1, "");
   static_assert(get(arr, 4) == 4, "");
   static_assert(get(arr, 0) == 4, ""); // expected-error{{not an integral constant expression}} \
-  // expected-note{{in call to 'get(arr, 0)'}}
+  // expected-note{{in call to 'get(arr, 0)'}}
 }
 
 namespace std { struct type_info; }
Index: clang/test/SemaCXX/builtin-align-cxx.cpp
===
--- clang/test/SemaCXX/builtin-align-cxx.cpp
+++ clang/test/SemaCXX/builtin-align-cxx.cpp
@@ -137,26 +137,26 @@
 constexpr long const_value(long l) { return l; }
 // Check some invalid values during constant-evaluation
 static_assert(wrap_align_down(1, const_value(-1)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_align_down(1, -1)'}}
+// expected-note@-1{{in call to 'wrap_align_down(1, -1)'}}
 static_assert(wrap_align_up(1, const_value(-2)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_align_up(1, -2)'}}
+// expected-note@-1{{in call to 'wrap_align_up(1, -2)'}}
 static_assert(wrap_is_aligned(1, const_value(-3)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_is_aligned(1, -3)'}}
+// expected-note@-1{{in call to 'wrap_is_aligned(1, -3)'}}
 static_assert(wrap_align_down(1, const_value(17)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_align_down(1, 17)'}}
+// expected-note@-1{{in call to 'wrap_align_down(1, 17)'}}
 static_assert(wrap_align_up(1, const_value(18)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_align_up(1, 18)'}}
+// expected-note@-1{{in call to 'wrap_align_up(1, 18)'}}
 

[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:11410
   } else {
-assert(C->getDependencyKind() == OMPC_DEPEND_sink);
+assert(ODK.isSink(C));
 RTLFn = OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),

Add a message, please



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.h:2279
+public:
+  bool isSink(const T *) { return false; }
+};

Add isSOurce 



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5860-5862
+  bool IsDependSource = false;
+  if (ODK.isSource(C))
+IsDependSource = true;

bool IsDependSource = ODK.isSource(C);


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

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


[PATCH] D135849: [llvm] Return canonical virtual path from `RedirectingFileSystem`

2023-07-03 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir added a comment.

> You mean diagnosing whenever the spelling in the VFS definition differs from 
> its realpath?

Right, this would be ideal, but may be too expensive in practice.

> How could we make that work with symlinks in place?

Ah right, we are intentionally allowing symlinks in the VFS path (e.g. 
Foo.framework/Headers) because we don't correctly handle symlink resolution in 
the VFS itself.

You can get the canonical spelling of a symlink in a couple of ways: you can 
readdir the parent directory and find all case-insensitive matches.  If there 
is only 1, that's the spelling, if there are more than 1  then it's a 
case-sensitive filesystem and the original path must be correct.  Another way 
that is OS-specific is on Darwin you can `open(..., O_SYMLINK)` the path 
component to open the symlink itself and then `fcntl(..., F_GETPATH, ...)` to 
get its realpath.  Both of these approaches require handling each component of 
the path individually, though each step is cacheable.  Not sure if there are 
any better ways.

As I said, not sure we can afford to diagnose this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135849

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


[PATCH] D154297: clang-tidy: accessing checks not done for aliases of `std::array`

2023-07-03 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGce2d44b0ab6d: [clang-tidy] Accessing checks not done for 
aliases of `std::array` (authored by sousajo, committed by PiotrZSL).

Changed prior to commit:
  https://reviews.llvm.org/D154297?vs=536622=536805#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154297

Files:
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
@@ -44,6 +44,28 @@
   a[1] = 3; // OK, constant index and inside bounds
   a[9] = 3; // OK, constant index and inside bounds
   a[const_index(6)] = 3; // OK, constant index and inside bounds
+
+  using MyArray = std::array;
+  MyArray m{};
+  m [ pos / 2 /*comment*/] = 1;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not use array subscript when 
the index is not an integer constant expression 
[cppcoreguidelines-pro-bounds-constant-array-index]
+  int jj = m[pos - 1];
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not use array subscript when 
the index is not an integer constant expression
+
+  m.at(pos-1) = 2; // OK, at() instead of []
+  gsl::at(m, pos-1) = 2; // OK, gsl::at() instead of []
+  m[-1] = 3;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index -1 is 
negative [cppcoreguidelines-pro-bounds-constant-array-index]
+  m[10] = 4;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index 10 is past 
the end of the array (which contains 10 elements) 
[cppcoreguidelines-pro-bounds-constant-array-index]
+
+  m[const_index(7)] = 3;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index 10 is past 
the end of the array (which contains 10 elements)
+
+  m[0] = 3; // OK, constant index and inside bounds
+  m[1] = 3; // OK, constant index and inside bounds
+  m[9] = 3; // OK, constant index and inside bounds
+  m[const_index(6)] = 3; // OK, constant index and inside bounds
 }
 
 void g() {
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -321,6 +321,10 @@
   :doc:`cppcoreguidelines-use-default-member-init
   ` instead.
 
+- Improved :doc:`cppcoreguidelines-pro-bounds-constant-array-index
+  ` check
+  to cover type aliases of ``std::array``.
+
 - Fixed a false positive in :doc:`cppcoreguidelines-slicing
   ` check when warning would be
   emitted in constructor for virtual base class initialization.
Index: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
===
--- 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
+++ 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
@@ -49,7 +49,8 @@
   cxxOperatorCallExpr(
   hasOverloadedOperatorName("[]"),
   hasArgument(
-  0, hasType(cxxRecordDecl(hasName("::std::array")).bind("type"))),
+  0, hasType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(
+ cxxRecordDecl(hasName("::std::array")).bind("type")),
   hasArgument(1, expr().bind("index")))
   .bind("expr"),
   this);


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
@@ -44,6 +44,28 @@
   a[1] = 3; // OK, constant index and inside bounds
   a[9] = 3; // OK, constant index and inside bounds
   a[const_index(6)] = 3; // OK, constant index and inside bounds
+
+  using MyArray = std::array;
+  MyArray m{};
+  m [ pos / 2 /*comment*/] = 1;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not use array subscript when the index is not an integer constant expression [cppcoreguidelines-pro-bounds-constant-array-index]
+  int jj = m[pos - 1];
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not use array subscript when the index is not an integer constant expression
+
+  m.at(pos-1) = 2; // OK, at() instead of []
+  gsl::at(m, pos-1) = 2; // OK, gsl::at() instead of []
+  m[-1] = 3;
+  // CHECK-MESSAGES: 

[clang-tools-extra] ce2d44b - [clang-tidy] Accessing checks not done for aliases of `std::array`

2023-07-03 Thread Piotr Zegar via cfe-commits

Author: Jorge Pinto Sousa
Date: 2023-07-03T16:43:08Z
New Revision: ce2d44b0ab6da147931e9711e01d44a672ec3854

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

LOG: [clang-tidy] Accessing checks not done for aliases of `std::array`

Index accessing checks are not performed for aliases
of `std::array`, as only `std::array` itself seems to be checked.

This patch aims to extend it for aliases such as:
 `using MyArray = std::array;`

Reviewed By: PiotrZSL

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

Added: 


Modified: 

clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
index da7e6a32167901..fbc3cd314ee53a 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
@@ -49,7 +49,8 @@ void 
ProBoundsConstantArrayIndexCheck::registerMatchers(MatchFinder *Finder) {
   cxxOperatorCallExpr(
   hasOverloadedOperatorName("[]"),
   hasArgument(
-  0, hasType(cxxRecordDecl(hasName("::std::array")).bind("type"))),
+  0, hasType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(
+ cxxRecordDecl(hasName("::std::array")).bind("type")),
   hasArgument(1, expr().bind("index")))
   .bind("expr"),
   this);

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 84333f6cb347bf..7c6efe60a013ae 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -321,6 +321,10 @@ Changes in existing checks
   :doc:`cppcoreguidelines-use-default-member-init
   ` instead.
 
+- Improved :doc:`cppcoreguidelines-pro-bounds-constant-array-index
+  ` check
+  to cover type aliases of ``std::array``.
+
 - Fixed a false positive in :doc:`cppcoreguidelines-slicing
   ` check when warning would be
   emitted in constructor for virtual base class initialization.

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
index 91c7fc1e3db597..e689677578f8d0 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
@@ -44,6 +44,28 @@ void f(std::array a, int pos) {
   a[1] = 3; // OK, constant index and inside bounds
   a[9] = 3; // OK, constant index and inside bounds
   a[const_index(6)] = 3; // OK, constant index and inside bounds
+
+  using MyArray = std::array;
+  MyArray m{};
+  m [ pos / 2 /*comment*/] = 1;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not use array subscript when 
the index is not an integer constant expression 
[cppcoreguidelines-pro-bounds-constant-array-index]
+  int jj = m[pos - 1];
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not use array subscript when 
the index is not an integer constant expression
+
+  m.at(pos-1) = 2; // OK, at() instead of []
+  gsl::at(m, pos-1) = 2; // OK, gsl::at() instead of []
+  m[-1] = 3;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index -1 is 
negative [cppcoreguidelines-pro-bounds-constant-array-index]
+  m[10] = 4;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index 10 is past 
the end of the array (which contains 10 elements) 
[cppcoreguidelines-pro-bounds-constant-array-index]
+
+  m[const_index(7)] = 3;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index 10 is past 
the end of the array (which contains 10 elements)
+
+  m[0] = 3; // OK, constant index and inside bounds
+  m[1] = 3; // OK, constant index and inside bounds
+  m[9] = 3; // OK, constant index and inside bounds
+  m[const_index(6)] = 3; // OK, constant index and inside bounds
 }
 
 void g() {



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


[PATCH] D154283: [clang-tidy] Fix width/precision argument order in modernize-use-std-print

2023-07-03 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2806cf4b5430: [clang-tidy] Fix width/precision argument 
order in modernize-use-std-print (authored by mikecrowe, committed by PiotrZSL).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154283

Files:
  clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
  clang-tools-extra/clang-tidy/utils/FormatStringConverter.h
  clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
@@ -1024,7 +1024,7 @@
 
   printf("Right-justified integer with field width argument %*d after\n", 5, 424242);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
-  // CHECK-FIXES: std::println("Right-justified integer with field width argument {:{}} after", 5, 424242);
+  // CHECK-FIXES: std::println("Right-justified integer with field width argument {:{}} after", 424242, 5);
 
   printf("Right-justified integer with field width argument %2$*1$d after\n", 5, 424242);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
@@ -1061,7 +1061,7 @@
 
   printf("Left-justified integer with field width argument %-*d after\n", 5, 424242);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
-  // CHECK-FIXES: std::println("Left-justified integer with field width argument {:<{}} after", 5, 424242);
+  // CHECK-FIXES: std::println("Left-justified integer with field width argument {:<{}} after", 424242, 5);
 
   printf("Left-justified integer with field width argument %2$-*1$d after\n", 5, 424242);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
@@ -1087,15 +1087,15 @@
 
   printf("Hello %.*f after\n", 10, 3.14159265358979323846);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
-  // CHECK-FIXES: std::println("Hello {:.{}f} after", 10, 3.14159265358979323846);
+  // CHECK-FIXES: std::println("Hello {:.{}f} after", 3.14159265358979323846, 10);
 
   printf("Hello %10.*f after\n", 3, 3.14159265358979323846);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
-  // CHECK-FIXES: std::println("Hello {:10.{}f} after", 3, 3.14159265358979323846);
+  // CHECK-FIXES: std::println("Hello {:10.{}f} after", 3.14159265358979323846, 3);
 
   printf("Hello %*.*f after\n", 10, 4, 3.14159265358979323846);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
-  // CHECK-FIXES: std::println("Hello {:{}.{}f} after", 10, 4, 3.14159265358979323846);
+  // CHECK-FIXES: std::println("Hello {:{}.{}f} after", 3.14159265358979323846, 10, 4);
 
   printf("Hello %1$.*2$f after\n", 3.14159265358979323846, 4);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
@@ -1112,9 +1112,33 @@
 }
 
 void printf_field_width_and_precision() {
-  printf("Hello %1$*2$.*3$f after\n", 3.14159265358979323846, 4, 2);
+  printf("width only:%*d width and precision:%*.*f precision only:%.*f\n", 3, 42, 4, 2, 3.14159265358979323846, 5, 2.718);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
-  // CHECK-FIXES: std::println("Hello {0:{1}.{2}f} after", 3.14159265358979323846, 4, 2);
+  // CHECK-FIXES: std::println("width only:{:{}} width and precision:{:{}.{}f} precision only:{:.{}f}", 42, 3, 3.14159265358979323846, 4, 2, 2.718, 5);
+
+  printf("width and precision positional:%1$*2$.*3$f after\n", 3.14159265358979323846, 4, 2);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+  // CHECK-FIXES: std::println("width and precision positional:{0:{1}.{2}f} after", 3.14159265358979323846, 4, 2);
+
+  const int width = 10, precision = 3;
+  printf("width only:%3$*1$d width and precision:%4$*1$.*2$f precision only:%5$.*2$f\n", width, precision, 42, 3.1415926, 2.718);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+  // CHECK-FIXES: std::println("width only:{2:{0}} width and precision:{3:{0}.{1}f} precision only:{4:.{1}f}", width, precision, 42, 3.1415926, 2.718);
+}
+
+void fprintf_field_width_and_precision() {
+  fprintf(stderr, "width only:%*d width and precision:%*.*f precision only:%.*f\n", 3, 42, 4, 2, 3.14159265358979323846, 5, 2.718);
+  // CHECK-MESSAGES: 

[clang-tools-extra] 2806cf4 - [clang-tidy] Fix width/precision argument order in modernize-use-std-print

2023-07-03 Thread Piotr Zegar via cfe-commits

Author: Mike Crowe
Date: 2023-07-03T16:39:04Z
New Revision: 2806cf4b5430ad6d4d5aa2d501aea1de67272876

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

LOG: [clang-tidy] Fix width/precision argument order in modernize-use-std-print

Victor Zverovich pointed out[1] that printf takes the field width and
precision arguments before the value to be printed whereas std::print
takes the value first (unless positional arguments are used.) Many of
the test cases in use-std-print.cpp were incorrect.

Teach the check to rotate the arguments when required to correct
this. Correct the test cases and add more.

[1] https://github.com/fmtlib/fmt/pull/3515#issuecomment-1615259893

Reviewed By: PiotrZSL

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
clang-tools-extra/clang-tidy/utils/FormatStringConverter.h
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp 
b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
index f12fa84ec6b141..3e6442c5fd63c1 100644
--- a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
+++ b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
@@ -340,6 +340,22 @@ void FormatStringConverter::emitPrecision(const 
PrintfSpecifier ,
   }
 }
 
+void FormatStringConverter::maybeRotateArguments(const PrintfSpecifier ) {
+  unsigned ArgCount = 0;
+  const OptionalAmount FieldWidth = FS.getFieldWidth();
+  const OptionalAmount FieldPrecision = FS.getPrecision();
+
+  if (FieldWidth.getHowSpecified() == OptionalAmount::Arg &&
+  !FieldWidth.usesPositionalArg())
+++ArgCount;
+  if (FieldPrecision.getHowSpecified() == OptionalAmount::Arg &&
+  !FieldPrecision.usesPositionalArg())
+++ArgCount;
+
+  if (ArgCount)
+ArgRotates.emplace_back(FS.getArgIndex() + ArgsOffset, ArgCount);
+}
+
 void FormatStringConverter::emitStringArgument(const Expr *Arg) {
   // If the argument is the result of a call to std::string::c_str() or
   // data() with a return type of char then we can remove that call and
@@ -531,6 +547,7 @@ bool FormatStringConverter::convertArgument(const 
PrintfSpecifier ,
 
   emitFieldWidth(FS, FormatSpec);
   emitPrecision(FS, FormatSpec);
+  maybeRotateArguments(FS);
 
   if (!emitType(FS, Arg, FormatSpec))
 return false;
@@ -682,5 +699,22 @@ void FormatStringConverter::applyFixes(DiagnosticBuilder 
,
 if (!ArgText.empty())
   Diag << FixItHint::CreateReplacement(Call->getSourceRange(), ArgText);
   }
+
+  // ArgCount is one less than the number of arguments to be rotated.
+  for (auto [ValueArgIndex, ArgCount] : ArgRotates) {
+assert(ValueArgIndex < NumArgs);
+assert(ValueArgIndex > ArgCount);
+
+// First move the value argument to the right place.
+Diag << tooling::fixit::createReplacement(*Args[ValueArgIndex - ArgCount],
+  *Args[ValueArgIndex], *Context);
+
+// Now shift down the field width and precision (if either are present) to
+// accommodate it.
+for (size_t Offset = 0; Offset < ArgCount; ++Offset)
+  Diag << tooling::fixit::createReplacement(
+  *Args[ValueArgIndex - Offset], *Args[ValueArgIndex - Offset - 1],
+  *Context);
+  }
 }
 } // namespace clang::tidy::utils

diff  --git a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.h 
b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.h
index b246013c24c457..200e530b40810b 100644
--- a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.h
+++ b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.h
@@ -67,6 +67,11 @@ class FormatStringConverter
   std::vector> ArgFixes;
   std::vector ArgCStrRemovals;
 
+  // Argument rotations to cope with the fact that std::print puts the value to
+  // be formatted first and the width and precision afterwards whereas printf
+  // puts the width and preicision first.
+  std::vector> ArgRotates;
+
   void emitAlignment(const PrintfSpecifier , std::string );
   void emitSign(const PrintfSpecifier , std::string );
   void emitAlternativeForm(const PrintfSpecifier , std::string );
@@ -81,6 +86,8 @@ class FormatStringConverter
   bool convertArgument(const PrintfSpecifier , const Expr *Arg,
std::string );
 
+  void maybeRotateArguments(const PrintfSpecifier );
+
   bool HandlePrintfSpecifier(const PrintfSpecifier ,
  const char *StartSpecifier, unsigned SpecifierLen,
  const TargetInfo ) override;

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp 

[PATCH] D154283: [clang-tidy] Fix width/precision argument order in modernize-use-std-print

2023-07-03 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added inline comments.



Comment at: clang-tools-extra/clang-tidy/utils/FormatStringConverter.h:73
+  // puts the width and preicision first.
+  std::vector> ArgRotates;
+

mikecrowe wrote:
> PiotrZSL wrote:
> > mikecrowe wrote:
> > > PiotrZSL wrote:
> > > > NOTE: You can use std::pair here.
> > > True, but in my mind `std::pair` only exists because `std::tuple` 
> > > couldn't be implemented in the C++98.
> > > 
> > > I was going to change it to use `std::pair` anyway, but I notice that I 
> > > already use `std::tuple` for `ArgFixes` just above. Should I change both 
> > > of them?
> > It will be compiled to same thing anyway. So it's up to you. Keep it 
> > consistent.
> > I personally use std::pair for 2 arguments, and std::tuple for more than 2.
> > But to be honest probably better would be to introduce some structure so 
> > that those two `unsigned` could be named. And probably same for ArgFixes, 
> > but there we got different types, so it's not a big problem.
> I think that you're probably right, but the names won't be used from the call 
> site since I use structured binding there. Do you mind if I do both together 
> in a separate commit?
Not a problem, lets leave it for a next change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154283

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


[PATCH] D153296: [AST] Stop evaluate constant expression if the condition expression which in switch statement contains errors

2023-07-03 Thread Yurong via Phabricator via cfe-commits
yronglin updated this revision to Diff 536802.
yronglin added a comment.

Address comment.

- Change `EvaluateDependentExpr`.
- Add more test for do/while/for/return/ctor.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153296

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaCXX/constexpr-function-recovery-crash.cpp

Index: clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
===
--- clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
+++ clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
@@ -78,6 +78,132 @@
 constexpr int test12() { return "wrong"; } // expected-error {{cannot initialize return object of type 'int'}}
 constexpr int force12 = test12();  // expected-error {{must be initialized by a constant}}
 
+constexpr int test13() {
+switch (invalid_value) { // expected-error {{use of undeclared identifier}}
+case 0:
+return 7;
+default:
+break;
+}
+return 0;
+}
+
+static_assert(test13(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test14() {
+int sum = 0;
+for (int i = 0; i < invalid_value; ++i) // expected-error {{use of undeclared identifier}}
+sum = sum + i;
+return sum;
+}
+
+static_assert(test14(), "should not crash"); // expected-error {{static assertion failed due to requirement}}
+
+constexpr int test15() {
+int sum = 0;
+for (int i = 0; i < 10; i += invalid_value) // expected-error {{use of undeclared identifier}}
+sum = sum + i;
+return sum;
+}
+
+static_assert(test15(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test16() {
+int sum = 0;
+for (int i = invalid_value; i < 10; ++i) // expected-error {{use of undeclared identifier}}
+sum = sum + i;
+return sum;
+}
+
+static_assert(test16(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test17() {
+int sum = 0, i = 0;
+do
+  sum += i;
+while (invalid_value); // expected-error {{use of undeclared identifier}}
+return sum;
+}
+
+static_assert(test17(), "should not crash"); // expected-error {{static assertion failed due to requirement}}
+
+constexpr int test18() {
+  int sum = 0, i = 0;
+  while (invalid_value) // expected-error {{use of undeclared identifier}}
+sum += i;
+  return sum;
+}
+
+static_assert(test18(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test19() {
+struct Test19 {
+int a[2] = {0, 1};
+constexpr const int *begin() const {
+return invalid_value;  // expected-error {{use of undeclared identifier}}
+}
+constexpr const int *end() const {
+return a + 2;
+}
+};
+
+int sum = 0;
+Test19 t;
+for (const auto v : t) {
+sum += v;
+}
+return sum;
+}
+
+static_assert(test19(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test20() {
+struct Test20 {
+int a[2] = {0, 1};
+constexpr const int *begin() const {
+return a;
+}
+constexpr const int *end() const {
+return invalid_value;  // expected-error {{use of undeclared identifier}}
+}
+};
+
+int sum = 0;
+Test20 t;
+for (const auto v : t) {
+sum += v;
+}
+return sum;
+}
+
+static_assert(test20(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test21() {
+  return invalid_value; // expected-error {{use of undeclared identifier}}
+}
+
+static_assert(test21(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test22() {
+  struct Test22 {
+int value = invalid_value; // expected-error {{use of undeclared identifier}}
+  };
+  return Test22().value;
+}
+
+static_assert(test22(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test23() {
+  struct Test23 {
+int value;
+constexpr Test23(int v) : value(v) {}
+constexpr Test23(int a, int b) : Test23(a * b * invalid_value) {} // expected-error {{use of undeclared identifier}}
+  };
+  return Test23(1, 2).value;
+}
+
+static_assert(test23(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
 #define TEST_EVALUATE(Name, X) \
   constexpr int testEvaluate##Name() { \
 X return 0;\
Index: 

[PATCH] D153600: Implement -frecord-command-line for XCOFF

2023-07-03 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan marked an inline comment as done.
Jake-Egan added inline comments.



Comment at: llvm/lib/MC/MCAsmStreamer.cpp:986
+
+  // If there's no metadata, the length is 0.
+  if (MetadataSize == 0) {

Handled the 0 length case here.


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

https://reviews.llvm.org/D153600

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


[PATCH] D153600: Implement -frecord-command-line for XCOFF

2023-07-03 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan marked 6 inline comments as done.
Jake-Egan added inline comments.



Comment at: llvm/lib/MC/MCAsmStreamer.cpp:1022
+  if (PaddingSize) {
+assert(PaddedSize - Index == WordSize);
+std::array LastWord = {0};

I changed the assert that you requested because it would always fail:

```
assert(Length - Index == MetadataPaddingSize);
```




Comment at: llvm/lib/MC/MCAsmStreamer.cpp:980
+  size_t MetadataSize = Metadata.size();
+  uint32_t MetadataPaddingSize = 3 - (MetadataSize - 1) % 4;
+

scott.linder wrote:
> scott.linder wrote:
> > I couldn't quickly find a reference for the alignment requirement, but it 
> > seems like there is an additional requirement that the length must also be 
> > non-zero, not just even?
> > 
> > If so, can you update the comment?
> > 
> > I would also rather explicitly use `alignTo` and `max` to express this (see 
> > suggestion), but if we don't expect the optimizer to clean it up I'm fine 
> > with the more terse version.
> Can you factor this out at function scope? It gets repeated below
The length can be zero. See second paragraph of the comment section: 
https://www.ibm.com/docs/en/aix/7.2?topic=formats-xcoff-object-file-format#XCOFF__a1pyfk2b4joyc__title__1


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

https://reviews.llvm.org/D153600

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


[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:11405-11406
+  llvm::OpenMPIRBuilder  = CGM.getOpenMPRuntime().getOMPBuilder();
+  const OMPDependClause *DepC = dyn_cast(C);
+  const OMPDoacrossClause *DoC = dyn_cast(C);
+  if ((DoC && DoC->getDependenceType() == OMPC_DOACROSS_source) ||

ABataev wrote:
> 1. const auto *
> 2. Can you try torework it to make it more C++-ish? Use template deduction to 
> avoid runtime dyn_casts.
> e.g. something like:
> ```
> namespace {
> template 
> class OMPDoacrossKind {
> public:
> bool isSink(const T *) {return false;}
> }
> }
> template <>
> class OMPDoacrossKInd {
> public:
> bool isSink(const OMPDependClause* C) {return C->getDependenceType();}
> }
> ...
> ```
> and use `if (OMPDoacrossKInd::isSink(C)) RTLFn = ...` and same for `Source`
Good idea!!!  Thank you so much.  Changed.



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5859-5868
+  const auto DOC = dyn_cast(C);
+  const auto DC = dyn_cast(C);
+  bool IsDependSource = false;
+  if ((DC && DC->getDependencyKind() == OMPC_DEPEND_source) ||
+  (DOC && DOC->getDependenceType() == OMPC_DOACROSS_source))
+IsDependSource = true;
+  CGF.Builder.restoreIP(

ABataev wrote:
> Same, use template-based analysis instead of runtime-based.
Thanks.  Changed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

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


[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 updated this revision to Diff 536798.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/test/OpenMP/ordered_doacross_codegen.c

Index: clang/test/OpenMP/ordered_doacross_codegen.c
===
--- clang/test/OpenMP/ordered_doacross_codegen.c
+++ clang/test/OpenMP/ordered_doacross_codegen.c
@@ -2,13 +2,21 @@
 // RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-NORMAL
 
+// RUN: %clang_cc1 -verify -fopenmp -triple x86_64-unknown-unknown -emit-llvm %s -o - -fopenmp-version=52 | FileCheck %s --check-prefixes=CHECK,CHECK-NORMAL
 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -fopenmp-version=52 -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
 // RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
 
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
+
 // RUN: %clang_cc1 -verify -fopenmp-simd -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
+// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
 // RUN: %clang_cc1 -fopenmp-simd -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp-simd -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
+// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
 // SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
 // expected-no-diagnostics
 
@@ -51,7 +59,11 @@
 // CHECK-NORMAL-NEXT: call void @__kmpc_doacross_post(ptr [[IDENT]], i32 [[GTID]], ptr [[TMP]])
 // CHECK-IRBUILDER-NEXT: [[GTID1:%.+]] = call i32 @__kmpc_global_thread_num(ptr [[IDENT:@.+]])
 // CHECK-IRBUILDER-NEXT: call void @__kmpc_doacross_post(ptr [[IDENT]], i32 [[GTID1]], ptr [[TMP]])
+#if _OPENMP >= 202111
+#pragma omp ordered doacross(source:)
+#else
 #pragma omp ordered depend(source)
+#endif
 c[i] = c[i] + 1;
 foo();
 // CHECK: call void @foo()
@@ -66,7 +78,11 @@
 // CHECK-NORMAL-NEXT: call void @__kmpc_doacross_wait(ptr [[IDENT]], i32 [[GTID]], ptr [[TMP]])
 // CHECK-IRBUILDER-NEXT: [[GTID2:%.+]] = call i32 @__kmpc_global_thread_num(ptr [[IDENT:@.+]])
 // CHECK-IRBUILDER-NEXT: call void @__kmpc_doacross_wait(ptr [[IDENT]], i32 [[GTID2]], ptr [[TMP]])
+#if _OPENMP >= 202111
+#pragma omp ordered doacross(sink : i - 2)
+#else
 #pragma omp ordered depend(sink : i - 2)
+#endif
 d[i] = a[i - 2];
   }
   // CHECK: call void @__kmpc_for_static_fini(
Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -5839,37 +5839,48 @@
   return Fn;
 }
 
+template 
+static void emitRestoreIP(CodeGenFunction , const T *C,
+  llvm::OpenMPIRBuilder::InsertPointTy AllocaIP,
+  llvm::OpenMPIRBuilder ) {
+
+  unsigned NumLoops = C->getNumLoops();
+  QualType Int64Ty = CGF.CGM.getContext().getIntTypeForBitwidth(
+  /*DestWidth=*/64, /*Signed=*/1);
+  llvm::SmallVector StoreValues;
+  for (unsigned I = 0; I < NumLoops; I++) {
+const Expr *CounterVal = C->getLoopData(I);
+assert(CounterVal);
+llvm::Value *StoreValue = CGF.EmitScalarConversion(
+CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
+CounterVal->getExprLoc());
+StoreValues.emplace_back(StoreValue);
+  }
+  OMPDoacrossKind ODK;
+  bool IsDependSource = false;
+  if (ODK.isSource(C))
+IsDependSource = true;
+  CGF.Builder.restoreIP(
+  OMPBuilder.createOrderedDepend(CGF.Builder, AllocaIP, NumLoops,
+   

[PATCH] D153600: Implement -frecord-command-line for XCOFF

2023-07-03 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan updated this revision to Diff 536795.
Jake-Egan added a comment.

Thanks for the review @scott.linder. I applied the changes you requested with 
some differences.


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

https://reviews.llvm.org/D153600

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  llvm/include/llvm/CodeGen/AsmPrinter.h
  llvm/include/llvm/MC/MCStreamer.h
  llvm/include/llvm/MC/MCXCOFFStreamer.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/MC/MCAsmStreamer.cpp
  llvm/lib/MC/MCStreamer.cpp
  llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
  llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll

Index: llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll
@@ -0,0 +1,22 @@
+; RUN: llc -mtriple powerpc-ibm-aix-xcoff < %s | \
+; RUN: FileCheck --check-prefix=ASM %s
+; RUN: llc -mtriple powerpc64-ibm-aix-xcoff < %s | \
+; RUN: FileCheck --check-prefix=ASM %s
+
+; RUN: not --crash llc -mtriple powerpc-ibm-aix-xcoff -filetype=obj  < %s 2>&1 | \
+; RUN: FileCheck --check-prefix=OBJ %s
+; RUN: not --crash llc -mtriple powerpc64-ibm-aix-xcoff -filetype=obj  < %s 2>&1 | \
+; RUN: FileCheck --check-prefix=OBJ %s
+
+; Verify that llvm.commandline metadata is emitted to .info sections and that the
+; metadata is padded if necessary.
+
+; OBJ: LLVM ERROR: emitXCOFFCInfoSym is not implemented yet on object generation path
+
+; ASM: .info ".GCC.command.line", 0x0030,
+; ASM: .info , 0x40282329, 0x636c616e, 0x67202d63, 0x6f6d6d61, 0x6e64202d, 0x6c696e65
+; ASM: .info , 0x00402823, 0x29736f6d, 0x65746869, 0x6e672065, 0x6c736531, 0x3233
+
+!llvm.commandline = !{!0, !1}
+!0 = !{!"clang -command -line"}
+!1 = !{!"something else123"}
Index: llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
===
--- llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
+++ llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
@@ -290,6 +290,8 @@
   bool doFinalization(Module ) override;
 
   void emitTTypeReference(const GlobalValue *GV, unsigned Encoding) override;
+
+  void emitModuleCommandLines(Module ) override;
 };
 
 } // end anonymous namespace
@@ -2954,6 +2956,26 @@
   return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
 }
 
+void PPCAIXAsmPrinter::emitModuleCommandLines(Module ) {
+  const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
+  if (!NMD || !NMD->getNumOperands())
+return;
+
+  std::string S;
+  raw_string_ostream RSOS(S);
+  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
+const MDNode *N = NMD->getOperand(i);
+assert(N->getNumOperands() == 1 &&
+   "llvm.commandline metadata entry can have only one operand");
+const MDString *MDS = cast(N->getOperand(0));
+// Add "@(#)" to support retrieving the command line information with the
+// AIX "what" command
+RSOS << "@(#)" << MDS->getString();
+RSOS.write('\0');
+  }
+  OutStreamer->emitXCOFFCInfoSym(".GCC.command.line", RSOS.str());
+}
+
 // Force static initialization.
 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() {
   TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
Index: llvm/lib/MC/MCStreamer.cpp
===
--- llvm/lib/MC/MCStreamer.cpp
+++ llvm/lib/MC/MCStreamer.cpp
@@ -1208,6 +1208,11 @@
  "XCOFF targets");
 }
 
+void MCStreamer::emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) {
+  llvm_unreachable("emitXCOFFCInfoSym is only supported on"
+   "XCOFF targets");
+}
+
 void MCStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
 void MCStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
 StringRef Name, bool KeepOriginalSym) {}
Index: llvm/lib/MC/MCAsmStreamer.cpp
===
--- llvm/lib/MC/MCAsmStreamer.cpp
+++ llvm/lib/MC/MCAsmStreamer.cpp
@@ -37,6 +37,7 @@
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/Path.h"
 #include 
+#include 
 
 using namespace llvm;
 
@@ -200,6 +201,7 @@
 const MCSymbol *Trap,
 unsigned Lang, unsigned Reason,
 unsigned FunctionSize, bool hasDebug) override;
+  void emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) override;
 
   void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
   void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
@@ -966,6 +968,65 @@
   EmitEOL();
 }
 
+void MCAsmStreamer::emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) {
+  const char *InfoDirective = "\t.info ";
+  const char *Separator = ", ";
+  constexpr int WordSize = sizeof(uint32_t);
+
+  // Start by emitting the .info pseudo-op and C_INFO symbol name.
+  OS << InfoDirective;
+  

[PATCH] D153296: [AST] Stop evaluate constant expression if the condition expression which in switch statement contains errors

2023-07-03 Thread Yurong via Phabricator via cfe-commits
yronglin added a comment.

In D153296#4468373 , @aaron.ballman 
wrote:

> In D153296#4459769 , @yronglin 
> wrote:
>
>> Please help me, I have no better idea on this issue, do you have any better 
>> ideas? @erichkeane @shafik
>
> I think what's being suggested is to change `EvaluateDependentExpr()` 
> somewhat along these lines:
>
>   static bool EvaluateDependentExpr(const Expr *E, EvalInfo ) {
> assert(E->isValueDependent());
>   
> // Note that we have a side effect that matters for constant evaluation.
> bool SideEffects = Info.noteSideEffect();
> // If the reason we're here is because of a recovery expression, we don't
> // want to continue to evaluate further as we will never know what the 
> actual
> // value is.
> if (isa(E))
>   return false;
>   
> // Otherwise, return whether we want to continue after noting the side
> // effects, which should only happen if the expression has errors but 
> isn't
> // a recovery expression on its own.
> assert(E->containsErrors() && "valid value-dependent expression should 
> never "
>   "reach invalid code path.");
> return SideEffects;
>   }
>
> This way, code paths that get down to a `RecoveryExpr` will not continue to 
> evaluate further (as there's really no point -- there's no way to get a 
> reasonable value from from the recovery expression anyway), but the fix isn't 
> specific to just switch statements. After making these changes, you should 
> look for places where `EvaluateDependentExpr()` is being called to try to 
> come up with a test case where that expression is a recovery expression so 
> that we can fill out test coverage beyond just the situation with `switch` 
> from the original report. Does that make sense?
>
> (Marking as requesting changes so it's clear this review isn't yet accepted.)

Thanks a lot! @aaron.ballman , I try to address comments and add more test, 
this case (https://godbolt.org/z/ExPoEKcrf) looks strange, why the do-statement 
missing in the printed AST?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153296

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


[PATCH] D154329: [lldb] Replace llvm::writeFileAtomically with llvm::writeToOutput API.

2023-07-03 Thread Alexey Lapshin via Phabricator via cfe-commits
avl added a comment.

this LGTM. thanks! Please, wait for approve from Jonas. I think someone from 
lldb needs to check whether new error reporting is OK.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154329

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


[PATCH] D151696: [x86] Remove CPU_SPECIFIC* MACROs and add getCPUDispatchMangling

2023-07-03 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added inline comments.



Comment at: llvm/lib/TargetParser/X86TargetParser.cpp:378
+  { {"core_3rd_gen_avx"}, CK_IvyBridge, FEATURE_AVX, FeaturesIvyBridge, 'S', 
true },
+  { {"core-avx-i"}, CK_IvyBridge, FEATURE_AVX, FeaturesIvyBridge, '\0', false 
},
   // Haswell microarchitecture based processors.

I'm still not clear on what determines the mangling mode and cpu dispatch flag 
for cpu targets are supposedly the same? For example, none of these ivybridge 
equivalent configs have the same values.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151696

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


[PATCH] D154359: [clang] Reset FP options before template instantiation

2023-07-03 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff created this revision.
sepavloff added reviewers: rsmith, rjmccall, aaron.ballman, efriedma.
Herald added a project: All.
sepavloff requested review of this revision.
Herald added a project: clang.

AST nodes that may depend on FP options keep them as a difference
relative to the options outside the AST node. At the moment of
instantiation the FP options may be different from the default values,
defined by command-line option. In such case FP attributes would have
unexpected values. For example, the code:

  template  void func_01(int last, C) {
func_01(last, int());
  }
  void func_02() { func_01(0, 1); }
  #pragma STDC FENV_ACCESS ON

caused compiler crash, because template instantiation takes place at the
end of translation unit, where pragma STDC FENV_ACCESS is in effect. As
a result, code in the template instantiation would use constrained
intrinsics while the function does not have StrictFP attribute.

To solve this problem, FP attributes in Sema must be set to default
values, defined by command line options.

This change resolves https://github.com/llvm/llvm-project/issues/63542.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154359

Files:
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/CodeGen/fp-template.cpp


Index: clang/test/CodeGen/fp-template.cpp
===
--- clang/test/CodeGen/fp-template.cpp
+++ clang/test/CodeGen/fp-template.cpp
@@ -15,4 +15,19 @@
 // CHECK-SAME:  (float noundef %{{.*}}, float noundef %{{.*}}) 
#[[ATTR01:[0-9]+]]{{.*}} {
 // CHECK:   call float @llvm.experimental.constrained.fadd.f32
 
+namespace PR63542 {
+  template  float stable_sort(float x, Compare) {
+float result = x + x;
+stable_sort(x, int());
+return result;
+  }
+  float linkage_wrap() { return stable_sort(0.0, 1); }
+}
+
+// CHECK-LABEL: define {{.*}} float @_ZN7PR6354211stable_sortIiEEffT_(
+// CHECK: fadd float
+
+// Must be at the end of translation unit.
+#pragma STDC FENV_ACCESS ON
+
 // CHECK: attributes #[[ATTR01]] = { {{.*}}strictfp
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5087,6 +5087,10 @@
 // PushDeclContext because we don't have a scope.
 Sema::ContextRAII savedContext(*this, Function);
 
+FPFeaturesStateRAII SavedFPFeatures(*this);
+CurFPFeatures = FPOptions(getLangOpts());
+FpPragmaStack.CurrentValue = FPOptionsOverride();
+
 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
  TemplateArgs))
   return;


Index: clang/test/CodeGen/fp-template.cpp
===
--- clang/test/CodeGen/fp-template.cpp
+++ clang/test/CodeGen/fp-template.cpp
@@ -15,4 +15,19 @@
 // CHECK-SAME:  (float noundef %{{.*}}, float noundef %{{.*}}) #[[ATTR01:[0-9]+]]{{.*}} {
 // CHECK:   call float @llvm.experimental.constrained.fadd.f32
 
+namespace PR63542 {
+  template  float stable_sort(float x, Compare) {
+float result = x + x;
+stable_sort(x, int());
+return result;
+  }
+  float linkage_wrap() { return stable_sort(0.0, 1); }
+}
+
+// CHECK-LABEL: define {{.*}} float @_ZN7PR6354211stable_sortIiEEffT_(
+// CHECK: fadd float
+
+// Must be at the end of translation unit.
+#pragma STDC FENV_ACCESS ON
+
 // CHECK: attributes #[[ATTR01]] = { {{.*}}strictfp
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5087,6 +5087,10 @@
 // PushDeclContext because we don't have a scope.
 Sema::ContextRAII savedContext(*this, Function);
 
+FPFeaturesStateRAII SavedFPFeatures(*this);
+CurFPFeatures = FPOptions(getLangOpts());
+FpPragmaStack.CurrentValue = FPOptionsOverride();
+
 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
  TemplateArgs))
   return;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154357: [Driver] Recognize powerpc-unknown-eabi as a bare-metal toolchain

2023-07-03 Thread Christian Walther via Phabricator via cfe-commits
cwalther created this revision.
cwalther added reviewers: MaskRay, jroelofs.
cwalther added projects: clang, PowerPC.
Herald added subscribers: luismarques, steven.zhang, s.egerton, shchenz, abidh, 
PkmX, simoncook, asb, kristof.beyls, arichardson, nemanjai.
Herald added a project: All.
cwalther requested review of this revision.
Herald added subscribers: cfe-commits, wangpc.

At Indel, we have been building bare-metal embedded applications that run on 
custom PowerPC and ARM systems with Clang and LLD for a couple of years now, 
using target triples `powerpc-indel-eabi`, `powerpc-indel-eabi750`, 
`arm-indel-eabi`, `aarch64-indel-eabi` (which I just learned from D153430 
 is wrong and should be `aarch64-indel-elf` 
instead, but that’s a different matter). This has worked fine for ARM, but for 
PowerPC we have been unable to call the linker (LLD) through the Clang driver, 
because it would insist on calling GCC as the linker, even when told 
`-fuse-ld=lld`. That does not work for us, there is no GCC around. Instead we 
had to call `ld.lld` directly, introducing some special cases in our build 
system to translate between linker-via-driver and linker-called-directly 
command line arguments. I have now dug into why that is, and found that the 
difference between ARM and PowerPC is that `arm-indel-eabi` hits a special case 
that causes the Clang driver to instantiate a `BareMetal` toolchain that is 
able to call LLD and works the way we need, whereas `powerpc-indel-eabi` lands 
in the default case of a `Generic_ELF` (subclass of `Generic_GCC`) toolchain 
which expects GCC.

It seems to me that maybe anything with OS `none` (although that doesn’t seem 
to be distinguished from `unknown`) or with environment `eabi` should be 
treated as bare-metal, but I don’t have a lot of experience in this regard. 
Since this seems to have been handled on a case-by-case basis in the past (arm 
, riscv , 
aarch64 ), what I am proposing here is to add 
another case to the list to also handle `powerpc[64][le]-unknown-unknown-eabi` 
using the `BareMetal` toolchain, following the example of the existing cases. 
(We don’t care about powerpc64 and powerpc[64]le, but it seemed appropriate to 
lump them in.)

I have run the `check-clang` tests and the patch didn’t break any of them, 
which makes me hopeful. Or do you think that this may break anyone’s usage? 
Should we additionally check for the presence of a `--gcc-toolchain` argument 
like in the RISC-V case? I am new here, so any guidance is appreciated.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154357

Files:
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/test/Driver/baremetal.cpp


Index: clang/test/Driver/baremetal.cpp
===
--- clang/test/Driver/baremetal.cpp
+++ clang/test/Driver/baremetal.cpp
@@ -345,6 +345,58 @@
 // CHECK-RV32IMAFC-SAME: 
"-L[[SYSROOT:[^"]+]]{{[/\\]+}}rv32imafc{{[/\\]+}}ilp32f{{[/\\]+}}lib"
 // CHECK-RV32IMAFC-SAME: 
"-L[[RESOURCE_DIR:[^"]+]]{{[/\\]+}}lib{{[/\\]+}}baremetal{{[/\\]+}}rv32imafc{{[/\\]+}}ilp32f"
 
+// RUN: %clang %s -### --target=powerpc-unknown-eabi 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-PPCEABI %s
+// CHECK-PPCEABI: InstalledDir: [[INSTALLEDDIR:.+]]
+// CHECK-PPCEABI: "-nostdsysteminc"
+// CHECK-PPCEABI-SAME: "-resource-dir" "[[RESOURCE:[^"]+]]"
+// CHECK-PPCEABI-SAME: "-internal-isystem" 
"[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}include{{[/\\]+}}c++{{[/\\]+}}v1"
+// CHECK-PPCEABI-SAME: "-internal-isystem" "[[RESOURCE]]{{[/\\]+}}include"
+// CHECK-PPCEABI-SAME: "-internal-isystem" 
"[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}include"
+// CHECK-PPCEABI-NEXT: ld{{(.exe)?}}" "{{.*}}.o" "-Bstatic"
+// CHECK-PPCEABI-SAME: 
"-L[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}lib"
+// CHECK-PPCEABI-SAME: "-L[[RESOURCE]]{{[/\\]+}}lib{{[/\\]+}}baremetal"
+// CHECK-PPCEABI-SAME: "-lc" "-lm" "-lclang_rt.builtins-powerpc" "-o" "a.out"
+
+// RUN: %clang %s -### --target=powerpc64-unknown-eabi 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-PPC64EABI %s
+// CHECK-PPC64EABI: InstalledDir: [[INSTALLEDDIR:.+]]
+// CHECK-PPC64EABI: "-nostdsysteminc"
+// CHECK-PPC64EABI-SAME: "-resource-dir" "[[RESOURCE:[^"]+]]"
+// CHECK-PPC64EABI-SAME: "-internal-isystem" 
"[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}include{{[/\\]+}}c++{{[/\\]+}}v1"
+// CHECK-PPC64EABI-SAME: "-internal-isystem" "[[RESOURCE]]{{[/\\]+}}include"
+// CHECK-PPC64EABI-SAME: "-internal-isystem" 
"[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}include"
+// CHECK-PPC64EABI-NEXT: ld{{(.exe)?}}" "{{.*}}.o" "-Bstatic"
+// CHECK-PPC64EABI-SAME: 

[PATCH] D153340: [include-cleaner] Add an IgnoreHeaders flag to the command-line tool.

2023-07-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h:67
 /// Determine which headers should be inserted or removed from the main file.
 /// This exposes conclusions but not reasons: use lower-level walkUsed for 
that.
+AnalysisResults analyze(

can you add some comments about how header filter works? `A predicate that 
receives absolute path or spelling without quotes/brackets, when a phyiscal 
file doesn't exist. No analysis will be performed for headers that satisfy the 
predicate.`



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h:72
+const HeaderSearch ,
+llvm::function_ref HeaderFilter =
+[](llvm::StringRef HeaderPath) {

rather than a default here, can we just do no filtering when `HeaderFilter` is 
null ?



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h:137
 
+  llvm::StringRef resolvedPath() const;
+

again some comments here could be useful



Comment at: clang-tools-extra/include-cleaner/lib/Analysis.cpp:65
+const HeaderSearch ,
+llvm::function_ref HeaderFilter) {
   const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID());

can you drop `Path` or put it in comments



Comment at: clang-tools-extra/include-cleaner/test/tool.cpp:17
 
+//RUN: clang-include-cleaner -print=changes %s 
--ignore-headers="foobar\.h,foo\.h" -- -I%S/Inputs/ | FileCheck 
--match-full-lines --allow-empty --check-prefix=IGNORE %s
+// IGNORE-NOT: - "foobar.h"

can you ignore one but keep other?

it'd be useful to also test the regex behaviour



Comment at: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp:106
+public:
+  Action(llvm::function_ref HeaderFilter)
+  : HeaderFilter(HeaderFilter){};

same as above, can you either drop or comment out `Path`



Comment at: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp:113
   PragmaIncludes PI;
+  llvm::function_ref HeaderFilter;
 

same here for `Path`



Comment at: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp:157
   case PrintStyle::Changes:
-for (const Include *I : Results.Unused)
+for (const Include *I : Results.Unused) {
   llvm::outs() << "- " << I->quote() << " @Line:" << I->Line << "\n";

nit: braces



Comment at: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp:225
   }
+  std::vector FilterRegs;
+  llvm::SmallVector Headers;

nit: might be better to extract this into a function like: 
`std::function headerFilter() { /* parses flags, returns a 
null function on failure */ }`



Comment at: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp:227
+  llvm::SmallVector Headers;
+  llvm::StringRef(IgnoreHeaders).split(Headers, ',', -1, /*KeepEmpty*/ false);
+  for (auto HeaderPattern : Headers) {

s/KeepEmpty/KeepEmpty=/


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153340

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


[PATCH] D153881: Create diagnostic group for definition deprecation warning

2023-07-03 Thread Nuri Amari via Phabricator via cfe-commits
nuriamari added a comment.

In D153881#4467127 , @aaron.ballman 
wrote:

> I think it's a bit odd that we'd leave `const` under `-Wdeprecated` but 
> separate `constexpr` out into its own warning flag, but I'm also not opposed.

Would moving both const and constexpr into their own warning flag work? I don't 
really see cases where you'd want to disable only one or the other.

> Can you explain the need a bit more though? I think our belief was that 
> silencing this diagnostic was pretty trivial (delete the line in question), 
> so we wouldn't need a separate diagnostic group for it.

In our case we have libraries that are consumed both with say C++14 and C++17, 
so we can't just delete them, we've needed to add a standard version check. 
Admittedly not a huge change either, but we ran into many occurrences of this 
warning trying to adopt the latest Clang. I suppose I don't see the downside of 
a little more granular control.

> Also, these changes should have a release note added to 
> `clang/docs/ReleaseNotes.rst`.

Will do.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153881

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


[PATCH] D154335: [clang][tooling] Fix early termination when there are nested expansions

2023-07-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9841daf27076: [clang][tooling] Fix early termination when 
there are nested expansions (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154335

Files:
  clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp
  clang/lib/Tooling/Syntax/Tokens.cpp
  clang/unittests/Tooling/Syntax/TokensTest.cpp

Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -769,12 +769,15 @@
   // Critical cases for mapping of Prev/Next in spelledForExpandedSlow.
   recordTokens(R"cpp(
 #define ID(X) X
-ID(prev ID(good))
+ID(prev good)
+ID(prev ID(good2))
 #define LARGE ID(prev ID(bad))
 LARGE
   )cpp");
   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
   ValueIs(SameRange(findSpelled("good";
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good2")),
+  ValueIs(SameRange(findSpelled("good2";
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), std::nullopt);
 
   recordTokens(R"cpp(
@@ -785,19 +788,32 @@
 LARGE
   )cpp");
   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
-ValueIs(SameRange(findSpelled("good";
+  ValueIs(SameRange(findSpelled("good";
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), std::nullopt);
 
   recordTokens(R"cpp(
 #define ID(X) X
 #define ID2(X, Y) X Y
-ID2(prev, ID(good))
+ID2(prev, good)
+ID2(prev, ID(good2))
 #define LARGE ID2(prev, bad)
 LARGE
   )cpp");
   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
-ValueIs(SameRange(findSpelled("good";
+  ValueIs(SameRange(findSpelled("good";
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good2")),
+  ValueIs(SameRange(findSpelled("good2";
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), std::nullopt);
+
+  // Prev from macro body.
+  recordTokens(R"cpp(
+#define ID(X) X
+#define ID2(X, Y) X prev ID(Y)
+ID2(not_prev, good)
+  )cpp");
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
+  ValueIs(SameRange(findSpelled("good";
+  EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("prev good")), std::nullopt);
 }
 
 TEST_F(TokenBufferTest, ExpandedTokensForRange) {
Index: clang/lib/Tooling/Syntax/Tokens.cpp
===
--- clang/lib/Tooling/Syntax/Tokens.cpp
+++ clang/lib/Tooling/Syntax/Tokens.cpp
@@ -103,66 +103,13 @@
 // The token `a` is wrapped in 4 arg-expansions, we only want to unwrap 2.
 // We distinguish them by whether the macro expands into the target file.
 // Fortunately, the target file ones will always appear first.
-auto  =
-SM.getSLocEntry(SM.getFileID(ExpFirst.getExpansionLocStart()))
-.getExpansion();
-if (ExpMacro.getExpansionLocStart().isMacroID())
+auto ExpFileID = SM.getFileID(ExpFirst.getExpansionLocStart());
+if (ExpFileID == TargetFile)
   break;
 // Replace each endpoint with its spelling inside the macro arg.
 // (This is getImmediateSpellingLoc without repeating lookups).
 First = ExpFirst.getSpellingLoc().getLocWithOffset(DecFirst.second);
 Last = ExpLast.getSpellingLoc().getLocWithOffset(DecLast.second);
-
-// Now: how do we adjust the previous/next bounds? Three cases:
-// A) If they are also part of the same macro arg, we translate them too.
-//   This will ensure that we don't select any macros nested within the
-//   macro arg that cover extra tokens. Critical case:
-//  #define ID(X) X
-//  ID(prev target) // selecting 'target' succeeds
-//  #define LARGE ID(prev target)
-//  LARGE // selecting 'target' fails.
-// B) They are not in the macro at all, then their expansion range is a
-//sibling to it, and we can safely substitute that.
-//  #define PREV prev
-//  #define ID(X) X
-//  PREV ID(target) // selecting 'target' succeeds.
-//  #define LARGE PREV ID(target)
-//  LARGE // selecting 'target' fails.
-// C) They are in a different arg of this macro, or the macro body.
-//Now selecting the whole macro arg is fine, but the whole macro is not.
-//Model this by setting using the edge of the macro call as the bound.
-//  #define ID2(X, Y) X Y
-//  ID2(prev, target) // selecting 'target' succeeds
-//  #define LARGE ID2(prev, target)
-//  LARGE // selecting 'target' fails
-auto AdjustBound = [&](SourceLocation ) {
-  if (Bound.isInvalid() || 

[clang] 9841daf - [clang][tooling] Fix early termination when there are nested expansions

2023-07-03 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-07-03T16:58:04+02:00
New Revision: 9841daf27076886c6ab8e155eb812bda76f77532

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

LOG: [clang][tooling] Fix early termination when there are nested expansions

This also does some cleanups, I am happy to undo them (or send as
separate patches):
- Change the early exit to stop only once we hit an expansion inside the
  main file, to make sure we keep following the nested expansions.
- Add more tests to cover all the cases mentioned in the implementation
- Drop the adjustments for prev/next tokens. We do the final checks
  based on the expansion locations anyway, so any intermediate mapping
  was a no-op.

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

Added: 


Modified: 
clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp
clang/lib/Tooling/Syntax/Tokens.cpp
clang/unittests/Tooling/Syntax/TokensTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp
index da76ecad145548..1fd2487378d705 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp
@@ -71,6 +71,13 @@ class cc {
   // NestedNameSpecifier, but no namespace.
   EXPECT_UNAVAILABLE(Header + "class Foo {}; class F^oo foo;");
 
+  // Nested macro case.
+  EXPECT_AVAILABLE(R"cpp(
+  #define ID2(X) X
+  #define ID(Y, X) Y;ID2(X)
+  namespace ns { struct Foo{}; }
+  ID(int xyz, ns::F^oo) f;)cpp");
+
   // Check that we do not trigger in header files.
   FileName = "test.h";
   ExtraArgs.push_back("-xc++-header"); // .h file is treated a C by default.

diff  --git a/clang/lib/Tooling/Syntax/Tokens.cpp 
b/clang/lib/Tooling/Syntax/Tokens.cpp
index 64e6eee6b62f2f..9c2f470e985fb6 100644
--- a/clang/lib/Tooling/Syntax/Tokens.cpp
+++ b/clang/lib/Tooling/Syntax/Tokens.cpp
@@ -103,66 +103,13 @@ SourceRange spelledForExpandedSlow(SourceLocation First, 
SourceLocation Last,
 // The token `a` is wrapped in 4 arg-expansions, we only want to unwrap 2.
 // We distinguish them by whether the macro expands into the target file.
 // Fortunately, the target file ones will always appear first.
-auto  =
-SM.getSLocEntry(SM.getFileID(ExpFirst.getExpansionLocStart()))
-.getExpansion();
-if (ExpMacro.getExpansionLocStart().isMacroID())
+auto ExpFileID = SM.getFileID(ExpFirst.getExpansionLocStart());
+if (ExpFileID == TargetFile)
   break;
 // Replace each endpoint with its spelling inside the macro arg.
 // (This is getImmediateSpellingLoc without repeating lookups).
 First = ExpFirst.getSpellingLoc().getLocWithOffset(DecFirst.second);
 Last = ExpLast.getSpellingLoc().getLocWithOffset(DecLast.second);
-
-// Now: how do we adjust the previous/next bounds? Three cases:
-// A) If they are also part of the same macro arg, we translate them too.
-//   This will ensure that we don't select any macros nested within the
-//   macro arg that cover extra tokens. Critical case:
-//  #define ID(X) X
-//  ID(prev target) // selecting 'target' succeeds
-//  #define LARGE ID(prev target)
-//  LARGE // selecting 'target' fails.
-// B) They are not in the macro at all, then their expansion range is a
-//sibling to it, and we can safely substitute that.
-//  #define PREV prev
-//  #define ID(X) X
-//  PREV ID(target) // selecting 'target' succeeds.
-//  #define LARGE PREV ID(target)
-//  LARGE // selecting 'target' fails.
-// C) They are in a 
diff erent arg of this macro, or the macro body.
-//Now selecting the whole macro arg is fine, but the whole macro is 
not.
-//Model this by setting using the edge of the macro call as the bound.
-//  #define ID2(X, Y) X Y
-//  ID2(prev, target) // selecting 'target' succeeds
-//  #define LARGE ID2(prev, target)
-//  LARGE // selecting 'target' fails
-auto AdjustBound = [&](SourceLocation ) {
-  if (Bound.isInvalid() || !Bound.isMacroID()) // Non-macro must be case B.
-return;
-  auto DecBound = SM.getDecomposedLoc(Bound);
-  auto  = SM.getSLocEntry(DecBound.first).getExpansion();
-  if (ExpBound.isMacroArgExpansion() &&
-  ExpBound.getExpansionLocStart() == ExpFirst.getExpansionLocStart()) {
-// Case A: translate to (spelling) loc within the macro arg.
-Bound = ExpBound.getSpellingLoc().getLocWithOffset(DecBound.second);
-return;
-  }
-  while (Bound.isMacroID()) {
-SourceRange Exp = SM.getImmediateExpansionRange(Bound).getAsRange();
-if 

[PATCH] D153969: [clang][ExprConstant] Fix crash on uninitialized base class subobject

2023-07-03 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet updated this revision to Diff 536771.
hazohelet edited the summary of this revision.
hazohelet added a comment.

- Removed the `base class inherited here` redundant note
- Provided source range and added test for it

The provided source range is NOT directly calling 
`CXXBaseSpecifier::getSourceRange` so as not to cover the access specifiers 
like `public`, `private` or `protected`


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

https://reviews.llvm.org/D153969

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/lib/AST/ExprConstant.cpp
  clang/test/Misc/constexpr-subobj-init-source-ranges.cpp
  clang/test/SemaCXX/constexpr-subobj-initialization.cpp

Index: clang/test/SemaCXX/constexpr-subobj-initialization.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/constexpr-subobj-initialization.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+namespace baseclass_uninit {
+struct DelBase {
+  constexpr DelBase() = delete; // expected-note {{'DelBase' has been explicitly marked deleted here}}
+};
+
+struct Foo : DelBase {  // expected-note 2{{constructor of base class 'DelBase' is not called}}
+  constexpr Foo() {}; // expected-error {{call to deleted constructor of 'DelBase'}}
+};
+constexpr Foo f; // expected-error {{must be initialized by a constant expression}}
+struct Bar : Foo {
+  constexpr Bar() {};
+};
+constexpr Bar bar; // expected-error {{must be initialized by a constant expression}}
+
+struct Base {};
+struct A : Base { // expected-note {{constructor of base class 'Base' is not called}}
+  constexpr A() : value() {} // expected-error {{member initializer 'value' does not name a non-static data member or base class}}
+};
+
+constexpr A a; // expected-error {{must be initialized by a constant expression}}
+
+struct B : Base { // expected-note {{constructor of base class 'Base' is not called}}
+  constexpr B() : {} // expected-error {{expected class member or base class name}}
+};
+
+constexpr B b; // expected-error {{must be initialized by a constant expression}}
+} // namespace baseclass_uninit
+
Index: clang/test/Misc/constexpr-subobj-init-source-ranges.cpp
===
--- /dev/null
+++ clang/test/Misc/constexpr-subobj-init-source-ranges.cpp
@@ -0,0 +1,11 @@
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-print-source-range-info %s 2>&1 | FileCheck %s --strict-whitespace
+
+struct DelBase {
+  constexpr DelBase() = delete;
+};
+
+// CHECK:  :{[[@LINE+1]]:21-[[@LINE+1]]:28}
+struct Foo : public DelBase {
+  constexpr Foo() {};
+};
+constexpr Foo f;
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -2415,9 +2415,16 @@
 if (const CXXRecordDecl *CD = dyn_cast(RD)) {
   unsigned BaseIndex = 0;
   for (const CXXBaseSpecifier  : CD->bases()) {
-if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
-   Value.getStructBase(BaseIndex), Kind,
-   /*SubobjectDecl=*/nullptr, CheckedTemps))
+const APValue  = Value.getStructBase(BaseIndex);
+if (!BaseValue.hasValue()) {
+  SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
+  Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
+  << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
+  return false;
+}
+if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
+   Kind, /*SubobjectDecl=*/nullptr,
+   CheckedTemps))
   return false;
 ++BaseIndex;
   }
Index: clang/include/clang/Basic/DiagnosticASTKinds.td
===
--- clang/include/clang/Basic/DiagnosticASTKinds.td
+++ clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -70,6 +70,8 @@
   "is not a constant expression">;
 def note_constexpr_uninitialized : Note<
   "subobject %0 is not initialized">;
+def note_constexpr_uninitialized_base : Note<
+  "constructor of base class %0 is not called">;
 def note_constexpr_static_local : Note<
   "control flows through the definition of a %select{static|thread_local}0 variable">;
 def note_constexpr_subobject_declared_here : Note<
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -379,6 +379,8 @@
   (`#57081: `_)
 - Clang no longer emits inappropriate notes about the loss of ``__unaligned`` qualifier
   on overload resolution, when the actual reason for the failure is loss of other qualifiers.
+- Clang contexpr evaluator now displays 

[PATCH] D154349: [include-cleaner] Add a signal to down-rank exporting headers

2023-07-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: hokein.
Herald added a project: All.
kadircet requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Currently exporter can have same relevance signals as the origin header
when name match signals don't trigger.
This patch introduces a tie braker signal to boost origin headers in
such cases, this is deliberately introduced with lower significance than
public-ness to make sure we still prefer a public-exporter instead of a
private-origin header.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154349

Files:
  clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
  clang-tools-extra/include-cleaner/lib/TypesInternal.h
  clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
  clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
@@ -8,17 +8,21 @@
 
 #include "AnalysisInternal.h"
 #include "TypesInternal.h"
+#include "clang-include-cleaner/Analysis.h"
 #include "clang-include-cleaner/Record.h"
 #include "clang-include-cleaner/Types.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/FileManager.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 #include 
 
 namespace clang::include_cleaner {
@@ -253,11 +257,11 @@
   EXPECT_THAT(
   findHeaders("private.inc"),
   UnorderedElementsAre(
-  HintedHeader(physicalHeader("private.inc"), Hints::None),
+  HintedHeader(physicalHeader("private.inc"), Hints::OriginHeader),
   HintedHeader(physicalHeader("public.h"), Hints::PublicHeader)));
   EXPECT_THAT(findHeaders("private.h"),
-  UnorderedElementsAre(
-  HintedHeader(physicalHeader("private.h"), Hints::None)));
+  UnorderedElementsAre(HintedHeader(physicalHeader("private.h"),
+Hints::OriginHeader)));
 }
 
 TEST_F(FindHeadersTest, PreferredHeaderHint) {
@@ -269,11 +273,12 @@
   )cpp");
   buildAST();
   // Headers explicitly marked should've preferred signal.
-  EXPECT_THAT(findHeaders("private.h"),
-  UnorderedElementsAre(
-  HintedHeader(physicalHeader("private.h"), Hints::None),
-  HintedHeader(Header("\"public.h\""),
-   Hints::PreferredHeader | Hints::PublicHeader)));
+  EXPECT_THAT(
+  findHeaders("private.h"),
+  UnorderedElementsAre(
+  HintedHeader(physicalHeader("private.h"), Hints::OriginHeader),
+  HintedHeader(Header("\"public.h\""),
+   Hints::PreferredHeader | Hints::PublicHeader)));
 }
 
 class HeadersForSymbolTest : public FindHeadersTest {
@@ -339,11 +344,12 @@
 }
 
 TEST_F(HeadersForSymbolTest, Ranking) {
-  // Sorting is done over (canonical, public, complete) triplet.
+  // Sorting is done over (canonical, public, complete, origin)-tuple.
   Inputs.Code = R"cpp(
 #include "private.h"
 #include "public.h"
 #include "public_complete.h"
+#include "exporter.h"
   )cpp";
   Inputs.ExtraFiles["public.h"] = guard(R"cpp(
 struct foo;
@@ -352,11 +358,15 @@
 // IWYU pragma: private, include "canonical.h"
 struct foo;
   )cpp");
+  Inputs.ExtraFiles["exporter.h"] = guard(R"cpp(
+  #include "private.h" // IWYU pragma: export
+  )cpp");
   Inputs.ExtraFiles["public_complete.h"] = guard("struct foo {};");
   buildAST();
   EXPECT_THAT(headersForFoo(), ElementsAre(Header("\"canonical.h\""),
physicalHeader("public_complete.h"),
physicalHeader("public.h"),
+   physicalHeader("exporter.h"),
physicalHeader("private.h")));
 }
 
@@ -424,6 +434,24 @@
physicalHeader("private.h")));
 }
 
+TEST_F(HeadersForSymbolTest, ExporterIsDownRanked) {
+  Inputs.Code = R"cpp(
+#include "exporter.h"
+#include "zoo.h"
+  )cpp";
+  // Deliberately named as zoo to make sure it doesn't get name-match boost and
+  // also gets lexicographically bigger order than "exporter".
+  Inputs.ExtraFiles["zoo.h"] = guard(R"cpp(
+struct foo {};
+  )cpp");
+  Inputs.ExtraFiles["exporter.h"] = guard(R"cpp(
+#include "zoo.h" // IWYU pragma: export
+  )cpp");
+  buildAST();
+  EXPECT_THAT(headersForFoo(), ElementsAre(physicalHeader("zoo.h"),

[PATCH] D154287: [clang-tidy] Add modernize-use-std-format check

2023-07-03 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-format.rst:6
+
+Converts calls to ``absl::StrFormat`` to equivalent calls to C++20's
+``std::format`` function, modifying the format string appropriately. The

Please synchronize first statement with Release Notes.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-format.rst:58
+  of -42 and the signed representation of 0x (often 4294967254
+  and -1 respectively.) When false (which is the default), these casts
+  will not be added which may cause a change in the output. Note that this

Please highlight `false` with single back-ticks.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-format.rst:70
+   immediately afterwards. The defaualt value for this option is
+   ``absl::StrFormat``.
+

Single back-ticks for option value.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-format.rst:84
+   `ReplacementFormatFunction` so that a ``#include`` directive can be added if
+   required. If `ReplacementFormatFunction` is ``std::format`` then this 
option will
+   default to , otherwise this option will default to nothing

Ditto.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154287

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


[PATCH] D143052: [CMake] Replace llvm_check_linker_flag and llvm_check_compiler_linker_flag

2023-07-03 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.
Herald added a subscriber: ekilmer.

What is the status of this? We now require CMake 3.20, can this be rebased and 
landed in some form?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143052

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


[PATCH] D154335: [clang][tooling] Fix early termination when there are nested expansions

2023-07-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:116
-
-// Now: how do we adjust the previous/next bounds? Three cases:
-// A) If they are also part of the same macro arg, we translate them too.

(no action needed)

we had extensive discussion of why this change is a no-op, and how to prove it, 
and what comments to leave.
However in the end I don't think such a comment is necessary, because the code 
makes sense in isolation, and equivalence-to-previous-version isn't very 
interesting!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154335

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


[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Mariya Podchishchaeva 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 rG2d4f2890823f: [clang] Add `__has_extension ()` for C++11 
features (authored by Fznamznon).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154334

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Features.def
  clang/test/Lexer/has_extension_cxx.cpp


Index: clang/test/Lexer/has_extension_cxx.cpp
===
--- clang/test/Lexer/has_extension_cxx.cpp
+++ clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@
 int c_generic_selections();
 #endif
 
+// CHECK: has_default_function_template_args
+#if __has_extension(cxx_default_function_template_args)
+int has_default_function_template_args();
+#endif
+
+// CHECK: has_defaulted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_defaulted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/Lexer/has_extension_cxx.cpp
===
--- clang/test/Lexer/has_extension_cxx.cpp
+++ clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@
 int c_generic_selections();
 #endif
 
+// CHECK: has_default_function_template_args
+#if __has_extension(cxx_default_function_template_args)
+int has_default_function_template_args();
+#endif
+
+// CHECK: has_defaulted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_defaulted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2d4f289 - [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Mariya Podchishchaeva via cfe-commits

Author: Mariya Podchishchaeva
Date: 2023-07-03T10:15:40-04:00
New Revision: 2d4f2890823fa3edc6ae563edec4dacad1989564

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

LOG: [clang] Add `__has_extension ()` for C++11 features

Add `__has_extension (cxx_defaulted_functions)` and
`__has_extension (cxx_default_function_template_args)` since they are
accepted in C++98 mode as extensions.

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

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/Features.def
clang/test/Lexer/has_extension_cxx.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 94eddd5e3b89c7..022d51b525c04c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@ Bug Fixes in This Version
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index 4113b4d868dda6..1eb4573a8f7fef 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@ EXTENSION(c_static_assert, true)
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)

diff  --git a/clang/test/Lexer/has_extension_cxx.cpp 
b/clang/test/Lexer/has_extension_cxx.cpp
index d1267eaf85d84b..1ae6a446b300a7 100644
--- a/clang/test/Lexer/has_extension_cxx.cpp
+++ b/clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@ int c_static_assert();
 int c_generic_selections();
 #endif
 
+// CHECK: has_default_function_template_args
+#if __has_extension(cxx_default_function_template_args)
+int has_default_function_template_args();
+#endif
+
+// CHECK: has_defaulted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_defaulted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();



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


[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D154334#4468404 , @Fznamznon wrote:

> In D154334#4468158 , @aaron.ballman 
> wrote:
>
>> Thank you for this! LGTM. but can you also be sure to update this table: 
>> https://github.com/llvm/llvm-project/blob/main/clang/docs/LanguageExtensions.rst?plain=1#L1429
>
> Hmm, I have a feeling that the table is for features that have `__cpp_*` 
> macros defined for them. The features I intended to fix are described by the 
> same doc here - 
> https://github.com/llvm/llvm-project/blob/29f4c398717184a019791ed52d1d0d69ed5dabb6/clang/docs/LanguageExtensions.rst?plain=1#L1071
>  .

Oh shoot, you're right, these don't have the typical feature testing macros 
from http://eel.is/c++draft/tab:cpp.predefined.ft ! Sorry for the noise, this 
is fine as-is.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154334

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


[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon added a comment.

In D154334#4468158 , @aaron.ballman 
wrote:

> Thank you for this! LGTM. but can you also be sure to update this table: 
> https://github.com/llvm/llvm-project/blob/main/clang/docs/LanguageExtensions.rst?plain=1#L1429

Hmm, I have a feeling that the table is for features that have `__cpp_*` macros 
defined for them. The features I intended to fix are described by the same doc 
here - 
https://github.com/llvm/llvm-project/blob/29f4c398717184a019791ed52d1d0d69ed5dabb6/clang/docs/LanguageExtensions.rst?plain=1#L1071
 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154334

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


[PATCH] D154297: clang-tidy: accessing checks not done for aliases of `std::array`

2023-07-03 Thread Jorge Pinto Sousa via Phabricator via cfe-commits
sousajo added a comment.

while landing it, if someone feels that the release work can be reworded please 
feel free to do so.


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

https://reviews.llvm.org/D154297

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


[PATCH] D153296: [AST] Stop evaluate constant expression if the condition expression which in switch statement contains errors

2023-07-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman requested changes to this revision.
aaron.ballman added a comment.
This revision now requires changes to proceed.

In D153296#4459769 , @yronglin wrote:

> Please help me, I have no better idea on this issue, do you have any better 
> ideas? @erichkeane @shafik

I think what's being suggested is to change `EvaluateDependentExpr()` somewhat 
along these lines:

  static bool EvaluateDependentExpr(const Expr *E, EvalInfo ) {
assert(E->isValueDependent());
  
// Note that we have a side effect that matters for constant evaluation.
bool SideEffects = Info.noteSideEffect();
// If the reason we're here is because of a recovery expression, we don't
// want to continue to evaluate further as we will never know what the 
actual
// value is.
if (isa(E))
  return false;
  
// Otherwise, return whether we want to continue after noting the side
// effects, which should only happen if the expression has errors but isn't
// a recovery expression on its own.
assert(E->containsErrors() && "valid value-dependent expression should 
never "
  "reach invalid code path.");
return SideEffects;
  }

This way, code paths that get down to a `RecoveryExpr` will not continue to 
evaluate further (as there's really no point -- there's no way to get a 
reasonable value from from the recovery expression anyway), but the fix isn't 
specific to just switch statements. After making these changes, you should look 
for places where `EvaluateDependentExpr()` is being called to try to come up 
with a test case where that expression is a recovery expression so that we can 
fill out test coverage beyond just the situation with `switch` from the 
original report. Does that make sense?

(Marking as requesting changes so it's clear this review isn't yet accepted.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153296

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


[PATCH] D153359: [clang][Diagnostics] Fix distant source ranges in bad-conversion notes

2023-07-03 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet updated this revision to Diff 536743.
hazohelet edited the summary of this revision.
hazohelet added a comment.

Edited release note so that it only mentions the clang 16 -> 17 changes, and 
not development internal ones


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

https://reviews.llvm.org/D153359

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaOverload.cpp
  clang/test/Misc/diag-overload-cand-ranges.cpp
  clang/test/Misc/diag-overload-cand-ranges.mm

Index: clang/test/Misc/diag-overload-cand-ranges.mm
===
--- /dev/null
+++ clang/test/Misc/diag-overload-cand-ranges.mm
@@ -0,0 +1,26 @@
+// RUN: not %clang_cc1 -fobjc-runtime-has-weak -fobjc-arc -fsyntax-only -fdiagnostics-print-source-range-info %s 2>&1 | FileCheck %s --strict-whitespace -check-prefixes=CHECK,ARC
+// RUN: not %clang_cc1 -fobjc-runtime-has-weak -fobjc-gc -fsyntax-only -fdiagnostics-print-source-range-info %s 2>&1 | FileCheck %s --strict-whitespace -check-prefixes=CHECK,GC
+
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:15-[[@LINE+1]]:28}: note: {{.*}}: 1st argument
+void powerful(__strong id &);
+void lifetime_gcattr_mismatch() {
+  static __weak id weak_id;
+  powerful(weak_id);
+}
+
+// CHECK:  error: no matching function
+// ARC::{[[@LINE+2]]:11-[[@LINE+2]]:21}: note: {{.*}}: cannot implicitly convert
+// GC: :{[[@LINE+1]]:11-[[@LINE+1]]:21}: note: {{.*}}: no known conversion
+void func(char *uiui);
+
+__attribute__((objc_root_class))
+@interface Interface
+- (void)something;
+@end
+
+@implementation Interface
+- (void)something{
+func(self);
+}
+@end
Index: clang/test/Misc/diag-overload-cand-ranges.cpp
===
--- /dev/null
+++ clang/test/Misc/diag-overload-cand-ranges.cpp
@@ -0,0 +1,72 @@
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-print-source-range-info %s 2>&1 | FileCheck %s --strict-whitespace
+// CHECK:  error: no matching function
+template  struct mcdata {
+  typedef int result_type;
+};
+template  typename mcdata::result_type wrap_mean(mcdata const &);
+// CHECK:  :{[[@LINE+1]]:19-[[@LINE+1]]:53}: note: {{.*}}: no overload of 'wrap_mean'
+void add_property(double (*)(mcdata const &));
+void f() { add_property(_mean); }
+
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:10-[[@LINE+1]]:51}: note: {{.*}}: cannot pass pointer to generic address space
+void baz(__attribute__((opencl_private)) int *Data) {}
+void fizz() {
+  int *Nop;
+  baz(Nop);
+  // CHECK:error: no matching function
+  // CHECK::[[@LINE+1]]:53: note: {{.*}}: 'this' object is in address space '__private'
+  __attribute__((opencl_private)) static auto err = [&]() {};
+  err();
+}
+
+// CHECK:  error: no matching function
+struct Bar {
+// CHECK:  :{[[@LINE+1]]:26-[[@LINE+1]]:32}: note: {{.*}} would lose const qualifier
+static void foo(int num, int *X) {}
+// CHECK:  :{[[@LINE+1]]:17-[[@LINE+1]]:25}: note: {{.*}} no known conversion
+static void foo(int *err, int *x) {}
+};
+void bar(const int *Y) {
+  Bar::foo(5, Y);
+}
+
+struct InComp;
+
+struct A {};
+struct B : public A{};
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+5]]:36-[[@LINE+5]]:50}: note: {{.*}}: cannot convert initializer
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+3]]:36-[[@LINE+3]]:50}: note: {{.*}}: cannot convert argument
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:11-[[@LINE+1]]:18}: note: {{.*}}: no known conversion
+void hoge(char aa, const char *bb, const A& third);
+
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:14-[[@LINE+1]]:16}: note: {{.*}}: cannot convert from base class
+void derived(B*);
+
+void func(const A ) {
+  hoge(1, "pass", {{{arg}}});
+  InComp *a;
+  hoge(1, "pass", a);
+  hoge("first", 5, 6);
+  A *b;
+  derived(b);
+}
+
+struct Q {
+  // CHECK:error: invalid operands
+  // CHECK::[[@LINE+1]]:6: note: {{.*}}: 'this' argument has type 'const Q'
+  Q +(void*);
+};
+
+void fuga(const Q q) { q + 3; }
+
+template  class Type1 {};
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:43-[[@LINE+1]]:54}: note: {{.*}}: expects an lvalue
+template  void Function1(int zz, Type1 , int ww) {}
+
+void Function() { Function1(33, Type1<-42>(), 66); }
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -10753,6 +10753,8 @@
   Expr *FromExpr = Conv.Bad.FromExpr;
   QualType FromTy = Conv.Bad.getFromType();
   QualType ToTy = Conv.Bad.getToType();
+  SourceRange ToParamRange =
+  !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange();
 
   if (FromTy == S.Context.OverloadTy) {
 assert(FromExpr && "overload set argument came from 

[PATCH] D152093: [clang][Analysis] Handle && and || against variable and its negation as tautology

2023-07-03 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet added a comment.

Ping


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

https://reviews.llvm.org/D152093

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


[PATCH] D151696: [x86] Remove CPU_SPECIFIC* MACROs and add getCPUDispatchMangling

2023-07-03 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe added a comment.

gentle ping. If no objections, I'll merge this tomorrow.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151696

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


[PATCH] D153006: [clang][dataflow] Perform deep copies in copy and move operations.

2023-07-03 Thread Martin Böhme via Phabricator via cfe-commits
mboehme marked 3 inline comments as done.
mboehme added a comment.

https://reviews.llvm.org/D154339 has changes in response to post-commit 
comments.




Comment at: clang/include/clang/Analysis/FlowSensitive/RecordOps.h:26
+/// fields of record type. It also copies properties from the `StructValue`
+/// associated with `Dst` to the `StructValue` associated with `Src` (if these
+/// `StructValue`s exist).

gribozavr2 wrote:
> Shouldn't it go the other way, from Src to Dst?
Oops. Fixed in https://reviews.llvm.org/D154339.



Comment at: clang/include/clang/Analysis/FlowSensitive/RecordOps.h:53
+/// refer to the same storage location. If `StructValue`s are associated with
+/// `Loc1` and `Loc2`, it also compares the properties on those `StructValue`s.
+///

gribozavr2 wrote:
> Could you add a caveat that only 'true' return values from this function 
> matter?
> 
> That is, "false" means "might or might not be equal at runtime, we don't 
> know".
Good point. Done in https://reviews.llvm.org/D154339.



Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:391
+llvm::Error
+runDataflowReturnError(llvm::StringRef Code, VerifyResultsT VerifyResults,
+   DataflowAnalysisOptions Options,

gribozavr2 wrote:
> Could you change VerifyResultsT to a std::function (like in other overloads 
> above) so that the type signature is clear?
> 
> I'm also unsure about the name - why start a new overload set? It seems like 
> another variant of the checkDataflow() functions above.
> Could you change VerifyResultsT to a std::function (like in other overloads 
> above) so that the type signature is clear?

Done in https://reviews.llvm.org/D154339.

I could have sworn that when I moved this from TransferTest.cpp to here that I 
tried making this change and realized I couldn't for some reason. But obviously 
I was wrong.

> I'm also unsure about the name - why start a new overload set? It seems like 
> another variant of the checkDataflow() functions above.

This is really just moved from TransferTest.cpp -- and it's more closely 
related to the `runDataflow()` functions there and in the newly added 
RecordOps.cpp. (I can't call it `runDataflow()` because then it would differ 
only in return type from one of the functions in the overload set.)

Let's continue the discussion on https://reviews.llvm.org/D154339 if necessary.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153006

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


[PATCH] D154339: [clang][dataflow] Make `runDataflowReturnError()` a non-template function.

2023-07-03 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

It turns out this didn't need to be a template at all.

Likewise, change callers to they're non-template functions.

Also, correct / clarify some comments in RecordOps.h.

This is in response to post-commit comments on https://reviews.llvm.org/D153006.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154339

Files:
  clang/include/clang/Analysis/FlowSensitive/RecordOps.h
  clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -38,21 +38,28 @@
 using ::testing::NotNull;
 using ::testing::UnorderedElementsAre;
 
-template 
-void runDataflow(llvm::StringRef Code, VerifyResultsT VerifyResults,
- DataflowAnalysisOptions Options,
- LangStandard::Kind Std = LangStandard::lang_cxx17,
- llvm::StringRef TargetFun = "target") {
+void runDataflow(
+llvm::StringRef Code,
+std::function<
+void(const llvm::StringMap> &,
+ ASTContext &)>
+VerifyResults,
+DataflowAnalysisOptions Options,
+LangStandard::Kind Std = LangStandard::lang_cxx17,
+llvm::StringRef TargetFun = "target") {
   ASSERT_THAT_ERROR(
   runDataflowReturnError(Code, VerifyResults, Options, Std, TargetFun),
   llvm::Succeeded());
 }
 
-template 
-void runDataflow(llvm::StringRef Code, VerifyResultsT VerifyResults,
- LangStandard::Kind Std = LangStandard::lang_cxx17,
- bool ApplyBuiltinTransfer = true,
- llvm::StringRef TargetFun = "target") {
+void runDataflow(
+llvm::StringRef Code,
+std::function<
+void(const llvm::StringMap> &,
+ ASTContext &)>
+VerifyResults,
+LangStandard::Kind Std = LangStandard::lang_cxx17,
+bool ApplyBuiltinTransfer = true, llvm::StringRef TargetFun = "target") {
   runDataflow(Code, std::move(VerifyResults),
   {ApplyBuiltinTransfer ? BuiltinOptions{}
 : std::optional()},
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -386,40 +386,15 @@
 
 /// Runs dataflow on `Code` with a `NoopAnalysis` and calls `VerifyResults` to
 /// verify the results.
-template 
-llvm::Error
-runDataflowReturnError(llvm::StringRef Code, VerifyResultsT VerifyResults,
-   DataflowAnalysisOptions Options,
-   LangStandard::Kind Std = LangStandard::lang_cxx17,
-   llvm::StringRef TargetFun = "target") {
-  using ast_matchers::hasName;
-  llvm::SmallVector ASTBuildArgs = {
-  // -fnodelayed-template-parsing is the default everywhere but on Windows.
-  // Set it explicitly so that tests behave the same on Windows as on other
-  // platforms.
-  "-fsyntax-only", "-fno-delayed-template-parsing",
-  "-std=" +
-  std::string(LangStandard::getLangStandardForKind(Std).getName())};
-  AnalysisInputs AI(
-  Code, hasName(TargetFun),
-  [UseBuiltinModel = Options.BuiltinOpts.has_value()](ASTContext ,
-  Environment ) {
-return NoopAnalysis(
-C,
-DataflowAnalysisOptions{
-UseBuiltinModel ? Env.getDataflowAnalysisContext().getOptions()
-: std::optional()});
-  });
-  AI.ASTBuildArgs = ASTBuildArgs;
-  if (Options.BuiltinOpts)
-AI.BuiltinOptions = *Options.BuiltinOpts;
-  return checkDataflow(
-  std::move(AI),
-  /*VerifyResults=*/
-  [](
-  const llvm::StringMap> ,
-  const AnalysisOutputs ) { VerifyResults(Results, AO.ASTCtx); });
-}
+llvm::Error runDataflowReturnError(
+llvm::StringRef Code,
+std::function<
+void(const llvm::StringMap> &,
+ ASTContext &)>
+VerifyResults,
+DataflowAnalysisOptions Options,
+LangStandard::Kind Std = LangStandard::lang_cxx17,
+llvm::StringRef TargetFun = "target");
 
 /// Returns the `ValueDecl` for the given identifier.
 ///
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
===
--- 

[clang] d963420 - [Headers][X86] Ensure all AVX broadcast scalar load intrinsics are unaligned

2023-07-03 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2023-07-03T14:04:50+01:00
New Revision: d9634205d999439807a9f6c5a18be58ac1a55ced

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

LOG: [Headers][X86] Ensure all AVX broadcast scalar load intrinsics are 
unaligned

Similar to the existing _mm_load1_pd/_mm_loaddup_pd and broadcast vector loads, 
these intrinsic should ensure the loads are unaligned and not assume type 
alignment

Fixes #62325

Added: 


Modified: 
clang/lib/Headers/avxintrin.h
clang/test/CodeGen/X86/avx-builtins.c

Removed: 




diff  --git a/clang/lib/Headers/avxintrin.h b/clang/lib/Headers/avxintrin.h
index bd119220559e47..94fac5e6c9da47 100644
--- a/clang/lib/Headers/avxintrin.h
+++ b/clang/lib/Headers/avxintrin.h
@@ -3017,8 +3017,11 @@ _mm256_zeroupper(void)
 static __inline __m128 __DEFAULT_FN_ATTRS128
 _mm_broadcast_ss(float const *__a)
 {
-  float __f = *__a;
-  return __extension__ (__m128)(__v4sf){ __f, __f, __f, __f };
+  struct __mm_broadcast_ss_struct {
+float __f;
+  } __attribute__((__packed__, __may_alias__));
+  float __f = ((const struct __mm_broadcast_ss_struct*)__a)->__f;
+  return __extension__ (__m128){ __f, __f, __f, __f };
 }
 
 /// Loads a scalar double-precision floating point value from the
@@ -3036,7 +3039,10 @@ _mm_broadcast_ss(float const *__a)
 static __inline __m256d __DEFAULT_FN_ATTRS
 _mm256_broadcast_sd(double const *__a)
 {
-  double __d = *__a;
+  struct __mm256_broadcast_sd_struct {
+double __d;
+  } __attribute__((__packed__, __may_alias__));
+  double __d = ((const struct __mm256_broadcast_sd_struct*)__a)->__d;
   return __extension__ (__m256d)(__v4df){ __d, __d, __d, __d };
 }
 
@@ -3055,7 +3061,10 @@ _mm256_broadcast_sd(double const *__a)
 static __inline __m256 __DEFAULT_FN_ATTRS
 _mm256_broadcast_ss(float const *__a)
 {
-  float __f = *__a;
+  struct __mm256_broadcast_ss_struct {
+float __f;
+  } __attribute__((__packed__, __may_alias__));
+  float __f = ((const struct __mm256_broadcast_ss_struct*)__a)->__f;
   return __extension__ (__m256)(__v8sf){ __f, __f, __f, __f, __f, __f, __f, 
__f };
 }
 

diff  --git a/clang/test/CodeGen/X86/avx-builtins.c 
b/clang/test/CodeGen/X86/avx-builtins.c
index 761ab6e9eb2cb0..b68d192051b9bf 100644
--- a/clang/test/CodeGen/X86/avx-builtins.c
+++ b/clang/test/CodeGen/X86/avx-builtins.c
@@ -99,7 +99,7 @@ __m256 test_mm256_broadcast_ps(__m128* A) {
 
 __m256d test_mm256_broadcast_sd(double* A) {
   // CHECK-LABEL: test_mm256_broadcast_sd
-  // CHECK: load double, ptr %{{.*}}
+  // CHECK: load double, ptr %{{.*}}, align 1{{$}}
   // CHECK: insertelement <4 x double> undef, double %{{.*}}, i32 0
   // CHECK: insertelement <4 x double> %{{.*}}, double %{{.*}}, i32 1
   // CHECK: insertelement <4 x double> %{{.*}}, double %{{.*}}, i32 2
@@ -109,7 +109,7 @@ __m256d test_mm256_broadcast_sd(double* A) {
 
 __m128 test_mm_broadcast_ss(float* A) {
   // CHECK-LABEL: test_mm_broadcast_ss
-  // CHECK: load float, ptr %{{.*}}
+  // CHECK: load float, ptr %{{.*}}, align 1{{$}}
   // CHECK: insertelement <4 x float> undef, float %{{.*}}, i32 0
   // CHECK: insertelement <4 x float> %{{.*}}, float %{{.*}}, i32 1
   // CHECK: insertelement <4 x float> %{{.*}}, float %{{.*}}, i32 2
@@ -119,7 +119,7 @@ __m128 test_mm_broadcast_ss(float* A) {
 
 __m256 test_mm256_broadcast_ss(float* A) {
   // CHECK-LABEL: test_mm256_broadcast_ss
-  // CHECK: load float, ptr %{{.*}}
+  // CHECK: load float, ptr %{{.*}}, align 1{{$}}
   // CHECK: insertelement <8 x float> undef, float %{{.*}}, i32 0
   // CHECK: insertelement <8 x float> %{{.*}}, float %{{.*}}, i32 1
   // CHECK: insertelement <8 x float> %{{.*}}, float %{{.*}}, i32 2



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


[PATCH] D154329: [lldb] Replace llvm::writeFileAtomically with llvm::writeToOutput API.

2023-07-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: lldb/tools/lldb-server/lldb-platform.cpp:112
 return Status("Failed to atomically write file %s",
   file_spec.GetPath().c_str());
   return status;

avl wrote:
> probably, it would be better to add error text here?
> 
> ```
> return Status("Failed to atomically write file %s: %s",
>   file_spec.GetPath().c_str(), 
> toString(std::move(Err)).c_str());
> ```
good idea.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154329

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


[PATCH] D154329: [lldb] Replace llvm::writeFileAtomically with llvm::writeToOutput API.

2023-07-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 536735.
hokein marked an inline comment as done.
hokein added a comment.

address a comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154329

Files:
  lldb/tools/lldb-server/lldb-platform.cpp


Index: lldb/tools/lldb-server/lldb-platform.cpp
===
--- lldb/tools/lldb-server/lldb-platform.cpp
+++ lldb/tools/lldb-server/lldb-platform.cpp
@@ -22,7 +22,6 @@
 #include 
 
 #include "llvm/Support/FileSystem.h"
-#include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -103,38 +102,15 @@
 return Status("Failed to create directory %s: %s",
   temp_file_spec.GetPath().c_str(), error.AsCString());
 
-  llvm::SmallString<64> temp_file_path;
-  temp_file_spec.AppendPathComponent("port-file.%%");
-  temp_file_path = temp_file_spec.GetPath();
-
   Status status;
-  if (auto Err =
-  handleErrors(llvm::writeFileAtomically(
-   temp_file_path, file_spec.GetPath(), socket_id),
-   [, _spec](const AtomicFileWriteError ) {
- std::string ErrorMsgBuffer;
- llvm::raw_string_ostream S(ErrorMsgBuffer);
- E.log(S);
-
- switch (E.Error) {
- case atomic_write_error::failed_to_create_uniq_file:
-   status = Status("Failed to create temp file: %s",
-   ErrorMsgBuffer.c_str());
-   break;
- case atomic_write_error::output_stream_error:
-   status = Status("Failed to write to port file.");
-   break;
- case atomic_write_error::failed_to_rename_temp_file:
-   status = Status("Failed to rename file %s to %s: 
%s",
-   ErrorMsgBuffer.c_str(),
-   file_spec.GetPath().c_str(),
-   ErrorMsgBuffer.c_str());
-   break;
- }
-   })) {
-return Status("Failed to atomically write file %s",
-  file_spec.GetPath().c_str());
-  }
+  if (auto Err = llvm::writeToOutput(file_spec.GetPath(),
+ [_id](llvm::raw_ostream ) {
+   OS << socket_id;
+   return llvm::Error::success();
+ }))
+return Status("Failed to atomically write file %s: %s",
+  file_spec.GetPath().c_str(),
+  llvm::toString(std::move(Err)).c_str());
   return status;
 }
 


Index: lldb/tools/lldb-server/lldb-platform.cpp
===
--- lldb/tools/lldb-server/lldb-platform.cpp
+++ lldb/tools/lldb-server/lldb-platform.cpp
@@ -22,7 +22,6 @@
 #include 
 
 #include "llvm/Support/FileSystem.h"
-#include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -103,38 +102,15 @@
 return Status("Failed to create directory %s: %s",
   temp_file_spec.GetPath().c_str(), error.AsCString());
 
-  llvm::SmallString<64> temp_file_path;
-  temp_file_spec.AppendPathComponent("port-file.%%");
-  temp_file_path = temp_file_spec.GetPath();
-
   Status status;
-  if (auto Err =
-  handleErrors(llvm::writeFileAtomically(
-   temp_file_path, file_spec.GetPath(), socket_id),
-   [, _spec](const AtomicFileWriteError ) {
- std::string ErrorMsgBuffer;
- llvm::raw_string_ostream S(ErrorMsgBuffer);
- E.log(S);
-
- switch (E.Error) {
- case atomic_write_error::failed_to_create_uniq_file:
-   status = Status("Failed to create temp file: %s",
-   ErrorMsgBuffer.c_str());
-   break;
- case atomic_write_error::output_stream_error:
-   status = Status("Failed to write to port file.");
-   break;
- case atomic_write_error::failed_to_rename_temp_file:
-   status = Status("Failed to rename file %s to %s: %s",
-   ErrorMsgBuffer.c_str(),
-   file_spec.GetPath().c_str(),
-   ErrorMsgBuffer.c_str());
-   break;
- }
- 

[PATCH] D154329: [lldb] Replace llvm::writeFileAtomically with llvm::writeToOutput API.

2023-07-03 Thread Alexey Lapshin via Phabricator via cfe-commits
avl added inline comments.



Comment at: lldb/tools/lldb-server/lldb-platform.cpp:112
 return Status("Failed to atomically write file %s",
   file_spec.GetPath().c_str());
   return status;

probably, it would be better to add error text here?

```
return Status("Failed to atomically write file %s: %s",
  file_spec.GetPath().c_str(), 
toString(std::move(Err)).c_str());
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154329

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


[PATCH] D153883: [Clang][OpenMP] Delay emission of __kmpc_alloc_shared for escaped VLAs

2023-07-03 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/CodeGen/CGDecl.cpp:1606
+  CGOpenMPRuntimeGPU  =
+  *(static_cast(()));
+  if (RT.isDelayedVariableLengthDecl(*this, )) {

1. use `static_cast(CGM.getOpenMPRuntime())`
2. It will crash if your device is not GPU. Better to make `getKmpcAllocShared` 
and `getKmpcFreeShared` virtual (just like `isDelayedVariableLengthDecl`) in 
base CGOpenMPRuntime, since it may be required not only for GPU-based devices.



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:261
+  else
+DelayedVariableLengthDecls.insert(VD);
+} else

Yep, this is what I meant. The only question: do you really need this new 
parameter? CGF.CapturedStmtInfo provides the list of captures and you can try 
to use it.



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:1100-1104
+// Check if the size of the VLA is available at this point i.e. check that
+// it has been emitted already. If not available then skip it and use
+// delayed emission of __kmpc_alloc_shared.
+if (llvm::is_contained(I->getSecond().DelayedVariableLengthDecls, VD))
+  continue;

Do you still need this check?


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

https://reviews.llvm.org/D153883

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


[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:11405-11406
+  llvm::OpenMPIRBuilder  = CGM.getOpenMPRuntime().getOMPBuilder();
+  const OMPDependClause *DepC = dyn_cast(C);
+  const OMPDoacrossClause *DoC = dyn_cast(C);
+  if ((DoC && DoC->getDependenceType() == OMPC_DOACROSS_source) ||

1. const auto *
2. Can you try torework it to make it more C++-ish? Use template deduction to 
avoid runtime dyn_casts.
e.g. something like:
```
namespace {
template 
class OMPDoacrossKind {
public:
bool isSink(const T *) {return false;}
}
}
template <>
class OMPDoacrossKInd {
public:
bool isSink(const OMPDependClause* C) {return C->getDependenceType();}
}
...
```
and use `if (OMPDoacrossKInd::isSink(C)) RTLFn = ...` and same for `Source`



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5859-5868
+  const auto DOC = dyn_cast(C);
+  const auto DC = dyn_cast(C);
+  bool IsDependSource = false;
+  if ((DC && DC->getDependencyKind() == OMPC_DEPEND_source) ||
+  (DOC && DOC->getDependenceType() == OMPC_DOACROSS_source))
+IsDependSource = true;
+  CGF.Builder.restoreIP(

Same, use template-based analysis instead of runtime-based.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

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


[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

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

Thank you for this! LGTM. but can you also be sure to update this table: 
https://github.com/llvm/llvm-project/blob/main/clang/docs/LanguageExtensions.rst?plain=1#L1429


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154334

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


[PATCH] D152356: [clang][ExtractAPI] Add --emit-symbol-graph option

2023-07-03 Thread Ankur Saini 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 rG8e9145e43142: [clang][ExtractAPI] Add --emit-symbol-graph 
option (authored by Arsenic).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152356

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/ExtractAPI/ExtractAPIActionBase.h
  clang/include/clang/ExtractAPI/FrontendActions.h
  clang/include/clang/Frontend/FrontendOptions.h
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  clang/test/ExtractAPI/emit-symbol-graph/multi_file.c
  clang/test/ExtractAPI/emit-symbol-graph/single_file.c

Index: clang/test/ExtractAPI/emit-symbol-graph/single_file.c
===
--- /dev/null
+++ clang/test/ExtractAPI/emit-symbol-graph/single_file.c
@@ -0,0 +1,213 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%{/t:regex_replacement}@g" \
+// RUN: %t/reference.output.json.in >> %t/reference.output.json
+// RUN: %clang_cc1 %t/main.c --emit-symbol-graph=%t/SymbolGraphs --product-name=basicfile -triple=x86_64-apple-macosx12.0.0
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/SymbolGraphs/main.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+// CHECK-NOT: error:
+// CHECK-NOT: warning:
+
+//--- main.c
+#define TESTMACRO1 2
+#define TESTMARCRO2 5
+
+int main ()
+{
+  return 0;
+}
+
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "basicfile",
+"platform": {
+  "architecture": "x86_64",
+  "operatingSystem": {
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationships": [],
+  "symbols": [
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:I",
+  "spelling": "int"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "main"
+},
+{
+  "kind": "text",
+  "spelling": "();"
+}
+  ],
+  "functionSignature": {
+"returns": [
+  {
+"kind": "typeIdentifier",
+"preciseIdentifier": "c:I",
+"spelling": "int"
+  }
+]
+  },
+  "identifier": {
+"interfaceLanguage": "c",
+"precise": "c:@F@main"
+  },
+  "kind": {
+"displayName": "Function",
+"identifier": "c.func"
+  },
+  "location": {
+"position": {
+  "character": 5,
+  "line": 4
+},
+"uri": "file://INPUT_DIR/main.c"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "main"
+  }
+],
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "main"
+  }
+],
+"title": "main"
+  },
+  "pathComponents": [
+"main"
+  ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "#define"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "TESTMACRO1"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "c",
+"precise": "c:main.c@8@macro@TESTMACRO1"
+  },
+  "kind": {
+"displayName": "Macro",
+"identifier": "c.macro"
+  },
+  "location": {
+"position": {
+  "character": 9,
+  "line": 1
+},
+"uri": "file://INPUT_DIR/main.c"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "TESTMACRO1"
+  }
+],
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "TESTMACRO1"
+  }
+],
+"title": "TESTMACRO1"
+  },
+  "pathComponents": [
+"TESTMACRO1"
+  ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "#define"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "TESTMARCRO2"
+}
+  ],
+  "identifier": {
+

[clang] 8e9145e - [clang][ExtractAPI] Add --emit-symbol-graph option

2023-07-03 Thread via cfe-commits

Author: Ankur
Date: 2023-07-03T17:32:30+05:30
New Revision: 8e9145e4314202b960dd883e6a7b21707ed5c176

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

LOG: [clang][ExtractAPI] Add --emit-symbol-graph option

Add new --emit-symbol-graph= option which generates ExtractAPI symbol
graph information of .c/.m files on regular compilation job and put them in
the provided "DIR" directory.

Reviewed By: dang

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

Added: 
clang/include/clang/ExtractAPI/ExtractAPIActionBase.h
clang/test/ExtractAPI/emit-symbol-graph/multi_file.c
clang/test/ExtractAPI/emit-symbol-graph/single_file.c

Modified: 
clang/include/clang/Driver/Options.td
clang/include/clang/ExtractAPI/FrontendActions.h
clang/include/clang/Frontend/FrontendOptions.h
clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c3242ac2a804b8..f74a589d1baaa6 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1198,6 +1198,9 @@ def extract_api : Flag<["-"], "extract-api">, 
Flags<[CC1Option]>, Group;
 def product_name_EQ: Joined<["--"], "product-name=">, Flags<[CC1Option]>,
   MarshallingInfoString>;
+def emit_symbol_graph_EQ: JoinedOrSeparate<["--"], "emit-symbol-graph=">, 
Flags<[CC1Option]>,
+HelpText<"Generate Extract API information as a side effect of 
compilation.">,
+MarshallingInfoString>;
 def extract_api_ignores_EQ: CommaJoined<["--"], "extract-api-ignores=">, 
Flags<[CC1Option]>,
 HelpText<"Comma separated list of files containing a new line separated 
list of API symbols to ignore when extracting API information.">,
 MarshallingInfoStringVector>;

diff  --git a/clang/include/clang/ExtractAPI/ExtractAPIActionBase.h 
b/clang/include/clang/ExtractAPI/ExtractAPIActionBase.h
new file mode 100644
index 00..ac4f391db5f14a
--- /dev/null
+++ b/clang/include/clang/ExtractAPI/ExtractAPIActionBase.h
@@ -0,0 +1,54 @@
+//===- ExtractAPI/ExtractAPIActionBase.h -*- C++
+//-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+///
+/// \file
+/// This file defines the ExtractAPIActionBase class.
+///
+//===--===//
+
+#ifndef LLVM_CLANG_EXTRACTAPI_ACTION_BASE_H
+#define LLVM_CLANG_EXTRACTAPI_ACTION_BASE_H
+
+#include "clang/ExtractAPI/API.h"
+#include "clang/ExtractAPI/APIIgnoresList.h"
+
+namespace clang {
+
+/// Base class to be used by front end actions to generate ExtarctAPI info
+///
+/// Deriving from this class equips an action with all the necessary tools to
+/// generate ExractAPI information in form of symbol-graphs
+class ExtractAPIActionBase {
+protected:
+  /// A representation of the APIs this action extracts.
+  std::unique_ptr API;
+
+  /// A stream to the output file of this action.
+  std::unique_ptr OS;
+
+  /// The product this action is extracting API information for.
+  std::string ProductName;
+
+  /// The synthesized input buffer that contains all the provided input header
+  /// files.
+  std::unique_ptr Buffer;
+
+  /// The list of symbols to ignore during serialization
+  extractapi::APIIgnoresList IgnoresList;
+
+  /// Implements EndSourceFileAction for Symbol-Graph generation
+  ///
+  /// Use the serializer to generate output symbol graph files from
+  /// the information gathered during the execution of Action.
+  void ImplEndSourceFileAction();
+};
+
+} // namespace clang
+
+#endif // LLVM_CLANG_EXTRACTAPI_ACTION_BASE_H

diff  --git a/clang/include/clang/ExtractAPI/FrontendActions.h 
b/clang/include/clang/ExtractAPI/FrontendActions.h
index e946b33abbd984..c67864aac9af9c 100644
--- a/clang/include/clang/ExtractAPI/FrontendActions.h
+++ b/clang/include/clang/ExtractAPI/FrontendActions.h
@@ -7,41 +7,27 @@
 
//===--===//
 ///
 /// \file
-/// This file defines the ExtractAPIAction frontend action.
+/// This file defines the ExtractAPIAction and WrappingExtractAPIAction 
frontend
+/// actions.
 ///
 
//===--===//
 
 #ifndef LLVM_CLANG_EXTRACTAPI_FRONTEND_ACTIONS_H
 #define LLVM_CLANG_EXTRACTAPI_FRONTEND_ACTIONS_H
 
-#include "clang/ExtractAPI/API.h"
-#include "clang/ExtractAPI/APIIgnoresList.h"
+#include 

[PATCH] D154335: [clang][tooling] Fix early termination when there are nested expansions

2023-07-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: sammccall.
Herald added a subscriber: arphaman.
Herald added a project: All.
kadircet requested review of this revision.
Herald added projects: clang, clang-tools-extra.
Herald added a subscriber: cfe-commits.

This also does some cleanups, I am happy to undo them (or send as
separate patches):

- Change the early exit to stop only once we hit an expansion inside the main 
file, to make sure we keep following the nested expansions.
- Add more tests to cover all the cases mentioned in the implementation
- Drop the adjustments for prev/next tokens. We do the final checks based on 
the expansion locations anyway, so any intermediate mapping was a no-op.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154335

Files:
  clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp
  clang/lib/Tooling/Syntax/Tokens.cpp
  clang/unittests/Tooling/Syntax/TokensTest.cpp

Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -769,12 +769,15 @@
   // Critical cases for mapping of Prev/Next in spelledForExpandedSlow.
   recordTokens(R"cpp(
 #define ID(X) X
-ID(prev ID(good))
+ID(prev good)
+ID(prev ID(good2))
 #define LARGE ID(prev ID(bad))
 LARGE
   )cpp");
   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
   ValueIs(SameRange(findSpelled("good";
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good2")),
+  ValueIs(SameRange(findSpelled("good2";
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), std::nullopt);
 
   recordTokens(R"cpp(
@@ -785,19 +788,32 @@
 LARGE
   )cpp");
   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
-ValueIs(SameRange(findSpelled("good";
+  ValueIs(SameRange(findSpelled("good";
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), std::nullopt);
 
   recordTokens(R"cpp(
 #define ID(X) X
 #define ID2(X, Y) X Y
-ID2(prev, ID(good))
+ID2(prev, good)
+ID2(prev, ID(good2))
 #define LARGE ID2(prev, bad)
 LARGE
   )cpp");
   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
-ValueIs(SameRange(findSpelled("good";
+  ValueIs(SameRange(findSpelled("good";
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good2")),
+  ValueIs(SameRange(findSpelled("good2";
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), std::nullopt);
+
+  // Prev from macro body.
+  recordTokens(R"cpp(
+#define ID(X) X
+#define ID2(X, Y) X prev ID(Y)
+ID2(not_prev, good)
+  )cpp");
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
+  ValueIs(SameRange(findSpelled("good";
+  EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("prev good")), std::nullopt);
 }
 
 TEST_F(TokenBufferTest, ExpandedTokensForRange) {
Index: clang/lib/Tooling/Syntax/Tokens.cpp
===
--- clang/lib/Tooling/Syntax/Tokens.cpp
+++ clang/lib/Tooling/Syntax/Tokens.cpp
@@ -103,66 +103,13 @@
 // The token `a` is wrapped in 4 arg-expansions, we only want to unwrap 2.
 // We distinguish them by whether the macro expands into the target file.
 // Fortunately, the target file ones will always appear first.
-auto  =
-SM.getSLocEntry(SM.getFileID(ExpFirst.getExpansionLocStart()))
-.getExpansion();
-if (ExpMacro.getExpansionLocStart().isMacroID())
+auto ExpFileID = SM.getFileID(ExpFirst.getExpansionLocStart());
+if (ExpFileID == TargetFile)
   break;
 // Replace each endpoint with its spelling inside the macro arg.
 // (This is getImmediateSpellingLoc without repeating lookups).
 First = ExpFirst.getSpellingLoc().getLocWithOffset(DecFirst.second);
 Last = ExpLast.getSpellingLoc().getLocWithOffset(DecLast.second);
-
-// Now: how do we adjust the previous/next bounds? Three cases:
-// A) If they are also part of the same macro arg, we translate them too.
-//   This will ensure that we don't select any macros nested within the
-//   macro arg that cover extra tokens. Critical case:
-//  #define ID(X) X
-//  ID(prev target) // selecting 'target' succeeds
-//  #define LARGE ID(prev target)
-//  LARGE // selecting 'target' fails.
-// B) They are not in the macro at all, then their expansion range is a
-//sibling to it, and we can safely substitute that.
-//  #define PREV prev
-//  #define ID(X) X
-//  PREV ID(target) // selecting 'target' succeeds.
-//  #define LARGE PREV ID(target)
-//  LARGE // selecting 'target' fails.
-// C) They are in a different arg of this macro, or the macro body.
-//Now selecting the whole macro 

[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon updated this revision to Diff 536715.
Fznamznon added a comment.

Fix test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154334

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Features.def
  clang/test/Lexer/has_extension_cxx.cpp


Index: clang/test/Lexer/has_extension_cxx.cpp
===
--- clang/test/Lexer/has_extension_cxx.cpp
+++ clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@
 int c_generic_selections();
 #endif
 
+// CHECK: has_default_function_template_args
+#if __has_extension(cxx_default_function_template_args)
+int has_default_function_template_args();
+#endif
+
+// CHECK: has_defaulted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_defaulted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/Lexer/has_extension_cxx.cpp
===
--- clang/test/Lexer/has_extension_cxx.cpp
+++ clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@
 int c_generic_selections();
 #endif
 
+// CHECK: has_default_function_template_args
+#if __has_extension(cxx_default_function_template_args)
+int has_default_function_template_args();
+#endif
+
+// CHECK: has_defaulted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_defaulted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon created this revision.
Herald added a project: All.
Fznamznon requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Add `__has_extension (cxx_defaulted_functions)` and
`__has_extension (cxx_defaulted_functions)` since they are accepted in
C++98 mode as extensions.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154334

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Features.def
  clang/test/Lexer/has_extension_cxx.cpp


Index: clang/test/Lexer/has_extension_cxx.cpp
===
--- clang/test/Lexer/has_extension_cxx.cpp
+++ clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@
 int c_generic_selections();
 #endif
 
+// CHECK: has_deleted_functions
+#if __has_extension(cxx_default_function_template_args)
+int has_deleted_functions();
+#endif
+
+// CHECK: has_deleted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_deleted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/Lexer/has_extension_cxx.cpp
===
--- clang/test/Lexer/has_extension_cxx.cpp
+++ clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@
 int c_generic_selections();
 #endif
 
+// CHECK: has_deleted_functions
+#if __has_extension(cxx_default_function_template_args)
+int has_deleted_functions();
+#endif
+
+// CHECK: has_deleted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_deleted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153228: [clang-format] Fixed bad performance with enabled qualifier fixer.

2023-07-03 Thread MyDeveloperDay via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG899c86779440: [clang-format] Fixed bad performance with 
enabled qualifier fixer. (authored by Sedeniono, committed by MyDeveloperDay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153228

Files:
  clang/lib/Format/Format.cpp
  clang/lib/Format/QualifierAlignmentFixer.cpp
  clang/lib/Format/QualifierAlignmentFixer.h
  clang/unittests/Format/QualifierFixerTest.cpp

Index: clang/unittests/Format/QualifierFixerTest.cpp
===
--- clang/unittests/Format/QualifierFixerTest.cpp
+++ clang/unittests/Format/QualifierFixerTest.cpp
@@ -1016,8 +1016,8 @@
   std::vector Left;
   std::vector Right;
   std::vector ConfiguredTokens;
-  QualifierAlignmentFixer::PrepareLeftRightOrdering(Style.QualifierOrder, Left,
-Right, ConfiguredTokens);
+  prepareLeftRightOrderingForQualifierAlignmentFixer(Style.QualifierOrder, Left,
+ Right, ConfiguredTokens);
 
   EXPECT_EQ(Left.size(), (size_t)2);
   EXPECT_EQ(Right.size(), (size_t)2);
@@ -1181,10 +1181,12 @@
   Style.QualifierAlignment = FormatStyle::QAS_Custom;
   Style.QualifierOrder = {"static", "const", "type"};
 
-  ReplacementCount = 0;
-  EXPECT_EQ(ReplacementCount, 0);
   verifyFormat("static const uint32 foo[] = {0, 31};", Style);
+  EXPECT_EQ(ReplacementCount, 0);
+
   verifyFormat("#define MACRO static const", Style);
+  EXPECT_EQ(ReplacementCount, 0);
+
   verifyFormat("using sc = static const", Style);
   EXPECT_EQ(ReplacementCount, 0);
 }
Index: clang/lib/Format/QualifierAlignmentFixer.h
===
--- clang/lib/Format/QualifierAlignmentFixer.h
+++ clang/lib/Format/QualifierAlignmentFixer.h
@@ -25,32 +25,13 @@
 const Environment &)>
 AnalyzerPass;
 
-class QualifierAlignmentFixer : public TokenAnalyzer {
-  // Left to Right ordering requires multiple passes
-  SmallVector Passes;
-  StringRef 
-  ArrayRef Ranges;
-  unsigned FirstStartColumn;
-  unsigned NextStartColumn;
-  unsigned LastStartColumn;
-  StringRef FileName;
+void addQualifierAlignmentFixerPasses(const FormatStyle ,
+  SmallVectorImpl );
 
-public:
-  QualifierAlignmentFixer(const Environment , const FormatStyle ,
-  StringRef , ArrayRef Ranges,
-  unsigned FirstStartColumn, unsigned NextStartColumn,
-  unsigned LastStartColumn, StringRef FileName);
-
-  std::pair
-  analyze(TokenAnnotator ,
-  SmallVectorImpl ,
-  FormatTokenLexer ) override;
-
-  static void PrepareLeftRightOrdering(const std::vector ,
-   std::vector ,
-   std::vector ,
-   std::vector );
-};
+void prepareLeftRightOrderingForQualifierAlignmentFixer(
+const std::vector , std::vector ,
+std::vector ,
+std::vector );
 
 class LeftRightQualifierAlignmentFixer : public TokenAnalyzer {
   std::string Qualifier;
Index: clang/lib/Format/QualifierAlignmentFixer.cpp
===
--- clang/lib/Format/QualifierAlignmentFixer.cpp
+++ clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -25,18 +25,13 @@
 namespace clang {
 namespace format {
 
-QualifierAlignmentFixer::QualifierAlignmentFixer(
-const Environment , const FormatStyle , StringRef ,
-ArrayRef Ranges, unsigned FirstStartColumn,
-unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName)
-: TokenAnalyzer(Env, Style), Code(Code), Ranges(Ranges),
-  FirstStartColumn(FirstStartColumn), NextStartColumn(NextStartColumn),
-  LastStartColumn(LastStartColumn), FileName(FileName) {
+void addQualifierAlignmentFixerPasses(const FormatStyle ,
+  SmallVectorImpl ) {
   std::vector LeftOrder;
   std::vector RightOrder;
   std::vector ConfiguredQualifierTokens;
-  PrepareLeftRightOrdering(Style.QualifierOrder, LeftOrder, RightOrder,
-   ConfiguredQualifierTokens);
+  prepareLeftRightOrderingForQualifierAlignmentFixer(
+  Style.QualifierOrder, LeftOrder, RightOrder, ConfiguredQualifierTokens);
 
   // Handle the left and right alignment separately.
   for (const auto  : LeftOrder) {
@@ -59,51 +54,6 @@
   }
 }
 
-std::pair QualifierAlignmentFixer::analyze(
-TokenAnnotator & /*Annotator*/,
-SmallVectorImpl & /*AnnotatedLines*/,
-FormatTokenLexer & /*Tokens*/) {
-  auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
-   NextStartColumn, LastStartColumn);
-  if (!Env)
-return {};
-  std::optional CurrentCode;
-  tooling::Replacements Fixes;
-  for (size_t 

[clang] 899c867 - [clang-format] Fixed bad performance with enabled qualifier fixer.

2023-07-03 Thread via cfe-commits

Author: Sedenion
Date: 2023-07-03T11:54:33+01:00
New Revision: 899c86779440dca84085fb53a1fbba6c5aa5a3b6

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

LOG: [clang-format] Fixed bad performance with enabled qualifier fixer.

This fixes github issue #57117: If the "QualifierAlignment"
option of clang-format is set to anything else but "Leave", the
"QualifierAlignmentFixer" pass gets enabled. This pass scales
quadratically with the number of preprocessor branches, i.e.
with the number of elements in TokenAnalyzer::UnwrappedLines.
The reason is that QualifierAlignmentFixer::process() generates
the UnwrappedLines, but then QualifierAlignmentFixer::analyze()
calls LeftRightQualifierAlignmentFixer::process() several times
(once for each qualifier) which again each time generates the
UnwrappedLines.

This commit gets rid of this double loop by registering the
individual LeftRightQualifierAlignmentFixer passes directly in
the top most container of passes (local variable "Passes" in
reformat()).
With this change, the original example in the github issue #57117
now takes only around 3s instead of >300s to format.

Since QualifierAlignmentFixer::analyze() got deleted, we also
no longer have the code with the NonNoOpFixes. This causes
replacements that end up not changing anything to appear in the
list of final replacements. There is a unit test to check that
this does not happen: QualifierFixerTest.NoOpQualifierReplacements.
However, it got broken at some point in time. So this commit
fixes the test. To keep the behavior that no no-op replacements
should appear from the qualifier fixer, the corresponding code
from QualifierAlignmentFixer::analyze() was moved to the top
reformat() function. Thus, is now done for **every** replacement
of every formatting pass. If no-op replacements are a problem
for the qualifier fixer, then it seems to be a good idea to
filter them out always.

See
https://github.com/llvm/llvm-project/issues/57117#issuecomment-1546716934
for some more details.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Added: 


Modified: 
clang/lib/Format/Format.cpp
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/lib/Format/QualifierAlignmentFixer.h
clang/unittests/Format/QualifierFixerTest.cpp

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 5fee5e6c261a93..fd46dfec21d8de 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3472,21 +3472,16 @@ reformat(const FormatStyle , StringRef Code,
   typedef std::function(
   const Environment &)>
   AnalyzerPass;
-  SmallVector Passes;
+
+  SmallVector Passes;
 
   Passes.emplace_back([&](const Environment ) {
 return IntegerLiteralSeparatorFixer().process(Env, Expanded);
   });
 
   if (Style.isCpp()) {
-if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
-  Passes.emplace_back([&](const Environment ) {
-return QualifierAlignmentFixer(Env, Expanded, Code, Ranges,
-   FirstStartColumn, NextStartColumn,
-   LastStartColumn, FileName)
-.process();
-  });
-}
+if (Style.QualifierAlignment != FormatStyle::QAS_Leave)
+  addQualifierAlignmentFixerPasses(Expanded, Passes);
 
 if (Style.InsertBraces) {
   FormatStyle S = Expanded;
@@ -3571,6 +3566,24 @@ reformat(const FormatStyle , StringRef Code,
 }
   }
 
+  if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
+// Don't make replacements that replace nothing. QualifierAlignment can
+// produce them if one of its early passes changes e.g. `const volatile` to
+// `volatile const` and then a later pass changes it back again.
+tooling::Replacements NonNoOpFixes;
+for (const tooling::Replacement  : Fixes) {
+  StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
+  if (!OriginalCode.equals(Fix.getReplacementText())) {
+auto Err = NonNoOpFixes.add(Fix);
+if (Err) {
+  llvm::errs() << "Error adding replacements : "
+   << llvm::toString(std::move(Err)) << "\n";
+}
+  }
+}
+Fixes = std::move(NonNoOpFixes);
+  }
+
   return {Fixes, Penalty};
 }
 } // namespace internal

diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index ff54fb75b3dd98..2e3b21cfda79eb 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -25,18 +25,13 @@
 namespace clang {
 namespace format {
 
-QualifierAlignmentFixer::QualifierAlignmentFixer(
-const Environment , const FormatStyle , StringRef ,
-ArrayRef 

  1   2   >