[PATCH] D99484: [cmake] Use `GNUInstallDirs` to support custom installation dirs.

2022-01-10 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 updated this revision to Diff 398857.
Ericson2314 added a comment.

Fix conflicts, one more thing for openmp


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D99484

Files:
  clang-tools-extra/CMakeLists.txt
  clang-tools-extra/clang-doc/tool/CMakeLists.txt
  clang-tools-extra/clang-include-fixer/find-all-symbols/tool/CMakeLists.txt
  clang-tools-extra/clang-include-fixer/tool/CMakeLists.txt
  clang-tools-extra/clang-tidy/CMakeLists.txt
  clang-tools-extra/clang-tidy/tool/CMakeLists.txt
  clang-tools-extra/modularize/CMakeLists.txt
  clang/CMakeLists.txt
  clang/cmake/modules/AddClang.cmake
  clang/tools/c-index-test/CMakeLists.txt
  clang/tools/clang-format/CMakeLists.txt
  clang/tools/clang-nvlink-wrapper/CMakeLists.txt
  clang/tools/clang-rename/CMakeLists.txt
  clang/tools/libclang/CMakeLists.txt
  clang/tools/scan-build-py/CMakeLists.txt
  clang/tools/scan-build/CMakeLists.txt
  clang/tools/scan-view/CMakeLists.txt
  clang/utils/hmaptool/CMakeLists.txt
  compiler-rt/cmake/base-config-ix.cmake
  libc/CMakeLists.txt
  libcxx/CMakeLists.txt
  libcxx/cmake/Modules/HandleLibCXXABI.cmake
  libcxxabi/CMakeLists.txt
  libunwind/CMakeLists.txt
  llvm/cmake/modules/LLVMInstallSymlink.cmake
  mlir/CMakeLists.txt
  mlir/cmake/modules/AddMLIR.cmake
  openmp/CMakeLists.txt
  openmp/libompd/src/CMakeLists.txt
  openmp/runtime/src/CMakeLists.txt
  openmp/tools/multiplex/CMakeLists.txt
  polly/CMakeLists.txt
  polly/cmake/CMakeLists.txt
  polly/lib/External/CMakeLists.txt
  pstl/CMakeLists.txt

Index: pstl/CMakeLists.txt
===
--- pstl/CMakeLists.txt
+++ pstl/CMakeLists.txt
@@ -7,6 +7,8 @@
 #===--===##
 cmake_minimum_required(VERSION 3.13.4)
 
+include(GNUInstallDirs)
+
 set(PARALLELSTL_VERSION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/include/pstl/internal/pstl_config.h")
 file(STRINGS "${PARALLELSTL_VERSION_FILE}" PARALLELSTL_VERSION_SOURCE REGEX "#define _PSTL_VERSION .*$")
 string(REGEX REPLACE "#define _PSTL_VERSION (.*)$" "\\1" PARALLELSTL_VERSION_SOURCE "${PARALLELSTL_VERSION_SOURCE}")
@@ -90,10 +92,10 @@
   "${CMAKE_CURRENT_BINARY_DIR}/ParallelSTLConfigVersion.cmake"
 DESTINATION lib/cmake/ParallelSTL)
 install(DIRECTORY include/
-DESTINATION include
+DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
 PATTERN "*.in" EXCLUDE)
 install(FILES "${PSTL_CONFIG_SITE_PATH}"
-DESTINATION include)
+DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
 
 add_custom_target(install-pstl
   COMMAND "${CMAKE_COMMAND}" -P "${PROJECT_BINARY_DIR}/cmake_install.cmake" -DCOMPONENT=ParallelSTL)
Index: polly/lib/External/CMakeLists.txt
===
--- polly/lib/External/CMakeLists.txt
+++ polly/lib/External/CMakeLists.txt
@@ -290,7 +290,7 @@
 install(DIRECTORY
   ${ISL_SOURCE_DIR}/include/
   ${ISL_BINARY_DIR}/include/
-  DESTINATION include/polly
+  DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/polly"
   FILES_MATCHING
   PATTERN "*.h"
   PATTERN "CMakeFiles" EXCLUDE
Index: polly/cmake/CMakeLists.txt
===
--- polly/cmake/CMakeLists.txt
+++ polly/cmake/CMakeLists.txt
@@ -1,5 +1,6 @@
 # Keep this in sync with llvm/cmake/CMakeLists.txt!
 
+include(ExtendPath)
 include(FindPrefixFromConfig)
 
 set(LLVM_INSTALL_PACKAGE_DIR "lib${LLVM_LIBDIR_SUFFIX}/cmake/llvm")
@@ -83,17 +84,18 @@
 # Generate PollyConfig.cmake for the install tree.
 unset(POLLY_EXPORTS)
 find_prefix_from_config(POLLY_CONFIG_CODE POLLY_INSTALL_PREFIX "${POLLY_INSTALL_PACKAGE_DIR}")
-set(POLLY_CONFIG_LLVM_CMAKE_DIR "\${POLLY_INSTALL_PREFIX}/${LLVM_INSTALL_PACKAGE_DIR}")
-set(POLLY_CONFIG_CMAKE_DIR "\${POLLY_INSTALL_PREFIX}/${POLLY_INSTALL_PACKAGE_DIR}")
-set(POLLY_CONFIG_LIBRARY_DIRS "\${POLLY_INSTALL_PREFIX}/lib${LLVM_LIBDIR_SUFFIX}")
+extend_path(POLLY_CONFIG_LLVM_CMAKE_DIR "\${POLLY_INSTALL_PREFIX}" "${LLVM_INSTALL_PACKAGE_DIR}")
+extend_path(POLLY_CONFIG_CMAKE_DIR "\${POLLY_INSTALL_PREFIX}" "${POLLY_INSTALL_PACKAGE_DIR}")
+extend_path(POLLY_CONFIG_LIBRARY_DIRS "\${POLLY_INSTALL_PREFIX}" "lib${LLVM_LIBDIR_SUFFIX}")
+extend_path(base_includedir "\${POLLY_INSTALL_PREFIX}" "${CMAKE_INSTALL_INCLUDEDIR}")
 if (POLLY_BUNDLED_ISL)
   set(POLLY_CONFIG_INCLUDE_DIRS
-"\${POLLY_INSTALL_PREFIX}/include"
-"\${POLLY_INSTALL_PREFIX}/include/polly"
+"${base_includedir}"
+"${base_includedir}/polly"
 )
 else()
   set(POLLY_CONFIG_INCLUDE_DIRS
-"\${POLLY_INSTALL_PREFIX}/include"
+"${base_includedir}"
 ${ISL_INCLUDE_DIRS}
 )
 endif()
@@ -110,12 +112,12 @@
 foreach(tgt IN LISTS POLLY_CONFIG_EXPORTED_TARGETS)
   get_target_property(tgt_type ${tgt} TYPE)
   if (tgt_type STREQUAL "EXECUTABLE")
-set(tgt_prefix "bin/")
+set(tgt_prefix "$

[PATCH] D116994: [RISCV] Add bfp and bfpw intrinsic in zbf extension

2022-01-10 Thread WangLian via Phabricator via cfe-commits
Jimerlife created this revision.
Jimerlife added reviewers: craig.topper, benshi001, asb, LevyHsu.
Jimerlife added a project: LLVM.
Herald added subscribers: VincentWu, luke957, achieveartificialintelligence, 
vkmr, frasercrmck, evandro, luismarques, apazos, sameer.abuasal, s.egerton, 
Jim, benna, psnobl, jocewei, PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, 
edward-jones, zzheng, jrtc27, kito-cheng, niosHD, sabuasal, simoncook, 
johnrusso, rbar, hiraditya.
Jimerlife requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, MaskRay.
Herald added a project: clang.

bfp
bfpw


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116994

Files:
  clang/include/clang/Basic/BuiltinsRISCV.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbf.c
  clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbf.c
  llvm/include/llvm/IR/IntrinsicsRISCV.td
  llvm/lib/Target/RISCV/RISCVInstrInfoZb.td
  llvm/test/CodeGen/RISCV/rv32zbf-intrinsic.ll
  llvm/test/CodeGen/RISCV/rv64zbf-intrinsic.ll

Index: llvm/test/CodeGen/RISCV/rv64zbf-intrinsic.ll
===
--- /dev/null
+++ llvm/test/CodeGen/RISCV/rv64zbf-intrinsic.ll
@@ -0,0 +1,25 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -mtriple=riscv64 -mattr=+experimental-zbf -verify-machineinstrs < %s \
+; RUN:   | FileCheck %s -check-prefix=RV64ZBF
+
+declare i64 @llvm.riscv.bfp.i64(i64 %a, i64 %b)
+
+define i64 @bfp64(i64 %a, i64 %b) nounwind {
+; RV64ZBF-LABEL: bfp64:
+; RV64ZBF:   # %bb.0:
+; RV64ZBF-NEXT:bfp a0, a0, a1
+; RV64ZBF-NEXT:ret
+  %tmp = call i64 @llvm.riscv.bfp.i64(i64 %a, i64 %b)
+ ret i64 %tmp
+}
+
+declare i64 @llvm.riscv.bfpw.i64(i64 %a, i64 %b)
+
+define i64 @bfpw64(i64 %a, i64 %b) nounwind {
+; RV64ZBF-LABEL: bfpw64:
+; RV64ZBF:   # %bb.0:
+; RV64ZBF-NEXT:bfpw a0, a0, a1
+; RV64ZBF-NEXT:ret
+  %tmp = call i64 @llvm.riscv.bfpw.i64(i64 %a, i64 %b)
+ ret i64 %tmp
+}
Index: llvm/test/CodeGen/RISCV/rv32zbf-intrinsic.ll
===
--- /dev/null
+++ llvm/test/CodeGen/RISCV/rv32zbf-intrinsic.ll
@@ -0,0 +1,14 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -mtriple=riscv32 -mattr=+experimental-zbf -verify-machineinstrs < %s \
+; RUN:   | FileCheck %s -check-prefix=RV32ZBF
+
+declare i32 @llvm.riscv.bfp.i32(i32 %a, i32 %b)
+
+define i32 @bfp32(i32 %a, i32 %b) nounwind {
+; RV32ZBF-LABEL: bfp32:
+; RV32ZBF:   # %bb.0:
+; RV32ZBF-NEXT:bfp a0, a0, a1
+; RV32ZBF-NEXT:ret
+  %tmp = call i32 @llvm.riscv.bfp.i32(i32 %a, i32 %b)
+ ret i32 %tmp
+}
Index: llvm/lib/Target/RISCV/RISCVInstrInfoZb.td
===
--- llvm/lib/Target/RISCV/RISCVInstrInfoZb.td
+++ llvm/lib/Target/RISCV/RISCVInstrInfoZb.td
@@ -1127,3 +1127,9 @@
 def : PatGpr;
 def : PatGpr;
 } // Predicates = [HasStdExtZbr, IsRV64]
+
+let Predicates = [HasStdExtZbf] in
+def : PatGprGpr;
+
+let Predicates = [HasStdExtZbf, IsRV64] in
+def : PatGprGpr;
Index: llvm/include/llvm/IR/IntrinsicsRISCV.td
===
--- llvm/include/llvm/IR/IntrinsicsRISCV.td
+++ llvm/include/llvm/IR/IntrinsicsRISCV.td
@@ -93,6 +93,10 @@
   def int_riscv_bcompress   : BitManipGPRGPRIntrinsics;
   def int_riscv_bdecompress : BitManipGPRGPRIntrinsics;
 
+  // Zbf
+  def int_riscv_bfp  : BitManipGPRGPRIntrinsics;
+  def int_riscv_bfpw : BitManipGPRGPRIntrinsics;
+
   // Zbp
   def int_riscv_grev  : BitManipGPRGPRIntrinsics;
   def int_riscv_gorc  : BitManipGPRGPRIntrinsics;
Index: clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbf.c
===
--- /dev/null
+++ clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbf.c
@@ -0,0 +1,33 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple riscv64 -target-feature +experimental-zbf -emit-llvm %s -o - \
+// RUN: | FileCheck %s  -check-prefix=RV64ZBF
+
+// RV64ZBF-LABEL: @bfp(
+// RV64ZBF-NEXT:  entry:
+// RV64ZBF-NEXT:[[A_ADDR:%.*]] = alloca i64, align 8
+// RV64ZBF-NEXT:[[B_ADDR:%.*]] = alloca i64, align 8
+// RV64ZBF-NEXT:store i64 [[A:%.*]], i64* [[A_ADDR]], align 8
+// RV64ZBF-NEXT:store i64 [[B:%.*]], i64* [[B_ADDR]], align 8
+// RV64ZBF-NEXT:[[TMP0:%.*]] = load i64, i64* [[A_ADDR]], align 8
+// RV64ZBF-NEXT:[[TMP1:%.*]] = load i64, i64* [[B_ADDR]], align 8
+// RV64ZBF-NEXT:[[TMP2:%.*]] = call i64 @llvm.riscv.bfp.i64(i64 [[TMP0]], i64 [[TMP1]])
+// RV64ZBF-NEXT:ret i64 [[TMP2]]
+//
+long bfp(long a, long b) {
+  return __builtin_riscv_bfp(a, b);
+}
+
+// RV64ZBF-LABEL: @bfpw(
+// RV64ZBF-NEXT:  entry:
+// RV64ZBF-NEXT:[[A_ADDR:%.*]] = alloca i64, align 8
+// RV64ZBF-NEXT:[[B_ADDR:%.*]] = alloca i64, align 8
+// RV64ZBF-NEX

[PATCH] D116503: [clang] Add --start-no-unused-arguments/--end-no-unused-arguments to silence some unused argument warnings

2022-01-10 Thread Martin Storsjö 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 rG50ec1306d060: [clang] Add 
--start-no-unused-arguments/--end-no-unused-arguments to silence… (authored by 
mstorsjo).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116503

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/diagnostics.c

Index: clang/test/Driver/diagnostics.c
===
--- clang/test/Driver/diagnostics.c
+++ clang/test/Driver/diagnostics.c
@@ -1,9 +1,53 @@
 // Parse diagnostic arguments in the driver
-// PR12181
 
-// RUN: not %clang -target x86_64-apple-darwin10 \
-// RUN:   -fsyntax-only -fzyzzybalubah \
-// RUN:   -Werror=unused-command-line-argument %s
+// Exactly which arguments are warned about and which aren't differ based
+// on what target is selected. -stdlib= and -fuse-ld= emit diagnostics when
+// compiling C code, for e.g. *-linux-gnu. Linker inputs, like -lfoo, emit
+// diagnostics when only compiling for all targets.
 
-// RUN: not %clang -target x86_64-apple-darwin10 \
-// RUN:   -fsyntax-only -fzyzzybalubah -Werror %s
+// This is normally a non-fatal warning:
+// RUN: %clang --target=x86_64-apple-darwin10 \
+// RUN:   -fsyntax-only -lfoo %s 2>&1 | FileCheck %s
+
+// Either with a specific -Werror=unused.. or a blanket -Werror, this
+// causes the command to fail.
+// RUN: not %clang --target=x86_64-apple-darwin10 \
+// RUN:   -fsyntax-only -lfoo \
+// RUN:   -Werror=unused-command-line-argument %s 2>&1 | FileCheck %s
+
+// RUN: not %clang --target=x86_64-apple-darwin10 \
+// RUN:   -fsyntax-only -lfoo -Werror %s 2>&1 | FileCheck %s
+
+// With a specific -Wno-..., no diagnostic should be printed.
+// RUN: %clang --target=x86_64-apple-darwin10 \
+// RUN:   -fsyntax-only -lfoo -Werror \
+// RUN:   -Wno-unused-command-line-argument %s 2>&1 | count 0
+
+// With -Qunused-arguments, no diagnostic should be printed.
+// RUN: %clang --target=x86_64-apple-darwin10 \
+// RUN:   -fsyntax-only -lfoo -Werror \
+// RUN:   -Qunused-arguments %s 2>&1 | count 0
+
+// With the argument enclosed in --{start,end}-no-unused-arguments,
+// there's no diagnostic.
+// RUN: %clang --target=x86_64-apple-darwin10 -fsyntax-only \
+// RUN:   --start-no-unused-arguments -lfoo --end-no-unused-arguments \
+// RUN:   -Werror %s 2>&1 | count 0
+
+// With --{start,end}-no-unused-argument around a different argument, it
+// still warns about the unused argument.
+// RUN: not %clang --target=x86_64-apple-darwin10 \
+// RUN:   --start-no-unused-arguments -fsyntax-only --end-no-unused-arguments \
+// RUN:   -lfoo -Werror %s 2>&1 | FileCheck %s
+
+// Test clang-cl warning about unused linker options.
+// RUN: not %clang_cl -fsyntax-only /WX %s \
+// RUN:   -link 2>&1 | FileCheck %s --check-prefix=CL-WARNING
+
+// Test clang-cl ignoring the warning with --start-no-unused-arguments.
+// RUN: %clang_cl -fsyntax-only /WX %s \
+// RUN:   --start-no-unused-arguments -link --end-no-unused-arguments 2>&1 | count 0
+
+// CHECK: -lfoo: 'linker' input unused
+
+// CL-WARNING: argument unused during compilation: '-link'
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -367,7 +367,20 @@
   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
   bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
   bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
+  bool IgnoreUnused = false;
   for (Arg *A : Args) {
+if (IgnoreUnused)
+  A->claim();
+
+if (A->getOption().matches(options::OPT_start_no_unused_arguments)) {
+  IgnoreUnused = true;
+  continue;
+}
+if (A->getOption().matches(options::OPT_end_no_unused_arguments)) {
+  IgnoreUnused = false;
+  continue;
+}
+
 // Unfortunately, we have to parse some forwarding options (-Xassembler,
 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1076,6 +1076,8 @@
 def emit_merged_ifs : Flag<["-"], "emit-merged-ifs">,
   Flags<[CC1Option]>, Group,
   HelpText<"Generate Interface Stub Files, emit merged text not binary.">;
+def end_no_unused_arguments : Flag<["--"], "end-no-unused-arguments">, Flags<[CoreOption]>,
+  HelpText<"Start emitting warnings for unused driver arguments">;
 def interface_stub_version_EQ : JoinedOrSeparate<["-"], "interface-stub-version=">, Flags<[CC1Option]>;
 def exported__symbols__list : Separate<["-"],

[clang] 50ec130 - [clang] Add --start-no-unused-arguments/--end-no-unused-arguments to silence some unused argument warnings

2022-01-10 Thread Martin Storsjö via cfe-commits

Author: Martin Storsjö
Date: 2022-01-11T09:22:00+02:00
New Revision: 50ec1306d060e46e0d53c9f5d8a052e1b0d10d3b

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

LOG: [clang] Add --start-no-unused-arguments/--end-no-unused-arguments to 
silence some unused argument warnings

When passing a set of flags to configure defaults for a specific
target (similar to the cmake settings `CLANG_DEFAULT_RTLIB`,
`CLANG_DEFAULT_UNWINDLIB`, `CLANG_DEFAULT_CXX_STDLIB` and
`CLANG_DEFAULT_LINKER`, but without hardcoding them in the binary),
some of the flags may cause warnings (e.g. `-stdlib=` when compiling C
code). Allow requesting selectively ignoring unused arguments among
some of the arguments on the command line, without needing to resort
to `-Qunused-arguments` or `-Wno-unused-command-line-argument`.

Fix up the existing diagnostics.c testcase. It was added in
response to PR12181 to fix handling of
`-Werror=unused-command-line-argument`, but the command line option
in the test (`-fzyzzybalubah`) now triggers "error: unknown argument"
instead of the intended warning. Change it into a linker input
(`-lfoo`) which triggers the intended diagnostic. Extend the
existing test case to check more cases and make sure that it keeps
testing the intended case.

Add testing of the new option to this existing test.

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

Added: 


Modified: 
clang/docs/ClangCommandLineReference.rst
clang/include/clang/Driver/Options.td
clang/lib/Driver/Driver.cpp
clang/test/Driver/diagnostics.c

Removed: 




diff  --git a/clang/docs/ClangCommandLineReference.rst 
b/clang/docs/ClangCommandLineReference.rst
index 72d571dd10ee3..8ae7d7f49f168 100644
--- a/clang/docs/ClangCommandLineReference.rst
+++ b/clang/docs/ClangCommandLineReference.rst
@@ -212,6 +212,10 @@ Enable linker job to emit a static library.
 
 Trivial automatic variable initialization to zero is only here for benchmarks, 
it'll eventually be removed, and I'm OK with that because I'm only using it to 
benchmark
 
+.. option:: --end-no-unused-arguments
+
+Start emitting warnings for unused driver arguments
+
 .. option:: -exported\_symbols\_list 
 
 .. option:: -faligned-new=
@@ -663,6 +667,10 @@ Dynamically link the sanitizer runtime
 
 .. option:: -single\_module
 
+.. option:: --start-no-unused-arguments
+
+Don't emit warnings about unused arguments for the following arguments
+
 .. option:: -static-libgcc
 
 .. option:: -static-libsan

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 6c56d9739de2a..4bcb7bd4c3969 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1076,6 +1076,8 @@ def emit_interface_stubs : Flag<["-"], 
"emit-interface-stubs">, Flags<[CC1Option
 def emit_merged_ifs : Flag<["-"], "emit-merged-ifs">,
   Flags<[CC1Option]>, Group,
   HelpText<"Generate Interface Stub Files, emit merged text not binary.">;
+def end_no_unused_arguments : Flag<["--"], "end-no-unused-arguments">, 
Flags<[CoreOption]>,
+  HelpText<"Start emitting warnings for unused driver arguments">;
 def interface_stub_version_EQ : JoinedOrSeparate<["-"], 
"interface-stub-version=">, Flags<[CC1Option]>;
 def exported__symbols__list : Separate<["-"], "exported_symbols_list">;
 def e : JoinedOrSeparate<["-"], "e">, Flags<[LinkerInput]>, Group;
@@ -3913,6 +3915,8 @@ def shared : Flag<["-", "--"], "shared">, 
Group;
 def single__module : Flag<["-"], "single_module">;
 def specs_EQ : Joined<["-", "--"], "specs=">, Group;
 def specs : Separate<["-", "--"], "specs">, Flags<[Unsupported]>;
+def start_no_unused_arguments : Flag<["--"], "start-no-unused-arguments">, 
Flags<[CoreOption]>,
+  HelpText<"Don't emit warnings about unused arguments for the following 
arguments">;
 def static_libgcc : Flag<["-"], "static-libgcc">;
 def static_libstdcxx : Flag<["-"], "static-libstdc++">;
 def static : Flag<["-", "--"], "static">, Group, 
Flags<[NoArgumentUnused]>;

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index ac8438bb45a6a..2c3b137554c0b 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -367,7 +367,20 @@ DerivedArgList *Driver::TranslateInputArgs(const 
InputArgList &Args) const {
   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
   bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
   bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
+  bool IgnoreUnused = false;
   for (Arg *A : Args) {
+if (IgnoreUnused)
+  A->claim();
+
+if (A->getOption().matches(options::OPT_start_no_unused_arguments)) {
+  IgnoreUnused = true;
+  continue;
+}
+if (A->getOption().matches(options::OPT_end_no_unused_arguments)) {
+  IgnoreUnused = 

[PATCH] D115982: [clang][AVR] Implement '__flashN' for variables on different flash banks

2022-01-10 Thread Ben Shi via Phabricator via cfe-commits
benshi001 updated this revision to Diff 398846.

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

https://reviews.llvm.org/D115982

Files:
  clang/lib/Basic/Targets/AVR.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/address-space-avr.c
  clang/test/CodeGen/avr-flash.c
  clang/test/Sema/avr-flash.c

Index: clang/test/Sema/avr-flash.c
===
--- /dev/null
+++ clang/test/Sema/avr-flash.c
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 %s -triple avr -target-cpu at90s8515 -fsyntax-only -verify
+
+int foo(int n) {
+  static __flash  const int a0[] = {4, 6}; // OK
+  static __flash1 const int a1[] = {4, 6}; // expected-error {{unknown type name '__flash1'}}
+  static __flash2 const int a2[] = {4, 6}; // expected-error {{unknown type name '__flash2'}}
+  static __flash3 const int a3[] = {4, 6}; // expected-error {{unknown type name '__flash3'}}
+  static __flash4 const int a4[] = {4, 6}; // expected-error {{unknown type name '__flash4'}}
+  static __flash5 const int a5[] = {4, 6}; // expected-error {{unknown type name '__flash5'}}
+  // TODO: It would be better to report "'__flash5' is not supported on at908515".
+  return a0[n] + a1[n];
+}
Index: clang/test/CodeGen/avr-flash.c
===
--- clang/test/CodeGen/avr-flash.c
+++ clang/test/CodeGen/avr-flash.c
@@ -1,6 +1,11 @@
-// RUN: %clang_cc1 -triple avr -emit-llvm-only -verify %s
+// RUN: %clang_cc1 -triple avr -target-cpu atxmega384c3 -emit-llvm-only -verify %s
 
 int foo(void) {
-  static __flash int b[] = {4, 6}; // expected-error {{qualifier 'const' is needed for variables in address space '__flash'}}
-  return b[0];
+  static __flash  int b[] = {4, 6}; // expected-error {{qualifier 'const' is needed for variables in address space '__flash*'}}
+  static __flash1 int c[] = {8, 1}; // expected-error {{qualifier 'const' is needed for variables in address space '__flash*'}}
+  static __flash2 int d[] = {8, 1}; // expected-error {{qualifier 'const' is needed for variables in address space '__flash*'}}
+  static __flash3 int e[] = {8, 1}; // expected-error {{qualifier 'const' is needed for variables in address space '__flash*'}}
+  static __flash4 int f[] = {8, 1}; // expected-error {{qualifier 'const' is needed for variables in address space '__flash*'}}
+  static __flash5 int g[] = {8, 1}; // expected-error {{qualifier 'const' is needed for variables in address space '__flash*'}}
+  return b[0] + c[1];
 }
Index: clang/test/CodeGen/address-space-avr.c
===
--- clang/test/CodeGen/address-space-avr.c
+++ clang/test/CodeGen/address-space-avr.c
@@ -1,8 +1,11 @@
-// RUN: %clang_cc1 -triple avr -emit-llvm < %s | FileCheck %s
+// RUN: %clang_cc1 -triple avr -target-cpu atmega2560 -emit-llvm < %s | FileCheck %s
 
 // CHECK: @var0 {{.*}} addrspace(1) constant [3 x i16]
+// CHECK: @f3var0 {{.*}} addrspace(4) constant [3 x i16]
 // CHECK: @bar.var2 {{.*}} addrspace(1) constant [3 x i16]
+// CHECK: @bar.f3var2 {{.*}} addrspace(4) constant [3 x i16]
 // CHECK: @var1 {{.*}} addrspace(1) constant [3 x i16]
+// CHECK: @f3var1 {{.*}} addrspace(4) constant [3 x i16]
 
 // CHECK: define{{.*}} void @bar() addrspace(1)
 // CHECK: call addrspace(1) void bitcast (void (...) addrspace(1)* @foo to void (i16) addrspace(1)*)
@@ -11,11 +14,16 @@
 __flash const int var0[] = {999, 888, 777};
 __flash static const int var1[] = {111, 222, 333};
 
+__flash3 const int f3var0[] = {12, 34, 56};
+__flash3 static const int f3var1[] = {52, 64, 96};
+
 int i;
 
 void foo();
 
 void bar() {
   static __flash const int var2[] = {555, 666, 777};
+  static __flash3 const int f3var2[] = {, , 7787};
   foo(var1[i]);
+  foo(f3var1[i]);
 }
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -8282,14 +8282,15 @@
 
   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
   const VarDecl *D) const override {
-// Check if a global/static variable is defined within address space 1
+// Check if global/static variable is defined in address space
+// 1~6 (__flash, __flash1, __flash2, __flash3, __flash4, __flash5)
 // but not constant.
 LangAS AS = D->getType().getAddressSpace();
-if (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 1 &&
-!D->getType().isConstQualified())
+if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) &&
+toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified())
   CGM.getDiags().Report(D->getLocation(),
 diag::err_verify_nonconst_addrspace)
-  << "__flash";
+  << "__flash*";
 return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D);
   }
 
Index: clang/lib/Basic/Targets/AVR.cpp
=

[PATCH] D116833: [clang] Introduce support for disabling warnings in system macros

2022-01-10 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

In D116833#3232739 , @efriedma wrote:

> I'll just note here that doing this globally is likely to have unexpected 
> results... consider, for example:
>
>   #include 
>   void f() { long x = M_PI; }
>
> Currently, the implicit conversion warning points into math.h.
>
> That said, I don't see any problem with the current implementation.

Yes, at first I set the default to "disable globally" and got around ~15 failed 
tests similar to your example. I don't have a good enough picture of all the 
existing warnings to determine what's preferred here, but I think we can take 
it in a separate patch. I get a much better insight now about why this has not 
been tackled before and why some warnings from system macros are needed!

I can also mention that we have recently merged a patch to disable clang-tidy 
warnings from system macros:
https://reviews.llvm.org/D116378


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116833

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


[PATCH] D116736: [Clang] Add __builtin_reduce_or and __builtin_reduce_and

2022-01-10 Thread Jun Zhang via Phabricator via cfe-commits
junaire updated this revision to Diff 398838.
junaire added a comment.

fix the comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116736

Files:
  clang/include/clang/Basic/Builtins.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-reduction-math.c
  clang/test/Sema/builtins-reduction-math.c

Index: clang/test/Sema/builtins-reduction-math.c
===
--- clang/test/Sema/builtins-reduction-math.c
+++ clang/test/Sema/builtins-reduction-math.c
@@ -52,3 +52,37 @@
   i = __builtin_reduce_xor(v);
   // expected-error@-1 {{1st argument must be a vector of integers (was 'float4' (vector of 4 'float' values))}}
 }
+
+void test_builtin_reduce_or(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_or(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_reduce_or();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_reduce_or(iv, iv);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_reduce_or(i);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 'int')}}
+
+  i = __builtin_reduce_or(v);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 'float4' (vector of 4 'float' values))}}
+}
+
+void test_builtin_reduce_and(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_and(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_reduce_and();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_reduce_and(iv, iv);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_reduce_and(i);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 'int')}}
+
+  i = __builtin_reduce_and(v);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 'float4' (vector of 4 'float' values))}}
+}
Index: clang/test/CodeGen/builtins-reduction-math.c
===
--- clang/test/CodeGen/builtins-reduction-math.c
+++ clang/test/CodeGen/builtins-reduction-math.c
@@ -68,3 +68,25 @@
   // CHECK-NEXT: call i32 @llvm.vector.reduce.xor.v4i32(<4 x i32> [[VU1]])
   unsigned r3 = __builtin_reduce_xor(vu1);
 }
+
+void test_builtin_reduce_or(si8 vi1, u4 vu1) {
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.or.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_or(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.or.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_or(vu1);
+}
+
+void test_builtin_reduce_and(si8 vi1, u4 vu1) {
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.and.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_and(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.and.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_and(vu1);
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -2235,8 +2235,10 @@
 break;
   }
 
-  // __builtin_reduce_xor supports vector of integers only.
-  case Builtin::BI__builtin_reduce_xor: {
+  // These builtins support vectors of integers only.
+  case Builtin::BI__builtin_reduce_xor:
+  case Builtin::BI__builtin_reduce_or:
+  case Builtin::BI__builtin_reduce_and: {
 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
   return ExprError();
 
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -3221,6 +3221,12 @@
   case Builtin::BI__builtin_reduce_xor:
 return RValue::get(emitUnaryBuiltin(
 *this, E, llvm::Intrinsic::vector_reduce_xor, "rdx.xor"));
+  case Builtin::BI__builtin_reduce_or:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_or, "rdx.or"));
+  case Builtin::BI__builtin_reduce_and:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_and, "rdx.and"));
 
   case Builtin::BI__builtin_matrix_transpose: {
 const auto *MatrixTy = E->getArg(0)->getType()->getAs();
Index: clang/include/clang/Basic/Builtins.def
===
--- clang/include/clang/Basic/Builtins.def

[PATCH] D116948: [CodeGen] Treat ObjC `__unsafe_unretained` and class types as trivial when generating copy/dispose helper functions

2022-01-10 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added inline comments.



Comment at: clang/lib/CodeGen/CGBlocks.cpp:2142
+if (capture.isConstantOrTrivial())
+  continue;
+

rjmccall wrote:
> ahatanak wrote:
> > rjmccall wrote:
> > > Should this condition be specific to whether it's trivial *to destroy*?  
> > > C++ types could be trivial to destroy but not to copy (and, 
> > > theoretically, vice-versa).
> > Adding the check here won't change anything since `pushCaptureCleanup` is a 
> > no-op if the type is trivial to destroy. But we can replace 
> > `NeedsCopyDispose` with `NeedsCopy` and `NeedsDispose` so that we can track 
> > whether copy and dispose helpers are needed separately and avoid emitting 
> > empty dispose helper functions.
> > 
> > I'm not sure whether we should do that in this patch or in another patch.
> Technically, it would save emitting a GEP, but I agree that that's probably 
> not worth thinking about, so nevermind.
> 
> Avoiding emitting the functions is probably best to do in a separate patch.  
> The runtime does allow null pointers here even if the descriptor says that 
> the helpers exist?
Yes, the runtime checks whether the copy/dispose helper function field is null 
before calling the function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116948

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


[PATCH] D116948: [CodeGen] Treat ObjC `__unsafe_unretained` and class types as trivial when generating copy/dispose helper functions

2022-01-10 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/CodeGen/CGBlocks.cpp:2142
+if (capture.isConstantOrTrivial())
+  continue;
+

ahatanak wrote:
> rjmccall wrote:
> > Should this condition be specific to whether it's trivial *to destroy*?  
> > C++ types could be trivial to destroy but not to copy (and, theoretically, 
> > vice-versa).
> Adding the check here won't change anything since `pushCaptureCleanup` is a 
> no-op if the type is trivial to destroy. But we can replace 
> `NeedsCopyDispose` with `NeedsCopy` and `NeedsDispose` so that we can track 
> whether copy and dispose helpers are needed separately and avoid emitting 
> empty dispose helper functions.
> 
> I'm not sure whether we should do that in this patch or in another patch.
Technically, it would save emitting a GEP, but I agree that that's probably not 
worth thinking about, so nevermind.

Avoiding emitting the functions is probably best to do in a separate patch.  
The runtime does allow null pointers here even if the descriptor says that the 
helpers exist?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116948

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


[PATCH] D93298: [RISCV] add the part of MC layer support of Zfinx extension

2022-01-10 Thread Shao-Ce SUN via Phabricator via cfe-commits
achieveartificialintelligence updated this revision to Diff 398824.
achieveartificialintelligence added a comment.

update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93298

Files:
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
  llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
  llvm/lib/Target/RISCV/RISCV.td
  llvm/lib/Target/RISCV/RISCVInstrInfoD.td
  llvm/lib/Target/RISCV/RISCVInstrInfoF.td
  llvm/lib/Target/RISCV/RISCVInstrInfoZfh.td
  llvm/lib/Target/RISCV/RISCVRegisterInfo.td
  llvm/lib/Target/RISCV/RISCVSubtarget.h
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/rv32i-invalid.s
  llvm/test/MC/RISCV/rv32zdinx-invalid.s
  llvm/test/MC/RISCV/rv32zdinx-valid.s
  llvm/test/MC/RISCV/rv32zfinx-invalid.s
  llvm/test/MC/RISCV/rv32zfinx-valid.s
  llvm/test/MC/RISCV/rv32zhinx-invalid.s
  llvm/test/MC/RISCV/rv32zhinx-valid.s
  llvm/test/MC/RISCV/rv32zhinxmin-invalid.s
  llvm/test/MC/RISCV/rv32zhinxmin-valid.s
  llvm/test/MC/RISCV/rv64zdinx-invalid.s
  llvm/test/MC/RISCV/rv64zdinx-valid.s
  llvm/test/MC/RISCV/rv64zfinx-invalid.s
  llvm/test/MC/RISCV/rv64zfinx-valid.s
  llvm/test/MC/RISCV/rv64zhinx-invalid.s
  llvm/test/MC/RISCV/rv64zhinx-valid.s
  llvm/test/MC/RISCV/rv64zhinxmin-invalid.s
  llvm/test/MC/RISCV/rv64zhinxmin-valid.s
  llvm/test/MC/RISCV/rvzdinx-aliases-valid.s
  llvm/test/MC/RISCV/rvzfinx-aliases-valid.s
  llvm/test/MC/RISCV/rvzhinx-aliases-valid.s

Index: llvm/test/MC/RISCV/rvzhinx-aliases-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rvzhinx-aliases-valid.s
@@ -0,0 +1,82 @@
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zhinx -riscv-no-aliases \
+# RUN: | FileCheck -check-prefix=CHECK-INST %s
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zhinx \
+# RUN: | FileCheck -check-prefix=CHECK-ALIAS %s
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zhinx -riscv-no-aliases \
+# RUN: | FileCheck -check-prefix=CHECK-INST %s
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zhinx \
+# RUN: | FileCheck -check-prefix=CHECK-ALIAS %s
+# RUN: llvm-mc -filetype=obj -triple riscv32 -mattr=+experimental-zhinx %s \
+# RUN: | llvm-objdump -d --mattr=+experimental-zhinx -M no-aliases - \
+# RUN: | FileCheck -check-prefix=CHECK-INST %s
+# RUN: llvm-mc -filetype=obj -triple riscv32 -mattr=+experimental-zhinx %s \
+# RUN: | llvm-objdump -d --mattr=+experimental-zhinx - \
+# RUN: | FileCheck -check-prefix=CHECK-ALIAS %s
+# RUN: llvm-mc -filetype=obj -triple riscv64 -mattr=+experimental-zhinx %s \
+# RUN: | llvm-objdump -d --mattr=+experimental-zhinx -M no-aliases - \
+# RUN: | FileCheck -check-prefix=CHECK-INST %s
+# RUN: llvm-mc -filetype=obj -triple riscv64 -mattr=+experimental-zhinx %s \
+# RUN: | llvm-objdump -d --mattr=+experimental-zhinx - \
+# RUN: | FileCheck -check-prefix=CHECK-ALIAS %s
+
+##===--===##
+## Assembler Pseudo Instructions (User-Level ISA, Version 2.2, Chapter 20)
+##===--===##
+
+# CHECK-INST: fsgnjx.h s1, s2, s2
+# CHECK-ALIAS: fabs.h s1, s2
+fabs.h s1, s2
+# CHECK-INST: fsgnjn.h s2, s3, s3
+# CHECK-ALIAS: fneg.h s2, s3
+fneg.h s2, s3
+
+# CHECK-INST: flt.h tp, s6, s5
+# CHECK-ALIAS: flt.h tp, s6, s5
+fgt.h x4, s5, s6
+# CHECK-INST: fle.h t2, s1, s0
+# CHECK-ALIAS: fle.h t2, s1, s0
+fge.h x7, x8, x9
+
+##===--===##
+## Aliases which omit the rounding mode.
+##===--===##
+
+# CHECK-INST: fmadd.h a0, a1, a2, a3, dyn
+# CHECK-ALIAS: fmadd.h a0, a1, a2, a3
+fmadd.h x10, x11, x12, x13
+# CHECK-INST: fmsub.h a4, a5, a6, a7, dyn
+# CHECK-ALIAS: fmsub.h a4, a5, a6, a7
+fmsub.h x14, x15, x16, x17
+# CHECK-INST: fnmsub.h s2, s3, s4, s5, dyn
+# CHECK-ALIAS: fnmsub.h s2, s3, s4, s5
+fnmsub.h x18, x19, x20, x21
+# CHECK-INST: fnmadd.h s6, s7, s8, s9, dyn
+# CHECK-ALIAS: fnmadd.h s6, s7, s8, s9
+fnmadd.h x22, x23, x24, x25
+# CHECK-INST: fadd.h s10, s11, t3, dyn
+# CHECK-ALIAS: fadd.h s10, s11, t3
+fadd.h x26, x27, x28
+# CHECK-INST: fsub.h t4, t5, t6, dyn
+# CHECK-ALIAS: fsub.h t4, t5, t6
+fsub.h x29, x30, x31
+# CHECK-INST: fmul.h s0, s1, s2, dyn
+# CHECK-ALIAS: fmul.h s0, s1, s2
+fmul.h s0, s1, s2
+# CHECK-INST: fdiv.h s3, s4, s5, dyn
+# CHECK-ALIAS: fdiv.h s3, s4, s5
+fdiv.h s3, s4, s5
+# CHECK-INST: fsqrt.h s6, s7, dyn
+# CHECK-ALIAS: fsqrt.h s6, s7
+fsqrt.h s6, s7
+# CHECK-INST: fcvt.w.h a0, s5, dyn
+# CHECK-ALIAS: fcvt.w.h a0, s5
+fcvt.w.h a0, s5
+# CHECK-INST: fcvt.wu.h a1, s6, dyn
+# CHECK-ALIAS: fcvt.wu.h a1, s6
+fcvt.wu.h a1, s6
+# CHECK-INST: fcvt.h.w t6, a4, dyn
+# CHECK-ALIAS: fcvt.h.w t6, a4
+fcvt.h.w t6, a4
+# CHECK-INST: fcvt.h.wu s0, a

[PATCH] D116659: [llvm][clang][vfs] NFC: Extract directory iteration boilerplate into macro

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

I think th eAPI is designed to ensure users don't forget to check the error 
code.

What about a new API/iterator type that wraps the existing one and has a 
"normal" `operator++`?

- Take an error as an out-parameter on construction
- Make it an `llvm::Error` which guarantees a crash if not checked
- This would wrap the other type and store a reference to the `Error`. If 
there's an error during iteration, advances to end and sets the error.

Here's what I'm thinking:

  Optional DirError;
  for (vfs::error_directory_iterator File = D.getVFS().dir_begin(Cand.Path, 
DirError),
 FileEnd;
   File != FileEnd; ++File) {
// ...
  }
  if (DirError)
return errorToErrorCode(std::move(*IterationEC));

At that point, it'd be easy to add a `dir_range` wrapper that creates an 
iterator range:

  for (auto &File : dir_range(Path, DirError)) {
// ...
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116659

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


[PATCH] D116975: [OpenMP] Initial Implementation of LTO and bitcode linking in linker wrapper

2022-01-10 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 398821.
jhuber6 added a comment.
Herald added subscribers: ormris, steven_wu.

Fix tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116975

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/tools/clang-linker-wrapper/CMakeLists.txt
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  llvm/lib/Passes/PassBuilderPipelines.cpp
  llvm/test/Other/new-pm-lto-defaults.ll

Index: llvm/test/Other/new-pm-lto-defaults.ll
===
--- llvm/test/Other/new-pm-lto-defaults.ll
+++ llvm/test/Other/new-pm-lto-defaults.ll
@@ -64,6 +64,7 @@
 ; CHECK-O23SZ-NEXT: Running pass: GlobalOptPass
 ; CHECK-O23SZ-NEXT: Running pass: PromotePass
 ; CHECK-O23SZ-NEXT: Running pass: ConstantMergePass
+; CHECK-O23SZ-NEXT: Running pass: OpenMPOptPass
 ; CHECK-O23SZ-NEXT: Running pass: DeadArgumentEliminationPass
 ; CHECK-O23SZ-NEXT: Running pass: InstCombinePass
 ; CHECK-O3-NEXT: Running pass: AggressiveInstCombinePass
Index: llvm/lib/Passes/PassBuilderPipelines.cpp
===
--- llvm/lib/Passes/PassBuilderPipelines.cpp
+++ llvm/lib/Passes/PassBuilderPipelines.cpp
@@ -1531,6 +1531,9 @@
   // keep one copy of each constant.
   MPM.addPass(ConstantMergePass());
 
+  // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
+  MPM.addPass(OpenMPOptPass());
+
   // Remove unused arguments from functions.
   MPM.addPass(DeadArgumentEliminationPass());
 
Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -17,9 +17,12 @@
 #include "clang/Basic/Version.h"
 #include "llvm/BinaryFormat/Magic.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/CommandFlags.h"
 #include "llvm/IR/Constants.h"
+#include "llvm/IR/DiagnosticPrinter.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IRReader/IRReader.h"
+#include "llvm/LTO/LTO.h"
 #include "llvm/Object/Archive.h"
 #include "llvm/Object/ArchiveWriter.h"
 #include "llvm/Object/Binary.h"
@@ -36,6 +39,7 @@
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/StringSaver.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -58,6 +62,15 @@
cl::desc("Path of linker binary"),
cl::cat(ClangLinkerWrapperCategory));
 
+static cl::opt
+TargetFeatures("target-feature", cl::desc("Target features for triple"),
+   cl::cat(ClangLinkerWrapperCategory));
+
+static cl::opt OptLevel("opt-level",
+ cl::desc("Optimization level for LTO"),
+ cl::init("O0"),
+ cl::cat(ClangLinkerWrapperCategory));
+
 // Do not parse linker options.
 static cl::list
 HostLinkerArgs(cl::Sink, cl::desc("..."));
@@ -68,6 +81,9 @@
 /// Temporary files created by the linker wrapper.
 static SmallVector TempFiles;
 
+/// Codegen flags for LTO backend.
+static codegen::RegisterCodeGenFlags CodeGenFlags;
+
 /// Magic section string that marks the existence of offloading data. The
 /// section string will be formatted as `.llvm.offloading..`.
 #define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading."
@@ -195,6 +211,28 @@
   if (ToBeStripped.empty())
 return None;
 
+  // If the object file to strip doesn't exist we need to write it so we can
+  // pass it to llvm-strip.
+  SmallString<128> StripFile = Obj.getFileName();
+  if (!sys::fs::exists(StripFile)) {
+SmallString<128> TempFile;
+if (std::error_code EC = sys::fs::createTemporaryFile(
+sys::path::stem(StripFile), "o", TempFile))
+  return createFileError(TempFile, EC);
+TempFiles.push_back(static_cast(TempFile));
+
+auto Contents = Obj.getMemoryBufferRef().getBuffer();
+Expected> OutputOrErr =
+FileOutputBuffer::create(TempFile, Contents.size());
+if (!OutputOrErr)
+  return OutputOrErr.takeError();
+std::unique_ptr Output = std::move(*OutputOrErr);
+std::copy(Contents.begin(), Contents.end(), Output->getBufferStart());
+if (Error E = Output->commit())
+  return E;
+StripFile = TempFile;
+  }
+
   // We will use llvm-strip to remove the now unneeded section containing the
   // offloading code.
   ErrorOr StripPath = sys::findProgramByName(
@@ -214,7 +252,7 @@
   SmallVector StripArgs;
   StripArgs.push_back(*StripPath);
   StripArgs.push_back("--no-strip-all");
-  StripArgs.push_back(Obj.getFileName());
+  StripArgs.push_back(StripFile);
   for (auto &Section : ToBeStripped) {
 StripA

[PATCH] D116948: [CodeGen] Treat ObjC `__unsafe_unretained` and class types as trivial when generating copy/dispose helper functions

2022-01-10 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added inline comments.



Comment at: clang/lib/CodeGen/CGBlocks.cpp:2142
+if (capture.isConstantOrTrivial())
+  continue;
+

rjmccall wrote:
> Should this condition be specific to whether it's trivial *to destroy*?  C++ 
> types could be trivial to destroy but not to copy (and, theoretically, 
> vice-versa).
Adding the check here won't change anything since `pushCaptureCleanup` is a 
no-op if the type is trivial to destroy. But we can replace `NeedsCopyDispose` 
with `NeedsCopy` and `NeedsDispose` so that we can track whether copy and 
dispose helpers are needed separately and avoid emitting empty dispose helper 
functions.

I'm not sure whether we should do that in this patch or in another patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116948

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


[PATCH] D116948: [CodeGen] Treat ObjC `__unsafe_unretained` and class types as trivial when generating copy/dispose helper functions

2022-01-10 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/CodeGen/CGBlocks.cpp:361
 
   /// Order by 1) all __strong together 2) next, all byfref together 3) next,
   /// all __weak together. Preserve descending alignment in all situations.

"byref"



Comment at: clang/lib/CodeGen/CGBlocks.cpp:1953
+  for (auto &capture : blockInfo.SortedCaptures) {
+if (capture.isConstantOrTrivial())
+  continue;

Should this be specific to whether this is trivial to copy?



Comment at: clang/lib/CodeGen/CGBlocks.cpp:2142
+if (capture.isConstantOrTrivial())
+  continue;
+

Should this condition be specific to whether it's trivial *to destroy*?  C++ 
types could be trivial to destroy but not to copy (and, theoretically, 
vice-versa).



Comment at: clang/lib/CodeGen/CGBlocks.h:268
 
   /// The mapping of allocated indexes within the block.
+  llvm::DenseMap Captures;

This comment is out-of-date, and it should also be updated to say that the 
values are pointers into `SortedCaptures`.



Comment at: clang/lib/CodeGen/CGBlocks.h:306
   Capture &getCapture(const VarDecl *var) {
-llvm::DenseMap::iterator
-  it = Captures.find(var);
+llvm::DenseMap::iterator it =
+Captures.find(var);

We can use `auto` now, and this seems like a good place for it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116948

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


[PATCH] D114639: Raise the minimum Visual Studio version to VS2019

2022-01-10 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added a comment.

>> https://lab.llvm.org/buildbot/#/builders/sanitizer-windows
>> https://lab.llvm.org/buildbot/#/builders/clang-x64-windows-msvc

Actually these were already on VS2019, version 16.8, so I only updated them 
both to 16.11.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114639

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


[PATCH] D116987: [clang][utils] Remove StringRef lldb summary provider

2022-01-10 Thread Dave Lee via Phabricator via cfe-commits
kastiglione created this revision.
kastiglione added reviewers: akyrtzi, jingham.
Herald added subscribers: usaxena95, arphaman.
kastiglione requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Remove the `StringRef` summary provider in favor of the implementation in
`llvm/utils/lldbDataFormatters.py`.

This implementation was resulting in errors in some cases.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116987

Files:
  clang/utils/ClangDataFormat.py


Index: clang/utils/ClangDataFormat.py
===
--- clang/utils/ClangDataFormat.py
+++ clang/utils/ClangDataFormat.py
@@ -24,7 +24,6 @@
 def __lldb_init_module(debugger, internal_dict):
debugger.HandleCommand("type summary add -F 
ClangDataFormat.SourceLocation_summary clang::SourceLocation")
debugger.HandleCommand("type summary add -F 
ClangDataFormat.QualType_summary clang::QualType")
-   debugger.HandleCommand("type summary add -F 
ClangDataFormat.StringRef_summary llvm::StringRef")
 
 def SourceLocation_summary(srcloc, internal_dict):
return SourceLocation(srcloc).summary()
@@ -32,9 +31,6 @@
 def QualType_summary(qualty, internal_dict):
return QualType(qualty).summary()
 
-def StringRef_summary(strref, internal_dict):
-   return StringRef(strref).summary()
-
 class SourceLocation(object):
def __init__(self, srcloc):
self.srcloc = srcloc
@@ -79,23 +75,6 @@
return ""
return desc
 
-class StringRef(object):
-   def __init__(self, strref):
-   self.strref = strref
-   self.Data_value = strref.GetChildAtIndex(0)
-   self.Length = strref.GetChildAtIndex(1).GetValueAsUnsigned()
-
-   def summary(self):
-   if self.Length == 0:
-   return '""'
-   data = self.Data_value.GetPointeeData(0, self.Length)
-   error = lldb.SBError()
-   string = data.ReadRawData(error, 0, data.GetByteSize())
-   if error.Fail():
-   return None
-   return '"%s"' % string
-
-
 # Key is a (function address, type name) tuple, value is the expression path 
for
 # an object with such a type name from inside that function.
 FramePathMapCache = {}


Index: clang/utils/ClangDataFormat.py
===
--- clang/utils/ClangDataFormat.py
+++ clang/utils/ClangDataFormat.py
@@ -24,7 +24,6 @@
 def __lldb_init_module(debugger, internal_dict):
 	debugger.HandleCommand("type summary add -F ClangDataFormat.SourceLocation_summary clang::SourceLocation")
 	debugger.HandleCommand("type summary add -F ClangDataFormat.QualType_summary clang::QualType")
-	debugger.HandleCommand("type summary add -F ClangDataFormat.StringRef_summary llvm::StringRef")
 
 def SourceLocation_summary(srcloc, internal_dict):
 	return SourceLocation(srcloc).summary()
@@ -32,9 +31,6 @@
 def QualType_summary(qualty, internal_dict):
 	return QualType(qualty).summary()
 
-def StringRef_summary(strref, internal_dict):
-	return StringRef(strref).summary()
-
 class SourceLocation(object):
 	def __init__(self, srcloc):
 		self.srcloc = srcloc
@@ -79,23 +75,6 @@
 			return ""
 		return desc
 
-class StringRef(object):
-	def __init__(self, strref):
-		self.strref = strref
-		self.Data_value = strref.GetChildAtIndex(0)
-		self.Length = strref.GetChildAtIndex(1).GetValueAsUnsigned()
-
-	def summary(self):
-		if self.Length == 0:
-			return '""'
-		data = self.Data_value.GetPointeeData(0, self.Length)
-		error = lldb.SBError()
-		string = data.ReadRawData(error, 0, data.GetByteSize())
-		if error.Fail():
-			return None
-		return '"%s"' % string
-
-
 # Key is a (function address, type name) tuple, value is the expression path for
 # an object with such a type name from inside that function.
 FramePathMapCache = {}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116948: [CodeGen] Treat ObjC `__unsafe_unretained` and class types as trivial when generating copy/dispose helper functions

2022-01-10 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 398800.
ahatanak marked 2 inline comments as done.
ahatanak added a comment.

Build the map (`Captures`) after building the vector (`SortedCaptures`).

Also fix a minor bug where a `BlockLayoutChunk` wasn't being removed after 
being copied when the end of the header wasn't aligned (see `test6` in 
`CodeGenObjC/blocks.m`), which was needed since 
`CodeGenObjC/arc-captured-32bit-block-var-layout-2.m` started failing after 
applying this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116948

Files:
  clang/lib/CodeGen/CGBlocks.cpp
  clang/lib/CodeGen/CGBlocks.h
  clang/lib/CodeGen/CGObjCMac.cpp
  clang/test/CodeGenObjC/arc-blocks.m
  clang/test/CodeGenObjC/blocks.m

Index: clang/test/CodeGenObjC/blocks.m
===
--- clang/test/CodeGenObjC/blocks.m
+++ clang/test/CodeGenObjC/blocks.m
@@ -1,5 +1,14 @@
 // RUN: %clang_cc1 -triple i386-apple-darwin9 -fobjc-runtime=macosx-fragile-10.5 -emit-llvm -fblocks -o - %s | FileCheck %s
 
+// CHECK: %[[STRUCT_BLOCK_DESCRIPTOR:.*]] = type { i32, i32 }
+
+// Check that there is only one capture (20o) in the copy/dispose function
+// names.
+
+// CHECK: @[[BLOCK_DESCRIPTOR0:.*]] = linkonce_odr hidden unnamed_addr constant { i32, i32, i8*, i8*, i8*, i32 } { i32 0, i32 28, i8* bitcast (void (i8*, i8*)* @__copy_helper_block_4_20o to i8*), i8* bitcast (void (i8*)* @__destroy_helper_block_4_20o to i8*), i8* getelementptr inbounds ([6 x i8], [6 x i8]* @{{.*}}, i32 0, i32 0), i32 512 },
+
+void (^gb0)(void);
+
 // test1.  All of this is somehow testing rdar://6676764
 struct S {
   void (^F)(struct S*);
@@ -132,3 +141,21 @@
 // CHECK-NEXT: [[T5:%.*]] = bitcast i8* [[T4]] to void (i8*, i32, i32, i32, i32)*
 // CHECK-NEXT: call void [[T5]](i8* [[T3]], i32 0, i32 1, i32 2, i32 3)
 // CHECK-NEXT: ret void
+
+void test5(A *a) {
+  __unsafe_unretained A *t = a;
+  gb0 = ^{ (void)a; (void)t; };
+}
+
+// CHECK-LABEL: define void @test5(
+// CHECK: %[[V0:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, {{.*}}*, {{.*}}* }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, {{.*}}*, {{.*}}* }>* %{{.*}}, i32 0, i32 4
+// CHECK: store %[[STRUCT_BLOCK_DESCRIPTOR]]* bitcast ({ i32, i32, i8*, i8*, i8*, i32 }* @[[BLOCK_DESCRIPTOR0]] to %[[STRUCT_BLOCK_DESCRIPTOR]]*), %[[STRUCT_BLOCK_DESCRIPTOR]]** %[[V0]],
+
+void test6(id a, long long b) {
+  void (^block)() = ^{ (void)b; (void)a; };
+}
+
+// Check that the block literal doesn't have two fields for capture 'a'.
+
+// CHECK-LABEL: define void @test6(
+// CHECK: alloca <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i64 }>,
Index: clang/test/CodeGenObjC/arc-blocks.m
===
--- clang/test/CodeGenObjC/arc-blocks.m
+++ clang/test/CodeGenObjC/arc-blocks.m
@@ -8,6 +8,10 @@
 // CHECK-COMMON: @[[BLOCK_DESCRIPTOR_TMP46:.*]] = linkonce_odr hidden unnamed_addr constant { i64, i64, i8*, i8*, i8*, i8* } { i64 0, i64 48, i8* bitcast (void (i8*, i8*)* @__copy_helper_block_8_32s to i8*), i8* bitcast (void (i8*)* @__destroy_helper_block_8_32s to i8*), i8* getelementptr inbounds ([6 x i8], [6 x i8]* @{{.*}}, i32 0, i32 0), i8* getelementptr inbounds ([3 x i8], [3 x i8]* @{{.*}}, i32 0, i32 0) }, align 8
 // CHECK-COMMON: @[[BLOCK_DESCRIPTOR_TMP48:.*]] = linkonce_odr hidden unnamed_addr constant { i64, i64, i8*, i8*, i8*, i64 } { i64 0, i64 40, i8* bitcast (void (i8*, i8*)* @__copy_helper_block_8_32b to i8*), i8* bitcast (void (i8*)* @__destroy_helper_block_8_32s to i8*), i8* getelementptr inbounds ([9 x i8], [9 x i8]* @{{.*}}, i32 0, i32 0), i64 256 }, align 8
 
+// Check that no copy/dispose helpers are emitted for this block.
+
+// CHECK-COMMON: @[[BLOCK_DESCRIPTOR_TMP10:.*]] = linkonce_odr hidden unnamed_addr constant { i64, i64, i8*, i8* } { i64 0, i64 40, i8* getelementptr inbounds ([6 x i8], [6 x i8]* @{{.*}}, i32 0, i32 0), i8* getelementptr inbounds ([1 x i8], [1 x i8]* @{{.*}}, i32 0, i32 0) }, align 8
+
 // This shouldn't crash.
 void test0(id (^maker)(void)) {
   maker();
@@ -769,5 +773,20 @@
   [t m:123, ^{ (void)x; }];
 }
 
+// CHECK-COMMON-LABEL: define internal void @"\01+[Test24 m]"(
+// CHECK-COMMON: %[[BLOCK_DESCRIPTOR:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8* }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8* }>* %{{.*}}, i32 0, i32 4
+// CHECK: store %[[STRUCT_BLOCK_DESCRIPTOR]]* bitcast ({ i64, i64, i8*, i8* }* @[[BLOCK_DESCRIPTOR_TMP10]] to %[[STRUCT_BLOCK_DESCRIPTOR]]*), %[[STRUCT_BLOCK_DESCRIPTOR]]** %[[BLOCK_DESCRIPTOR]],
+
+@interface Test24
+@property (class) void (^block)(void);
++(void)m;
+@end
+
+@implementation Test24
++(void)m {
+  self.block = ^{ (void)self; };
+}
+@end
+
 // CHECK: attributes [[NUW]] = { nounwind }
 // CHECK-UNOPT: attributes [[NUW]] = { nounwind }
Index: clang/l

[PATCH] D116792: [AST] lookup in parent DeclContext for transparent DeclContext

2022-01-10 Thread Chuanqi Xu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd9d63fc1088c: [AST] lookup in parent DeclContext for 
transparent DeclContext (authored by ChuanqiXu).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116792

Files:
  clang/lib/AST/DeclBase.cpp
  clang/test/Modules/Inputs/template_name_lookup/foo.cppm
  clang/test/Modules/template_name_lookup.cpp
  clang/test/SemaCXX/lookup-template-name-extern-CXX.cpp


Index: clang/test/SemaCXX/lookup-template-name-extern-CXX.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/lookup-template-name-extern-CXX.cpp
@@ -0,0 +1,12 @@
+// Tests that the lookup in transparent declaration context
+// (linkage specifiaction context) wouldn't cause compiler crash.
+// RUN: %clang_cc1 -std=c++20 %s -fsyntax-only -verify
+extern "C++" {
+template 
+class X {}; // expected-note {{candidate template ignored: couldn't infer 
template argument 'T'}}
+// expected-note@-1 {{candidate function template not viable: 
requires 1 argument, but 0 were provided}}
+}
+
+void foo() {
+  X x; // expected-error {{no viable constructor or deduction guide for 
deduction of template arguments of 'X'}}
+}
Index: clang/test/Modules/template_name_lookup.cpp
===
--- /dev/null
+++ clang/test/Modules/template_name_lookup.cpp
@@ -0,0 +1,11 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: %clang_cc1 -std=c++20 %S/Inputs/template_name_lookup/foo.cppm 
-emit-module-interface -o %t/foo.pcm
+// RUN: %clang_cc1 -std=c++20 -fprebuilt-module-path=%t %s -fsyntax-only 
-verify
+
+import foo;
+void use() {
+  X x; // expected-error {{no viable constructor or deduction guide for 
deduction of template arguments of 'X'}}
+   // expected-note@Inputs/template_name_lookup/foo.cppm:3 {{candidate 
template ignored: couldn't infer template argument 'T'}}
+   // expected-note@Inputs/template_name_lookup/foo.cppm:3 {{candidate 
function template not viable: requires 1 argument, but 0 were provided}}
+}
Index: clang/test/Modules/Inputs/template_name_lookup/foo.cppm
===
--- /dev/null
+++ clang/test/Modules/Inputs/template_name_lookup/foo.cppm
@@ -0,0 +1,3 @@
+export module foo;
+export template 
+class X {};
Index: clang/lib/AST/DeclBase.cpp
===
--- clang/lib/AST/DeclBase.cpp
+++ clang/lib/AST/DeclBase.cpp
@@ -1644,9 +1644,9 @@
 
 DeclContext::lookup_result
 DeclContext::lookup(DeclarationName Name) const {
-  assert(getDeclKind() != Decl::LinkageSpec &&
- getDeclKind() != Decl::Export &&
- "should not perform lookups into transparent contexts");
+  // For transparent DeclContext, we should lookup in their enclosing context.
+  if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
+return getParent()->lookup(Name);
 
   const DeclContext *PrimaryContext = getPrimaryContext();
   if (PrimaryContext != this)


Index: clang/test/SemaCXX/lookup-template-name-extern-CXX.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/lookup-template-name-extern-CXX.cpp
@@ -0,0 +1,12 @@
+// Tests that the lookup in transparent declaration context
+// (linkage specifiaction context) wouldn't cause compiler crash.
+// RUN: %clang_cc1 -std=c++20 %s -fsyntax-only -verify
+extern "C++" {
+template 
+class X {}; // expected-note {{candidate template ignored: couldn't infer template argument 'T'}}
+// expected-note@-1 {{candidate function template not viable: requires 1 argument, but 0 were provided}}
+}
+
+void foo() {
+  X x; // expected-error {{no viable constructor or deduction guide for deduction of template arguments of 'X'}}
+}
Index: clang/test/Modules/template_name_lookup.cpp
===
--- /dev/null
+++ clang/test/Modules/template_name_lookup.cpp
@@ -0,0 +1,11 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: %clang_cc1 -std=c++20 %S/Inputs/template_name_lookup/foo.cppm -emit-module-interface -o %t/foo.pcm
+// RUN: %clang_cc1 -std=c++20 -fprebuilt-module-path=%t %s -fsyntax-only -verify
+
+import foo;
+void use() {
+  X x; // expected-error {{no viable constructor or deduction guide for deduction of template arguments of 'X'}}
+   // expected-note@Inputs/template_name_lookup/foo.cppm:3 {{candidate template ignored: couldn't infer template argument 'T'}}
+   // expected-note@Inputs/template_name_lookup/foo.cppm:3 {{candidate function template not viable: requires 1 argument, but 0 were provided}}
+}
Index: clang/test/Modules/Inputs/template_name_lookup/foo.cppm
===
--- /dev/null
+++ clang/test/Modules/Inputs/template_name

[clang] d9d63fc - [AST] lookup in parent DeclContext for transparent DeclContext

2022-01-10 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-01-11T10:16:26+08:00
New Revision: d9d63fc1088c22129cde9c3d3a84f356c875190e

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

LOG: [AST] lookup in parent DeclContext for transparent DeclContext

The compiler would crash if we lookup for name in transparent decl
context. See the tests attached for example.

I think this should make sense since the member declared in transparent
DeclContext are semantically defined in the enclosing (non-transparent)
DeclContext, this is the definition for transparent DeclContext.

Reviewed By: erichkeane

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

Added: 
clang/test/Modules/Inputs/template_name_lookup/foo.cppm
clang/test/Modules/template_name_lookup.cpp
clang/test/SemaCXX/lookup-template-name-extern-CXX.cpp

Modified: 
clang/lib/AST/DeclBase.cpp

Removed: 




diff  --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index 52b8a45721105..98a5c6b664713 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -1644,9 +1644,9 @@ void DeclContext::buildLookupImpl(DeclContext *DCtx, bool 
Internal) {
 
 DeclContext::lookup_result
 DeclContext::lookup(DeclarationName Name) const {
-  assert(getDeclKind() != Decl::LinkageSpec &&
- getDeclKind() != Decl::Export &&
- "should not perform lookups into transparent contexts");
+  // For transparent DeclContext, we should lookup in their enclosing context.
+  if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
+return getParent()->lookup(Name);
 
   const DeclContext *PrimaryContext = getPrimaryContext();
   if (PrimaryContext != this)

diff  --git a/clang/test/Modules/Inputs/template_name_lookup/foo.cppm 
b/clang/test/Modules/Inputs/template_name_lookup/foo.cppm
new file mode 100644
index 0..ee1973f65e716
--- /dev/null
+++ b/clang/test/Modules/Inputs/template_name_lookup/foo.cppm
@@ -0,0 +1,3 @@
+export module foo;
+export template 
+class X {};

diff  --git a/clang/test/Modules/template_name_lookup.cpp 
b/clang/test/Modules/template_name_lookup.cpp
new file mode 100644
index 0..29375e514025f
--- /dev/null
+++ b/clang/test/Modules/template_name_lookup.cpp
@@ -0,0 +1,11 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: %clang_cc1 -std=c++20 %S/Inputs/template_name_lookup/foo.cppm 
-emit-module-interface -o %t/foo.pcm
+// RUN: %clang_cc1 -std=c++20 -fprebuilt-module-path=%t %s -fsyntax-only 
-verify
+
+import foo;
+void use() {
+  X x; // expected-error {{no viable constructor or deduction guide for 
deduction of template arguments of 'X'}}
+   // expected-note@Inputs/template_name_lookup/foo.cppm:3 {{candidate 
template ignored: couldn't infer template argument 'T'}}
+   // expected-note@Inputs/template_name_lookup/foo.cppm:3 {{candidate 
function template not viable: requires 1 argument, but 0 were provided}}
+}

diff  --git a/clang/test/SemaCXX/lookup-template-name-extern-CXX.cpp 
b/clang/test/SemaCXX/lookup-template-name-extern-CXX.cpp
new file mode 100644
index 0..93e7fb6199354
--- /dev/null
+++ b/clang/test/SemaCXX/lookup-template-name-extern-CXX.cpp
@@ -0,0 +1,12 @@
+// Tests that the lookup in transparent declaration context
+// (linkage specifiaction context) wouldn't cause compiler crash.
+// RUN: %clang_cc1 -std=c++20 %s -fsyntax-only -verify
+extern "C++" {
+template 
+class X {}; // expected-note {{candidate template ignored: couldn't infer 
template argument 'T'}}
+// expected-note@-1 {{candidate function template not viable: 
requires 1 argument, but 0 were provided}}
+}
+
+void foo() {
+  X x; // expected-error {{no viable constructor or deduction guide for 
deduction of template arguments of 'X'}}
+}



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


[PATCH] D116911: [AST] Don't consider 'ExportDecl' when calculating DeclContext 'Encloses'

2022-01-10 Thread Chuanqi Xu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG86c5b870b2e5: [AST] Don't consider 
'ExportDecl' when calculating DeclContext 'Encloses' 
(authored by ChuanqiXu).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116911

Files:
  clang/lib/AST/DeclBase.cpp
  clang/test/SemaCXX/lookup-through-export.cpp


Index: clang/test/SemaCXX/lookup-through-export.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/lookup-through-export.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -std=c++20 %s -verify
+
+// expected-no-diagnostics
+export module X;
+export {
+  namespace A {
+  namespace B {
+  int bar;
+  }
+  } // namespace A
+  namespace C {
+  void foo() {
+using namespace A;
+(void)B::bar;
+  }
+  } // namespace C
+}
+
+export {
+  namespace D {
+  namespace E {
+  int bar;
+  }
+  } // namespace D
+  namespace F {
+  void foo() {
+using namespace D;
+(void)E::bar;
+  }
+  } // namespace F
+}
Index: clang/lib/AST/DeclBase.cpp
===
--- clang/lib/AST/DeclBase.cpp
+++ clang/lib/AST/DeclBase.cpp
@@ -1212,7 +1212,8 @@
 return getPrimaryContext()->Encloses(DC);
 
   for (; DC; DC = DC->getParent())
-if (!isa(DC) && DC->getPrimaryContext() == this)
+if (!isa(DC) && !isa(DC) &&
+DC->getPrimaryContext() == this)
   return true;
   return false;
 }


Index: clang/test/SemaCXX/lookup-through-export.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/lookup-through-export.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -std=c++20 %s -verify
+
+// expected-no-diagnostics
+export module X;
+export {
+  namespace A {
+  namespace B {
+  int bar;
+  }
+  } // namespace A
+  namespace C {
+  void foo() {
+using namespace A;
+(void)B::bar;
+  }
+  } // namespace C
+}
+
+export {
+  namespace D {
+  namespace E {
+  int bar;
+  }
+  } // namespace D
+  namespace F {
+  void foo() {
+using namespace D;
+(void)E::bar;
+  }
+  } // namespace F
+}
Index: clang/lib/AST/DeclBase.cpp
===
--- clang/lib/AST/DeclBase.cpp
+++ clang/lib/AST/DeclBase.cpp
@@ -1212,7 +1212,8 @@
 return getPrimaryContext()->Encloses(DC);
 
   for (; DC; DC = DC->getParent())
-if (!isa(DC) && DC->getPrimaryContext() == this)
+if (!isa(DC) && !isa(DC) &&
+DC->getPrimaryContext() == this)
   return true;
   return false;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 86c5b87 - [AST] Don't consider 'ExportDecl' when calculating DeclContext 'Encloses'

2022-01-10 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-01-11T09:54:57+08:00
New Revision: 86c5b870b2e5192a9414204500a53b31524db065

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

LOG: [AST] Don't consider 'ExportDecl' when calculating DeclContext 'Encloses'

This mimics the style of 90010c2e1 (Don't consider 'LinkageSpec' when
calculating DeclContext 'Encloses'). Since ExportDecl and LinkageSpec
are transparent DeclContext, they share some similarity.

Reviewed By: erichkeane

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

Added: 
clang/test/SemaCXX/lookup-through-export.cpp

Modified: 
clang/lib/AST/DeclBase.cpp

Removed: 




diff  --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index 064012ba865c8..52b8a45721105 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -1212,7 +1212,8 @@ bool DeclContext::Encloses(const DeclContext *DC) const {
 return getPrimaryContext()->Encloses(DC);
 
   for (; DC; DC = DC->getParent())
-if (!isa(DC) && DC->getPrimaryContext() == this)
+if (!isa(DC) && !isa(DC) &&
+DC->getPrimaryContext() == this)
   return true;
   return false;
 }

diff  --git a/clang/test/SemaCXX/lookup-through-export.cpp 
b/clang/test/SemaCXX/lookup-through-export.cpp
new file mode 100644
index 0..503a694655608
--- /dev/null
+++ b/clang/test/SemaCXX/lookup-through-export.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -std=c++20 %s -verify
+
+// expected-no-diagnostics
+export module X;
+export {
+  namespace A {
+  namespace B {
+  int bar;
+  }
+  } // namespace A
+  namespace C {
+  void foo() {
+using namespace A;
+(void)B::bar;
+  }
+  } // namespace C
+}
+
+export {
+  namespace D {
+  namespace E {
+  int bar;
+  }
+  } // namespace D
+  namespace F {
+  void foo() {
+using namespace D;
+(void)E::bar;
+  }
+  } // namespace F
+}



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


[PATCH] D111566: [SYCL] Fix function pointer address space

2022-01-10 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/AST/ASTContext.cpp:11496
+   .getProgramAddressSpace()
+ : getTargetAddressSpace(T.getQualifiers());
+}

Oh, I'm sorry I missed this.  Parsing the data layout string into an 
`llvm::DataLayout` is definitely not an okay thing to be doing here.  The IRGen 
version of this had a cached `DataLayout` object which it queried, which was 
okay, but this function is used too tightly to be doing that much redundant 
work.

We could just cache a `DataLayout` in the `clang::TargetInfo`, but I think 
we've been trying to avoid that as a layering violation.  Instead, `TargetInfo` 
should just have a `getProgramAddressSpace` method or something like that, and 
the targets with non-default address spaces for code should set that manually.



Comment at: clang/lib/AST/ASTContext.cpp:11497
+   .getProgramAddressSpace()
+ : getTargetAddressSpace(T.getQualifiers());
+}

eandrews wrote:
> rjmccall wrote:
> > If a function type has an address space qualifier, we should prefer that, 
> > right?  Or is that impossible by construction?
> I thought you could only use address space qualifiers for variables. I am not 
> sure though. 
> 
> This patch retains existing behavior for pointers.  The existing code 
> (deleted in CodeGenTypes.cpp in his patch) doesn't take qualifiers into 
> consideration. 
Ah, yes, I see.  Alright.


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

https://reviews.llvm.org/D111566

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


[PATCH] D114908: [clang] Don't call inheritDefaultTemplateArguments() on CXXDeductionGuideDecl's template parameters

2022-01-10 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added inline comments.



Comment at: clang/lib/Serialization/ASTReaderDecl.cpp:3784-3790
+  if (auto *TD = dyn_cast(D)) {
+// CXXDeductionGuideDecls reference the class template parameters so we 
need
+// to make sure not to call this twice on the same template parameters.
+if (!isa(TD->getTemplatedDecl()))
+  inheritDefaultTemplateArguments(Reader.getContext(),
+  cast(Previous), TD);
+  }

rsmith wrote:
> An implicit deduction guide can get template parameters from both the class 
> template and the constructor template. The ones from the class template are 
> not copied and owned by the deduction guide, but the ones from the 
> constructor template are. So I think we may need to do this for *some* of the 
> template parameters and not others. Perhaps we could check to see if the 
> template parameter is actually owned by this template and skip updating it if 
> not.
> 
> (Alternatively, I think it'd be fine, and probably simpler and cleaner, to 
> make implicit deduction guide generation always clone the template parameters 
> of the class template. The confusion caused by having the template parameters 
> appear in the "wrong" template is probably not justified by the time / memory 
> savings.)
I tried https://reviews.llvm.org/D116983 and it still doesn't fix this issue, 
although I'm having trouble understanding the Clang AST and the decl chains.
How would you check that the template parameter is owned by this template?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114908

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


[clang] 140a6b1 - [clang][OpenMP5.1] Initial parsing/sema for 'indirect' clause

2022-01-10 Thread Jennifer Yu via cfe-commits

Author: Jennifer Yu
Date: 2022-01-10T16:58:56-08:00
New Revision: 140a6b1e5c6857617a83f66680b4829ff2b08d82

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

LOG: [clang][OpenMP5.1] Initial parsing/sema for 'indirect' clause

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

Added: 


Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/lib/AST/AttrImpl.cpp
clang/lib/CodeGen/CGStmtOpenMP.cpp
clang/lib/Parse/ParseOpenMP.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Serialization/ASTReaderDecl.cpp
clang/test/OpenMP/declare_target_ast_print.cpp
clang/test/OpenMP/declare_target_messages.cpp
flang/lib/Semantics/check-omp-structure.cpp
llvm/include/llvm/Frontend/OpenMP/OMP.td

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 10c5c7f1b879a..b071ebb4d576b 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3686,6 +3686,8 @@ def OMPDeclareTargetDecl : InheritableAttr {
 EnumArgument<"DevType", "DevTypeTy",
  [ "host", "nohost", "any" ],
  [ "DT_Host", "DT_NoHost", "DT_Any" ]>,
+ExprArgument<"IndirectExpr">,
+BoolArgument<"Indirect">,
 UnsignedArgument<"Level">
   ];
   let AdditionalMembers = [{

diff  --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 9dc036c03faa8..193dff8b9c8f6 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1344,15 +1344,17 @@ def warn_omp_unknown_assumption_clause_without_args
 def note_omp_assumption_clause_continue_here
 : Note<"the ignored tokens spans until here">;
 def err_omp_declare_target_unexpected_clause: Error<
-  "unexpected '%0' clause, only %select{'device_type'|'to' or 'link'|'to', 
'link' or 'device_type'}1 clauses expected">;
+  "unexpected '%0' clause, only %select{'device_type'|'to' or 'link'|'to', 
'link' or 'device_type'|'device_type', 'indirect'|'to', 'link', 'device_type' 
or 'indirect'}1 clauses expected">;
 def err_omp_begin_declare_target_unexpected_implicit_to_clause: Error<
   "unexpected '(', only 'to', 'link' or 'device_type' clauses expected for 
'begin declare target' directive">;
 def err_omp_declare_target_unexpected_clause_after_implicit_to: Error<
   "unexpected clause after an implicit 'to' clause">;
 def err_omp_declare_target_missing_to_or_link_clause: Error<
-  "expected at least one 'to' or 'link' clause">;
+  "expected at least one %select{'to' or 'link'|'to', 'link' or 'indirect'}0 
clause">;
 def err_omp_declare_target_multiple : Error<
   "%0 appears multiple times in clauses on the same declare target directive">;
+def err_omp_declare_target_indirect_device_type: Error<
+  "only 'device_type(any)' clause is allowed with indirect clause">;
 def err_omp_expected_clause: Error<
   "expected at least one clause on '#pragma omp %0' directive">;
 def err_omp_mapper_illegal_identifier : Error<

diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index a98ad78401f02..74935c8900178 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -3316,6 +3316,11 @@ class Parser : public CodeCompletionHandler {
   /// nullptr.
   ///
   OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
+  /// Parses indirect clause
+  /// \param ParseOnly true to skip the clause's semantic actions and return
+  // false;
+  bool ParseOpenMPIndirectClause(Sema::DeclareTargetContextInfo &DTCI,
+ bool ParseOnly);
   /// Parses clause with a single expression and an additional argument
   /// of a kind \a Kind.
   ///

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 9b6d9d20ca431..f1e90356c8367 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10333,6 +10333,9 @@ class Sema final {
 /// The directive kind, `begin declare target` or `declare target`.
 OpenMPDirectiveKind Kind;
 
+/// The directive with indirect clause.
+Optional Indirect;
+
 /// The directive location.
 SourceLocation Loc;
 
@@ -10639,7 +10642,7 @@ class Sema final {
   /// Called on correct id-expression from the '#pragma omp declare target'.
   void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
 OMPDeclareTargetDeclAttr::MapTypeTy MT,
-OMPDeclareTargetDeclAttr::DevTypeTy DT);
+DeclareTargetContextIn

[PATCH] D116764: [clang][OpenMP5.1] Initial parsing/sema for 'indirect' clause

2022-01-10 Thread Jennifer Yu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG140a6b1e5c68: [clang][OpenMP5.1] Initial parsing/sema for 
'indirect' clause (authored by jyu2).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116764

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/AttrImpl.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/test/OpenMP/declare_target_ast_print.cpp
  clang/test/OpenMP/declare_target_messages.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -358,6 +358,7 @@
 def OMPC_Link : Clause<"link"> {
   let flangClass = "OmpObjectList";
 }
+def OMPC_Indirect : Clause<"indirect"> {}
 def OMPC_Inbranch : Clause<"inbranch"> {}
 def OMPC_Notinbranch : Clause<"notinbranch"> {}
 def OMPC_Filter : Clause<"filter"> {
@@ -973,12 +974,14 @@
 VersionedClause,
 VersionedClause,
 VersionedClause,
+VersionedClause
   ];
 }
 def OMP_DeclareTarget : Directive<"declare target"> {
   let allowedClauses = [
 VersionedClause,
-VersionedClause
+VersionedClause,
+VersionedClause
   ];
 }
 def OMP_EndDeclareTarget : Directive<"end declare target"> {}
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -1528,6 +1528,7 @@
 CHECK_SIMPLE_CLAUSE(Inbranch, OMPC_inbranch)
 CHECK_SIMPLE_CLAUSE(IsDevicePtr, OMPC_is_device_ptr)
 CHECK_SIMPLE_CLAUSE(Link, OMPC_link)
+CHECK_SIMPLE_CLAUSE(Indirect, OMPC_indirect)
 CHECK_SIMPLE_CLAUSE(Mergeable, OMPC_mergeable)
 CHECK_SIMPLE_CLAUSE(Nogroup, OMPC_nogroup)
 CHECK_SIMPLE_CLAUSE(Notinbranch, OMPC_notinbranch)
Index: clang/test/OpenMP/declare_target_messages.cpp
===
--- clang/test/OpenMP/declare_target_messages.cpp
+++ clang/test/OpenMP/declare_target_messages.cpp
@@ -5,11 +5,13 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp5,host5 -fopenmp-simd -fopenmp-targets=x86_64-apple-macos10.7.0 -fnoopenmp-use-tls -ferror-limit 100 -o - %s
 // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp5,host5 -fopenmp-simd -fopenmp-is-device -fopenmp-targets=x86_64-apple-macos10.7.0 -fnoopenmp-use-tls -ferror-limit 100 -o - %s
 // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp45 -fopenmp-version=45 -fopenmp-simd -fnoopenmp-use-tls -ferror-limit 100 -o - %s
+// RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp51 -fopenmp -fopenmp-version=51 -fnoopenmp-use-tls -ferror-limit 100 -o - %s
+// RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp51 -fopenmp-version=51 -fopenmp-simd -fnoopenmp-use-tls -ferror-limit 100 -o - %s
 
 // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp5 -fopenmp -fnoopenmp-use-tls -ferror-limit 100 -o - %s
 #pragma omp end declare target // expected-error {{unexpected OpenMP directive '#pragma omp end declare target'}}
 
-int a, b, z; // omp5-error {{variable captured in declare target region must appear in a to clause}}
+int a, b, z; // omp5-error {{variable captured in declare target region must appear in a to clause}} // omp51-error {{variable captured in declare target region must appear in a to clause}}
 __thread int t; // expected-note {{defined as threadprivate or thread local}}
 
 #pragma omp declare target . // expected-error {{expected '(' after 'declare target'}}
@@ -18,7 +20,7 @@
 void f();
 #pragma omp end declare target shared(a) // expected-warning {{extra tokens at the end of '#pragma omp end declare target' are ignored}}
 
-#pragma omp declare target map(a) // expected-error {{expected at least one 'to' or 'link' clause}} omp45-error {{unexpected 'map' clause, only 'to' or 'link' clauses expected}} omp5-error {{unexpected 'map' clause, only 'to', 'link' or 'device_type' clauses expected}}
+#pragma omp declare target map(a) // omp45-error {{expected at least one 'to' or 'link' clause}} omp5-error {{expected at least one 'to' or 'link' clause}} omp51-error {{expected at least one 'to', 'link' or 'indirect' clause}} omp45-error {{unexpected 'map' clause, only 'to' or 'link' clauses expected}} omp5-error {{unexpected 'map' clause, only 'to', 'link' or 'device_type' clauses expected}} omp51-error {{unexpected 'map' clause, only 'to', 'link', 'device_type' or 'indirect' clauses expected}}
 
 #prag

[PATCH] D111566: [SYCL] Fix function pointer address space

2022-01-10 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews updated this revision to Diff 398784.
eandrews added a comment.

Implement review comments - add a comment + remove unnecessary code


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

https://reviews.llvm.org/D111566

Files:
  clang/include/clang/AST/ASTContext.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/test/CodeGenSYCL/functionptr-addressspace.cpp

Index: clang/test/CodeGenSYCL/functionptr-addressspace.cpp
===
--- /dev/null
+++ clang/test/CodeGenSYCL/functionptr-addressspace.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -fsycl-is-device -emit-llvm -triple spir64 -verify -emit-llvm %s -o - | FileCheck %s
+
+// expected-no-diagnostics
+
+template 
+__attribute__((sycl_kernel)) void kernel_single_task(const Func &kernelFunc) {
+  kernelFunc();
+}
+
+// CHECK: define dso_local spir_func{{.*}}invoke_function{{.*}}(i32 ()* %fptr, i32 addrspace(4)* %ptr)
+void invoke_function(int (*fptr)(), int *ptr) {}
+
+int f() { return 0; }
+
+int main() {
+  kernel_single_task([=]() {
+int (*p)() = f;
+int (&r)() = *p;
+int a = 10;
+invoke_function(p, &a);
+invoke_function(r, &a);
+invoke_function(f, &a);
+  });
+  return 0;
+}
Index: clang/lib/CodeGen/CodeGenTypes.cpp
===
--- clang/lib/CodeGen/CodeGenTypes.cpp
+++ clang/lib/CodeGen/CodeGenTypes.cpp
@@ -643,11 +643,7 @@
 llvm::Type *PointeeType = ConvertTypeForMem(ETy);
 if (PointeeType->isVoidTy())
   PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
-
-unsigned AS = PointeeType->isFunctionTy()
-  ? getDataLayout().getProgramAddressSpace()
-  : Context.getTargetAddressSpace(ETy);
-
+unsigned AS = Context.getTargetAddressSpace(ETy);
 ResultType = llvm::PointerType::get(PointeeType, AS);
 break;
   }
@@ -748,7 +744,13 @@
 llvm::Type *PointeeType = CGM.getLangOpts().OpenCL
   ? CGM.getGenericBlockLiteralType()
   : ConvertTypeForMem(FTy);
-unsigned AS = Context.getTargetAddressSpace(FTy);
+// Block pointers lower to function type. For function type,
+// getTargetAddressSpace() returns default address space for
+// function pointer i.e. program address space. Therefore, for block
+// pointers, it is important to pass qualifiers when calling
+// getTargetAddressSpace(), to ensure that we get the address space
+// for data pointers and not function pointers.
+unsigned AS = Context.getTargetAddressSpace(FTy.getQualifiers());
 ResultType = llvm::PointerType::get(PointeeType, AS);
 break;
   }
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -80,6 +80,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/IR/DataLayout.h"
 #include "llvm/Support/Capacity.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/Compiler.h"
@@ -11488,6 +11489,17 @@
   return getTargetInfo().getNullPointerValue(AS);
 }
 
+unsigned ASTContext::getTargetAddressSpace(QualType T) const {
+  return T->isFunctionType()
+ ? llvm::DataLayout(getTargetInfo().getDataLayoutString())
+   .getProgramAddressSpace()
+ : getTargetAddressSpace(T.getQualifiers());
+}
+
+unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const {
+  return getTargetAddressSpace(Q.getAddressSpace());
+}
+
 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
   if (isTargetAddressSpace(AS))
 return toTargetAddressSpace(AS);
Index: clang/include/clang/AST/ASTContext.h
===
--- clang/include/clang/AST/ASTContext.h
+++ clang/include/clang/AST/ASTContext.h
@@ -2709,13 +2709,9 @@
   QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
  QualType typeDomain) const;
 
-  unsigned getTargetAddressSpace(QualType T) const {
-return getTargetAddressSpace(T.getQualifiers());
-  }
+  unsigned getTargetAddressSpace(QualType T) const;
 
-  unsigned getTargetAddressSpace(Qualifiers Q) const {
-return getTargetAddressSpace(Q.getAddressSpace());
-  }
+  unsigned getTargetAddressSpace(Qualifiers Q) const;
 
   unsigned getTargetAddressSpace(LangAS AS) const;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116721: [Tooling] When transferring compile commands between files, always use '--'

2022-01-10 Thread Sam McCall 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 rG4258d68dc737: [Tooling] When transferring compile commands 
between files, always use '--' (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116721

Files:
  clang-tools-extra/clangd/CompileCommands.cpp
  clang/include/clang/Tooling/CompilationDatabase.h
  clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
  clang/unittests/Tooling/CompilationDatabaseTest.cpp


Index: clang/unittests/Tooling/CompilationDatabaseTest.cpp
===
--- clang/unittests/Tooling/CompilationDatabaseTest.cpp
+++ clang/unittests/Tooling/CompilationDatabaseTest.cpp
@@ -739,6 +739,9 @@
 EXPECT_EQ(Results[0].CommandLine.back(), MakeNative ? path(F) : F)
 << "Last arg should be the file";
 Results[0].CommandLine.pop_back();
+EXPECT_EQ(Results[0].CommandLine.back(), "--")
+<< "Second-last arg should be --";
+Results[0].CommandLine.pop_back();
 return llvm::join(Results[0].CommandLine, " ");
   }
 
@@ -826,18 +829,6 @@
   EXPECT_EQ(getCommand("dir/bar.cpp"), "clang -D dir/foo.cpp -Wall 
-std=c++14");
 }
 
-TEST_F(InterpolateTest, InsertDoubleDash) {
-  add("dir/foo.cpp", "-o foo.o -std=c++14 -Wall");
-  EXPECT_EQ(getCommand("-dir/bar.cpp", false),
-"clang -D dir/foo.cpp -Wall -std=c++14 --");
-}
-
-TEST_F(InterpolateTest, InsertDoubleDashForClangCL) {
-  add("dir/foo.cpp", "clang-cl", "/std:c++14 /W4");
-  EXPECT_EQ(getCommand("/dir/bar.cpp", false),
-"clang-cl -D dir/foo.cpp /W4 /std:c++14 --");
-}
-
 TEST_F(InterpolateTest, Case) {
   add("FOO/BAR/BAZ/SHOUT.cc");
   add("foo/bar/baz/quiet.cc");
@@ -879,7 +870,7 @@
   CompileCommand Transferred = transferCompileCommand(std::move(Cmd), "foo.h");
   EXPECT_EQ(Transferred.Filename, "foo.h");
   EXPECT_THAT(Transferred.CommandLine,
-  ElementsAre("clang", "-Wall", "-x", "c++-header", "foo.h"));
+  ElementsAre("clang", "-Wall", "-x", "c++-header", "--", 
"foo.h"));
   EXPECT_EQ(Transferred.Directory, "dir");
 }
 
Index: clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
===
--- clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
+++ clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
@@ -243,8 +243,7 @@
   llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
   LangStandard::getLangStandardForKind(Std).getName()).str());
 }
-if (Filename.startswith("-") || (ClangCLMode && Filename.startswith("/")))
-  Result.CommandLine.push_back("--");
+Result.CommandLine.push_back("--");
 Result.CommandLine.push_back(std::string(Filename));
 return Result;
   }
Index: clang/include/clang/Tooling/CompilationDatabase.h
===
--- clang/include/clang/Tooling/CompilationDatabase.h
+++ clang/include/clang/Tooling/CompilationDatabase.h
@@ -216,6 +216,8 @@
 /// Transforms a compile command so that it applies the same configuration to
 /// a different file. Most args are left intact, but tweaks may be needed
 /// to certain flags (-x, -std etc).
+///
+/// The output command will always end in {"--", Filename}.
 tooling::CompileCommand transferCompileCommand(tooling::CompileCommand,
StringRef Filename);
 
Index: clang-tools-extra/clangd/CompileCommands.cpp
===
--- clang-tools-extra/clangd/CompileCommands.cpp
+++ clang-tools-extra/clangd/CompileCommands.cpp
@@ -290,16 +290,9 @@
 TransferCmd.CommandLine = std::move(Cmd);
 TransferCmd = transferCompileCommand(std::move(TransferCmd), File);
 Cmd = std::move(TransferCmd.CommandLine);
-
-// Restore the canonical "driver --opts -- filename" form we expect.
-// FIXME: This is ugly and coupled. Make transferCompileCommand ensure it?
-assert(!Cmd.empty() && Cmd.back() == File);
-Cmd.pop_back();
-if (!Cmd.empty() && Cmd.back() == "--")
-  Cmd.pop_back();
-assert(!llvm::is_contained(Cmd, "--"));
-Cmd.push_back("--");
-Cmd.push_back(File.str());
+assert(Cmd.size() >= 2 && Cmd.back() == File &&
+   Cmd[Cmd.size() - 2] == "--" &&
+   "TransferCommand should produce a command ending in -- filename");
   }
 
   for (auto &Edit : Config::current().CompileFlags.Edits)


Index: clang/unittests/Tooling/CompilationDatabaseTest.cpp
===
--- clang/unittests/Tooling/CompilationDatabaseTest.cpp
+++ clang/unittests/Tooling/CompilationDatabaseTest.cpp
@@ -739,6 +739,9 @@
 EXPECT_EQ(Results[0].CommandLine.back(), MakeNative ? path(F) : F)
 << "Last arg should be the file";
 Resu

[clang-tools-extra] 4258d68 - [Tooling] When transferring compile commands between files, always use '--'

2022-01-10 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-11T01:41:42+01:00
New Revision: 4258d68dc73789bc7fc491734c9c392809b1b29a

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

LOG: [Tooling] When transferring compile commands between files, always use '--'

"driver  -- " is a particularly convenient form of the
compile command to manipulate, with fewer special cases to handle.

Guaranteeing that the output command is of that form is cheap and makes
it easier to consume the result in some cases.

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

Added: 


Modified: 
clang-tools-extra/clangd/CompileCommands.cpp
clang/include/clang/Tooling/CompilationDatabase.h
clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
clang/unittests/Tooling/CompilationDatabaseTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CompileCommands.cpp 
b/clang-tools-extra/clangd/CompileCommands.cpp
index 5c98e40a87fdd..7d6f612cb8b96 100644
--- a/clang-tools-extra/clangd/CompileCommands.cpp
+++ b/clang-tools-extra/clangd/CompileCommands.cpp
@@ -290,16 +290,9 @@ void CommandMangler::adjust(std::vector &Cmd,
 TransferCmd.CommandLine = std::move(Cmd);
 TransferCmd = transferCompileCommand(std::move(TransferCmd), File);
 Cmd = std::move(TransferCmd.CommandLine);
-
-// Restore the canonical "driver --opts -- filename" form we expect.
-// FIXME: This is ugly and coupled. Make transferCompileCommand ensure it?
-assert(!Cmd.empty() && Cmd.back() == File);
-Cmd.pop_back();
-if (!Cmd.empty() && Cmd.back() == "--")
-  Cmd.pop_back();
-assert(!llvm::is_contained(Cmd, "--"));
-Cmd.push_back("--");
-Cmd.push_back(File.str());
+assert(Cmd.size() >= 2 && Cmd.back() == File &&
+   Cmd[Cmd.size() - 2] == "--" &&
+   "TransferCommand should produce a command ending in -- filename");
   }
 
   for (auto &Edit : Config::current().CompileFlags.Edits)

diff  --git a/clang/include/clang/Tooling/CompilationDatabase.h 
b/clang/include/clang/Tooling/CompilationDatabase.h
index 90af15536961e..fee584acb4862 100644
--- a/clang/include/clang/Tooling/CompilationDatabase.h
+++ b/clang/include/clang/Tooling/CompilationDatabase.h
@@ -216,6 +216,8 @@ class FixedCompilationDatabase : public CompilationDatabase 
{
 /// Transforms a compile command so that it applies the same configuration to
 /// a 
diff erent file. Most args are left intact, but tweaks may be needed
 /// to certain flags (-x, -std etc).
+///
+/// The output command will always end in {"--", Filename}.
 tooling::CompileCommand transferCompileCommand(tooling::CompileCommand,
StringRef Filename);
 

diff  --git a/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp 
b/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
index c1e25c41f7198..51e8439b6b79b 100644
--- a/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
+++ b/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
@@ -243,8 +243,7 @@ struct TransferableCommand {
   llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
   LangStandard::getLangStandardForKind(Std).getName()).str());
 }
-if (Filename.startswith("-") || (ClangCLMode && Filename.startswith("/")))
-  Result.CommandLine.push_back("--");
+Result.CommandLine.push_back("--");
 Result.CommandLine.push_back(std::string(Filename));
 return Result;
   }

diff  --git a/clang/unittests/Tooling/CompilationDatabaseTest.cpp 
b/clang/unittests/Tooling/CompilationDatabaseTest.cpp
index 218a352f86f06..adb9de0c1cbaa 100644
--- a/clang/unittests/Tooling/CompilationDatabaseTest.cpp
+++ b/clang/unittests/Tooling/CompilationDatabaseTest.cpp
@@ -739,6 +739,9 @@ class InterpolateTest : public MemDBTest {
 EXPECT_EQ(Results[0].CommandLine.back(), MakeNative ? path(F) : F)
 << "Last arg should be the file";
 Results[0].CommandLine.pop_back();
+EXPECT_EQ(Results[0].CommandLine.back(), "--")
+<< "Second-last arg should be --";
+Results[0].CommandLine.pop_back();
 return llvm::join(Results[0].CommandLine, " ");
   }
 
@@ -826,18 +829,6 @@ TEST_F(InterpolateTest, StripDoubleDash) {
   EXPECT_EQ(getCommand("dir/bar.cpp"), "clang -D dir/foo.cpp -Wall 
-std=c++14");
 }
 
-TEST_F(InterpolateTest, InsertDoubleDash) {
-  add("dir/foo.cpp", "-o foo.o -std=c++14 -Wall");
-  EXPECT_EQ(getCommand("-dir/bar.cpp", false),
-"clang -D dir/foo.cpp -Wall -std=c++14 --");
-}
-
-TEST_F(InterpolateTest, InsertDoubleDashForClangCL) {
-  add("dir/foo.cpp", "clang-cl", "/std:c++14 /W4");
-  EXPECT_EQ(getCommand("/dir/bar.cpp", false),
-"clang-cl -D dir/foo.cpp /W4 /std:c++14 --");
-}
-
 TEST_F(InterpolateTest, Case) {
   add("FOO/BAR/BAZ/SHOUT.cc");
   add("foo/bar/baz/quiet.cc");

[PATCH] D116387: [CodeCompletion][clangd] Clean __uglified parameter names in completion & hover

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 398779.
sammccall added a comment.

Fix printName


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116387

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/AST.h
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp
  clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
  clang/include/clang/AST/PrettyPrinter.h
  clang/include/clang/Basic/IdentifierTable.h
  clang/lib/AST/DeclPrinter.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/AST/TemplateName.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/Basic/IdentifierTable.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/deuglify.cpp
  clang/unittests/AST/DeclPrinterTest.cpp
  clang/unittests/AST/StmtPrinterTest.cpp
  clang/unittests/AST/TypePrinterTest.cpp

Index: clang/unittests/AST/TypePrinterTest.cpp
===
--- clang/unittests/AST/TypePrinterTest.cpp
+++ clang/unittests/AST/TypePrinterTest.cpp
@@ -62,4 +62,21 @@
   ASSERT_TRUE(PrintedTypeMatches(
   Code, {}, Matcher, "const N::Type &",
   [](PrintingPolicy &Policy) { Policy.FullyQualifiedName = true; }));
-}
\ No newline at end of file
+}
+
+TEST(TypePrinter, ParamsUglified) {
+  llvm::StringLiteral Code = R"cpp(
+template  class __f>
+const __f<_Tp&> *A = nullptr;
+  )cpp";
+  auto Clean = [](PrintingPolicy &Policy) {
+Policy.CleanUglifiedParameters = true;
+  };
+
+  ASSERT_TRUE(PrintedTypeMatches(Code, {},
+ varDecl(hasType(qualType().bind("id"))),
+ "const __f<_Tp &> *", nullptr));
+  ASSERT_TRUE(PrintedTypeMatches(Code, {},
+ varDecl(hasType(qualType().bind("id"))),
+ "const f *", Clean));
+}
Index: clang/unittests/AST/StmtPrinterTest.cpp
===
--- clang/unittests/AST/StmtPrinterTest.cpp
+++ clang/unittests/AST/StmtPrinterTest.cpp
@@ -263,3 +263,22 @@
 
   [](PrintingPolicy &PP) { PP.TerseOutput = true; }));
 }
+
+TEST(StmtPrinter, ParamsUglified) {
+  llvm::StringLiteral Code = R"cpp(
+template  class _C>
+auto foo(int __j) {
+  return typename _C<_T>::_F(_I, __j);
+}
+  )cpp";
+  auto Clean = [](PrintingPolicy &Policy) {
+Policy.CleanUglifiedParameters = true;
+  };
+
+  ASSERT_TRUE(PrintedStmtCXXMatches(StdVer::CXX14, Code,
+returnStmt().bind("id"),
+"return typename _C<_T>::_F(_I, __j);\n"));
+  ASSERT_TRUE(
+  PrintedStmtCXXMatches(StdVer::CXX14, Code, returnStmt().bind("id"),
+"return typename C::_F(I, j);\n", Clean));
+}
Index: clang/unittests/AST/DeclPrinterTest.cpp
===
--- clang/unittests/AST/DeclPrinterTest.cpp
+++ clang/unittests/AST/DeclPrinterTest.cpp
@@ -1336,6 +1336,41 @@
   ASSERT_TRUE(PrintedDeclCXX11Matches(Code, "NT2", "int NT2 = 5"));
 }
 
+TEST(DeclPrinter, TestFunctionParamUglified) {
+  llvm::StringLiteral Code = R"cpp(
+class __c;
+void _A(__c *__param);
+  )cpp";
+  auto Clean = [](PrintingPolicy &Policy) {
+Policy.CleanUglifiedParameters = true;
+  };
+
+  ASSERT_TRUE(PrintedDeclCXX17Matches(Code, namedDecl(hasName("_A")).bind("id"),
+  "void _A(__c *__param)"));
+  ASSERT_TRUE(PrintedDeclCXX17Matches(Code, namedDecl(hasName("_A")).bind("id"),
+  "void _A(__c *param)", Clean));
+}
+
+TEST(DeclPrinter, TestTemplateParamUglified) {
+  llvm::StringLiteral Code = R"cpp(
+template  class _Container>
+struct _A{};
+  )cpp";
+  auto Clean = [](PrintingPolicy &Policy) {
+Policy.CleanUglifiedParameters = true;
+  };
+
+  ASSERT_TRUE(PrintedDeclCXX17Matches(
+  Code, classTemplateDecl(hasName("_A")).bind("id"),
+  "template  class _Container> "
+  "struct _A {}"));
+  ASSERT_TRUE(PrintedDeclCXX17Matches(
+  Code, classTemplateDecl(hasName("_A")).bind("id"),
+  "template  class Container> "
+  "struct _A {}",
+  Clean));
+}
+
 TEST(DeclPrinter, TestStaticAssert1) {
   ASSERT_TRUE(PrintedDeclCXX17Matches("static_assert(true);",
   staticAssertDecl().bind("id"),
Index: clang/test/CodeCompletion/deuglify.cpp
===
--- /dev/null
+++ clang/test/CodeCompletion/deuglify.cpp
@@ -0,0 +1,25 @@
+// Fake standard library with uglified names.
+// Parameters (including template params) get ugliness stripped.
+namespace std {
+
+template 
+class __vector_base {};
+
+template 
+class vector : private __vector_base<_Tp> {
+public:
+  _Tp &at(unsigned __index) const;
+  int __stays_ugly();
+};
+
+} // namespace std
+
+int x = std:

[PATCH] D109981: [Diagnostics] Don't drop a statically set NoWarningAsError flag during option processing

2022-01-10 Thread Wolfgang Pieb via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd789ea713372: [Diagnostics] Don't drop a statically set 
NoWarningAsError flag during option… (authored by wolfgangp).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D109981?vs=373255&id=398778#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109981

Files:
  clang/lib/Basic/Diagnostic.cpp
  clang/test/Lexer/pragma-message.c


Index: clang/test/Lexer/pragma-message.c
===
--- clang/test/Lexer/pragma-message.c
+++ clang/test/Lexer/pragma-message.c
@@ -1,6 +1,5 @@
 /* Test pragma message directive from
http://msdn.microsoft.com/en-us/library/x7dkzch2.aspx */
-
 // message: Sends a string literal to the standard output without terminating
 // the compilation.
 // #pragma message(messagestring)
@@ -8,6 +7,7 @@
 // #pragma message messagestring
 //
 // RUN: %clang_cc1 -fsyntax-only -verify -Werror %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Werror -W#pragma-messages %s
 #define STRING2(x) #x
 #define STRING(x) STRING2(x)
 #pragma message(":O I'm a message! " STRING(__LINE__)) // expected-warning 
{{:O I'm a message! 13}}
Index: clang/lib/Basic/Diagnostic.cpp
===
--- clang/lib/Basic/Diagnostic.cpp
+++ clang/lib/Basic/Diagnostic.cpp
@@ -374,6 +374,12 @@
   DiagnosticMapping Mapping = makeUserMapping(Map, L);
   Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
 
+  // Make sure we propagate the NoWarningAsError flag from an existing
+  // mapping (which may be the default mapping).
+  DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
+  Mapping.setNoWarningAsError(Info.hasNoWarningAsError() ||
+  Mapping.hasNoWarningAsError());
+
   // Common case; setting all the diagnostics of a group in one place.
   if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
   DiagStatesByLoc.getCurDiagState()) {


Index: clang/test/Lexer/pragma-message.c
===
--- clang/test/Lexer/pragma-message.c
+++ clang/test/Lexer/pragma-message.c
@@ -1,6 +1,5 @@
 /* Test pragma message directive from
http://msdn.microsoft.com/en-us/library/x7dkzch2.aspx */
-
 // message: Sends a string literal to the standard output without terminating
 // the compilation.
 // #pragma message(messagestring)
@@ -8,6 +7,7 @@
 // #pragma message messagestring
 //
 // RUN: %clang_cc1 -fsyntax-only -verify -Werror %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Werror -W#pragma-messages %s
 #define STRING2(x) #x
 #define STRING(x) STRING2(x)
 #pragma message(":O I'm a message! " STRING(__LINE__)) // expected-warning {{:O I'm a message! 13}}
Index: clang/lib/Basic/Diagnostic.cpp
===
--- clang/lib/Basic/Diagnostic.cpp
+++ clang/lib/Basic/Diagnostic.cpp
@@ -374,6 +374,12 @@
   DiagnosticMapping Mapping = makeUserMapping(Map, L);
   Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
 
+  // Make sure we propagate the NoWarningAsError flag from an existing
+  // mapping (which may be the default mapping).
+  DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
+  Mapping.setNoWarningAsError(Info.hasNoWarningAsError() ||
+  Mapping.hasNoWarningAsError());
+
   // Common case; setting all the diagnostics of a group in one place.
   if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
   DiagStatesByLoc.getCurDiagState()) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] d789ea7 - [Diagnostics] Don't drop a statically set NoWarningAsError flag during option processing

2022-01-10 Thread Wolfgang Pieb via cfe-commits

Author: Wolfgang Pieb
Date: 2022-01-10T16:38:01-08:00
New Revision: d789ea713372d44e50ff52a85a198ac6bbedaef9

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

LOG: [Diagnostics] Don't drop a statically set NoWarningAsError flag during 
option processing

When a -W option is given on the command line, and the corresponding 
diagnostic has
the NoWarnOnError flag set, prevent the flag from being dropped when the 
severity is reevaluated.
This fixes PR51837.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/lib/Basic/Diagnostic.cpp
clang/test/Lexer/pragma-message.c

Removed: 




diff  --git a/clang/lib/Basic/Diagnostic.cpp b/clang/lib/Basic/Diagnostic.cpp
index 9b7ad96b949f1..ac4b9d2cd5a2b 100644
--- a/clang/lib/Basic/Diagnostic.cpp
+++ b/clang/lib/Basic/Diagnostic.cpp
@@ -374,6 +374,12 @@ void DiagnosticsEngine::setSeverity(diag::kind Diag, 
diag::Severity Map,
   DiagnosticMapping Mapping = makeUserMapping(Map, L);
   Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
 
+  // Make sure we propagate the NoWarningAsError flag from an existing
+  // mapping (which may be the default mapping).
+  DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
+  Mapping.setNoWarningAsError(Info.hasNoWarningAsError() ||
+  Mapping.hasNoWarningAsError());
+
   // Common case; setting all the diagnostics of a group in one place.
   if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
   DiagStatesByLoc.getCurDiagState()) {

diff  --git a/clang/test/Lexer/pragma-message.c 
b/clang/test/Lexer/pragma-message.c
index d0bbe9ea3a628..aca9f14fa2f6d 100644
--- a/clang/test/Lexer/pragma-message.c
+++ b/clang/test/Lexer/pragma-message.c
@@ -1,6 +1,5 @@
 /* Test pragma message directive from
http://msdn.microsoft.com/en-us/library/x7dkzch2.aspx */
-
 // message: Sends a string literal to the standard output without terminating
 // the compilation.
 // #pragma message(messagestring)
@@ -8,6 +7,7 @@
 // #pragma message messagestring
 //
 // RUN: %clang_cc1 -fsyntax-only -verify -Werror %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Werror -W#pragma-messages %s
 #define STRING2(x) #x
 #define STRING(x) STRING2(x)
 #pragma message(":O I'm a message! " STRING(__LINE__)) // expected-warning 
{{:O I'm a message! 13}}



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


[PATCH] D111566: [SYCL] Fix function pointer address space

2022-01-10 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews added inline comments.



Comment at: clang/lib/AST/ASTContext.cpp:11494
+  const Type *TypePtr = T.getTypePtr();
+  return TypePtr->isFunctionType()
+ ? llvm::DataLayout(getTargetInfo().getDataLayoutString())

rjmccall wrote:
> You can just do `T->isFunctionType()`.
Thanks! I'll make the change



Comment at: clang/lib/AST/ASTContext.cpp:11497
+   .getProgramAddressSpace()
+ : getTargetAddressSpace(T.getQualifiers());
+}

rjmccall wrote:
> If a function type has an address space qualifier, we should prefer that, 
> right?  Or is that impossible by construction?
I thought you could only use address space qualifiers for variables. I am not 
sure though. 

This patch retains existing behavior for pointers.  The existing code (deleted 
in CodeGenTypes.cpp in his patch) doesn't take qualifiers into consideration. 


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

https://reviews.llvm.org/D111566

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


[PATCH] D116503: [clang] Add --start-no-unused-arguments/--end-no-unused-arguments to silence some unused argument warnings

2022-01-10 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added a comment.

In D116503#3231138 , @mstorsjo wrote:

> In D116503#3223094 , @MaskRay wrote:
>
>> But make sure to wait a bit to see what others think.
>
> Do you think it's ok to go ahead and land this change now, or should I wait a 
> bit more? (I'd like to have it landed with enough margin before the 14.x 
> branch so that it has time to settle before that.)

The wait time has been sufficiently long to me:) Go head.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116503

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


[PATCH] D116294: [CodeCompletion] (mostly) fix completion in incomplete C++ ctor initializers.

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 398775.
sammccall added a comment.

Never eat malformed decl while code completing


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116294

Files:
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang/lib/Parse/ParseCXXInlineMethods.cpp
  clang/test/CodeCompletion/ctor-initializer.cpp

Index: clang/test/CodeCompletion/ctor-initializer.cpp
===
--- clang/test/CodeCompletion/ctor-initializer.cpp
+++ clang/test/CodeCompletion/ctor-initializer.cpp
@@ -103,3 +103,23 @@
 // RUN: %clang_cc1 -fsyntax-only -std=c++98 -code-completion-at=%s:100:9 %s -o - | FileCheck -check-prefix=CHECK-CC11 %s
 // RUN: %clang_cc1 -fsyntax-only -std=c++14 -code-completion-at=%s:100:9 %s -o - | FileCheck -check-prefix=CHECK-CC11 %s
 // CHECK-CC11: Pattern : Y(<#Y#>)
+
+// Test with incomplete init lists. (Relevant as parsing is *not* cut off).
+struct Incomplete1 {
+  Incomplete1() : mem
+
+  int member1;
+  int member2;
+};
+// RUN: not %clang_cc1 -fsyntax-only -std=c++14 -code-completion-at=%s:109:19 %s -o - | FileCheck -check-prefix=CHECK-CC12 %s
+// CHECK-CC12: COMPLETION: Pattern : member1(<#int#>)
+// CHECK-CC12: COMPLETION: Pattern : member2(<#int#>)
+
+struct Incomplete2 {
+  Incomplete2() : member2(
+
+  int member1;
+  int member2;
+};
+// RUN: not %clang_cc1 -fsyntax-only -std=c++14 -code-completion-at=%s:119:27 %s -o - | FileCheck -check-prefix=CHECK-CC13 %s
+// CHECK-CC13: PREFERRED-TYPE: int
Index: clang/lib/Parse/ParseCXXInlineMethods.cpp
===
--- clang/lib/Parse/ParseCXXInlineMethods.cpp
+++ clang/lib/Parse/ParseCXXInlineMethods.cpp
@@ -140,8 +140,22 @@
   // function body.
   if (ConsumeAndStoreFunctionPrologue(Toks)) {
 // We didn't find the left-brace we expected after the
-// constructor initializer; we already printed an error, and it's likely
-// impossible to recover, so don't try to parse this method later.
+// constructor initializer.
+
+// If we're code-completing and the completion point was in the broken
+// initializer, we want to parse it even though that will fail.
+if (PP.isCodeCompletionEnabled() &&
+llvm::any_of(Toks, [](const Token &Tok) {
+  return Tok.is(tok::code_completion);
+})) {
+  // If we gave up at the completion point, the initializer list was
+  // likely truncated, so don't eat more tokens. We'll hit some extra
+  // errors, but they should be ignored in code completion.
+  return FnD;
+}
+
+// We already printed an error, and it's likely impossible to recover,
+// so don't try to parse this method later.
 // Skip over the rest of the decl and back to somewhere that looks
 // reasonable.
 SkipMalformedDecl();
Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -2006,6 +2006,36 @@
   UnorderedElementsAre(AllOf(Scope("ns::X::"), Named("x_";
 }
 
+// Like other class members, constructor init lists have to parse what's below,
+// after the completion point.
+// But recovering from an incomplete constructor init list is particularly
+// tricky because the bulk of the list is not surrounded by brackets.
+TEST(CompletionTest, ConstructorInitListIncomplete) {
+  auto Results = completions(
+  R"cpp(
+namespace ns {
+  struct X {
+X() : x^
+int xyz_;
+  };
+}
+  )cpp");
+  EXPECT_THAT(Results.Completions, ElementsAre(Named("xyz_")));
+
+  Results = completions(
+  R"cpp(
+int foo();
+
+namespace ns {
+  struct X {
+X() : xyz_(fo^
+int xyz_;
+  };
+}
+  )cpp");
+  EXPECT_THAT(Results.Completions, ElementsAre(Named("foo")));
+}
+
 TEST(CompletionTest, CodeCompletionContext) {
   auto Results = completions(
   R"cpp(
@@ -2650,9 +2680,7 @@
 TEST(SignatureHelpTest, ConstructorInitializeFields) {
   {
 const auto Results = signatures(R"cpp(
-  struct A {
-A(int);
-  };
+  struct A { A(int); };
   struct B {
 B() : a_elem(^) {}
 A a_elem;
@@ -2662,6 +2690,31 @@
 UnorderedElementsAre(Sig("A([[int]])"), Sig("A([[A &&]])"),
  Sig("A([[const A &]])")));
   }
+  {
+const auto Results = signatures(R"cpp(
+  struct A { A(int); };
+  struct B {
+B() : a_elem(^
+A a_elem;
+  };
+)cpp");
+// FIXME: currently the parser skips over the decl of a_elem as part of the
+// (broken) init list, so we don't get signatures for the first member.
+EXPECT_THAT(Results.signatures, 

[PATCH] D116294: [CodeCompletion] (mostly) fix completion in incomplete C++ ctor initializers.

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang/lib/Parse/ParseCXXInlineMethods.cpp:153
+  // probably truncated, so don't eat more tokens.
+  if (!Toks.back().is(tok::code_completion))
+SkipMalformedDecl();

kadircet wrote:
> i don't follow the logic here. maybe i am reading the comment wrong, but we 
> are actually going to eat **more** tokens by calling `SkipMalformedDecl`, 
> possibly the following one, right? for example in a scenario like:
> ```
> struct Foo {
>   Foo : ^b
>   int bar;
> }
> ```
> `ConsumeAndStoreFunctionPrologue` will actually put `b` following the code 
> completion token (`^`) into `Toks` as well, hence when we skip, we actually 
> skip until the next semicolon and throw away bar. But when the code 
> completion token is after `b`, `ConsumeAndStoreFunctionPrologue` we'll have 
> code completion token at the end of the `Toks` and won't skip anything
> 
>  Do we have cases that break miserably when we don't perform an extra skip 
> here for the (possible) reminder of current initalizer?
> i don't follow the logic here. maybe i am reading the comment wrong, 

Neither the code nor the comment are very good, but I think they are consistent.

Baseline behavior: we're going to recover by letting SkipMalformedDecl() eat 
tokens.
Exception: if we already ate the code completion token *and* stopped right 
afterwards.
Reason: CC token followed by heuristic stop are consistent with the function 
being truncated at the code completion point.

This exception allows some motivating testcases to pass. I thought maybe 
further improvements were possible but didn't want to get into them in this 
patch. However

>  Do we have cases that break miserably when we don't perform an extra skip 
> here for the (possible) reminder of current initalizer?

Um, apparently not. I thought I did!
Never skipping is simple and intuitive and makes more testcases pass.
Let's try it, the risk seems low.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116294

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


[PATCH] D116790: C++ -gmodules .pcm files don't have the same DW_AT_language dialect

2022-01-10 Thread Adrian Prantl via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGeb200e584ece: Emit the C++ dialect in -gmodules .pcm files. 
(authored by aprantl).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116790

Files:
  clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
  clang/test/Modules/ModuleDebugInfo.cpp


Index: clang/test/Modules/ModuleDebugInfo.cpp
===
--- clang/test/Modules/ModuleDebugInfo.cpp
+++ clang/test/Modules/ModuleDebugInfo.cpp
@@ -24,7 +24,7 @@
 // CHECK-MOD: distinct !DICompileUnit(language: DW_LANG_{{.*}}C_plus_plus,
 
 // CHECK: distinct !DICompileUnit(language: DW_LANG_{{.*}}C_plus_plus,
-// CHECK-CXX: distinct !DICompileUnit(language: DW_LANG_C_plus_plus,
+// CHECK-CXX: distinct !DICompileUnit(language: DW_LANG_C_plus_plus_11,
 // CHECK-SAME:isOptimized: false,
 // CHECK-NOT: splitDebugFilename:
 // CHECK-SAME:dwoId:
Index: clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
===
--- clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
+++ clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
@@ -156,6 +156,7 @@
 CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
 CodeGenOpts.DebugPrefixMap =
 CI.getInvocation().getCodeGenOpts().DebugPrefixMap;
+CodeGenOpts.DebugStrictDwarf = CI.getCodeGenOpts().DebugStrictDwarf;
   }
 
   ~PCHContainerGenerator() override = default;


Index: clang/test/Modules/ModuleDebugInfo.cpp
===
--- clang/test/Modules/ModuleDebugInfo.cpp
+++ clang/test/Modules/ModuleDebugInfo.cpp
@@ -24,7 +24,7 @@
 // CHECK-MOD: distinct !DICompileUnit(language: DW_LANG_{{.*}}C_plus_plus,
 
 // CHECK: distinct !DICompileUnit(language: DW_LANG_{{.*}}C_plus_plus,
-// CHECK-CXX: distinct !DICompileUnit(language: DW_LANG_C_plus_plus,
+// CHECK-CXX: distinct !DICompileUnit(language: DW_LANG_C_plus_plus_11,
 // CHECK-SAME:isOptimized: false,
 // CHECK-NOT: splitDebugFilename:
 // CHECK-SAME:dwoId:
Index: clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
===
--- clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
+++ clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
@@ -156,6 +156,7 @@
 CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
 CodeGenOpts.DebugPrefixMap =
 CI.getInvocation().getCodeGenOpts().DebugPrefixMap;
+CodeGenOpts.DebugStrictDwarf = CI.getCodeGenOpts().DebugStrictDwarf;
   }
 
   ~PCHContainerGenerator() override = default;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] eb200e5 - Emit the C++ dialect in -gmodules .pcm files.

2022-01-10 Thread Adrian Prantl via cfe-commits

Author: Adrian Prantl
Date: 2022-01-10T16:13:40-08:00
New Revision: eb200e584ece7ca8c1f8cac59ca5418956ccf1e4

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

LOG: Emit the C++ dialect in -gmodules .pcm files.

Because of commit: https://reviews.llvm.org/D104291 the -gmodules .pcm
files do not have the same DW_AT_language dialect as the .o file. This
was a simple matter of passing the DebugStrictDwarf flag to the
PCHContainerGenerator object's CodeGenOpts from the CompilerInstance
passed in to it.

Before this change if you ran dwarfdump on the gmodule cache folder
you would get DW_AT_language (DW_LANG_C_plus_plus) even when using
-std=c++14 with clang

Patch by Shubham Rastogi!

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

Added: 


Modified: 
clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
clang/test/Modules/ModuleDebugInfo.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp 
b/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
index f7b83c45022d6..9fe7e5d1f5c31 100644
--- a/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
+++ b/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
@@ -156,6 +156,7 @@ class PCHContainerGenerator : public ASTConsumer {
 CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
 CodeGenOpts.DebugPrefixMap =
 CI.getInvocation().getCodeGenOpts().DebugPrefixMap;
+CodeGenOpts.DebugStrictDwarf = CI.getCodeGenOpts().DebugStrictDwarf;
   }
 
   ~PCHContainerGenerator() override = default;

diff  --git a/clang/test/Modules/ModuleDebugInfo.cpp 
b/clang/test/Modules/ModuleDebugInfo.cpp
index 433002c6cdbe3..558e2e223a880 100644
--- a/clang/test/Modules/ModuleDebugInfo.cpp
+++ b/clang/test/Modules/ModuleDebugInfo.cpp
@@ -24,7 +24,7 @@
 // CHECK-MOD: distinct !DICompileUnit(language: DW_LANG_{{.*}}C_plus_plus,
 
 // CHECK: distinct !DICompileUnit(language: DW_LANG_{{.*}}C_plus_plus,
-// CHECK-CXX: distinct !DICompileUnit(language: DW_LANG_C_plus_plus,
+// CHECK-CXX: distinct !DICompileUnit(language: DW_LANG_C_plus_plus_11,
 // CHECK-SAME:isOptimized: false,
 // CHECK-NOT: splitDebugFilename:
 // CHECK-SAME:dwoId:



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


[PATCH] D116717: [CodeCompletion] Complete designators for fields in anonymous structs/unions

2022-01-10 Thread Sam McCall 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 rGbbf234b56a82: [CodeCompletion] Complete designators for 
fields in anonymous structs/unions (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116717

Files:
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/desig-init.cpp


Index: clang/test/CodeCompletion/desig-init.cpp
===
--- clang/test/CodeCompletion/desig-init.cpp
+++ clang/test/CodeCompletion/desig-init.cpp
@@ -77,3 +77,11 @@
   // CHECK-SIGNATURE-REGRESSION-NOT: OVERLOAD: [#int#]wrongFunction
 }
 
+struct WithAnon {
+  int outer;
+  struct { int inner; };
+};
+auto TestWithAnon = WithAnon { .inner = 2 };
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns 
-code-completion-at=%s:84:33 %s -o - -std=c++2a | FileCheck 
-check-prefix=CHECK-CC5 %s
+  // CHECK-CC5: COMPLETION: inner : [#int#]inner
+  // CHECK-CC5: COMPLETION: outer : [#int#]outer
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -6344,7 +6344,15 @@
 CodeCompleter->getCodeCompletionTUInfo(), CCC);
 
   Results.EnterNewScope();
-  for (const auto *FD : RD->fields()) {
+  for (const Decl *D : RD->decls()) {
+const FieldDecl *FD;
+if (auto *IFD = dyn_cast(D))
+  FD = IFD->getAnonField();
+else if (auto *DFD = dyn_cast(D))
+  FD = DFD;
+else
+  continue;
+
 // FIXME: Make use of previous designators to mark any fields before those
 // inaccessible, and also compute the next initializer priority.
 ResultBuilder::Result Result(FD, Results.getBasePriority(FD));


Index: clang/test/CodeCompletion/desig-init.cpp
===
--- clang/test/CodeCompletion/desig-init.cpp
+++ clang/test/CodeCompletion/desig-init.cpp
@@ -77,3 +77,11 @@
   // CHECK-SIGNATURE-REGRESSION-NOT: OVERLOAD: [#int#]wrongFunction
 }
 
+struct WithAnon {
+  int outer;
+  struct { int inner; };
+};
+auto TestWithAnon = WithAnon { .inner = 2 };
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:84:33 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC5 %s
+  // CHECK-CC5: COMPLETION: inner : [#int#]inner
+  // CHECK-CC5: COMPLETION: outer : [#int#]outer
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -6344,7 +6344,15 @@
 CodeCompleter->getCodeCompletionTUInfo(), CCC);
 
   Results.EnterNewScope();
-  for (const auto *FD : RD->fields()) {
+  for (const Decl *D : RD->decls()) {
+const FieldDecl *FD;
+if (auto *IFD = dyn_cast(D))
+  FD = IFD->getAnonField();
+else if (auto *DFD = dyn_cast(D))
+  FD = DFD;
+else
+  continue;
+
 // FIXME: Make use of previous designators to mark any fields before those
 // inaccessible, and also compute the next initializer priority.
 ResultBuilder::Result Result(FD, Results.getBasePriority(FD));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] bbf234b - [CodeCompletion] Complete designators for fields in anonymous structs/unions

2022-01-10 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-11T00:58:49+01:00
New Revision: bbf234b56a82d1b9b7fa58f8b10f16d417500d9b

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

LOG: [CodeCompletion] Complete designators for fields in anonymous 
structs/unions

Fixes https://github.com/clangd/clangd/issues/836

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

Added: 


Modified: 
clang/lib/Sema/SemaCodeComplete.cpp
clang/test/CodeCompletion/desig-init.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index c075cbf536caf..9266deb6699af 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -6344,7 +6344,15 @@ void Sema::CodeCompleteDesignator(QualType BaseType,
 CodeCompleter->getCodeCompletionTUInfo(), CCC);
 
   Results.EnterNewScope();
-  for (const auto *FD : RD->fields()) {
+  for (const Decl *D : RD->decls()) {
+const FieldDecl *FD;
+if (auto *IFD = dyn_cast(D))
+  FD = IFD->getAnonField();
+else if (auto *DFD = dyn_cast(D))
+  FD = DFD;
+else
+  continue;
+
 // FIXME: Make use of previous designators to mark any fields before those
 // inaccessible, and also compute the next initializer priority.
 ResultBuilder::Result Result(FD, Results.getBasePriority(FD));

diff  --git a/clang/test/CodeCompletion/desig-init.cpp 
b/clang/test/CodeCompletion/desig-init.cpp
index 999f368ba5634..76f6d2dea010d 100644
--- a/clang/test/CodeCompletion/desig-init.cpp
+++ b/clang/test/CodeCompletion/desig-init.cpp
@@ -77,3 +77,11 @@ namespace signature_regression {
   // CHECK-SIGNATURE-REGRESSION-NOT: OVERLOAD: [#int#]wrongFunction
 }
 
+struct WithAnon {
+  int outer;
+  struct { int inner; };
+};
+auto TestWithAnon = WithAnon { .inner = 2 };
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns 
-code-completion-at=%s:84:33 %s -o - -std=c++2a | FileCheck 
-check-prefix=CHECK-CC5 %s
+  // CHECK-CC5: COMPLETION: inner : [#int#]inner
+  // CHECK-CC5: COMPLETION: outer : [#int#]outer



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


[PATCH] D45438: [CodeView] Enable debugging of captured variables within C++ lambdas

2022-01-10 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: lib/CodeGen/CGDebugInfo.cpp:812-814
+  // CodeView types with C++ mangling need a type identifier.
+  if (CGM.getCodeGenOpts().EmitCodeView)
+return true;

Just came across this code today - it's /probably/ a problem for LTO. LLVM IR 
linking depends on the identifier to determine if two structs are the same for 
linkage purposes - so if an identifier is added for a non-linkage (local/not 
externally visible) type, LLVM will consider them to be the same even though 
they're unrelated:
```
namespace { struct t1 { int i; int j; }; }
t1 v1;
void *v3 = &v1;
```
```
namespace { struct t1 { int i; }; }
t1 v1;
void *v2 = &v1;
```
```
$ clang++-tot -emit-llvm -S a.cpp b.cpp -g -gcodeview  && 
~/dev/llvm/build/default/bin/llvm-link -o ab.bc a.ll b.ll && 
~/dev/llvm/build/default/bin/llvm-dis ab.bc && cat ab.ll | grep "\"t1\""
!8 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t1", scope: 
!9, file: !3, line: 1, size: 64, flags: DIFlagTypePassByValue, elements: !10, 
identifier: "_ZTSN12_GLOBAL__N_12t1E")
$ clang++-tot -emit-llvm -S a.cpp b.cpp -g && 
~/dev/llvm/build/default/bin/llvm-link -o ab.bc a.ll b.ll && 
~/dev/llvm/build/default/bin/llvm-dis ab.bc && cat ab.ll | grep "\"t1\""
!8 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t1", scope: 
!9, file: !3, line: 1, size: 64, flags: DIFlagTypePassByValue, elements: !10)
!21 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t1", scope: 
!9, file: !17, line: 1, size: 32, flags: DIFlagTypePassByValue, elements: !22)
```

So in linking, now both `a.cpp` and `b.cpp` refer to a single `t1` type (in 
this case, it looks like the first one - the 64 bit wide one).

If CodeView actually can't represent these two distinct types with the same 
name in the same object file, so be it? But this looks like it's likely to 
cause problems for consumers/users.


Repository:
  rC Clang

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

https://reviews.llvm.org/D45438

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


[PATCH] D116920: [clang-format] clang-format eats space in front of attributes for operator delete

2022-01-10 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:9463
+
+  verifyFormat("void operator delete(void *foo) ATTRIB;");
+  verifyFormat("void operator new(void *foo) ATTRIB;");

Please add a test for `operator delete[]`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116920

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


[PATCH] D116978: [clangd] Selection: Prune gtest TEST()s earlier

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 398757.
sammccall added a comment.

Use the other end too


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116978

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


Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -313,12 +313,22 @@
   bool mayHit(SourceRange R) const {
 if (SpelledTokens.empty())
   return false;
-auto B = SM.getDecomposedLoc(R.getBegin());
-auto E = SM.getDecomposedLoc(R.getEnd());
-if (B.first == SelFile && E.first == SelFile)
-  if (E.second < SpelledTokens.front().Offset ||
-  B.second > SpelledTokens.back().Offset)
-return false;
+// If the node starts after the selection ends, it is not selected.
+// All tokens a macro location might claim are >= its expansion site.
+// So it's safe to use the expansions location for the comparison.
+// (This is particularly helpful for GTest's TEST macro).
+auto B = SM.getDecomposedExpansionLoc(R.getBegin());
+if (B.first == SelFile && B.second > SpelledTokens.back().Offset)
+  return false;
+// If the node ends before the selection begins, it is not selected.
+SourceLocation EndLoc = R.getEnd();
+while (EndLoc.isMacroID())
+  EndLoc = SM.getImmediateExpansionRange(EndLoc).getEnd();
+auto E = SM.getDecomposedLoc(EndLoc);
+// In the rare case that the expansion range is a char range, EndLoc is
+// ~one token too far to the right. We may fail to prune, that's OK.
+if (E.first == SelFile && E.second < SpelledTokens.front().Offset)
+  return false;
 return true;
   }
 


Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -313,12 +313,22 @@
   bool mayHit(SourceRange R) const {
 if (SpelledTokens.empty())
   return false;
-auto B = SM.getDecomposedLoc(R.getBegin());
-auto E = SM.getDecomposedLoc(R.getEnd());
-if (B.first == SelFile && E.first == SelFile)
-  if (E.second < SpelledTokens.front().Offset ||
-  B.second > SpelledTokens.back().Offset)
-return false;
+// If the node starts after the selection ends, it is not selected.
+// All tokens a macro location might claim are >= its expansion site.
+// So it's safe to use the expansions location for the comparison.
+// (This is particularly helpful for GTest's TEST macro).
+auto B = SM.getDecomposedExpansionLoc(R.getBegin());
+if (B.first == SelFile && B.second > SpelledTokens.back().Offset)
+  return false;
+// If the node ends before the selection begins, it is not selected.
+SourceLocation EndLoc = R.getEnd();
+while (EndLoc.isMacroID())
+  EndLoc = SM.getImmediateExpansionRange(EndLoc).getEnd();
+auto E = SM.getDecomposedLoc(EndLoc);
+// In the rare case that the expansion range is a char range, EndLoc is
+// ~one token too far to the right. We may fail to prune, that's OK.
+if (E.first == SelFile && E.second < SpelledTokens.front().Offset)
+  return false;
 return true;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D7982: [clang-tidy] Add readability-duplicate-include check

2022-01-10 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood updated this revision to Diff 398756.
LegalizeAdulthood added a comment.

clang-format


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

https://reviews.llvm.org/D7982

Files:
  clang-tools-extra/clang-tidy/readability/CMakeLists.txt
  clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp
  clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.h
  clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/readability-duplicate-include.rst
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/iostream
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/readability-duplicate-include.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/string.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/sys/types.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/types.h
  clang-tools-extra/test/clang-tidy/checkers/readability-duplicate-include.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-duplicate-include.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-duplicate-include.cpp
@@ -0,0 +1,72 @@
+// RUN: %check_clang_tidy -std=c++98-or-later %s readability-duplicate-include %t -- -- -I%S/Inputs/readability-duplicate-include
+
+int a;
+#include 
+int b;
+#include 
+int c;
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: duplicate include [readability-duplicate-include]
+// CHECK-FIXES:  {{^int a;$}}
+// CHECK-FIXES-NEXT: {{^#include $}}
+// CHECK-FIXES-NEXT: {{^int b;$}}
+// CHECK-FIXES-NEXT: {{^int c;$}}
+
+int d;
+#include 
+int e;
+#include  // extra stuff that will also be removed
+int f;
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: {{.*}}
+// CHECK-FIXES:  {{^int d;$}}
+// CHECK-FIXES-NEXT: {{^#include $}}
+// CHECK-FIXES-NEXT: {{^int e;$}}
+// CHECK-FIXES-NEXT: {{^int f;$}}
+
+int g;
+#include "readability-duplicate-include.h"
+int h;
+#include "readability-duplicate-include.h"
+int i;
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: {{.*}}
+// CHECK-FIXES:  {{^int g;$}}
+// CHECK-FIXES-NEXT: {{^#include "readability-duplicate-include.h"$}}
+// CHECK-FIXES-NEXT: {{^int h;$}}
+// CHECK-FIXES-NEXT: {{^int i;$}}
+
+#include "types.h"
+
+int j;
+#include 
+int k;
+#include 
+int l;
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: {{.*}}
+// CHECK-FIXES:  {{^int j;$}}
+// CHECK-FIXES-NEXT: {{^#include $}}
+// CHECK-FIXES-NEXT: {{^int k;$}}
+// CHECK-FIXES-NEXT: {{^int l;$}}
+
+int m;
+#  include   // lots of space
+int n;
+// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: {{.*}}
+// CHECK-FIXES:  {{^int m;$}}
+// CHECK-FIXES-NEXT: {{^int n;$}}
+
+// defining a macro in the main file resets the included file cache
+#define ARBITRARY_MACRO
+int o;
+#include 
+int p;
+// CHECK-FIXES:  {{^int o;$}}
+// CHECK-FIXES-NEXT: {{^#include $}}
+// CHECK-FIXES-NEXT: {{^int p;$}}
+
+// undefining a macro resets the cache
+#undef ARBITRARY_MACRO
+int q;
+#include 
+int r;
+// CHECK-FIXES:  {{^int q;$}}
+// CHECK-FIXES-NEXT: {{^#include $}}
+// CHECK-FIXES-NEXT: {{^int r;$}}
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/types.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/types.h
@@ -0,0 +1 @@
+// empty file used by readability-duplicate-include.cpp
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/sys/types.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/sys/types.h
@@ -0,0 +1 @@
+// empty file used by readability-duplicate-include.cpp
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/string.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/string.h
@@ -0,0 +1 @@
+// empty file used by readability-duplicate-include.cpp
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/readability-duplicate-include.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/readability-duplicate-include.h
@@ -0,0 +1 @@
+// empty file used by readability-duplicate-include.cpp
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/iostream
===
--- 

[PATCH] D116978: [clangd] Selection: Prune gtest TEST()s earlier

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

When searching for AST nodes that may overlap the selection, mayHit() was only
attempting to prune nodes whose begin/end are both in the main file.

While failing to prune never gives wrong results, it hurts performance.
In GTest unit-tests, `TEST()` macros at the top level declare classes.
These were never pruned and we traversed *every* such class for any selection.

We fix this by reasoning about what tokens such a node might claim.
They must lie within its ultimate macro expansion range, so if this doesn't
overlap with the selection, we can prune the node.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116978

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


Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -313,12 +313,19 @@
   bool mayHit(SourceRange R) const {
 if (SpelledTokens.empty())
   return false;
-auto B = SM.getDecomposedLoc(R.getBegin());
-auto E = SM.getDecomposedLoc(R.getEnd());
-if (B.first == SelFile && E.first == SelFile)
-  if (E.second < SpelledTokens.front().Offset ||
-  B.second > SpelledTokens.back().Offset)
+// If the node ends before the selection begins, it is not selected.
+if (R.getEnd().isFileID()) {
+  auto E = SM.getDecomposedLoc(R.getEnd());
+  if (E.first == SelFile && E.second < SpelledTokens.front().Offset)
 return false;
+}
+// If the node starts after the selection ends, it is not selected.
+// All tokens a macro location might claim are >= its expansion site.
+// So it's safe to use the expansions location for the comparison.
+// (This is particularly helpful for GTest's TEST macro).
+auto B = SM.getDecomposedExpansionLoc(R.getBegin());
+if (B.first == SelFile && B.second > SpelledTokens.back().Offset)
+  return false;
 return true;
   }
 


Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -313,12 +313,19 @@
   bool mayHit(SourceRange R) const {
 if (SpelledTokens.empty())
   return false;
-auto B = SM.getDecomposedLoc(R.getBegin());
-auto E = SM.getDecomposedLoc(R.getEnd());
-if (B.first == SelFile && E.first == SelFile)
-  if (E.second < SpelledTokens.front().Offset ||
-  B.second > SpelledTokens.back().Offset)
+// If the node ends before the selection begins, it is not selected.
+if (R.getEnd().isFileID()) {
+  auto E = SM.getDecomposedLoc(R.getEnd());
+  if (E.first == SelFile && E.second < SpelledTokens.front().Offset)
 return false;
+}
+// If the node starts after the selection ends, it is not selected.
+// All tokens a macro location might claim are >= its expansion site.
+// So it's safe to use the expansions location for the comparison.
+// (This is particularly helpful for GTest's TEST macro).
+auto B = SM.getDecomposedExpansionLoc(R.getBegin());
+if (B.first == SelFile && B.second > SpelledTokens.back().Offset)
+  return false;
 return true;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116518: [ast-matchers] Add hasSubstatementSequence matcher

2022-01-10 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood updated this revision to Diff 398754.
LegalizeAdulthood added a comment.

clang-format


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

https://reviews.llvm.org/D116518

Files:
  clang/docs/LibASTMatchersReference.html
  clang/docs/ReleaseNotes.rst
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -2604,6 +2604,73 @@
   EXPECT_TRUE(matchesObjC("void f() { ^{}(); }", blockExpr()));
 }
 
+TEST_P(ASTMatchersTest, HasSubstatementSequenceSimple) {
+  const char *Text = "int f() { int x = 5; if (x < 0) return 1; return 0; }";
+  EXPECT_TRUE(matches(
+  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
+  EXPECT_FALSE(matches(
+  Text, compoundStmt(hasSubstatementSequence(ifStmt(), labelStmt();
+  EXPECT_FALSE(matches(
+  Text, compoundStmt(hasSubstatementSequence(returnStmt(), ifStmt();
+  EXPECT_FALSE(matches(
+  Text, compoundStmt(hasSubstatementSequence(switchStmt(), labelStmt();
+}
+
+TEST_P(ASTMatchersTest, HasSubstatementSequenceAlmost) {
+  const char *Text = R"code(
+int f() {
+  int x = 5;
+  if (x < 10)
+;
+  if (x < 0)
+return 1;
+  return 0;
+}
+)code";
+  EXPECT_TRUE(matches(
+  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
+  EXPECT_TRUE(
+  matches(Text, compoundStmt(hasSubstatementSequence(ifStmt(), ifStmt();
+}
+
+TEST_P(ASTMatchersTest, HasSubstatementSequenceComplex) {
+  const char *Text = R"code(
+int f() {
+  int x = 5;
+  if (x < 10)
+x -= 10;
+  if (x < 0)
+return 1;
+  return 0;
+}
+)code";
+  EXPECT_TRUE(matches(
+  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
+  EXPECT_FALSE(
+  matches(Text, compoundStmt(hasSubstatementSequence(ifStmt(), expr();
+}
+
+TEST_P(ASTMatchersTest, HasSubstatementSequenceExpression) {
+  const char *Text = R"code(
+int f() {
+  return ({ int x = 5;
+  int result;
+  if (x < 10)
+x -= 10;
+  if (x < 0)
+result = 1;
+  else
+result = 0;
+  result;
+});
+  }
+)code";
+  EXPECT_TRUE(
+  matches(Text, stmtExpr(hasSubstatementSequence(ifStmt(), expr();
+  EXPECT_FALSE(
+  matches(Text, stmtExpr(hasSubstatementSequence(ifStmt(), returnStmt();
+}
+
 TEST_P(ASTMatchersTest,
StatementCountIs_FindsNoStatementsInAnEmptyCompoundStatement) {
   EXPECT_TRUE(matches("void f() { }", compoundStmt(statementCountIs(0;
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -355,6 +355,7 @@
   REGISTER_MATCHER(hasSpecializedTemplate);
   REGISTER_MATCHER(hasStaticStorageDuration);
   REGISTER_MATCHER(hasStructuredBlock);
+  REGISTER_MATCHER(hasSubstatementSequence);
   REGISTER_MATCHER(hasSyntacticForm);
   REGISTER_MATCHER(hasTargetDecl);
   REGISTER_MATCHER(hasTemplateArgument);
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -5431,6 +5431,35 @@
   Builder) != CS->body_end();
 }
 
+/// Matches two consecutive statements within a compound statement.
+///
+/// Given
+/// \code
+///   { if (x > 0) return true; return false; }
+/// \endcode
+/// compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt()))
+///   matches '{ if (x > 0) return true; return false; }'
+AST_POLYMORPHIC_MATCHER_P2(hasSubstatementSequence,
+   AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
+   StmtExpr),
+   internal::Matcher, InnerMatcher1,
+   internal::Matcher, InnerMatcher2) {
+  if (const CompoundStmt *CS = CompoundStmtMatcher::get(Node)) {
+auto It = matchesFirstInPointerRange(InnerMatcher1, CS->body_begin(),
+ CS->body_end(), Finder, Builder);
+while (It != CS->body_end()) {
+  ++It;
+  if (It == CS->body_end())
+return false;
+  if (InnerMatcher2.matches(**It, Finder, Builder))
+return true;
+  It = matchesFirstInPointerRange(InnerMatcher1, It, CS->body_end(), Finder,
+  Builder);
+}
+  }
+  return false;
+}
+
 /// Checks that a compound statement contains a specific number of
 /// child statements.
 ///
Index: clang/docs/ReleaseNotes.rst
==

[PATCH] D116412: [Clang][Sema] Fix attribute mismatch warning for ObjC class properties

2022-01-10 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan updated this revision to Diff 398753.
egorzhdan added a comment.

Fix clang-format warning


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116412

Files:
  clang/include/clang/AST/DeclObjC.h
  clang/lib/AST/DeclObjC.cpp
  clang/lib/Sema/SemaObjCProperty.cpp
  clang/test/SemaObjC/class-property-inheritance.m

Index: clang/test/SemaObjC/class-property-inheritance.m
===
--- /dev/null
+++ clang/test/SemaObjC/class-property-inheritance.m
@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+@class MyObject;
+
+
+@interface TopClassWithClassProperty0
+@property(nullable, readonly, strong, class) MyObject *foo;
+@end
+
+@interface SubClassWithClassProperty0 : TopClassWithClassProperty0
+@property(nonnull, readonly, copy, class) MyObject *foo; // expected-warning {{'copy' attribute on property 'foo' does not match the property inherited from 'TopClassWithClassProperty0'}}
+@end
+
+
+
+@interface TopClassWithInstanceProperty1
+@property(nullable, readonly, strong) MyObject *foo;
+@end
+
+@interface ClassWithClassProperty1 : TopClassWithInstanceProperty1
+@property(nonnull, readonly, copy, class) MyObject *foo; // no-warning
+@end
+
+@interface SubClassWithInstanceProperty1 : ClassWithClassProperty1
+@property(nullable, readonly, copy) MyObject *foo; // expected-warning {{'copy' attribute on property 'foo' does not match the property inherited from 'TopClassWithInstanceProperty1'}}
+@end
+
+
+@interface TopClassWithClassProperty2
+@property(nullable, readonly, strong, class) MyObject *foo;
+@end
+
+@interface ClassWithInstanceProperty2 : TopClassWithClassProperty2
+@property(nonnull, readonly, copy) MyObject *foo; // no-warning
+@end
+
+@interface SubClassWithClassProperty2 : ClassWithInstanceProperty2
+@property(nonnull, readonly, copy, class) MyObject *foo; // expected-warning {{'copy' attribute on property 'foo' does not match the property inherited from 'TopClassWithClassProperty2'}}
+@end
Index: clang/lib/Sema/SemaObjCProperty.cpp
===
--- clang/lib/Sema/SemaObjCProperty.cpp
+++ clang/lib/Sema/SemaObjCProperty.cpp
@@ -112,8 +112,8 @@
 return;
 
   // Look for a property with the same name.
-  if (ObjCPropertyDecl *ProtoProp =
-  Proto->lookup(Prop->getDeclName()).find_first()) {
+  if (ObjCPropertyDecl *ProtoProp = Proto->getProperty(
+  Prop->getIdentifier(), Prop->isInstanceProperty())) {
 S.DiagnosePropertyMismatch(Prop, ProtoProp, Proto->getIdentifier(), true);
 return;
   }
@@ -231,8 +231,8 @@
 bool FoundInSuper = false;
 ObjCInterfaceDecl *CurrentInterfaceDecl = IFace;
 while (ObjCInterfaceDecl *Super = CurrentInterfaceDecl->getSuperClass()) {
-  if (ObjCPropertyDecl *SuperProp =
-  Super->lookup(Res->getDeclName()).find_first()) {
+  if (ObjCPropertyDecl *SuperProp = Super->getProperty(
+  Res->getIdentifier(), Res->isInstanceProperty())) {
 DiagnosePropertyMismatch(Res, SuperProp, Super->getIdentifier(), false);
 FoundInSuper = true;
 break;
Index: clang/lib/AST/DeclObjC.cpp
===
--- clang/lib/AST/DeclObjC.cpp
+++ clang/lib/AST/DeclObjC.cpp
@@ -232,6 +232,18 @@
   return &Ctx.Idents.get(ivarName.str());
 }
 
+ObjCPropertyDecl *ObjCContainerDecl::getProperty(const IdentifierInfo *Id,
+ bool IsInstance) const {
+  for (auto *LookupResult : lookup(Id)) {
+if (auto *Prop = dyn_cast(LookupResult)) {
+  if (Prop->isInstanceProperty() == IsInstance) {
+return Prop;
+  }
+}
+  }
+  return nullptr;
+}
+
 /// FindPropertyDeclaration - Finds declaration of the property given its name
 /// in 'PropertyId' and returns it. It returns 0, if not found.
 ObjCPropertyDecl *ObjCContainerDecl::FindPropertyDeclaration(
Index: clang/include/clang/AST/DeclObjC.h
===
--- clang/include/clang/AST/DeclObjC.h
+++ clang/include/clang/AST/DeclObjC.h
@@ -1071,6 +1071,9 @@
   bool HasUserDeclaredSetterMethod(const ObjCPropertyDecl *P) const;
   ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const;
 
+  ObjCPropertyDecl *getProperty(const IdentifierInfo *Id,
+bool IsInstance) const;
+
   ObjCPropertyDecl *
   FindPropertyDeclaration(const IdentifierInfo *PropertyId,
   ObjCPropertyQueryKind QueryKind) const;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D56343: [clang-tidy] Refactor: Extract Class CheckRunner on check_clang_tidy.py

2022-01-10 Thread Richard via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa2c33b0ec976: [clang-tidy] Refactor: Extract Class 
CheckRunner on check_clang_tidy.py (authored by LegalizeAdulthood).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D56343

Files:
  clang-tools-extra/test/clang-tidy/check_clang_tidy.py

Index: clang-tools-extra/test/clang-tidy/check_clang_tidy.py
===
--- clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -39,170 +39,169 @@
 f.truncate()
 
 
-def run_test_once(args, extra_args):
-  resource_dir = args.resource_dir
-  assume_file_name = args.assume_filename
-  input_file_name = args.input_file_name
-  check_name = args.check_name
-  temp_file_name = args.temp_file_name
-  expect_clang_tidy_error = args.expect_clang_tidy_error
-  std = args.std
-
-  file_name_with_extension = assume_file_name or input_file_name
-  _, extension = os.path.splitext(file_name_with_extension)
-  if extension not in ['.c', '.hpp', '.m', '.mm']:
-extension = '.cpp'
-  temp_file_name = temp_file_name + extension
-
-  clang_tidy_extra_args = extra_args
-  clang_extra_args = []
-  if '--' in extra_args:
-i = clang_tidy_extra_args.index('--')
-clang_extra_args = clang_tidy_extra_args[i + 1:]
-clang_tidy_extra_args = clang_tidy_extra_args[:i]
-
-  # If the test does not specify a config style, force an empty one; otherwise
-  # autodetection logic can discover a ".clang-tidy" file that is not related to
-  # the test.
-  if not any(
-  [arg.startswith('-config=') for arg in clang_tidy_extra_args]):
-clang_tidy_extra_args.append('-config={}')
-
-  if extension in ['.m', '.mm']:
-clang_extra_args = ['-fobjc-abi-version=2', '-fobjc-arc', '-fblocks'] + \
-clang_extra_args
-
-  if extension in ['.cpp', '.hpp', '.mm']:
-clang_extra_args.append('-std=' + std)
-
-  # Tests should not rely on STL being available, and instead provide mock
-  # implementations of relevant APIs.
-  clang_extra_args.append('-nostdinc++')
-
-  if resource_dir is not None:
-clang_extra_args.append('-resource-dir=%s' % resource_dir)
-
-  with open(input_file_name, 'r', encoding='utf-8') as input_file:
-input_text = input_file.read()
-
-  check_fixes_prefixes = []
-  check_messages_prefixes = []
-  check_notes_prefixes = []
-
-  has_check_fixes = False
-  has_check_messages = False
-  has_check_notes = False
-
-  for check in args.check_suffix:
-if check and not re.match('^[A-Z0-9\-]+$', check):
-  sys.exit('Only A..Z, 0..9 and "-" are ' +
-'allowed in check suffixes list, but "%s" was given' % (check))
-
-file_check_suffix = ('-' + check) if check else ''
-check_fixes_prefix = 'CHECK-FIXES' + file_check_suffix
-check_messages_prefix = 'CHECK-MESSAGES' + file_check_suffix
-check_notes_prefix = 'CHECK-NOTES' + file_check_suffix
-
-has_check_fix = check_fixes_prefix in input_text
-has_check_message = check_messages_prefix in input_text
-has_check_note = check_notes_prefix in input_text
-
-if has_check_note and has_check_message:
-  sys.exit('Please use either %s or %s but not both' %
-(check_notes_prefix, check_messages_prefix))
-
-if not has_check_fix and not has_check_message and not has_check_note:
-  sys.exit('%s, %s or %s not found in the input' %
-(check_fixes_prefix, check_messages_prefix, check_notes_prefix))
-
-has_check_fixes = has_check_fixes or has_check_fix
-has_check_messages = has_check_messages or has_check_message
-has_check_notes = has_check_notes or has_check_note
-
-if has_check_fix:
-  check_fixes_prefixes.append(check_fixes_prefix)
-if has_check_message:
-  check_messages_prefixes.append(check_messages_prefix)
-if has_check_note:
-  check_notes_prefixes.append(check_notes_prefix)
-
-  assert has_check_fixes or has_check_messages or has_check_notes
-  # Remove the contents of the CHECK lines to avoid CHECKs matching on
-  # themselves.  We need to keep the comments to preserve line numbers while
-  # avoiding empty lines which could potentially trigger formatting-related
-  # checks.
-  cleaned_test = re.sub('// *CHECK-[A-Z0-9\-]*:[^\r\n]*', '//', input_text)
-
-  write_file(temp_file_name, cleaned_test)
-
-  original_file_name = temp_file_name + ".orig"
-  write_file(original_file_name, cleaned_test)
-
-  args = ['clang-tidy', temp_file_name, '-fix', '--checks=-*,' + check_name] + \
-  clang_tidy_extra_args + ['--'] + clang_extra_args
-  if expect_clang_tidy_error:
-args.insert(0, 'not')
-  print('Running ' + repr(args) + '...')
+def try_run(args, raise_error=True):
   try:
-clang_tidy_output = \
-subprocess.check_output(args, stderr=subprocess.STDOUT).decode()
+process_output = \
+  subprocess.check_output(args

[clang-tools-extra] a2c33b0 - [clang-tidy] Refactor: Extract Class CheckRunner on check_clang_tidy.py

2022-01-10 Thread via cfe-commits

Author: Richard
Date: 2022-01-10T15:44:12-07:00
New Revision: a2c33b0ec976c894dc45558d0b50c9c2fe87e1da

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

LOG: [clang-tidy] Refactor: Extract Class CheckRunner on check_clang_tidy.py

Break up the huge function by extracting a class, storing intermediate
state as class members and breaking up the big function into a group
of class methods all at the same level of abstraction.

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

Added: 


Modified: 
clang-tools-extra/test/clang-tidy/check_clang_tidy.py

Removed: 




diff  --git a/clang-tools-extra/test/clang-tidy/check_clang_tidy.py 
b/clang-tools-extra/test/clang-tidy/check_clang_tidy.py
index 4edae67f7076..1a234029b60b 100755
--- a/clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ b/clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -39,170 +39,169 @@ def write_file(file_name, text):
 f.truncate()
 
 
-def run_test_once(args, extra_args):
-  resource_dir = args.resource_dir
-  assume_file_name = args.assume_filename
-  input_file_name = args.input_file_name
-  check_name = args.check_name
-  temp_file_name = args.temp_file_name
-  expect_clang_tidy_error = args.expect_clang_tidy_error
-  std = args.std
-
-  file_name_with_extension = assume_file_name or input_file_name
-  _, extension = os.path.splitext(file_name_with_extension)
-  if extension not in ['.c', '.hpp', '.m', '.mm']:
-extension = '.cpp'
-  temp_file_name = temp_file_name + extension
-
-  clang_tidy_extra_args = extra_args
-  clang_extra_args = []
-  if '--' in extra_args:
-i = clang_tidy_extra_args.index('--')
-clang_extra_args = clang_tidy_extra_args[i + 1:]
-clang_tidy_extra_args = clang_tidy_extra_args[:i]
-
-  # If the test does not specify a config style, force an empty one; otherwise
-  # autodetection logic can discover a ".clang-tidy" file that is not related 
to
-  # the test.
-  if not any(
-  [arg.startswith('-config=') for arg in clang_tidy_extra_args]):
-clang_tidy_extra_args.append('-config={}')
-
-  if extension in ['.m', '.mm']:
-clang_extra_args = ['-fobjc-abi-version=2', '-fobjc-arc', '-fblocks'] + \
-clang_extra_args
-
-  if extension in ['.cpp', '.hpp', '.mm']:
-clang_extra_args.append('-std=' + std)
-
-  # Tests should not rely on STL being available, and instead provide mock
-  # implementations of relevant APIs.
-  clang_extra_args.append('-nostdinc++')
-
-  if resource_dir is not None:
-clang_extra_args.append('-resource-dir=%s' % resource_dir)
-
-  with open(input_file_name, 'r', encoding='utf-8') as input_file:
-input_text = input_file.read()
-
-  check_fixes_prefixes = []
-  check_messages_prefixes = []
-  check_notes_prefixes = []
-
-  has_check_fixes = False
-  has_check_messages = False
-  has_check_notes = False
-
-  for check in args.check_suffix:
-if check and not re.match('^[A-Z0-9\-]+$', check):
-  sys.exit('Only A..Z, 0..9 and "-" are ' +
-'allowed in check suffixes list, but "%s" was given' % (check))
-
-file_check_suffix = ('-' + check) if check else ''
-check_fixes_prefix = 'CHECK-FIXES' + file_check_suffix
-check_messages_prefix = 'CHECK-MESSAGES' + file_check_suffix
-check_notes_prefix = 'CHECK-NOTES' + file_check_suffix
-
-has_check_fix = check_fixes_prefix in input_text
-has_check_message = check_messages_prefix in input_text
-has_check_note = check_notes_prefix in input_text
-
-if has_check_note and has_check_message:
-  sys.exit('Please use either %s or %s but not both' %
-(check_notes_prefix, check_messages_prefix))
-
-if not has_check_fix and not has_check_message and not has_check_note:
-  sys.exit('%s, %s or %s not found in the input' %
-(check_fixes_prefix, check_messages_prefix, check_notes_prefix))
-
-has_check_fixes = has_check_fixes or has_check_fix
-has_check_messages = has_check_messages or has_check_message
-has_check_notes = has_check_notes or has_check_note
-
-if has_check_fix:
-  check_fixes_prefixes.append(check_fixes_prefix)
-if has_check_message:
-  check_messages_prefixes.append(check_messages_prefix)
-if has_check_note:
-  check_notes_prefixes.append(check_notes_prefix)
-
-  assert has_check_fixes or has_check_messages or has_check_notes
-  # Remove the contents of the CHECK lines to avoid CHECKs matching on
-  # themselves.  We need to keep the comments to preserve line numbers while
-  # avoiding empty lines which could potentially trigger formatting-related
-  # checks.
-  cleaned_test = re.sub('// *CHECK-[A-Z0-9\-]*:[^\r\n]*', '//', input_text)
-
-  write_file(temp_file_name, cleaned_test)
-
-  original_file_name = temp_file_name + ".orig"
-  write_file(original_file_nam

[PATCH] D116412: [Clang][Sema] Fix attribute mismatch warning for ObjC class properties

2022-01-10 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman accepted this revision.
arphaman added a comment.
This revision is now accepted and ready to land.

LGTM, Cheers!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116412

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


[PATCH] D116975: [OpenMP] Initial Implementation of LTO and bitcode linking in linker wrapper

2022-01-10 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 398748.
jhuber6 added a comment.

Undoing accidental clang format.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116975

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/tools/clang-linker-wrapper/CMakeLists.txt
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  llvm/lib/Passes/PassBuilderPipelines.cpp

Index: llvm/lib/Passes/PassBuilderPipelines.cpp
===
--- llvm/lib/Passes/PassBuilderPipelines.cpp
+++ llvm/lib/Passes/PassBuilderPipelines.cpp
@@ -1464,6 +1464,9 @@
   // libraries and other oracles.
   MPM.addPass(InferFunctionAttrsPass());
 
+  if (Level.getSpeedupLevel() > 1)
+MPM.addPass(OpenMPOptPass());
+
   if (Level.getSpeedupLevel() > 1) {
 FunctionPassManager EarlyFPM;
 EarlyFPM.addPass(CallSiteSplittingPass());
@@ -1773,6 +1776,7 @@
   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
   CGSCCPassManager CGPM;
   CGPM.addPass(CoroSplitPass());
+  CGPM.addPass(OpenMPOptCGSCCPass());
   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
 
Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -17,9 +17,12 @@
 #include "clang/Basic/Version.h"
 #include "llvm/BinaryFormat/Magic.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/CommandFlags.h"
 #include "llvm/IR/Constants.h"
+#include "llvm/IR/DiagnosticPrinter.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IRReader/IRReader.h"
+#include "llvm/LTO/LTO.h"
 #include "llvm/Object/Archive.h"
 #include "llvm/Object/ArchiveWriter.h"
 #include "llvm/Object/Binary.h"
@@ -36,6 +39,7 @@
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/StringSaver.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -58,6 +62,15 @@
cl::desc("Path of linker binary"),
cl::cat(ClangLinkerWrapperCategory));
 
+static cl::opt
+TargetFeatures("target-feature", cl::desc("Target features for triple"),
+   cl::cat(ClangLinkerWrapperCategory));
+
+static cl::opt OptLevel("opt-level",
+ cl::desc("Optimization level for LTO"),
+ cl::init("O0"),
+ cl::cat(ClangLinkerWrapperCategory));
+
 // Do not parse linker options.
 static cl::list
 HostLinkerArgs(cl::Sink, cl::desc("..."));
@@ -68,6 +81,9 @@
 /// Temporary files created by the linker wrapper.
 static SmallVector TempFiles;
 
+/// Codegen flags for LTO backend.
+static codegen::RegisterCodeGenFlags CodeGenFlags;
+
 /// Magic section string that marks the existence of offloading data. The
 /// section string will be formatted as `.llvm.offloading..`.
 #define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading."
@@ -195,6 +211,28 @@
   if (ToBeStripped.empty())
 return None;
 
+  // If the object file to strip doesn't exist we need to write it so we can
+  // pass it to llvm-strip.
+  SmallString<128> StripFile = Obj.getFileName();
+  if (!sys::fs::exists(StripFile)) {
+SmallString<128> TempFile;
+if (std::error_code EC = sys::fs::createTemporaryFile(
+sys::path::stem(StripFile), "o", TempFile))
+  return createFileError(TempFile, EC);
+TempFiles.push_back(static_cast(TempFile));
+
+auto Contents = Obj.getMemoryBufferRef().getBuffer();
+Expected> OutputOrErr =
+FileOutputBuffer::create(TempFile, Contents.size());
+if (!OutputOrErr)
+  return OutputOrErr.takeError();
+std::unique_ptr Output = std::move(*OutputOrErr);
+std::copy(Contents.begin(), Contents.end(), Output->getBufferStart());
+if (Error E = Output->commit())
+  return E;
+StripFile = TempFile;
+  }
+
   // We will use llvm-strip to remove the now unneeded section containing the
   // offloading code.
   ErrorOr StripPath = sys::findProgramByName(
@@ -214,7 +252,7 @@
   SmallVector StripArgs;
   StripArgs.push_back(*StripPath);
   StripArgs.push_back("--no-strip-all");
-  StripArgs.push_back(Obj.getFileName());
+  StripArgs.push_back(StripFile);
   for (auto &Section : ToBeStripped) {
 StripArgs.push_back("--remove-section");
 StripArgs.push_back(Section);
@@ -419,6 +457,44 @@
 
 // TODO: Move these to a separate file.
 namespace nvptx {
+Expected assemble(StringRef InputFile, Triple TheTriple,
+   StringRef Arch) {
+  // NVPTX uses the nvlink binary to link device object files.
+  Error

[PATCH] D116840: [HIP] Fix device only linking for -fgpu-rdc

2022-01-10 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 rG98ab43a1d209: [HIP] Fix device only linking for -fgpu-rdc 
(authored by yaxunl).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116840

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/hip-phases.hip
  clang/test/Driver/hip-toolchain-rdc-separate.hip

Index: clang/test/Driver/hip-toolchain-rdc-separate.hip
===
--- clang/test/Driver/hip-toolchain-rdc-separate.hip
+++ clang/test/Driver/hip-toolchain-rdc-separate.hip
@@ -88,47 +88,66 @@
 // RUN:   --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   -fuse-ld=lld -fgpu-rdc -nogpuinc \
 // RUN:   %T/a.o %T/b.o \
-// RUN: 2>&1 | FileCheck -check-prefix=LINK %s
+// RUN: 2>&1 | FileCheck -check-prefixes=LINK,LINK-HOST-UNBUNDLE,LLD-TMP,LINK-BUNDLE,LINK-EMBED %s
 
-// LINK: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
-// LINK-SAME: "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900"
-// LINK-SAME: "-inputs=[[A_O:.*a.o]]" "-outputs=[[A_OBJ_HOST:.*o]],{{.*o}},{{.*o}}"
-// LINK: "-unbundle" "-allow-missing-bundles"
+// RUN: %clang --hip-link -### -target x86_64-linux-gnu \
+// RUN:   --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
+// RUN:   -fuse-ld=lld -fgpu-rdc -nogpuinc \
+// RUN:   %T/a.o %T/b.o --cuda-device-only \
+// RUN: 2>&1 | FileCheck -check-prefixes=LINK,LLD-TMP,LINK-BUNDLE,LINK-NOEMBED %s
 
-// LINK: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
-// LINK-SAME: "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900"
-// LINK-SAME: "-inputs=[[B_O:.*b.o]]" "-outputs=[[B_OBJ_HOST:.*o]],{{.*o}},{{.*o}}"
-// LINK: "-unbundle" "-allow-missing-bundles"
+// RUN: %clang --hip-link -### -target x86_64-linux-gnu \
+// RUN:   --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
+// RUN:   -fuse-ld=lld -fgpu-rdc -nogpuinc \
+// RUN:   %T/a.o %T/b.o --cuda-device-only --no-gpu-bundle-output \
+// RUN: 2>&1 | FileCheck -check-prefixes=LINK,LLD-FIN,LINK-NOBUNDLE,LINK-NOEMBED %s
+
+// LINK-HOST-UNBUNDLE: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
+// LINK-HOST-UNBUNDLE-SAME: "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900"
+// LINK-HOST-UNBUNDLE-SAME: "-inputs=[[A_O:.*a.o]]" "-outputs=[[A_OBJ_HOST:.*o]],{{.*o}},{{.*o}}"
+// LINK-HOST-UNBUNDLE: "-unbundle" "-allow-missing-bundles"
+
+// LINK-HOST-UNBUNDLE: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
+// LINK-HOST-UNBUNDLE-SAME: "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900"
+// LINK-HOST-UNBUNDLE-SAME: "-inputs=[[B_O:.*b.o]]" "-outputs=[[B_OBJ_HOST:.*o]],{{.*o}},{{.*o}}"
+// LINK-HOST-UNBUNDLE: "-unbundle" "-allow-missing-bundles"
 
 // LINK: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
 // LINK-SAME: "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900"
-// LINK-SAME: "-inputs=[[A_O]]" "-outputs={{.*o}},[[A_BC1:.*o]],[[A_BC2:.*o]]"
-// LINK: "-unbundle" "-allow-missing-bundles"
+// LINK-SAME: "-inputs=[[A_O:.*a.o]]" "-outputs={{.*o}},[[A_BC1:.*o]],[[A_BC2:.*o]]"
+// LINK-SAME: "-unbundle" "-allow-missing-bundles"
 
 // LINK: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
 // LINK-SAME: "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900"
-// LINK-SAME: "-inputs=[[B_O]]" "-outputs={{.*o}},[[B_BC1:.*o]],[[B_BC2:.*o]]"
-// LINK: "-unbundle" "-allow-missing-bundles"
+// LINK-SAME: "-inputs=[[B_O:.*b.o]]" "-outputs={{.*o}},[[B_BC1:.*o]],[[B_BC2:.*o]]"
+// LINK-SAME: "-unbundle" "-allow-missing-bundles"
 
 // LINK-NOT: "*.llvm-link"
 // LINK-NOT: ".*opt"
 // LINK-NOT: ".*llc"
 // LINK: {{".*lld.*"}} {{.*}} "-plugin-opt=-amdgpu-internalize-symbols"
-// LINK: "-plugin-opt=mcpu=gfx803"
-// LINK-SAME: "-o" "[[IMG_DEV1:.*.out]]" "[[A_BC1]]" "[[B_BC1]]"
+// LINK-SAME: "-plugin-opt=mcpu=gfx803"
+// LLD-TMP-SAME: "-o" "[[IMG_DEV1:.*.out]]"
+// LLD-FIN-SAME: "-o" "[[IMG_DEV1:a.out-.*gfx803]]"
+// LINK-SAME "[[A_BC1]]" "[[B_BC1]]"
 
 // LINK-NOT: "*.llvm-link"
 // LINK-NOT: ".*opt"
 // LINK-NOT: ".*llc"
 // LINK: {{".*lld.*"}} {{.*}} "-plugin-opt=-amdgpu-internalize-symbols"
-// LINK: "-plugin-opt=mcpu=gfx900"
-// LINK-SAME: "-o" "[[IMG_DEV2:.*.out]]" "[[A_BC2]]" "[[B_BC2]]"
-
-// LINK: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
-// LINK-SAME: "-targets={{.*}},hipv4-amdgcn-amd-amdhsa--gfx803,hipv4-amdgcn-amd-amdhsa--gfx900"
-// LINK-SAME: "-inputs={{.*}},[[IMG_DEV1]],[[IMG_DEV2]]" "-outputs=[[BUNDLE:.*hipfb]]"
-
-// LINK: {{".*llvm-mc.*"}} "-o" "[[OBJBUNDLE:.*o]]" "{{.*}}.mcin" "--filetype=obj"
-
-// LINK: [[LD:".*ld.*"]] {{.*}} "-o" "a.out" {{.*}} "[[A_OBJ_HOST]]"
-// LINK-SAME: "[[B_OBJ_HOST]]" "[[OBJBU

[clang] 98ab43a - [HIP] Fix device only linking for -fgpu-rdc

2022-01-10 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2022-01-10T17:38:02-05:00
New Revision: 98ab43a1d209875ce9cc39420d3e6af57ed0f5b2

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

LOG: [HIP] Fix device only linking for -fgpu-rdc

Currently when -fgpu-rdc is specified, HIP toolchain always does host linking 
even
if --cuda-device-only is specified.

This patch fixes that. Only device linking is performed when --cuda-device-only
is specified.

Reviewed by: Artem Belevich

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

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
clang/test/Driver/hip-phases.hip
clang/test/Driver/hip-toolchain-rdc-separate.hip

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index bb7ccf7dd97eb..ac8438bb45a6a 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -3110,7 +3110,7 @@ class OffloadingActionBuilder final {
 // We will pass the device action as a host dependence, so we don't
 // need to do anything else with them.
 CudaDeviceActions.clear();
-return ABRT_Success;
+return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
   }
 
   // By default, we produce an action for each device arch.
@@ -3143,6 +3143,7 @@ class OffloadingActionBuilder final {
   assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
  "Linker inputs and GPU arch list sizes do not match.");
 
+  ActionList Actions;
   // Append a new link action for each device.
   unsigned I = 0;
   for (auto &LI : DeviceLinkerInputs) {
@@ -3154,22 +3155,29 @@ class OffloadingActionBuilder final {
 OffloadAction::DeviceDependences DeviceLinkDeps;
 DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
 GpuArchList[I], AssociatedOffloadKind);
-AL.push_back(C.MakeAction(DeviceLinkDeps,
-DeviceLinkAction->getType()));
+Actions.push_back(C.MakeAction(
+DeviceLinkDeps, DeviceLinkAction->getType()));
 ++I;
   }
   DeviceLinkerInputs.clear();
 
   // Create a host object from all the device images by embedding them
-  // in a fat binary.
+  // in a fat binary for mixed host-device compilation. For device-only
+  // compilation, creates a fat binary.
   OffloadAction::DeviceDependences DDeps;
-  auto *TopDeviceLinkAction =
-  C.MakeAction(AL, types::TY_Object);
-  DDeps.add(*TopDeviceLinkAction, *ToolChains[0],
-  nullptr, AssociatedOffloadKind);
-
-  // Offload the host object to the host linker.
-  AL.push_back(C.MakeAction(DDeps, 
TopDeviceLinkAction->getType()));
+  if (!CompileDeviceOnly || !BundleOutput.hasValue() ||
+  BundleOutput.getValue()) {
+auto *TopDeviceLinkAction = C.MakeAction(
+Actions,
+CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object);
+DDeps.add(*TopDeviceLinkAction, *ToolChains[0], nullptr,
+  AssociatedOffloadKind);
+// Offload the host object to the host linker.
+AL.push_back(
+C.MakeAction(DDeps, 
TopDeviceLinkAction->getType()));
+  } else {
+AL.append(Actions);
+  }
 }
 
 Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); 
}
@@ -3556,15 +3564,18 @@ class OffloadingActionBuilder final {
 return false;
   }
 
-  Action* makeHostLinkAction() {
-// Build a list of device linking actions.
-ActionList DeviceAL;
+  void appendDeviceLinkActions(ActionList &AL) {
 for (DeviceActionBuilder *SB : SpecializedBuilders) {
   if (!SB->isValid())
 continue;
-  SB->appendLinkDeviceActions(DeviceAL);
+  SB->appendLinkDeviceActions(AL);
 }
+  }
 
+  Action *makeHostLinkAction() {
+// Build a list of device linking actions.
+ActionList DeviceAL;
+appendDeviceLinkActions(DeviceAL);
 if (DeviceAL.empty())
   return nullptr;
 
@@ -3893,6 +3904,13 @@ void Driver::BuildActions(Compilation &C, DerivedArgList 
&Args,
   }
 
   // Add a link action if necessary.
+
+  if (LinkerInputs.empty()) {
+Arg *FinalPhaseArg;
+if (getFinalPhase(Args, &FinalPhaseArg) == phases::Link)
+  OffloadBuilder.appendDeviceLinkActions(Actions);
+  }
+
   if (!LinkerInputs.empty()) {
 if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
   LinkerInputs.push_back(Wrapper);

diff  --git a/clang/test/Driver/hip-phases.hip 
b/clang/test/Driver/hip-phases.hip
index 623299b13dd0c..93bf635dab63f 100644
--- a/clang/test/Driver/hip-phases.hip
+++ b/clang/test/Driver/hip-phases.hip
@@ -311,22 +311,36 @@
 //
 // RUN: %clang -target x86_64-unknown-linux-gnu -ccc-print-phases --hip-link \
 // RUN: --cuda-gpu-arch=gfx803 --cuda-

[PATCH] D116975: [OpenMP] Initial Implementation of LTO and bitcode linking in linker wrapper

2022-01-10 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, gregrodgers, JonChesterfield, ronlieb.
Herald added subscribers: guansong, hiraditya, inglorion, yaxunl, mgorny.
jhuber6 requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, sstefan1.
Herald added projects: clang, LLVM.

This patch implements the fist support for handling LTO in the
offloading pipeline. The flag `-foffload-lto` is used to control if
bitcode is embedded into the device. If bitcode is found in the device,
the extracted files will be sent to the LTO pipeline to be linked and
sent to the backend. This implementation does not separately link the
device bitcode libraries yet.

Depends on D116675 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116975

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/tools/clang-linker-wrapper/CMakeLists.txt
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  llvm/lib/Passes/PassBuilderPipelines.cpp

Index: llvm/lib/Passes/PassBuilderPipelines.cpp
===
--- llvm/lib/Passes/PassBuilderPipelines.cpp
+++ llvm/lib/Passes/PassBuilderPipelines.cpp
@@ -1464,6 +1464,9 @@
   // libraries and other oracles.
   MPM.addPass(InferFunctionAttrsPass());
 
+  if (Level.getSpeedupLevel() > 1)
+MPM.addPass(OpenMPOptPass());
+
   if (Level.getSpeedupLevel() > 1) {
 FunctionPassManager EarlyFPM;
 EarlyFPM.addPass(CallSiteSplittingPass());
@@ -1773,6 +1776,7 @@
   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
   CGSCCPassManager CGPM;
   CGPM.addPass(CoroSplitPass());
+  CGPM.addPass(OpenMPOptCGSCCPass());
   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
 
Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -17,9 +17,12 @@
 #include "clang/Basic/Version.h"
 #include "llvm/BinaryFormat/Magic.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/CommandFlags.h"
 #include "llvm/IR/Constants.h"
+#include "llvm/IR/DiagnosticPrinter.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IRReader/IRReader.h"
+#include "llvm/LTO/LTO.h"
 #include "llvm/Object/Archive.h"
 #include "llvm/Object/ArchiveWriter.h"
 #include "llvm/Object/Binary.h"
@@ -36,6 +39,7 @@
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/StringSaver.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -58,6 +62,15 @@
cl::desc("Path of linker binary"),
cl::cat(ClangLinkerWrapperCategory));
 
+static cl::opt
+TargetFeatures("target-feature", cl::desc("Target features for triple"),
+   cl::cat(ClangLinkerWrapperCategory));
+
+static cl::opt OptLevel("opt-level",
+ cl::desc("Optimization level for LTO"),
+ cl::init("O0"),
+ cl::cat(ClangLinkerWrapperCategory));
+
 // Do not parse linker options.
 static cl::list
 HostLinkerArgs(cl::Sink, cl::desc("..."));
@@ -68,6 +81,9 @@
 /// Temporary files created by the linker wrapper.
 static SmallVector TempFiles;
 
+/// Codegen flags for LTO backend.
+static codegen::RegisterCodeGenFlags CodeGenFlags;
+
 /// Magic section string that marks the existence of offloading data. The
 /// section string will be formatted as `.llvm.offloading..`.
 #define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading."
@@ -195,6 +211,28 @@
   if (ToBeStripped.empty())
 return None;
 
+  // If the object file to strip doesn't exist we need to write it so we can
+  // pass it to llvm-strip.
+  SmallString<128> StripFile = Obj.getFileName();
+  if (!sys::fs::exists(StripFile)) {
+SmallString<128> TempFile;
+if (std::error_code EC = sys::fs::createTemporaryFile(
+sys::path::stem(StripFile), "o", TempFile))
+  return createFileError(TempFile, EC);
+TempFiles.push_back(static_cast(TempFile));
+
+auto Contents = Obj.getMemoryBufferRef().getBuffer();
+Expected> OutputOrErr =
+FileOutputBuffer::create(TempFile, Contents.size());
+if (!OutputOrErr)
+  return OutputOrErr.takeError();
+std::unique_ptr Output = std::move(*OutputOrErr);
+std::copy(Contents.begin(), Contents.end(), Output->getBufferStart());
+if (Error E = Output->commit())
+  return E;
+StripFile = TempFile;
+  }
+
   // We will use llvm-strip to remove the now unneeded section containing the
   // offloading code.
   ErrorOr StripPath = sys::findProgramByName(
@@ -214

[PATCH] D116935: [IRBuilder] Introduce folder using inst-simplify, use for Or fold.

2022-01-10 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

In D116935#3232584 , @fhahn wrote:

> Rebased and made sure comments are consistent between different folders.
>
> In D116935#3232227 , @craig.topper 
> wrote:
>
>> In D116935#3232203 , @lebedev.ri 
>> wrote:
>>
>>> In D116935#3232126 , 
>>> @craig.topper wrote:
>>>
 If I remember correctly, the Or and And folds for 0 and all 1s are there 
 to optimize bitfield codegen for the frontend. Are we losing that 
 optimization if this patch goes in before switching clang to 
 InstSimplifyFolder?
>>>
>>> True, but why is that optimization there in the first place?
>>> Presumably it shouldn't matter nowadays.
>>
>> Probably for -O0 where there is no optimizer,
>>
>>   commit 0fc4311f0ea4034b4bad1c82c652dc04bb763cda
>>   Author: Chris Lattner 
>>   Date:   Wed Nov 4 05:00:12 2009 +
>>   
>>   make IRBuilder zap "X|0" and "X&-1" when building IR, this happens
>>   during bitfield codegen and slows down -O0 compile times by making
>>   useless IR.  rdar://7362516
>>   
>>   llvm-svn: 86006
>
> I collected numbers using the compile-time tracker and the data seems to 
> indicate this is not an issue any longer, there are no notable changes for 
> any config: 
> http://llvm-compile-time-tracker.com/compare.php?from=baa5b54d43419b5d4a1ec36f3788c36d52187e11&to=e22fc3bb9b024699fdfd12b89c68205565215b27&stat=instructions

Do the programs in compile-time tracker make much use of bitfields? Is there 
any indication in rdar://7362516 what program needed this? It looks like 
assigning a bitfield to 0 is enough to generate an or with 0 that survives 
through fast isel at -O0 on X86. But a few assignments to 0 wouldn't make for a 
huge problem, so I imagine there must have been something pathological about 
some program.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116935

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


[PATCH] D116833: [clang] Introduce support for disabling warnings in system macros

2022-01-10 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

I'll just note here that doing this globally is likely to have unexpected 
results... consider, for example:

  #include 
  void f() { long x = M_PI; }

Currently, the implicit conversion warning points into math.h.

That said, I don't see any problem with the current implementation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116833

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


[PATCH] D116549: [OpenMP][Clang] Allow passing target features in ISA trait for metadirective clause

2022-01-10 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added inline comments.



Comment at: clang/lib/Parse/ParseOpenMP.cpp:2533
+std::function DiagUnknownTrait = [this, Loc](
+StringRef ISATrait) {};
+TargetOMPContext OMPCtx(ASTContext, std::move(DiagUnknownTrait),

saiislam wrote:
> jdoerfert wrote:
> > jdoerfert wrote:
> > > saiislam wrote:
> > > > jdoerfert wrote:
> > > > > Why doesn't this diagnose nothing?
> > > > Because an isa-feature will fail at least once, for either host 
> > > > compilation or device compilation. So, no point in always giving a 
> > > > warning.
> > > That is debatable. 
> > > 
> > > First, if I compile for a single architecture there is no device 
> > > compilation and it should warn.
> > > Second, if I place the metadirective into a declare variant function or 
> > > add a `kind(...)` selector to it it will also not warn even if you have 
> > > multiple architectures.
> > > 
> > > 
> > ```
> > ASTContext &Context = getASTContext();
> > std::function DiagUnknownTrait = [this,
> > ┊ ┊ ┊ ┊ ┊ ┊ ┊ ┊ ┊ ┊CE](StringRef 
> > ISATrait) {
> > ┊ // TODO Track the selector locations in a way that is accessible here 
> > to
> > ┊ // improve the diagnostic location.
> > ┊ Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
> > ┊ ┊ ┊ << ISATrait;   
> > };
> > TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),   
> > 
> > 
> >
> > ┊ ┊ ┊ ┊ ┊ ┊ ┊ ┊ ┊ ┊ getCurFunctionDecl(), 
> > DSAStack->getConstructTraits());
> > ```
> > Already exists (SemaOpenMP). Why do we need a second, different diagnostic?
> Isn't giving a remark better than a warning, when we know in many cases this 
> will be hit during a normal (expected) compilation for target offload?
> Remark diagnostic will give ample handle for understanding the flow without 
> the need to explicitly deal with this warning during compilation of user 
> programs.
> 
> I am fine changing it to a warning if you feel strongly about this.
1) Having two diagnostics for the same thing is generally bad and there doesn't 
seem to be a reason why we would need/want to treat metadirective and declare 
variant differently.
 Thus, if we want to move to remarks we should move the second diagnostic as 
well. Cleaning up existing code is more important than adding new code.
2) I still don't see why this is "normal" or "expected" at all. The warning 
reads:
`isa trait 'foo' is not known to the current target; verify the spelling or 
consider restricting the context selector with the 'arch' selector further`.
Hence, `device={isa("flat..."), arch(amdgcn)}` should not cause a warning even 
if you compile it for the host, an nvidia gpu, or anything other than AMDGCN.
FWIW, this is [supposed to be] ensured by the positioning of the isa trait 
selector in OMPKinds.def:
```
  // Note that we put isa last so that the other conditions are checked first.
  // This allows us to issue warnings wrt. isa only if we match otherwise.
  __OMP_TRAIT_SELECTOR(device, isa, true)
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116549

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


[PATCH] D115932: [Analyzer] Create and handle SymbolCast for pointer to integral conversion

2022-01-10 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:420
+  auto FromTy = symRHS->getType();
+  auto ToTy = RLocAsInt->getType(this->Context);
+  symRHS = this->getSymbolManager().getCastSymbol(symRHS, FromTy, ToTy);

ASDenysPetrov wrote:
> Please take into account that `SVal::getType` may return NULL `QualType`. See 
> function's description.
Yup, `SVal::getType()` is relatively speculative. It arguably shouldn't be but 
as of now it is.

In this case though it'll probably always work correctly. Despite the relevant 
code making relatively little sense:
```lang=c++
   QualType VisitNonLocLocAsInteger(nonloc::LocAsInteger LI) {
 // Who cares about the pointer type? It's turned into an integer anyway.
 QualType NestedType = Visit(LI.getLoc());

 // Ok, now we suddenly have a failure condition when there's no pointer 
type
 // even though the pointer type is completely immaterial.
 // It probably never fails in practice though, because there's usually at 
least some
 // pointer type (void pointer in the worst case, but it's still something).
 if (NestedType.isNull())
   return NestedType;
  
 // See? We can get bit width without pointer type.
 return Context.getIntTypeForBitwidth(LI.getNumBits(),
  // Oh I know this one! It's a pointer 
type. It isn't an integer type at all.
  // Whelp I guess "always unsigned" 
works for us as well as anything else.
  // We don't have any information 
about signedness one way or the other.
  NestedType->isSignedIntegerType());
   }
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115932

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


[PATCH] D111566: [SYCL] Fix function pointer address space

2022-01-10 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/AST/ASTContext.cpp:11494
+  const Type *TypePtr = T.getTypePtr();
+  return TypePtr->isFunctionType()
+ ? llvm::DataLayout(getTargetInfo().getDataLayoutString())

You can just do `T->isFunctionType()`.



Comment at: clang/lib/AST/ASTContext.cpp:11497
+   .getProgramAddressSpace()
+ : getTargetAddressSpace(T.getQualifiers());
+}

If a function type has an address space qualifier, we should prefer that, 
right?  Or is that impossible by construction?



Comment at: clang/lib/CodeGen/CodeGenTypes.cpp:747
   : ConvertTypeForMem(FTy);
-unsigned AS = Context.getTargetAddressSpace(FTy);
+unsigned AS = Context.getTargetAddressSpace(FTy.getQualifiers());
 ResultType = llvm::PointerType::get(PointeeType, AS);

Please add a comment here explaining that it's important to not just use `FTy` 
because in the absence of an explicit address space we need to get the default 
address space for a data pointer, not a function.


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

https://reviews.llvm.org/D111566

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


[PATCH] D105340: [analyzer] Produce SymbolCast symbols for integral types in SValBuilder::evalCast

2022-01-10 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

This looks great with the option flag. Landing this patch will enable more 
people to test the new mode and produce feedback on whether the constraint 
solver keeps working well enough in presence of the new symbols.




Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:1004
+  QualType CastTy) {
+  // We use seven conditions to recognize a simplification case.
+  // For the clarity let `CastTy` be `C`, SE->getType() - `T`, root type - `R`,

I really hope these are correct with respect to sign extension 🤞



Comment at: clang/test/Analysis/produce-symbolcast_x64.cpp:15
+void test_schar(schar x) {
+  clang_analyzer_dump(x); // expected-warning{{reg_$0}}
+

There's `clang_analyzer_denote()`/`clang_analyzer_express()` which is slightly 
better because it avoids testing the specific dump format (so we could change 
it more easily if we want). No pressure though, if it's too much work to re-do 
then let's keep them as is.


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

https://reviews.llvm.org/D105340

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


[PATCH] D116967: [HIP] Fix device malloc/free

2022-01-10 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Headers/__clang_hip_runtime_wrapper.h:80
 
+#if HIP_VERSION_MAJOR > 4 || (HIP_VERSION_MAJOR == 4 && HIP_VERSION_MINOR >= 5)
+extern "C" __device__ unsigned long long __ockl_dm_alloc(unsigned long long 
__size);

Nit: perhaps something like this would express the intent a bit more directly:

```
# if HIP_VERSION_MAJOR*100+HIP_VERSION_MINOR*10 > 450
```




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

https://reviews.llvm.org/D116967

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


[libunwind] 914fffc - [libunwind][cmake] Create `LIBUNWIND_INSTALL_INCLUDE_DIR` CACHE PATH

2022-01-10 Thread John Ericson via cfe-commits

Author: John Ericson
Date: 2022-01-10T21:31:52Z
New Revision: 914fffc7f2492a1e4bc419a80c30fdb3f9440698

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

LOG: [libunwind][cmake] Create `LIBUNWIND_INSTALL_INCLUDE_DIR` CACHE PATH

This is created on analogy with the other CACHE PATHs in this package,
and other `*_INSTALL_INCLUDE_DIR` in other packages.

The branching is adjusted to deduplicate some existing code, and
likewise avoid having to define this new variable more than once.

This will be used for D99484.

Reviewed By: #libunwind, compnerd

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

Added: 


Modified: 
libunwind/CMakeLists.txt
libunwind/include/CMakeLists.txt

Removed: 




diff  --git a/libunwind/CMakeLists.txt b/libunwind/CMakeLists.txt
index e3cc66dd22267..efbd88a27f05a 100644
--- a/libunwind/CMakeLists.txt
+++ b/libunwind/CMakeLists.txt
@@ -141,26 +141,25 @@ if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)
   set(LIBUNWIND_LIBRARY_DIR 
${LLVM_LIBRARY_OUTPUT_INTDIR}/${LLVM_DEFAULT_TARGET_TRIPLE})
   set(LIBUNWIND_INSTALL_LIBRARY_DIR 
lib${LLVM_LIBDIR_SUFFIX}/${LLVM_DEFAULT_TARGET_TRIPLE} CACHE PATH
   "Path where built libunwind libraries should be installed.")
-  set(LIBUNWIND_INSTALL_RUNTIME_DIR bin CACHE PATH
-  "Path where built libunwind runtime libraries should be installed.")
   if(LIBCXX_LIBDIR_SUBDIR)
 string(APPEND LIBUNWIND_LIBRARY_DIR /${LIBUNWIND_LIBDIR_SUBDIR})
 string(APPEND LIBUNWIND_INSTALL_LIBRARY_DIR /${LIBUNWIND_LIBDIR_SUBDIR})
   endif()
-elseif(LLVM_LIBRARY_OUTPUT_INTDIR)
-  set(LIBUNWIND_LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
-  set(LIBUNWIND_INSTALL_LIBRARY_DIR lib${LIBUNWIND_LIBDIR_SUFFIX} CACHE PATH
-  "Path where built libunwind libraries should be installed.")
-  set(LIBUNWIND_INSTALL_RUNTIME_DIR bin CACHE PATH
-  "Path where built libunwind runtime libraries should be installed.")
 else()
-  set(LIBUNWIND_LIBRARY_DIR ${CMAKE_BINARY_DIR}/lib${LIBUNWIND_LIBDIR_SUFFIX})
+  if(LLVM_LIBRARY_OUTPUT_INTDIR)
+set(LIBUNWIND_LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
+  else()
+set(LIBUNWIND_LIBRARY_DIR 
${CMAKE_BINARY_DIR}/lib${LIBUNWIND_LIBDIR_SUFFIX})
+  endif()
   set(LIBUNWIND_INSTALL_LIBRARY_DIR lib${LIBUNWIND_LIBDIR_SUFFIX} CACHE PATH
   "Path where built libunwind libraries should be installed.")
-  set(LIBUNWIND_INSTALL_RUNTIME_DIR bin CACHE PATH
-  "Path where built libunwind runtime libraries should be installed.")
 endif()
 
+set(LIBUNWIND_INSTALL_INCLUDE_DIR include CACHE PATH
+"Path where built libunwind headers should be installed.")
+set(LIBUNWIND_INSTALL_RUNTIME_DIR bin CACHE PATH
+"Path where built libunwind runtime libraries should be installed.")
+
 set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${LIBUNWIND_LIBRARY_DIR})
 set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${LIBUNWIND_LIBRARY_DIR})
 set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${LIBUNWIND_LIBRARY_DIR})

diff  --git a/libunwind/include/CMakeLists.txt 
b/libunwind/include/CMakeLists.txt
index c3bb1dd0f69fa..adf1766c44cbc 100644
--- a/libunwind/include/CMakeLists.txt
+++ b/libunwind/include/CMakeLists.txt
@@ -14,7 +14,7 @@ if(LIBUNWIND_INSTALL_HEADERS)
   foreach(file ${files})
 get_filename_component(dir ${file} DIRECTORY)
 install(FILES ${file}
-  DESTINATION "include/${dir}"
+  DESTINATION "${LIBUNWIND_INSTALL_INCLUDE_DIR}/${dir}"
   COMPONENT unwind-headers
   PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ
 )



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


[PATCH] D111566: [SYCL] Fix function pointer address space

2022-01-10 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews added a comment.

In D111566#3228949 , @rjmccall wrote:

> Block pointers are actually data pointers and should stay in the generic 
> address space if they don't have an address space qualifier.  That might 
> require new logic.

Thanks! I kept the existing behavior for block pointers by passing qualifiers 
to `getTargetAddressSpace`.


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

https://reviews.llvm.org/D111566

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


[PATCH] D111566: [SYCL] Fix function pointer address space

2022-01-10 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews updated this revision to Diff 398723.
eandrews added a comment.

Implemented review comment to move logic into function 
(`getTargetAddressSpace`) as opposed to call site.


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

https://reviews.llvm.org/D111566

Files:
  clang/include/clang/AST/ASTContext.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/test/CodeGenSYCL/functionptr-addressspace.cpp

Index: clang/test/CodeGenSYCL/functionptr-addressspace.cpp
===
--- /dev/null
+++ clang/test/CodeGenSYCL/functionptr-addressspace.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -fsycl-is-device -emit-llvm -triple spir64 -verify -emit-llvm %s -o - | FileCheck %s
+
+// expected-no-diagnostics
+
+template 
+__attribute__((sycl_kernel)) void kernel_single_task(const Func &kernelFunc) {
+  kernelFunc();
+}
+
+// CHECK: define dso_local spir_func{{.*}}invoke_function{{.*}}(i32 ()* %fptr, i32 addrspace(4)* %ptr)
+void invoke_function(int (*fptr)(), int *ptr) {}
+
+int f() { return 0; }
+
+int main() {
+  kernel_single_task([=]() {
+int (*p)() = f;
+int (&r)() = *p;
+int a = 10;
+invoke_function(p, &a);
+invoke_function(r, &a);
+invoke_function(f, &a);
+  });
+  return 0;
+}
Index: clang/lib/CodeGen/CodeGenTypes.cpp
===
--- clang/lib/CodeGen/CodeGenTypes.cpp
+++ clang/lib/CodeGen/CodeGenTypes.cpp
@@ -643,11 +643,7 @@
 llvm::Type *PointeeType = ConvertTypeForMem(ETy);
 if (PointeeType->isVoidTy())
   PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
-
-unsigned AS = PointeeType->isFunctionTy()
-  ? getDataLayout().getProgramAddressSpace()
-  : Context.getTargetAddressSpace(ETy);
-
+unsigned AS = Context.getTargetAddressSpace(ETy);
 ResultType = llvm::PointerType::get(PointeeType, AS);
 break;
   }
@@ -748,7 +744,7 @@
 llvm::Type *PointeeType = CGM.getLangOpts().OpenCL
   ? CGM.getGenericBlockLiteralType()
   : ConvertTypeForMem(FTy);
-unsigned AS = Context.getTargetAddressSpace(FTy);
+unsigned AS = Context.getTargetAddressSpace(FTy.getQualifiers());
 ResultType = llvm::PointerType::get(PointeeType, AS);
 break;
   }
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -80,6 +80,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/IR/DataLayout.h"
 #include "llvm/Support/Capacity.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/Compiler.h"
@@ -11488,6 +11489,18 @@
   return getTargetInfo().getNullPointerValue(AS);
 }
 
+unsigned ASTContext::getTargetAddressSpace(QualType T) const {
+  const Type *TypePtr = T.getTypePtr();
+  return TypePtr->isFunctionType()
+ ? llvm::DataLayout(getTargetInfo().getDataLayoutString())
+   .getProgramAddressSpace()
+ : getTargetAddressSpace(T.getQualifiers());
+}
+
+unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const {
+  return getTargetAddressSpace(Q.getAddressSpace());
+}
+
 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
   if (isTargetAddressSpace(AS))
 return toTargetAddressSpace(AS);
Index: clang/include/clang/AST/ASTContext.h
===
--- clang/include/clang/AST/ASTContext.h
+++ clang/include/clang/AST/ASTContext.h
@@ -2709,13 +2709,9 @@
   QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
  QualType typeDomain) const;
 
-  unsigned getTargetAddressSpace(QualType T) const {
-return getTargetAddressSpace(T.getQualifiers());
-  }
+  unsigned getTargetAddressSpace(QualType T) const;
 
-  unsigned getTargetAddressSpace(Qualifiers Q) const {
-return getTargetAddressSpace(Q.getAddressSpace());
-  }
+  unsigned getTargetAddressSpace(Qualifiers Q) const;
 
   unsigned getTargetAddressSpace(LangAS AS) const;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116859: Fix for: clang-format: break added to macro define with ColumnLimit: 0

2022-01-10 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:4810-4811
+
+  verifyFormat("#define STRINGIFY(t) #t\n"
+   "#define MAKEVERSIONSTRING(x, y, z, build) STRINGIFY(x) \".\" 
STRINGIFY(y) \".\" STRINGIFY(z) \".\" STRINGIFY(build)\n",
+   ZeroColumn);

HazardyKnusperkeks wrote:
> curdeius wrote:
> > Please test with something simpler.
> Did this show the bugged behavior without the patch?
> 
> Regarding the `// clang-format off` there is the question what do we want in 
> the tests? Show the long lines as the long lines, then we need to turn it off 
> some times. Or do we want to keep the limit and break the strings, thus 
> making it harder to read for the human?
> Did this show the bugged behavior without the patch?
Yes. I checked with a pretty fresh master.

> Regarding the `// clang-format off` there is the question what do we want in 
> the tests? Show the long lines as the long lines, then we need to turn it off 
> some times. Or do we want to keep the limit and break the strings, thus 
> making it harder to read for the human?
I'm pretty much against adding `// clang-format off` too, it hurts more than it 
helps IMO.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116859

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


[PATCH] D115440: Provide __builtin_alloca*_uninitialized variants

2022-01-10 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

Yes, this LGTM implementation-wise.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115440

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


[PATCH] D116967: [HIP] Fix device malloc/free

2022-01-10 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added reviewers: tra, b-sumner.
yaxunl requested review of this revision.

ROCm 4.5 device library introduced `__ockl_dm_alloc` and `__oclk_dm_dealloc`
for supporting device side malloc/free.

This patch redefines device malloc/free to use these functions.

It also fixes a bug in the wrapper header which incorrectly defines free
with return type void* instead of void.


https://reviews.llvm.org/D116967

Files:
  clang/lib/Headers/__clang_hip_runtime_wrapper.h
  clang/test/Headers/hip-header.hip

Index: clang/test/Headers/hip-header.hip
===
--- clang/test/Headers/hip-header.hip
+++ clang/test/Headers/hip-header.hip
@@ -4,7 +4,7 @@
 // RUN:   -internal-isystem %S/Inputs/include \
 // RUN:   -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-unknown \
 // RUN:   -target-cpu gfx906 -emit-llvm %s -fcuda-is-device -o - \
-// RUN:   -D__HIPCC_RTC__ | FileCheck %s
+// RUN:   -D__HIPCC_RTC__ | FileCheck -check-prefixes=CHECK,NOMALLOC %s
 // RUN: %clang_cc1 -include __clang_hip_runtime_wrapper.h \
 // RUN:   -internal-isystem %S/../../lib/Headers/cuda_wrappers \
 // RUN:   -internal-isystem %S/Inputs/include \
@@ -25,6 +25,13 @@
 // RUN:   -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-unknown \
 // RUN:   -target-cpu gfx906 -emit-llvm %s -fcuda-is-device -o - \
 // RUN:   -D__HIPCC_RTC__ -std=c++14 | FileCheck -check-prefixes=CHECK,CXX14 %s
+// RUN: %clang_cc1 -include __clang_hip_runtime_wrapper.h \
+// RUN:   -internal-isystem %S/../../lib/Headers/cuda_wrappers \
+// RUN:   -internal-isystem %S/Inputs/include \
+// RUN:   -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-unknown \
+// RUN:   -target-cpu gfx906 -emit-llvm %s -fcuda-is-device -o - \
+// RUN:   -DHIP_VERSION_MAJOR=4 -DHIP_VERSION_MINOR=5 \
+// RUN:   -D__HIPCC_RTC__ | FileCheck -check-prefixes=CHECK,MALLOC %s
 
 // expected-no-diagnostics
 
@@ -120,14 +127,18 @@
 #include 
 // CHECK-LABEL: define{{.*}}@_Z11test_malloc
 // CHECK: call {{.*}}i8* @malloc(i64
-// CHECK: define weak {{.*}}i8* @malloc(i64
+// CHECK-LABEL: define weak {{.*}}i8* @malloc(i64
+// MALLOC:  call i64 @__ockl_dm_alloc
+// NOMALLOC:  call void @llvm.trap
 __device__ void test_malloc(void *a) {
   a = malloc(42);
 }
 
 // CHECK-LABEL: define{{.*}}@_Z9test_free
-// CHECK: call {{.*}}i8* @free(i8*
-// CHECK: define weak {{.*}}i8* @free(i8*
+// CHECK: call {{.*}}void @free(i8*
+// CHECK-LABEL: define weak {{.*}}void @free(i8*
+// MALLOC:  call void @__ockl_dm_dealloc
+// NOMALLOC: call void @llvm.trap
 __device__ void test_free(void *a) {
   free(a);
 }
Index: clang/lib/Headers/__clang_hip_runtime_wrapper.h
===
--- clang/lib/Headers/__clang_hip_runtime_wrapper.h
+++ clang/lib/Headers/__clang_hip_runtime_wrapper.h
@@ -50,6 +50,9 @@
 #include 
 #include 
 #include 
+#if __has_include("hip/hip_version.h")
+#include "hip/hip_version.h"
+#endif // __has_include("hip/hip_version.h")
 #else
 typedef __SIZE_TYPE__ size_t;
 // Define macros which are needed to declare HIP device API's without standard
@@ -74,25 +77,35 @@
 extern "C" {
 #endif //__cplusplus
 
+#if HIP_VERSION_MAJOR > 4 || (HIP_VERSION_MAJOR == 4 && HIP_VERSION_MINOR >= 5)
+extern "C" __device__ unsigned long long __ockl_dm_alloc(unsigned long long __size);
+extern "C" __device__ void __ockl_dm_dealloc(unsigned long long __addr);
+__attribute__((weak)) inline __device__ void *malloc(__hip_size_t __size) {
+  return (void *) __ockl_dm_alloc(__size);
+}
+__attribute__((weak)) inline __device__ void free(void *__ptr) {
+  __ockl_dm_dealloc((unsigned long long)__ptr);
+}
+#else  // HIP version check
 #if __HIP_ENABLE_DEVICE_MALLOC__
 __device__ void *__hip_malloc(__hip_size_t __size);
 __device__ void *__hip_free(void *__ptr);
 __attribute__((weak)) inline __device__ void *malloc(__hip_size_t __size) {
   return __hip_malloc(__size);
 }
-__attribute__((weak)) inline __device__ void *free(void *__ptr) {
-  return __hip_free(__ptr);
+__attribute__((weak)) inline __device__ void free(void *__ptr) {
+  __hip_free(__ptr);
 }
 #else
 __attribute__((weak)) inline __device__ void *malloc(__hip_size_t __size) {
   __builtin_trap();
   return (void *)0;
 }
-__attribute__((weak)) inline __device__ void *free(void *__ptr) {
+__attribute__((weak)) inline __device__ void free(void *__ptr) {
   __builtin_trap();
-  return (void *)0;
 }
 #endif
+#endif // HIP version check
 
 #ifdef __cplusplus
 } // extern "C"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116948: [CodeGen] Treat ObjC `__unsafe_unretained` and class types as trivial when generating copy/dispose helper functions

2022-01-10 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/CodeGen/CGBlocks.cpp:41
+  // Reserve space now to prevent reallocation.
+  Captures.reserve(Block->getNumCaptures());
 

Does this actually work?  It's a hashtable, so I'm worried about the 
possibility of e.g. a bad set of collisions causing it to grow.  Even if it 
works today, it seems like a dangerous assumption to make.

If we're going to make `SortedCaptures` stick around, is there any way we can 
keep the `Capture` objects there and then have `Captures` just store pointers 
into it?  We'd just have to build `Captures` after the sorting was complete; I 
don't know if that's possible.



Comment at: clang/lib/CodeGen/CGBlocks.h:241
 
+  bool NoEscape : 1;
+

Please explain what this means in a comment — it's just whether the whole block 
itself is noescape, right?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116948

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


[PATCH] D116966: [analyzer] Don't specify PLUGIN_TOOL for analyzer plugins

2022-01-10 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX created this revision.
ArcsinX added reviewers: aaronpuchert, hintonda, NoQ, Szelethus, lebedev.ri.
Herald added subscribers: manas, wenlei, steakhal, ASDenysPetrov, usaxena95, 
dkrupp, donat.nagy, kadircet, mikhail.ramalho, a.sidorin, szepet, 
baloghadamsoftware, xazax.hun, mgorny.
ArcsinX requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1, ilya-biryukov.
Herald added a reviewer: jdoerfert.
Herald added a project: clang.

Analyzer plugins explicitly export clang_registerCheckers and 
clang_analyzerAPIVersionString symbols, so we don't need to specify a tool to 
link agains.

Also, without this patch MSVC build fails with cmake flags 
-DLLVM_ENABLE_PLUGINS=On -DCLANG_PLUGINS_SUPPORT=On 
-DLLVM_EXPORT_SYMBOLS_FOR_PLUGINS=On

  [936/936] Linking CXX shared module bin\SampleAnalyzerPlugin.dll
  FAILED: bin/SampleAnalyzerPlugin.dll
  cmd.exe /C "cd . && "D:\Program Files\CMake\bin\cmake.exe" -E vs_link_dll 
--intdir=tools\clang\lib\Analysis\plugins\SampleAnalyzer\CMakeFiles\SampleAnalyzerPlugin.dir
 --rc=C:\PROGRA~2\WI3CF2~1\10\bin\100183~1.0\x64\rc.exe 
--mt=C:\PROGRA~2\WI3CF2~1\10\bin\100183~1.0\x64\mt.exe --manifests  -- 
C:\PROGRA~2\MICROS~4\2019\COMMUN~1\VC\Tools\MSVC\1428~1.299\bin\Hostx64\x64\link.exe
 /nologo 
tools\clang\lib\Analysis\plugins\SampleAnalyzer\CMakeFiles\SampleAnalyzerPlugin.dir\MainCallChecker.cpp.obj
  /out:bin\SampleAnalyzerPlugin.dll /implib:lib\SampleAnalyzerPlugin.lib 
/pdb:bin\SampleAnalyzerPlugin.pdb /dll /version:0.0 /machine:x64 
/INCREMENTAL:NO  
/DEF:"D:/work/llvm-project-original/build-plugins/tools/clang/lib/Analysis/plugins/SampleAnalyzer/SampleAnalyzerPlugin.def"
  lib\clang.lib  lib\clangAnalysis.lib  lib\clangAST.lib  
lib\clangStaticAnalyzerCore.lib  lib\clangStaticAnalyzerFrontend.lib  
lib\clangStaticAnalyzerCheckers.lib  lib\clangStaticAnalyzerCore.lib  
lib\clangCrossTU.lib  lib\clangIndex.lib  lib\clangFormat.lib  
lib\clangToolingInclusions.lib  lib\clangFrontend.lib  lib\clangDriver.lib  
version.lib  lib\clangParse.lib  lib\clangSerialization.lib  lib\clangSema.lib  
lib\clangAnalysis.lib  lib\clangEdit.lib  lib\LLVMOption.lib  
lib\clangToolingCore.lib  lib\clangRewrite.lib  lib\clangASTMatchers.lib  
lib\clangAST.lib  lib\clangLex.lib  lib\clangBasic.lib  
lib\LLVMFrontendOpenMP.lib  lib\LLVMScalarOpts.lib  
lib\LLVMAggressiveInstCombine.lib  lib\LLVMInstCombine.lib  
lib\LLVMTransformUtils.lib  lib\LLVMAnalysis.lib  lib\LLVMProfileData.lib  
lib\LLVMDebugInfoDWARF.lib  lib\LLVMObject.lib  lib\LLVMBitReader.lib  
lib\LLVMCore.lib  lib\LLVMRemarks.lib  lib\LLVMBitstreamReader.lib  
lib\LLVMMCParser.lib  lib\LLVMMC.lib  lib\LLVMDebugInfoCodeView.lib  
lib\LLVMTextAPI.lib  lib\LLVMBinaryFormat.lib  lib\LLVMSupport.lib  psapi.lib  
shell32.lib  ole32.lib  uuid.lib  advapi32.lib  delayimp.lib  
-delayload:shell32.dll  -delayload:ole32.dll  lib\LLVMDemangle.lib  
kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib 
oleaut32.lib uuid.lib comdlg32.lib advapi32.lib  && cd ."
  LINK: command 
"C:\PROGRA~2\MICROS~4\2019\COMMUN~1\VC\Tools\MSVC\1428~1.299\bin\Hostx64\x64\link.exe
 /nologo 
tools\clang\lib\Analysis\plugins\SampleAnalyzer\CMakeFiles\SampleAnalyzerPlugin.dir\MainCallChecker.cpp.obj
 /out:bin\SampleAnalyzerPlugin.dll /implib:lib\SampleAnalyzerPlugin.lib 
/pdb:bin\SampleAnalyzerPlugin.pdb /dll /version:0.0 /machine:x64 
/INCREMENTAL:NO 
/DEF:D:/work/llvm-project-original/build-plugins/tools/clang/lib/Analysis/plugins/SampleAnalyzer/SampleAnalyzerPlugin.def
 lib\clang.lib lib\clangAnalysis.lib lib\clangAST.lib 
lib\clangStaticAnalyzerCore.lib lib\clangStaticAnalyzerFrontend.lib 
lib\clangStaticAnalyzerCheckers.lib lib\clangStaticAnalyzerCore.lib 
lib\clangCrossTU.lib lib\clangIndex.lib lib\clangFormat.lib 
lib\clangToolingInclusions.lib lib\clangFrontend.lib lib\clangDriver.lib 
version.lib lib\clangParse.lib lib\clangSerialization.lib lib\clangSema.lib 
lib\clangAnalysis.lib lib\clangEdit.lib lib\LLVMOption.lib 
lib\clangToolingCore.lib lib\clangRewrite.lib lib\clangASTMatchers.lib 
lib\clangAST.lib lib\clangLex.lib lib\clangBasic.lib lib\LLVMFrontendOpenMP.lib 
lib\LLVMScalarOpts.lib lib\LLVMAggressiveInstCombine.lib 
lib\LLVMInstCombine.lib lib\LLVMTransformUtils.lib lib\LLVMAnalysis.lib 
lib\LLVMProfileData.lib lib\LLVMDebugInfoDWARF.lib lib\LLVMObject.lib 
lib\LLVMBitReader.lib lib\LLVMCore.lib lib\LLVMRemarks.lib 
lib\LLVMBitstreamReader.lib lib\LLVMMCParser.lib lib\LLVMMC.lib 
lib\LLVMDebugInfoCodeView.lib lib\LLVMTextAPI.lib lib\LLVMBinaryFormat.lib 
lib\LLVMSupport.lib psapi.lib shell32.lib ole32.lib uuid.lib advapi32.lib 
delayimp.lib -delayload:shell32.dll -delayload:ole32.dll lib\LLVMDemangle.lib 
kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib 
oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST 
/MANIFESTFILE:bin\SampleAnalyzerPlugin.dll.manifest" failed (exit code 1169) 
with the following output:
  clangStaticAnalyzerCore.lib(BugReporter.cpp.obj) : error LNK2005: 

[PATCH] D116960: [ADT] Add an in-place version of toHex()

2022-01-10 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

Mostly LGTM, just a couple of comments on the drive-by changes to `hexdigit()` 
(I might split that (and the new call in toHex()) into a separate commit, but 
if you keep them here please mention them in the commit message).




Comment at: llvm/include/llvm/ADT/StringExtras.h:37
 inline char hexdigit(unsigned X, bool LowerCase = false) {
-  const char HexChar = LowerCase ? 'a' : 'A';
-  return X < 10 ? '0' + X : HexChar + X - 10;
+  assert(X <= 16);
+  static const char *const LUT = "0123456789ABCDEF";

Should this be `X < 16`?



Comment at: llvm/include/llvm/ADT/StringExtras.h:38
+  assert(X <= 16);
+  static const char *const LUT = "0123456789ABCDEF";
+  const uint8_t Offset = LowerCase ? 32 : 0;

Can you use `constexpr StringLiteral` here?


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

https://reviews.llvm.org/D116960

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


[PATCH] D98895: [X86][clang] Disable long double type for -mno-x87 option

2022-01-10 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D98895#3232453 , @nickdesaulniers 
wrote:

> Linus Torvalds' thoughts 
> 
>  on the patches as a result of this change.
>
>> Those uses of 1E6L were perhaps strange, but they were only used in
>> constant compile-time expressions that were cast to 'unsigned long' in
>> the end, so how the heck did llvm end up with any floating point in
>> there?
>>
>> In this case there was really no excuse not to just use a better
>> constant, but there are other situations where it might well be quite
>> reasonable to use floating point calculations to create an integer
>> constant (eg maybe some spec describes an algorithm in FP, but the
>> implementation uses fixed-point arithmetic and has initializers that
>> do the conversion).
>>
>> Imagine for a moment that you want to do fixed-point math (perhaps
>> because you have a microcontroller without an FP unit - it's not
>> limited to just "the kernel doesn't do FP"). Further imagine just for
>> a moment that you still want some fundamental constants like PI in
>> that fixed-point format.
>>
>> The sane way to generate said constants is to do something like
>>
>>   #define FIXPT_1 (1u << FIXPT_SHIFT)
>>   #define FIXPT_FP(x) ((fixpt_t) (((x)*FIXPT_1)+0.5))
>>   #define FIXPT_PI FIXPT_FP(3.14159265)
>>
>> rather than have to do something incredibly stupid and illogical and
>> unreadable like
>>
>>   #define FIXPT_PI 205887
>>
>> So honestly, this seems to be just llvm being completely stupid. The
>> fact that you don't want to generate floating point code has *NOTHING*
>> to do with floating point literals for constant expressions.
>>
>> In fact, even if you don't want to generate floating point code -
>> again, maybe you don't have a FP unit - doesn't mean that you might
>> not want to generate normal floating point constants. You may end up
>> having explicit software floating point, and doing things like passing
>> the floating point values around manually, ie
>>
>>union fp {
>>uint64_t val;
>>double fp_val;
>>   };
>>
>> and having code like
>>
>>   static const union fp sqrt2 = { .fp_val = 1.4142 };
>>
>> and then doing all the math in 'uint64_t' just because you wrote a
>> couple of math routines yourself:
>>
>>   fp_mul(&res,  sqrt2.val, x);
>>
>> again, there's no floating point *code* generated, but that doesn't
>> mean that the compiler shouldn't allow users to use floating point
>> *values*.
>>
>> The two
>> examples above are very much not about the Linux kernel (although I
>> think we actually have a couple of places that do things exactly like
>> that) they are about generic coding issues.

I saw that and responded to it on the ClangBuiltLinux thread...

Generally, our policy is that we should do all our diagnostics in the CFE/Sema. 
I believe GCC implements this limitation in the code-generator, so the result 
is that depending on optimization settings, you don't get these errors.  I'm 
going to disagree with Linus, from a language design perspective, if we want to 
decide a type is 'illegal', we need to do so consistently, not JUST when it 
shows up. The Clang project has had this opinion as long as I've been around, 
and we've had to have GCC incompatibilities in the past as a result.  I don't 
see this as any different from what we have done before.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D98895

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


[PATCH] D116859: Fix for: clang-format: break added to macro define with ColumnLimit: 0

2022-01-10 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:4810-4811
+
+  verifyFormat("#define STRINGIFY(t) #t\n"
+   "#define MAKEVERSIONSTRING(x, y, z, build) STRINGIFY(x) \".\" 
STRINGIFY(y) \".\" STRINGIFY(z) \".\" STRINGIFY(build)\n",
+   ZeroColumn);

curdeius wrote:
> Please test with something simpler.
Did this show the bugged behavior without the patch?

Regarding the `// clang-format off` there is the question what do we want in 
the tests? Show the long lines as the long lines, then we need to turn it off 
some times. Or do we want to keep the limit and break the strings, thus making 
it harder to read for the human?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116859

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


[PATCH] D98895: [X86][clang] Disable long double type for -mno-x87 option

2022-01-10 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

Linus Torvalds thoughts 

 on the patches as a result of this change.

> Those uses of 1E6L were perhaps strange, but they were only used in
> constant compile-time expressions that were cast to 'unsigned long' in
> the end, so how the heck did llvm end up with any floating point in
> there?
>
> In this case there was really no excuse not to just use a better
> constant, but there are other situations where it might well be quite
> reasonable to use floating point calculations to create an integer
> constant (eg maybe some spec describes an algorithm in FP, but the
> implementation uses fixed-point arithmetic and has initializers that
> do the conversion).
>
> Imagine for a moment that you want to do fixed-point math (perhaps
> because you have a microcontroller without an FP unit - it's not
> limited to just "the kernel doesn't do FP"). Further imagine just for
> a moment that you still want some fundamental constants like PI in
> that fixed-point format.
>
> The sane way to generate said constants is to do something like
>
>   #define FIXPT_1 (1u << FIXPT_SHIFT)
>   #define FIXPT_FP(x) ((fixpt_t) (((x)*FIXPT_1)+0.5))
>   #define FIXPT_PI FIXPT_FP(3.14159265)
>
> rather than have to do something incredibly stupid and illogical and
> unreadable like
>
>   #define FIXPT_PI 205887
>
> So honestly, this seems to be just llvm being completely stupid. The
> fact that you don't want to generate floating point code has *NOTHING*
> to do with floating point literals for constant expressions.
>
> In fact, even if you don't want to generate floating point code -
> again, maybe you don't have a FP unit - doesn't mean that you might
> not want to generate normal floating point constants. You may end up
> having explicit software floating point, and doing things like passing
> the floating point values around manually, ie
>
>union fp {
>uint64_t val;
>double fp_val;
>   };
>
> and having code like
>
>   static const union fp sqrt2 = { .fp_val = 1.4142 };
>
> and then doing all the math in 'uint64_t' just because you wrote a
> couple of math routines yourself:
>
>   fp_mul(&res,  sqrt2.val, x);
>
> again, there's no floating point *code* generated, but that doesn't
> mean that the compiler shouldn't allow users to use floating point
> *values*.
>
> The two
> examples above are very much not about the Linux kernel (although I
> think we actually have a couple of places that do things exactly like
> that) they are about generic coding issues.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D98895

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


[PATCH] D112718: Add intrinsics and builtins for PTX atomics with semantic orders

2022-01-10 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/include/clang/Basic/BuiltinsNVPTX.def:1057
+
+BUILTIN(__nvvm_atom_xchg_global_i, "iiD*i", "n")
+TARGET_BUILTIN(__nvvm_atom_cta_xchg_global_i, "iiD*i", "n", SM_60)

t4c1 wrote:
> tra wrote:
> > t4c1 wrote:
> > > tra wrote:
> > > > We need to figure out how address-space-specific builtins are supposed 
> > > > to work.
> > > > Right now two competing approaches.
> > > > 
> > > > This patch declares builtins with generic pointer as an argument, but, 
> > > > according to the test, expects to be used with the AS-specific pointer.
> > > > It probably does not catch a wrong-AS pointer passed as an argument, 
> > > > either.
> > > > It does happen to work, but I think it's mostly due to the fact that 
> > > > LLVM intrinsics are overloaded and we happen to end up 
> > > > addrspacecast'ing  things correctly if the builtin gets the right kind 
> > > > of pointer.
> > > > 
> > > > The other approach is to declare the pointer with the expected AS. E.g:
> > > > > TARGET_BUILTIN(__nvvm_mbarrier_init_shared, "vWi*3i", "", 
> > > > > AND(SM_80,PTX70))
> > > > 
> > > > IMO, this is the correct way to do it, but it is also rather 
> > > > inconvenient to use from CUDA code as it operates on generic pointers.
> > > > 
> > > > @jdoerfert - WDYT?
> > > >TARGET_BUILTIN(__nvvm_mbarrier_init_shared, "vWi*3i", "", 
> > > >AND(SM_80,PTX70))
> > > >IMO, this is the correct way to do it, but it is also rather 
> > > >inconvenient to use from CUDA code as it operates on generic pointers.
> > > 
> > > I tried doing this, however it is also completely unusable from OpenCL 
> > > code (which is our use case). Trying to use it gives you errors about how 
> > > casting pointers to different address spaces  - for example from local to 
> > > AS3 is not allowed.
> > Hmm. It should've worked. It would need the same explicit cast to a pointer 
> > in AS(3) as in your tests, but it would safeguard against attempts to pass 
> > it a generic pointer. E.g. https://godbolt.org/z/qE6oxzheM
> > 
> > Explicit casting to AS(X) for AS-specific variants is annoying, but it's 
> > probably unavoidable at the moment regardless of whether we declare the 
> > pointer argument to be AS-specific or not.  LLVM will not always be able to 
> > infer that a pointer is in particular AS.
> > Using specific AS in the declaration has a minor benefit of safeguarding at 
> > compile time against unintentional use of generic pointers.
> > 
> > Ideally we may want to convert generic variant of the builtin to 
> > AS-specific one, if LLVM does know the AS. We currently do this for 
> > loads/stores, but not for other instructions.
> > 
> Well, it does not work. See: https://godbolt.org/z/vM6bKncc4. Declaring the 
> pointer to be in generic AS is the only way I got it to work. If you know a 
> way to call a builtin declared with AS numbers in OpenCL, I am happy to do 
> that instead.
Could you help me understand how different address spaces are handled by OpenCL 
in clang and LLVM?
What exactly are `__local` or `__private` in OpenCL? Do they map to LLVM's 
address spaces? 
Clang does complain that we're trying to change AS, but I do not see AS used in 
the IR: https://godbolt.org/z/soajoE991

AFAICT what happens is:
* OpenCL does use explicit AS for pointers (`__local`, `__private` seem to pop 
up in the error messages)
* `__attribute__((address_space(3)))` does not match the AS of `__local` and 
that leads to an error.
* generic pointer argument works because we are allowed to cast any specific AS 
to generic one.

In other words, having specific-AS arguemt works as intended, we just have a 
mismatch between AS number used by OpenCL and AS number used by NVPTX and we're 
not allowed to cast between two specific AS.

If that's indeed the case, then what we appear to be missing is the mapping 
from OpenCL AS to the target-specific AS, which should, ideally, be done by 
clang itself. So, if NVPTX-specific builtin operating on shared pointer is 
called with a pointer in OpenCL's equivalent of CUDA's `__shared__`, it should 
be mapped to AS(3).



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112718

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


[PATCH] D116596: [clang][dataflow] Add transfer functions for assignment

2022-01-10 Thread Stanislav Gatev 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 rGe7481f6ee591: [clang][dataflow] Add transfer functions for 
assignment (authored by sgatev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116596

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  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
@@ -82,7 +82,8 @@
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "foo");
 ASSERT_THAT(FooDecl, NotNull());
 
-const StorageLocation *FooLoc = Env.getStorageLocation(*FooDecl);
+const StorageLocation *FooLoc =
+Env.getStorageLocation(*FooDecl, SkipPast::None);
 ASSERT_TRUE(isa_and_nonnull(FooLoc));
 
 const Value *FooVal = Env.getValue(*FooLoc);
@@ -125,8 +126,8 @@
 }
 ASSERT_THAT(BarDecl, NotNull());
 
-const auto *FooLoc =
-cast(Env.getStorageLocation(*FooDecl));
+const auto *FooLoc = cast(
+Env.getStorageLocation(*FooDecl, SkipPast::None));
 const auto *BarLoc =
 cast(&FooLoc->getChild(*BarDecl));
 
@@ -171,8 +172,8 @@
 }
 ASSERT_THAT(BarDecl, NotNull());
 
-const auto *FooLoc =
-cast(Env.getStorageLocation(*FooDecl));
+const auto *FooLoc = cast(
+Env.getStorageLocation(*FooDecl, SkipPast::None));
 const auto *BarLoc =
 cast(&FooLoc->getChild(*BarDecl));
 
@@ -204,7 +205,8 @@
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "foo");
 ASSERT_THAT(FooDecl, NotNull());
 
-const StorageLocation *FooLoc = Env.getStorageLocation(*FooDecl);
+const StorageLocation *FooLoc =
+Env.getStorageLocation(*FooDecl, SkipPast::None);
 ASSERT_TRUE(isa_and_nonnull(FooLoc));
 
 const ReferenceValue *FooVal =
@@ -293,8 +295,8 @@
 ASSERT_THAT(BazRefDecl, NotNull());
 ASSERT_THAT(BazPtrDecl, NotNull());
 
-const auto *FooLoc =
-cast(Env.getStorageLocation(*FooDecl));
+const auto *FooLoc = cast(
+Env.getStorageLocation(*FooDecl, SkipPast::None));
 const auto *FooVal = cast(Env.getValue(*FooLoc));
 const auto *FooPointeeVal =
 cast(Env.getValue(FooVal->getPointeeLoc()));
@@ -348,7 +350,8 @@
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "foo");
 ASSERT_THAT(FooDecl, NotNull());
 
-const StorageLocation *FooLoc = Env.getStorageLocation(*FooDecl);
+const StorageLocation *FooLoc =
+Env.getStorageLocation(*FooDecl, SkipPast::None);
 ASSERT_TRUE(isa_and_nonnull(FooLoc));
 
 const PointerValue *FooVal = cast(Env.getValue(*FooLoc));
@@ -449,8 +452,8 @@
 ASSERT_THAT(BazRefDecl, NotNull());
 ASSERT_THAT(BazPtrDecl, NotNull());
 
-const auto *FooLoc =
-cast(Env.getStorageLocation(*FooDecl));
+const auto *FooLoc = cast(
+Env.getStorageLocation(*FooDecl, SkipPast::None));
 const auto *FooVal = cast(Env.getValue(*FooLoc));
 const auto *FooPointeeVal =
 cast(Env.getValue(FooVal->getPointeeLoc()));
@@ -498,42 +501,225 @@
   // [[p4]]
 }
   )";
+  runDataflow(Code, [](llvm::ArrayRef>>
+   Results,
+   ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p4", _), Pair("p3", _),
+ Pair("p2", _), Pair("p1", _)));
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const Environment &Env1 = Results[3].second.Env;
+const StorageLocation *FooLoc =
+Env1.getStorageLocation(*FooDecl, SkipPast::None);
+ASSERT_THAT(FooLoc, NotNull());
+ASSERT_THAT(Env1.getStorageLocation(*BarDecl, SkipPast::None), IsNull());
+ASSERT_THAT(Env1.getStorageLocation(*BazDecl, SkipPast::None), IsNull());
+
+const Environment &Env2 = Results[2].second.Env;
+ASSERT_EQ(Env2.getStorageLocation(*FooDecl, SkipPast::None), FooLoc);
+ASSERT_THAT(Env2.getStorageLocation(*BarDecl, SkipPast::None), NotNull());
+ASSERT_THAT(Env2.getStorageLocation(*BazDecl, SkipPast::None), IsNull());
+
+const Environment 

[clang] e7481f6 - [clang][dataflow] Add transfer functions for assignment

2022-01-10 Thread Stanislav Gatev via cfe-commits

Author: Stanislav Gatev
Date: 2022-01-10T19:35:50Z
New Revision: e7481f6ee591678e3a70569c2e87597f148adb3e

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

LOG: [clang][dataflow] Add transfer functions for assignment

This is part of the implementation of the dataflow analysis framework.
See "[RFC] A dataflow analysis framework for Clang AST" on cfe-dev.

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/lib/Analysis/FlowSensitive/Transfer.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
index a99d32df018b0..8a836713e3392 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
@@ -16,6 +16,7 @@
 #define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSISCONTEXT_H
 
 #include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
@@ -70,6 +71,23 @@ class DataflowAnalysisContext {
 return It == DeclToLoc.end() ? nullptr : It->second;
   }
 
+  /// Assigns `Loc` as the storage location of `E`.
+  ///
+  /// Requirements:
+  ///
+  ///  `E` must not be assigned a storage location.
+  void setStorageLocation(const Expr &E, StorageLocation &Loc) {
+assert(ExprToLoc.find(&E) == ExprToLoc.end());
+ExprToLoc[&E] = &Loc;
+  }
+
+  /// Returns the storage location assigned to `E` or null if `E` has no
+  /// assigned storage location.
+  StorageLocation *getStorageLocation(const Expr &E) const {
+auto It = ExprToLoc.find(&E);
+return It == ExprToLoc.end() ? nullptr : It->second;
+  }
+
 private:
   // Storage for the state of a program.
   std::vector> Locs;
@@ -81,7 +99,7 @@ class DataflowAnalysisContext {
   // basic blocks are evaluated multiple times. The storage locations that are
   // in scope for a particular basic block are stored in `Environment`.
   llvm::DenseMap DeclToLoc;
-  // FIXME: Add `Expr` to `StorageLocation` map.
+  llvm::DenseMap ExprToLoc;
 
   // FIXME: Add `StorageLocation` for `this`.
 

diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 2a0ad6dad1239..2138e0fb6da63 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -16,6 +16,7 @@
 #define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWENVIRONMENT_H
 
 #include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/Type.h"
 #include "clang/AST/TypeOrdering.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
@@ -28,6 +29,18 @@
 namespace clang {
 namespace dataflow {
 
+/// Indicates what kind of indirections should be skipped past when retrieving
+/// storage locations or values.
+///
+/// FIXME: Consider renaming this or replacing it with a more appropriate 
model.
+/// See the discussion in https://reviews.llvm.org/D116596 for context.
+enum class SkipPast {
+  /// No indirections should be skipped past.
+  None,
+  /// An optional reference should be skipped past.
+  Reference,
+};
+
 /// Holds the state of the program (store and heap) at a given program point.
 class Environment {
 public:
@@ -50,6 +63,11 @@ class Environment {
   /// returned storage location in the environment.
   StorageLocation &createStorageLocation(const VarDecl &D);
 
+  /// Creates a storage location for `E`. Does not assign the returned storage
+  /// location to `E` in the environment. Does not assign a value to the
+  /// returned storage location in the environment.
+  StorageLocation &createStorageLocation(const Expr &E);
+
   /// Assigns `Loc` as the storage location of `D` in the environment.
   ///
   /// Requirements:
@@ -57,9 +75,22 @@ class Environment {
   ///  `D` must not be assigned a storage location in the environment.
   void setStorageLocation(const ValueDecl &D, StorageLocation &Loc);
 
-  /// Returns the storage location assigned to `D` in the environment or null 
if
-  /// `D` isn't assigned a storage location in the environment.
-  StorageLocation *getStorageLocation(const ValueDecl &D) const;
+  /// Returns the storage location assigned to `D` in the environment, applying
+  /// the `SP` policy for skipping past indirecti

[PATCH] D116755: Revert "[CodeGen] Mark fma as const for Android"

2022-01-10 Thread Pirama Arumuga Nainar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf5b387988bd4: Revert "[CodeGen] Mark fma as const for 
Android" (authored by alxu, committed by pirama).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116755

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/CodeGen/math-builtins.c


Index: clang/test/CodeGen/math-builtins.c
===
--- clang/test/CodeGen/math-builtins.c
+++ clang/test/CodeGen/math-builtins.c
@@ -1,7 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm
  %s | FileCheck %s -check-prefix=NO__ERRNO
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm 
-fmath-errno %s | FileCheck %s -check-prefix=HAS_ERRNO
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown-gnu -w -S -o - -emit-llvm 
-fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_GNU
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown-android -w -S -o - 
-emit-llvm -fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_ANDROID
 // RUN: %clang_cc1 -triple x86_64-unknown-windows-msvc -w -S -o - -emit-llvm 
-fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_WIN
 
 // Test attributes and codegen of math builtins.
@@ -345,10 +344,6 @@
 // HAS_ERRNO_GNU: declare float @llvm.fma.f32(float, float, float) 
[[READNONE_INTRINSIC]]
 // HAS_ERRNO_GNU: declare x86_fp80 @llvm.fma.f80(x86_fp80, x86_fp80, x86_fp80) 
[[READNONE_INTRINSIC]]
 
-// HAS_ERRNO_ANDROID: declare double @llvm.fma.f64(double, double, double) 
[[READNONE_INTRINSIC:#[0-9]+]]
-// HAS_ERRNO_ANDROID: declare float @llvm.fma.f32(float, float, float) 
[[READNONE_INTRINSIC]]
-// HAS_ERRNO_ANDROID: declare x86_fp80 @llvm.fma.f80(x86_fp80, x86_fp80, 
x86_fp80) [[READNONE_INTRINSIC]]
-
 // HAS_ERRNO_WIN: declare double @llvm.fma.f64(double, double, double) 
[[READNONE_INTRINSIC:#[0-9]+]]
 // HAS_ERRNO_WIN: declare float @llvm.fma.f32(float, float, float) 
[[READNONE_INTRINSIC]]
 // Long double is just double on win, so no f80 use/declaration.
@@ -696,6 +691,5 @@
 // HAS_ERRNO: attributes [[READNONE]] = { {{.*}}readnone{{.*}} }
 
 // HAS_ERRNO_GNU: attributes [[READNONE_INTRINSIC]] = { {{.*}}readnone{{.*}} }
-// HAS_ERRNO_ANDROID: attributes [[READNONE_INTRINSIC]] = { 
{{.*}}readnone{{.*}} }
 // HAS_ERRNO_WIN: attributes [[READNONE_INTRINSIC]] = { {{.*}}readnone{{.*}} }
 
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -15196,11 +15196,11 @@
 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
   FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
 
-// We make "fma" on some platforms const because we know it does not set
+// We make "fma" on GNU or Windows const because we know it does not set
 // errno in those environments even though it could set errno based on the
 // C standard.
 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
-if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
+if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
 !FD->hasAttr()) {
   switch (BuiltinID) {
   case Builtin::BI__builtin_fma:


Index: clang/test/CodeGen/math-builtins.c
===
--- clang/test/CodeGen/math-builtins.c
+++ clang/test/CodeGen/math-builtins.c
@@ -1,7 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm  %s | FileCheck %s -check-prefix=NO__ERRNO
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm -fmath-errno %s | FileCheck %s -check-prefix=HAS_ERRNO
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown-gnu -w -S -o - -emit-llvm -fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_GNU
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown-android -w -S -o - -emit-llvm -fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_ANDROID
 // RUN: %clang_cc1 -triple x86_64-unknown-windows-msvc -w -S -o - -emit-llvm -fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_WIN
 
 // Test attributes and codegen of math builtins.
@@ -345,10 +344,6 @@
 // HAS_ERRNO_GNU: declare float @llvm.fma.f32(float, float, float) [[READNONE_INTRINSIC]]
 // HAS_ERRNO_GNU: declare x86_fp80 @llvm.fma.f80(x86_fp80, x86_fp80, x86_fp80) [[READNONE_INTRINSIC]]
 
-// HAS_ERRNO_ANDROID: declare double @llvm.fma.f64(double, double, double) [[READNONE_INTRINSIC:#[0-9]+]]
-// HAS_ERRNO_ANDROID: declare float @llvm.fma.f32(float, float, float) [[READNONE_INTRINSIC]]
-// HAS_ERRNO_ANDROID: declare x86_fp80 @llvm.fma.f80(x86_fp80, x86_fp80, x86_fp80) [[READNONE_INTRINSIC]]
-
 // HAS_ERRNO_WIN: declare double @llvm.fma.f64(double, double, double) [[READNONE_INTRINSIC:#[0-9]+]]
 // HAS_ERRNO_WIN: declare float @llvm.fma.f32(float, float, floa

[clang] f5b3879 - Revert "[CodeGen] Mark fma as const for Android"

2022-01-10 Thread Pirama Arumuga Nainar via cfe-commits

Author: Alex Xu (Hello71)
Date: 2022-01-10T11:31:09-08:00
New Revision: f5b387988bd4885a973f35deaf3881524f526e3f

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

LOG: Revert "[CodeGen] Mark fma as const for Android"

This code is intended to give a special exception for platforms which set errno 
in some math functions but not fma. This does not apply to Android, which does 
not set errno in any math functions 
(https://cs.android.com/android/platform/superproject/+/master:bionic/libc/include/math.h;drc=master;l=59).
 The correct implementation for Android is to set -fno-math-errno by default, 
which was done in https://reviews.llvm.org/D51068. Therefore, this special 
exception is no longer needed for Android. Deleting it slightly reduces code 
complexity, clang executable size, compile time, and test time.

This reverts fbfba29d74748b8fffd2f7cc654fb4c3659c8f67.

Reviewed By: pirama

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

Added: 


Modified: 
clang/lib/Sema/SemaDecl.cpp
clang/test/CodeGen/math-builtins.c

Removed: 




diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 1e6d4fd04604e..f10acb22eb306 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -15196,11 +15196,11 @@ void Sema::AddKnownFunctionAttributes(FunctionDecl 
*FD) {
 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
   FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
 
-// We make "fma" on some platforms const because we know it does not set
+// We make "fma" on GNU or Windows const because we know it does not set
 // errno in those environments even though it could set errno based on the
 // C standard.
 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
-if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
+if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
 !FD->hasAttr()) {
   switch (BuiltinID) {
   case Builtin::BI__builtin_fma:

diff  --git a/clang/test/CodeGen/math-builtins.c 
b/clang/test/CodeGen/math-builtins.c
index 80e463c7ddb4a..152217bd58674 100644
--- a/clang/test/CodeGen/math-builtins.c
+++ b/clang/test/CodeGen/math-builtins.c
@@ -1,7 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm
  %s | FileCheck %s -check-prefix=NO__ERRNO
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm 
-fmath-errno %s | FileCheck %s -check-prefix=HAS_ERRNO
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown-gnu -w -S -o - -emit-llvm 
-fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_GNU
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown-android -w -S -o - 
-emit-llvm -fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_ANDROID
 // RUN: %clang_cc1 -triple x86_64-unknown-windows-msvc -w -S -o - -emit-llvm 
-fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_WIN
 
 // Test attributes and codegen of math builtins.
@@ -345,10 +344,6 @@ __builtin_fma(f,f,f);__builtin_fmaf(f,f,f);   
__builtin_fmal(f,f,f);
 // HAS_ERRNO_GNU: declare float @llvm.fma.f32(float, float, float) 
[[READNONE_INTRINSIC]]
 // HAS_ERRNO_GNU: declare x86_fp80 @llvm.fma.f80(x86_fp80, x86_fp80, x86_fp80) 
[[READNONE_INTRINSIC]]
 
-// HAS_ERRNO_ANDROID: declare double @llvm.fma.f64(double, double, double) 
[[READNONE_INTRINSIC:#[0-9]+]]
-// HAS_ERRNO_ANDROID: declare float @llvm.fma.f32(float, float, float) 
[[READNONE_INTRINSIC]]
-// HAS_ERRNO_ANDROID: declare x86_fp80 @llvm.fma.f80(x86_fp80, x86_fp80, 
x86_fp80) [[READNONE_INTRINSIC]]
-
 // HAS_ERRNO_WIN: declare double @llvm.fma.f64(double, double, double) 
[[READNONE_INTRINSIC:#[0-9]+]]
 // HAS_ERRNO_WIN: declare float @llvm.fma.f32(float, float, float) 
[[READNONE_INTRINSIC]]
 // Long double is just double on win, so no f80 use/declaration.
@@ -696,6 +691,5 @@ __builtin_trunc(f);  __builtin_truncf(f); 
__builtin_truncl(f); __builtin
 // HAS_ERRNO: attributes [[READNONE]] = { {{.*}}readnone{{.*}} }
 
 // HAS_ERRNO_GNU: attributes [[READNONE_INTRINSIC]] = { {{.*}}readnone{{.*}} }
-// HAS_ERRNO_ANDROID: attributes [[READNONE_INTRINSIC]] = { 
{{.*}}readnone{{.*}} }
 // HAS_ERRNO_WIN: attributes [[READNONE_INTRINSIC]] = { {{.*}}readnone{{.*}} }
 



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


[PATCH] D116960: [ADT] Add an in-place version of toHex()

2022-01-10 Thread Hans Wennborg via Phabricator via cfe-commits
hans updated this revision to Diff 398704.
hans added a comment.

(avoid toStringRef -> arrayRefFromStringRef by reshuffling the toHex overloads)


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

https://reviews.llvm.org/D116960

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  llvm/include/llvm/ADT/StringExtras.h
  llvm/include/llvm/Support/MD5.h
  llvm/lib/Support/MD5.cpp

Index: llvm/lib/Support/MD5.cpp
===
--- llvm/lib/Support/MD5.cpp
+++ llvm/lib/Support/MD5.cpp
@@ -40,10 +40,9 @@
 #include "llvm/Support/MD5.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Endian.h"
-#include "llvm/Support/Format.h"
-#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 #include 
@@ -281,14 +280,12 @@
 
 SmallString<32> MD5::MD5Result::digest() const {
   SmallString<32> Str;
-  raw_svector_ostream Res(Str);
-  for (int i = 0; i < 16; ++i)
-Res << format("%.2x", Bytes[i]);
+  toHex(Bytes, /*LowerCase*/ true, Str);
   return Str;
 }
 
-void MD5::stringifyResult(MD5Result &Result, SmallString<32> &Str) {
-  Str = Result.digest();
+void MD5::stringifyResult(MD5Result &Result, SmallVectorImpl &Str) {
+  toHex(Result.Bytes, /*LowerCase*/ true, Str);
 }
 
 std::array MD5::hash(ArrayRef Data) {
Index: llvm/include/llvm/Support/MD5.h
===
--- llvm/include/llvm/Support/MD5.h
+++ llvm/include/llvm/Support/MD5.h
@@ -88,7 +88,7 @@
 
   /// Translates the bytes in \p Res to a hex string that is
   /// deposited into \p Str. The result will be of length 32.
-  static void stringifyResult(MD5Result &Result, SmallString<32> &Str);
+  static void stringifyResult(MD5Result &Result, SmallVectorImpl &Str);
 
   /// Computes the hash for a given bytes.
   static std::array hash(ArrayRef Data);
Index: llvm/include/llvm/ADT/StringExtras.h
===
--- llvm/include/llvm/ADT/StringExtras.h
+++ llvm/include/llvm/ADT/StringExtras.h
@@ -29,14 +29,15 @@
 
 namespace llvm {
 
-template class SmallVectorImpl;
 class raw_ostream;
 
 /// hexdigit - Return the hexadecimal character for the
 /// given number \p X (which should be less than 16).
 inline char hexdigit(unsigned X, bool LowerCase = false) {
-  const char HexChar = LowerCase ? 'a' : 'A';
-  return X < 10 ? '0' + X : HexChar + X - 10;
+  assert(X <= 16);
+  static const char *const LUT = "0123456789ABCDEF";
+  const uint8_t Offset = LowerCase ? 32 : 0;
+  return LUT[X] | Offset;
 }
 
 /// Given an array of c-style strings terminated by a null pointer, construct
@@ -164,23 +165,26 @@
 
 /// Convert buffer \p Input to its hexadecimal representation.
 /// The returned string is double the size of \p Input.
-inline std::string toHex(StringRef Input, bool LowerCase = false) {
-  static const char *const LUT = "0123456789ABCDEF";
-  const uint8_t Offset = LowerCase ? 32 : 0;
-  size_t Length = Input.size();
-
-  std::string Output;
-  Output.reserve(2 * Length);
-  for (size_t i = 0; i < Length; ++i) {
-const unsigned char c = Input[i];
-Output.push_back(LUT[c >> 4] | Offset);
-Output.push_back(LUT[c & 15] | Offset);
+inline void toHex(ArrayRef Input, bool LowerCase,
+  SmallVectorImpl &Output) {
+  const size_t Length = Input.size();
+  Output.resize_for_overwrite(Length * 2);
+
+  for (size_t i = 0; i < Length; i++) {
+const uint8_t c = Input[i];
+Output[i * 2] = hexdigit(c >> 4, LowerCase);
+Output[i * 2 + 1] = hexdigit(c & 15, LowerCase);
   }
-  return Output;
 }
 
 inline std::string toHex(ArrayRef Input, bool LowerCase = false) {
-  return toHex(toStringRef(Input), LowerCase);
+  SmallString<16> Output;
+  toHex(Input, LowerCase, Output);
+  return std::string(Output);
+}
+
+inline std::string toHex(StringRef Input, bool LowerCase = false) {
+  return toHex(arrayRefFromStringRef(Input), LowerCase);
 }
 
 /// Store the binary representation of the two provided values, \p MSB and
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -354,13 +354,9 @@
   if (!MemBuffer)
 return None;
 
-  llvm::MD5 Hash;
-  llvm::MD5::MD5Result Result;
-
-  Hash.update(MemBuffer->getBuffer());
-  Hash.final(Result);
-
-  Hash.stringifyResult(Result, Checksum);
+  llvm::toHex(
+  llvm::MD5::hash(llvm::arrayRefFromStringRef(MemBuffer->getBuffer())),
+  /*LowerCase*/ true, Checksum);
   return llvm::DIFile::CSK_MD5;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116939: [AArch64] clang support for Armv8.8/9.3 HBC

2022-01-10 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added inline comments.



Comment at: clang/lib/Basic/Targets/AArch64.cpp:666-675
+  HasHBC |= ArchKind == llvm::AArch64::ArchKind::ARMV8_8A ||
+ArchKind == llvm::AArch64::ArchKind::ARMV9_3A;
+
+  // Check features that are manually disabled by command line options.
+  // This needs to be checked after architecture-related features are handled,
+  // making sure they are properly disabled when required.
+  for (const auto &Feature : Features) {

this whole block is suspect to me. Why is HBC special with regards to all other 
architectural extensions?



Comment at: clang/lib/Basic/Targets/AArch64.cpp:672
+  // making sure they are properly disabled when required.
+  for (const auto &Feature : Features) {
+if (Feature == "-hbc")

Sorry, why do we need another trip through `Features` for this?



Comment at: llvm/include/llvm/Support/AArch64TargetParser.def:148
 AARCH64_ARCH_EXT_NAME("pmuv3p4",  AArch64::AEK_PERFMON, "+perfmon", 
"-perfmon")
+AARCH64_ARCH_EXT_NAME("hbc",  AArch64::AEK_HBC, "+hbc",  
"-hbc")
 #undef AARCH64_ARCH_EXT_NAME

there seems to be extra whitespace between the final 2 params, but it doesn't 
align anything. Either remove the excess padding, or align it to a previous 
column.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116939

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


[PATCH] D116960: [ADT] Add an in-place version of toHex()

2022-01-10 Thread Hans Wennborg via Phabricator via cfe-commits
hans updated this revision to Diff 398699.
hans added a comment.

Trying to upload the right diff this time.


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

https://reviews.llvm.org/D116960

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  llvm/include/llvm/ADT/StringExtras.h
  llvm/include/llvm/Support/MD5.h
  llvm/lib/Support/MD5.cpp

Index: llvm/lib/Support/MD5.cpp
===
--- llvm/lib/Support/MD5.cpp
+++ llvm/lib/Support/MD5.cpp
@@ -40,10 +40,9 @@
 #include "llvm/Support/MD5.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Endian.h"
-#include "llvm/Support/Format.h"
-#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 #include 
@@ -281,14 +280,12 @@
 
 SmallString<32> MD5::MD5Result::digest() const {
   SmallString<32> Str;
-  raw_svector_ostream Res(Str);
-  for (int i = 0; i < 16; ++i)
-Res << format("%.2x", Bytes[i]);
+  toHex(Bytes, /*LowerCase*/ true, Str);
   return Str;
 }
 
-void MD5::stringifyResult(MD5Result &Result, SmallString<32> &Str) {
-  Str = Result.digest();
+void MD5::stringifyResult(MD5Result &Result, SmallVectorImpl &Str) {
+  toHex(Result.Bytes, /*LowerCase*/ true, Str);
 }
 
 std::array MD5::hash(ArrayRef Data) {
Index: llvm/include/llvm/Support/MD5.h
===
--- llvm/include/llvm/Support/MD5.h
+++ llvm/include/llvm/Support/MD5.h
@@ -88,7 +88,7 @@
 
   /// Translates the bytes in \p Res to a hex string that is
   /// deposited into \p Str. The result will be of length 32.
-  static void stringifyResult(MD5Result &Result, SmallString<32> &Str);
+  static void stringifyResult(MD5Result &Result, SmallVectorImpl &Str);
 
   /// Computes the hash for a given bytes.
   static std::array hash(ArrayRef Data);
Index: llvm/include/llvm/ADT/StringExtras.h
===
--- llvm/include/llvm/ADT/StringExtras.h
+++ llvm/include/llvm/ADT/StringExtras.h
@@ -29,14 +29,15 @@
 
 namespace llvm {
 
-template class SmallVectorImpl;
 class raw_ostream;
 
 /// hexdigit - Return the hexadecimal character for the
 /// given number \p X (which should be less than 16).
 inline char hexdigit(unsigned X, bool LowerCase = false) {
-  const char HexChar = LowerCase ? 'a' : 'A';
-  return X < 10 ? '0' + X : HexChar + X - 10;
+  assert(X <= 16);
+  static const char *const LUT = "0123456789ABCDEF";
+  const uint8_t Offset = LowerCase ? 32 : 0;
+  return LUT[X] | Offset;
 }
 
 /// Given an array of c-style strings terminated by a null pointer, construct
@@ -164,19 +165,22 @@
 
 /// Convert buffer \p Input to its hexadecimal representation.
 /// The returned string is double the size of \p Input.
-inline std::string toHex(StringRef Input, bool LowerCase = false) {
-  static const char *const LUT = "0123456789ABCDEF";
-  const uint8_t Offset = LowerCase ? 32 : 0;
-  size_t Length = Input.size();
-
-  std::string Output;
-  Output.reserve(2 * Length);
-  for (size_t i = 0; i < Length; ++i) {
-const unsigned char c = Input[i];
-Output.push_back(LUT[c >> 4] | Offset);
-Output.push_back(LUT[c & 15] | Offset);
+inline void toHex(ArrayRef Input, bool LowerCase,
+  SmallVectorImpl &Output) {
+  const size_t Length = Input.size();
+  Output.resize_for_overwrite(Length * 2);
+
+  for (size_t i = 0; i < Length; i++) {
+const uint8_t c = Input[i];
+Output[i * 2] = hexdigit(c >> 4, LowerCase);
+Output[i * 2 + 1] = hexdigit(c & 15, LowerCase);
   }
-  return Output;
+}
+
+inline std::string toHex(StringRef Input, bool LowerCase = false) {
+  SmallString<16> Output;
+  toHex(arrayRefFromStringRef(Input), LowerCase, Output);
+  return std::string(Output);
 }
 
 inline std::string toHex(ArrayRef Input, bool LowerCase = false) {
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -354,13 +354,9 @@
   if (!MemBuffer)
 return None;
 
-  llvm::MD5 Hash;
-  llvm::MD5::MD5Result Result;
-
-  Hash.update(MemBuffer->getBuffer());
-  Hash.final(Result);
-
-  Hash.stringifyResult(Result, Checksum);
+  llvm::toHex(
+  llvm::MD5::hash(llvm::arrayRefFromStringRef(MemBuffer->getBuffer())),
+  /*LowerCase*/ true, Checksum);
   return llvm::DIFile::CSK_MD5;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116935: [IRBuilder] Introduce folder using inst-simplify, use for Or fold.

2022-01-10 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

In D116935#3232203 , @lebedev.ri 
wrote:

> In D116935#3232126 , @craig.topper 
> wrote:
>
>> If I remember correctly, the Or and And folds for 0 and all 1s are there to 
>> optimize bitfield codegen for the frontend. Are we losing that optimization 
>> if this patch goes in before switching clang to InstSimplifyFolder?
>
> True, but why is that optimization there in the first place?
> Presumably it shouldn't matter nowadays.

Probably for -O0 where there is no optimizer,


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116935

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


[PATCH] D116960: [ADT] Add an in-place version of toHex()

2022-01-10 Thread Hans Wennborg via Phabricator via cfe-commits
hans created this revision.
hans added reviewers: thakis, arlosi, rnk.
Herald added subscribers: dexonsmith, hiraditya.
hans requested review of this revision.
Herald added projects: clang, LLVM.
Herald added a subscriber: cfe-commits.

and use that to simplify MD5's hex string code which was previously using a 
string stream, as well as Clang's CGDebugInfo::computeChecksum().

NFC.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116960

Files:
  clang/include/clang/Basic/LangOptions.h
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/test/CodeGen/debug-info-file-checksum.c
  llvm/include/llvm/ADT/StringExtras.h
  llvm/include/llvm/Support/MD5.h
  llvm/lib/Support/MD5.cpp

Index: llvm/lib/Support/MD5.cpp
===
--- llvm/lib/Support/MD5.cpp
+++ llvm/lib/Support/MD5.cpp
@@ -40,10 +40,9 @@
 #include "llvm/Support/MD5.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Endian.h"
-#include "llvm/Support/Format.h"
-#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 #include 
@@ -281,14 +280,12 @@
 
 SmallString<32> MD5::MD5Result::digest() const {
   SmallString<32> Str;
-  raw_svector_ostream Res(Str);
-  for (int i = 0; i < 16; ++i)
-Res << format("%.2x", Bytes[i]);
+  toHex(Bytes, /*LowerCase*/ true, Str);
   return Str;
 }
 
-void MD5::stringifyResult(MD5Result &Result, SmallString<32> &Str) {
-  Str = Result.digest();
+void MD5::stringifyResult(MD5Result &Result, SmallVectorImpl &Str) {
+  toHex(Result.Bytes, /*LowerCase*/ true, Str);
 }
 
 std::array MD5::hash(ArrayRef Data) {
Index: llvm/include/llvm/Support/MD5.h
===
--- llvm/include/llvm/Support/MD5.h
+++ llvm/include/llvm/Support/MD5.h
@@ -88,7 +88,7 @@
 
   /// Translates the bytes in \p Res to a hex string that is
   /// deposited into \p Str. The result will be of length 32.
-  static void stringifyResult(MD5Result &Result, SmallString<32> &Str);
+  static void stringifyResult(MD5Result &Result, SmallVectorImpl &Str);
 
   /// Computes the hash for a given bytes.
   static std::array hash(ArrayRef Data);
Index: llvm/include/llvm/ADT/StringExtras.h
===
--- llvm/include/llvm/ADT/StringExtras.h
+++ llvm/include/llvm/ADT/StringExtras.h
@@ -162,21 +162,26 @@
   return std::string(BufPtr, std::end(Buffer));
 }
 
-/// Convert buffer \p Input to its hexadecimal representation.
-/// The returned string is double the size of \p Input.
-inline std::string toHex(StringRef Input, bool LowerCase = false) {
+inline void toHex(ArrayRef Input, bool LowerCase,
+  SmallVectorImpl &Output) {
   static const char *const LUT = "0123456789ABCDEF";
   const uint8_t Offset = LowerCase ? 32 : 0;
   size_t Length = Input.size();
+  Output.resize_for_overwrite(Length * 2);
 
-  std::string Output;
-  Output.reserve(2 * Length);
   for (size_t i = 0; i < Length; ++i) {
-const unsigned char c = Input[i];
-Output.push_back(LUT[c >> 4] | Offset);
-Output.push_back(LUT[c & 15] | Offset);
+const uint8_t c = Input[i];
+Output[i * 2] = LUT[c >> 4] | Offset;
+Output[i * 2 + 1] = LUT[c & 15] | Offset;
   }
-  return Output;
+}
+
+/// Convert buffer \p Input to its hexadecimal representation.
+/// The returned string is double the size of \p Input.
+inline std::string toHex(StringRef Input, bool LowerCase = false) {
+  SmallString<16> Output;
+  toHex(arrayRefFromStringRef(Input), LowerCase, Output);
+  return std::string(Output);
 }
 
 inline std::string toHex(ArrayRef Input, bool LowerCase = false) {
Index: clang/test/CodeGen/debug-info-file-checksum.c
===
--- clang/test/CodeGen/debug-info-file-checksum.c
+++ clang/test/CodeGen/debug-info-file-checksum.c
@@ -16,3 +16,7 @@
 // RUN: %clang -emit-llvm -S -g -gcodeview -x c %S/Inputs/debug-info-file-checksum-line.cpp -o - | FileCheck %s --check-prefix CHECKSUM
 
 // CHECKSUM: !DIFile(filename: "{{.*}}debug-info-file-checksum-line.cpp", directory:{{.*}}, checksumkind: CSK_MD5, checksum: "7b568574d0e3c56c28e5e0234d1f4a06")
+
+// Later MSVC versions use SHA256.
+// RUN: %clang -target i686-pc-windows-msvc19.30.0 -emit-llvm -S -g -gcodeview -x c %S/Inputs/debug-info-file-checksum-line.cpp -o - | FileCheck %s --check-prefix SHA256
+// SHA256: !DIFile(filename: "{{.*}}debug-info-file-checksum-line.cpp", directory:{{.*}}, checksumkind: CSK_SHA256, checksum: "e28b727db04814680c02d0d2ec72bcd77f5e54131dafc34163bd1576e9428d42")
Index: clang/lib/CodeGen/CGDebugInfo.h
===
--- clang/lib/CodeGen/CGDebugInfo.h
+++ clang/lib/CodeGen/CGDebugInfo.h
@@ -617,7 +617,7 @@
 
   /// Compute the file checksum debug info for input file ID.
   

[PATCH] D116939: [AArch64] clang support for Armv8.8/9.3 HBC

2022-01-10 Thread Son Tuan Vu via Phabricator via cfe-commits
tyb0807 updated this revision to Diff 398698.
tyb0807 edited the summary of this revision.
tyb0807 added a comment.

Update patch author in commit message.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116939

Files:
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Basic/Targets/AArch64.h
  clang/test/Driver/aarch64-hbc.c
  llvm/include/llvm/Support/AArch64TargetParser.def
  llvm/include/llvm/Support/AArch64TargetParser.h
  llvm/lib/Support/AArch64TargetParser.cpp
  llvm/unittests/Support/TargetParserTest.cpp

Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -1518,6 +1518,7 @@
   {"sme-f64", "nosme-f64", "+sme-f64", "-sme-f64"},
   {"sme-i64", "nosme-i64", "+sme-i64", "-sme-i64"},
   {"pmuv3p4", "nopmuv3p4", "+perfmon", "-perfmon"},
+  {"hbc", "nohbc", "+hbc", "-hbc"},
   };
 
   for (unsigned i = 0; i < array_lengthof(ArchExt); i++) {
Index: llvm/lib/Support/AArch64TargetParser.cpp
===
--- llvm/lib/Support/AArch64TargetParser.cpp
+++ llvm/lib/Support/AArch64TargetParser.cpp
@@ -116,6 +116,8 @@
 Features.push_back("+sme-i64");
   if (Extensions & AArch64::AEK_PERFMON)
 Features.push_back("+perfmon");
+  if (Extensions & AArch64::AEK_HBC)
+Features.push_back("+hbc");
 
   return true;
 }
Index: llvm/include/llvm/Support/AArch64TargetParser.h
===
--- llvm/include/llvm/Support/AArch64TargetParser.h
+++ llvm/include/llvm/Support/AArch64TargetParser.h
@@ -70,6 +70,7 @@
   AEK_SMEF64 =  1ULL << 38,
   AEK_SMEI64 =  1ULL << 39,
   AEK_PERFMON = 1ULL << 40,
+  AEK_HBC = 1ULL << 41,
 };
 
 enum class ArchKind {
Index: llvm/include/llvm/Support/AArch64TargetParser.def
===
--- llvm/include/llvm/Support/AArch64TargetParser.def
+++ llvm/include/llvm/Support/AArch64TargetParser.def
@@ -145,6 +145,7 @@
 AARCH64_ARCH_EXT_NAME("sme-f64",  AArch64::AEK_SMEF64,  "+sme-f64", "-sme-f64")
 AARCH64_ARCH_EXT_NAME("sme-i64",  AArch64::AEK_SMEI64,  "+sme-i64", "-sme-i64")
 AARCH64_ARCH_EXT_NAME("pmuv3p4",  AArch64::AEK_PERFMON, "+perfmon", "-perfmon")
+AARCH64_ARCH_EXT_NAME("hbc",  AArch64::AEK_HBC, "+hbc",  "-hbc")
 #undef AARCH64_ARCH_EXT_NAME
 
 #ifndef AARCH64_CPU_NAME
Index: clang/test/Driver/aarch64-hbc.c
===
--- /dev/null
+++ clang/test/Driver/aarch64-hbc.c
@@ -0,0 +1,12 @@
+// Test that target feature hbc is implemented and available correctly
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+hbc %s 2>&1 | FileCheck %s
+// CHECK: "-target-feature" "+hbc"
+
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+nohbc %s 2>&1 | FileCheck %s --check-prefix=NO_HBC
+// NO_HBC: "-target-feature" "-hbc"
+
+// RUN: %clang -### -target aarch64-none-none-eabi  %s 2>&1 | FileCheck %s --check-prefix=ABSENT_HBC
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a %s 2>&1 | FileCheck %s --check-prefix=ABSENT_HBC
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a %s 2>&1 | FileCheck %s --check-prefix=ABSENT_HBC
+// ABSENT_HBC-NOT: "-target-feature" "+hbc"
+// ABSENT_HBC-NOT: "-target-feature" "-hbc"
Index: clang/lib/Basic/Targets/AArch64.h
===
--- clang/lib/Basic/Targets/AArch64.h
+++ clang/lib/Basic/Targets/AArch64.h
@@ -53,6 +53,7 @@
   bool HasMatmulFP32;
   bool HasLSE;
   bool HasFlagM;
+  bool HasHBC;
 
   llvm::AArch64::ArchKind ArchKind;
 
Index: clang/lib/Basic/Targets/AArch64.cpp
===
--- clang/lib/Basic/Targets/AArch64.cpp
+++ clang/lib/Basic/Targets/AArch64.cpp
@@ -543,6 +543,7 @@
   HasMatmulFP64 = false;
   HasMatmulFP32 = false;
   HasLSE = false;
+  HasHBC = false;
 
   ArchKind = llvm::AArch64::ArchKind::INVALID;
 
@@ -658,6 +659,19 @@
   HasRandGen = true;
 if (Feature == "+flagm")
   HasFlagM = true;
+if (Feature == "+hbc")
+  HasHBC = true;
+  }
+
+  HasHBC |= ArchKind == llvm::AArch64::ArchKind::ARMV8_8A ||
+ArchKind == llvm::AArch64::ArchKind::ARMV9_3A;
+
+  // Check features that are manually disabled by command line options.
+  // This needs to be checked after architecture-related features are handled,
+  // making sure they are properly disabled when required.
+  for (const auto &Feature : Features) {
+if (Feature == "-hbc")
+  HasHBC = false;
   }
 
   setDataLayout();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://l

[PATCH] D116939: [AArch64] clang support for Armv8.8/9.3 HBC

2022-01-10 Thread Son Tuan Vu via Phabricator via cfe-commits
tyb0807 updated this revision to Diff 398697.
tyb0807 added a comment.

Update patch author in commit message


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116939

Files:
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Basic/Targets/AArch64.h
  clang/test/Driver/aarch64-hbc.c
  llvm/include/llvm/Support/AArch64TargetParser.def
  llvm/include/llvm/Support/AArch64TargetParser.h
  llvm/lib/Support/AArch64TargetParser.cpp
  llvm/unittests/Support/TargetParserTest.cpp

Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -1518,6 +1518,7 @@
   {"sme-f64", "nosme-f64", "+sme-f64", "-sme-f64"},
   {"sme-i64", "nosme-i64", "+sme-i64", "-sme-i64"},
   {"pmuv3p4", "nopmuv3p4", "+perfmon", "-perfmon"},
+  {"hbc", "nohbc", "+hbc", "-hbc"},
   };
 
   for (unsigned i = 0; i < array_lengthof(ArchExt); i++) {
Index: llvm/lib/Support/AArch64TargetParser.cpp
===
--- llvm/lib/Support/AArch64TargetParser.cpp
+++ llvm/lib/Support/AArch64TargetParser.cpp
@@ -116,6 +116,8 @@
 Features.push_back("+sme-i64");
   if (Extensions & AArch64::AEK_PERFMON)
 Features.push_back("+perfmon");
+  if (Extensions & AArch64::AEK_HBC)
+Features.push_back("+hbc");
 
   return true;
 }
Index: llvm/include/llvm/Support/AArch64TargetParser.h
===
--- llvm/include/llvm/Support/AArch64TargetParser.h
+++ llvm/include/llvm/Support/AArch64TargetParser.h
@@ -70,6 +70,7 @@
   AEK_SMEF64 =  1ULL << 38,
   AEK_SMEI64 =  1ULL << 39,
   AEK_PERFMON = 1ULL << 40,
+  AEK_HBC = 1ULL << 41,
 };
 
 enum class ArchKind {
Index: llvm/include/llvm/Support/AArch64TargetParser.def
===
--- llvm/include/llvm/Support/AArch64TargetParser.def
+++ llvm/include/llvm/Support/AArch64TargetParser.def
@@ -145,6 +145,7 @@
 AARCH64_ARCH_EXT_NAME("sme-f64",  AArch64::AEK_SMEF64,  "+sme-f64", "-sme-f64")
 AARCH64_ARCH_EXT_NAME("sme-i64",  AArch64::AEK_SMEI64,  "+sme-i64", "-sme-i64")
 AARCH64_ARCH_EXT_NAME("pmuv3p4",  AArch64::AEK_PERFMON, "+perfmon", "-perfmon")
+AARCH64_ARCH_EXT_NAME("hbc",  AArch64::AEK_HBC, "+hbc",  "-hbc")
 #undef AARCH64_ARCH_EXT_NAME
 
 #ifndef AARCH64_CPU_NAME
Index: clang/test/Driver/aarch64-hbc.c
===
--- /dev/null
+++ clang/test/Driver/aarch64-hbc.c
@@ -0,0 +1,12 @@
+// Test that target feature hbc is implemented and available correctly
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+hbc %s 2>&1 | FileCheck %s
+// CHECK: "-target-feature" "+hbc"
+
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+nohbc %s 2>&1 | FileCheck %s --check-prefix=NO_HBC
+// NO_HBC: "-target-feature" "-hbc"
+
+// RUN: %clang -### -target aarch64-none-none-eabi  %s 2>&1 | FileCheck %s --check-prefix=ABSENT_HBC
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a %s 2>&1 | FileCheck %s --check-prefix=ABSENT_HBC
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a %s 2>&1 | FileCheck %s --check-prefix=ABSENT_HBC
+// ABSENT_HBC-NOT: "-target-feature" "+hbc"
+// ABSENT_HBC-NOT: "-target-feature" "-hbc"
Index: clang/lib/Basic/Targets/AArch64.h
===
--- clang/lib/Basic/Targets/AArch64.h
+++ clang/lib/Basic/Targets/AArch64.h
@@ -53,6 +53,7 @@
   bool HasMatmulFP32;
   bool HasLSE;
   bool HasFlagM;
+  bool HasHBC;
 
   llvm::AArch64::ArchKind ArchKind;
 
Index: clang/lib/Basic/Targets/AArch64.cpp
===
--- clang/lib/Basic/Targets/AArch64.cpp
+++ clang/lib/Basic/Targets/AArch64.cpp
@@ -543,6 +543,7 @@
   HasMatmulFP64 = false;
   HasMatmulFP32 = false;
   HasLSE = false;
+  HasHBC = false;
 
   ArchKind = llvm::AArch64::ArchKind::INVALID;
 
@@ -658,6 +659,19 @@
   HasRandGen = true;
 if (Feature == "+flagm")
   HasFlagM = true;
+if (Feature == "+hbc")
+  HasHBC = true;
+  }
+
+  HasHBC |= ArchKind == llvm::AArch64::ArchKind::ARMV8_8A ||
+ArchKind == llvm::AArch64::ArchKind::ARMV9_3A;
+
+  // Check features that are manually disabled by command line options.
+  // This needs to be checked after architecture-related features are handled,
+  // making sure they are properly disabled when required.
+  for (const auto &Feature : Features) {
+if (Feature == "-hbc")
+  HasHBC = false;
   }
 
   setDataLayout();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-com

[PATCH] D116935: [IRBuilder] Introduce folder using inst-simplify, use for Or fold.

2022-01-10 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D116935#3232126 , @craig.topper 
wrote:

> If I remember correctly, the Or and And folds for 0 and all 1s are there to 
> optimize bitfield codegen for the frontend. Are we losing that optimization 
> if this patch goes in before switching clang to InstSimplifyFolder?

True, but why is that optimization there in the first place?
Presumably it shouldn't matter nowadays.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116935

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


[PATCH] D116859: Fix for: clang-format: break added to macro define with ColumnLimit: 0

2022-01-10 Thread Armen Khachkinaev via Phabricator via cfe-commits
futuarmo updated this revision to Diff 398695.
futuarmo edited the summary of this revision.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116859

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -4804,6 +4804,15 @@
Style);
 }
 
+TEST_F(FormatTest, FormatMacroWithZeroColumnWidth) {
+  FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
+
+  // clang-format off
+  verifyFormat("#define A LOOONG() LOOONG()\n",
+   ZeroColumn);
+  // clang-format on
+}
+
 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
   verifyFormat("#define A \\\n"
"  f({ \\\n"
Index: clang/lib/Format/ContinuationIndenter.cpp
===
--- clang/lib/Format/ContinuationIndenter.cpp
+++ clang/lib/Format/ContinuationIndenter.cpp
@@ -485,7 +485,8 @@
 // different LineFormatter would be used otherwise.
 if (Previous.ClosesTemplateDeclaration)
   return Style.AlwaysBreakTemplateDeclarations != FormatStyle::BTDS_No;
-if (Previous.is(TT_FunctionAnnotationRParen))
+if (Previous.is(TT_FunctionAnnotationRParen) &&
+State.Line->Type != LT_PreprocessorDirective)
   return true;
 if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
 Current.isNot(TT_LeadingJavaAnnotation))


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -4804,6 +4804,15 @@
Style);
 }
 
+TEST_F(FormatTest, FormatMacroWithZeroColumnWidth) {
+  FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
+
+  // clang-format off
+  verifyFormat("#define A LOOONG() LOOONG()\n",
+   ZeroColumn);
+  // clang-format on
+}
+
 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
   verifyFormat("#define A \\\n"
"  f({ \\\n"
Index: clang/lib/Format/ContinuationIndenter.cpp
===
--- clang/lib/Format/ContinuationIndenter.cpp
+++ clang/lib/Format/ContinuationIndenter.cpp
@@ -485,7 +485,8 @@
 // different LineFormatter would be used otherwise.
 if (Previous.ClosesTemplateDeclaration)
   return Style.AlwaysBreakTemplateDeclarations != FormatStyle::BTDS_No;
-if (Previous.is(TT_FunctionAnnotationRParen))
+if (Previous.is(TT_FunctionAnnotationRParen) &&
+State.Line->Type != LT_PreprocessorDirective)
   return true;
 if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
 Current.isNot(TT_LeadingJavaAnnotation))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116939: [AArch64] clang support for Armv8.8/9.3 HBC

2022-01-10 Thread Son Tuan Vu via Phabricator via cfe-commits
tyb0807 updated this revision to Diff 398693.
tyb0807 added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116939

Files:
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Basic/Targets/AArch64.h
  clang/test/Driver/aarch64-hbc.c
  llvm/include/llvm/Support/AArch64TargetParser.def
  llvm/include/llvm/Support/AArch64TargetParser.h
  llvm/lib/Support/AArch64TargetParser.cpp
  llvm/unittests/Support/TargetParserTest.cpp

Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -1518,6 +1518,7 @@
   {"sme-f64", "nosme-f64", "+sme-f64", "-sme-f64"},
   {"sme-i64", "nosme-i64", "+sme-i64", "-sme-i64"},
   {"pmuv3p4", "nopmuv3p4", "+perfmon", "-perfmon"},
+  {"hbc", "nohbc", "+hbc", "-hbc"},
   };
 
   for (unsigned i = 0; i < array_lengthof(ArchExt); i++) {
Index: llvm/lib/Support/AArch64TargetParser.cpp
===
--- llvm/lib/Support/AArch64TargetParser.cpp
+++ llvm/lib/Support/AArch64TargetParser.cpp
@@ -116,6 +116,8 @@
 Features.push_back("+sme-i64");
   if (Extensions & AArch64::AEK_PERFMON)
 Features.push_back("+perfmon");
+  if (Extensions & AArch64::AEK_HBC)
+Features.push_back("+hbc");
 
   return true;
 }
Index: llvm/include/llvm/Support/AArch64TargetParser.h
===
--- llvm/include/llvm/Support/AArch64TargetParser.h
+++ llvm/include/llvm/Support/AArch64TargetParser.h
@@ -70,6 +70,7 @@
   AEK_SMEF64 =  1ULL << 38,
   AEK_SMEI64 =  1ULL << 39,
   AEK_PERFMON = 1ULL << 40,
+  AEK_HBC = 1ULL << 41,
 };
 
 enum class ArchKind {
Index: llvm/include/llvm/Support/AArch64TargetParser.def
===
--- llvm/include/llvm/Support/AArch64TargetParser.def
+++ llvm/include/llvm/Support/AArch64TargetParser.def
@@ -145,6 +145,7 @@
 AARCH64_ARCH_EXT_NAME("sme-f64",  AArch64::AEK_SMEF64,  "+sme-f64", "-sme-f64")
 AARCH64_ARCH_EXT_NAME("sme-i64",  AArch64::AEK_SMEI64,  "+sme-i64", "-sme-i64")
 AARCH64_ARCH_EXT_NAME("pmuv3p4",  AArch64::AEK_PERFMON, "+perfmon", "-perfmon")
+AARCH64_ARCH_EXT_NAME("hbc",  AArch64::AEK_HBC, "+hbc",  "-hbc")
 #undef AARCH64_ARCH_EXT_NAME
 
 #ifndef AARCH64_CPU_NAME
Index: clang/test/Driver/aarch64-hbc.c
===
--- /dev/null
+++ clang/test/Driver/aarch64-hbc.c
@@ -0,0 +1,12 @@
+// Test that target feature hbc is implemented and available correctly
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+hbc %s 2>&1 | FileCheck %s
+// CHECK: "-target-feature" "+hbc"
+
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+nohbc %s 2>&1 | FileCheck %s --check-prefix=NO_HBC
+// NO_HBC: "-target-feature" "-hbc"
+
+// RUN: %clang -### -target aarch64-none-none-eabi  %s 2>&1 | FileCheck %s --check-prefix=ABSENT_HBC
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a %s 2>&1 | FileCheck %s --check-prefix=ABSENT_HBC
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a %s 2>&1 | FileCheck %s --check-prefix=ABSENT_HBC
+// ABSENT_HBC-NOT: "-target-feature" "+hbc"
+// ABSENT_HBC-NOT: "-target-feature" "-hbc"
Index: clang/lib/Basic/Targets/AArch64.h
===
--- clang/lib/Basic/Targets/AArch64.h
+++ clang/lib/Basic/Targets/AArch64.h
@@ -53,6 +53,7 @@
   bool HasMatmulFP32;
   bool HasLSE;
   bool HasFlagM;
+  bool HasHBC;
 
   llvm::AArch64::ArchKind ArchKind;
 
Index: clang/lib/Basic/Targets/AArch64.cpp
===
--- clang/lib/Basic/Targets/AArch64.cpp
+++ clang/lib/Basic/Targets/AArch64.cpp
@@ -543,6 +543,7 @@
   HasMatmulFP64 = false;
   HasMatmulFP32 = false;
   HasLSE = false;
+  HasHBC = false;
 
   ArchKind = llvm::AArch64::ArchKind::INVALID;
 
@@ -658,6 +659,19 @@
   HasRandGen = true;
 if (Feature == "+flagm")
   HasFlagM = true;
+if (Feature == "+hbc")
+  HasHBC = true;
+  }
+
+  HasHBC |= ArchKind == llvm::AArch64::ArchKind::ARMV8_8A ||
+ArchKind == llvm::AArch64::ArchKind::ARMV9_3A;
+
+  // Check features that are manually disabled by command line options.
+  // This needs to be checked after architecture-related features are handled,
+  // making sure they are properly disabled when required.
+  for (const auto &Feature : Features) {
+if (Feature == "-hbc")
+  HasHBC = false;
   }
 
   setDataLayout();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116824: [clang-tidy] Fix RenamerClangTidyChecks suggesting invalid macro identifiers

2022-01-10 Thread Logan Smith via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG988c3f5f9692: [clang-tidy] Fix RenamerClangTidyChecks 
suggesting invalid macro identifiers (authored by logan-5).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116824

Files:
  clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp
@@ -171,6 +171,11 @@
 // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: declaration uses identifier '_', 
which is reserved in the global namespace; cannot be fixed automatically 
[bugprone-reserved-identifier]
 // CHECK-FIXES: {{^}}int _;{{$}}
 
+// https://github.com/llvm/llvm-project/issues/52895
+#define _5_kmph_rpm 459
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: declaration uses identifier 
'_5_kmph_rpm', which is reserved in the global namespace; cannot be fixed 
automatically [bugprone-reserved-identifier]
+// CHECK-FIXES: {{^}}#define _5_kmph_rpm 459{{$}}
+
 // these should pass
 #define MACRO(m) int m = 0
 
Index: clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -486,6 +486,9 @@
   NamingCheckFailure &Failure = NamingCheckFailures[ID];
   SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
 
+  if (!isValidAsciiIdentifier(Info.Fixup))
+Failure.FixStatus = ShouldFixStatus::FixInvalidIdentifier;
+
   Failure.Info = std::move(Info);
   addUsage(ID, Range);
 }


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp
@@ -171,6 +171,11 @@
 // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: declaration uses identifier '_', which is reserved in the global namespace; cannot be fixed automatically [bugprone-reserved-identifier]
 // CHECK-FIXES: {{^}}int _;{{$}}
 
+// https://github.com/llvm/llvm-project/issues/52895
+#define _5_kmph_rpm 459
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: declaration uses identifier '_5_kmph_rpm', which is reserved in the global namespace; cannot be fixed automatically [bugprone-reserved-identifier]
+// CHECK-FIXES: {{^}}#define _5_kmph_rpm 459{{$}}
+
 // these should pass
 #define MACRO(m) int m = 0
 
Index: clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -486,6 +486,9 @@
   NamingCheckFailure &Failure = NamingCheckFailures[ID];
   SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
 
+  if (!isValidAsciiIdentifier(Info.Fixup))
+Failure.FixStatus = ShouldFixStatus::FixInvalidIdentifier;
+
   Failure.Info = std::move(Info);
   addUsage(ID, Range);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 988c3f5 - [clang-tidy] Fix RenamerClangTidyChecks suggesting invalid macro identifiers

2022-01-10 Thread Logan Smith via cfe-commits

Author: Logan Smith
Date: 2022-01-10T10:35:04-08:00
New Revision: 988c3f5f96925e3bcd757043314e345b8f65589f

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

LOG: [clang-tidy] Fix RenamerClangTidyChecks suggesting invalid macro 
identifiers

This behavior was fixed for regular identifiers in
9f3edc323a88c1a179a0a5a9dc9a87a2964c0d48, but the same fix was not applied to
macro fixits. This addresses https://github.com/llvm/llvm-project/issues/52895.

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
index a0dcca7f9973c..73b47dca20930 100644
--- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -486,6 +486,9 @@ void RenamerClangTidyCheck::checkMacro(SourceManager 
&SourceMgr,
   NamingCheckFailure &Failure = NamingCheckFailures[ID];
   SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
 
+  if (!isValidAsciiIdentifier(Info.Fixup))
+Failure.FixStatus = ShouldFixStatus::FixInvalidIdentifier;
+
   Failure.Info = std::move(Info);
   addUsage(ID, Range);
 }

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp
index 555c673a3f43b..da8a27588611e 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp
@@ -171,6 +171,11 @@ int _;
 // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: declaration uses identifier '_', 
which is reserved in the global namespace; cannot be fixed automatically 
[bugprone-reserved-identifier]
 // CHECK-FIXES: {{^}}int _;{{$}}
 
+// https://github.com/llvm/llvm-project/issues/52895
+#define _5_kmph_rpm 459
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: declaration uses identifier 
'_5_kmph_rpm', which is reserved in the global namespace; cannot be fixed 
automatically [bugprone-reserved-identifier]
+// CHECK-FIXES: {{^}}#define _5_kmph_rpm 459{{$}}
+
 // these should pass
 #define MACRO(m) int m = 0
 



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


[PATCH] D116750: [clang][lex] Keep references to `DirectoryLookup` objects up-to-date

2022-01-10 Thread Alex Hoppen via Phabricator via cfe-commits
ahoppen added inline comments.



Comment at: clang/include/clang/Lex/HeaderSearch.h:179
   /// directory is suppressed.
-  std::vector SearchDirs;
-  /// Whether the DirectoryLookup at the corresponding index in SearchDirs has
-  /// been successfully used to lookup a file.
-  std::vector SearchDirsUsage;
+  std::vector SearchDirs;
+  /// Set of SearchDirs that have been successfully used to lookup a file.

jansvoboda11 wrote:
> ahoppen wrote:
> > I haven’t tried it but is there a particular reason why this can’t be a 
> > `const DirectoryLookup *`?
> While iterating over `SearchDirs`, the elements can be passed to 
> `HeaderSearch::loadSubdirectoryModuleMaps` that mutates them.
OK. Makes sense. Thanks.



Comment at: clang/lib/Lex/HeaderSearch.cpp:323
+
+if (SearchDirs[Idx]->isFramework()) {
   // Search for or infer a module map for a framework. Here we use

jansvoboda11 wrote:
> ahoppen wrote:
> > Nitpick: `SearchDirs[Idx]` can be simplified to `SearchDir->isFramework()`. 
> > Similarly below.
> `SearchDir` will be removed in the following patch: D113676.
Ah, OK. In that case it makes sense to keep using `SearchDirs[Idx]`.



Comment at: clang/unittests/Lex/HeaderSearchTest.cpp:276
+std::vector ExpectedSearchDirUsageAfterM2{false, true, false};
+EXPECT_EQ(Search.getSearchDirUsage(), ExpectedSearchDirUsageAfterM2);
+std::vector ExpectedUserEntryUsageAfterM2{false, true, false};

jansvoboda11 wrote:
> ahoppen wrote:
> > Wouldn’t it be cleaner to just check that `UsedSearchDirs` only contains a 
> > single element and that it’s name is `/M2`? In that case we could also 
> > remove `getSearchDirUsage`.
> Maybe I'm misunderstanding you, but I don't think so. We'd still need 
> accessor for `HeaderSearch::UsedSearchDirs` and we don't have the expected 
> `DirectoryLookup *` lying around, making matching more cumbersome:
> 
> ```
> const llvm::DenseSet &UsedSearchDirs =
> Search.getUsedSearchDirs();
> EXPECT_EQ(UsedSearchDirs.size(), 2);
> EXPECT_EQ(1, llvm::count_if(UsedSearchDirs, [](const auto *SearchDir) {
> return SearchDir->getName() == "/M1";
>   }));
> EXPECT_EQ(1, llvm::count_if(UsedSearchDirs, [](const auto *SearchDir) {
> return SearchDir->getName() == "/M2";
>   }));
> ```
> 
> or
> 
> ```
> llvm::DenseSet UsedSearchDirsStr;
> for (const auto *SearchDir : Search.getUsedSearchDirs())
>   UsedSearchDirsStr.insert(SearchDir->getName());
> EXPECT_EQ(UsedSearchDirsStr, (llvm::DenseSet{"/M1", "/M2"}));
> ```
> 
> I think having bit-vector, whose indices correspond to the directory names 
> (`"/M{i}"`), and using `operator==` for matching is simpler.
> 
> Let me know if you had something else in mind.
I just don’t like the bit-vectors and basically thought of the second option 
you were suggesting, but maybe that’s really just personal taste. If you’d like 
to keep the bit-vector, could you change the comment of `getSearchDirUsage` to 
something like 
```
/// Return a vector of length \c SearchDirs.size() that indicates for each 
search directory whether it was used.
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116750

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


[PATCH] D116935: [IRBuilder] Introduce folder using inst-simplify, use for Or fold.

2022-01-10 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

If I remember correctly, the Or and And folds for 0 and all 1s are there to 
optimize bitfield codegen for the frontend. Are we losing that optimization if 
this patch goes in before switching clang to InstSimplifyFolder?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116935

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


[PATCH] D116835: Use sha256 for source file debug info checksums with MSVC compat >= 1930

2022-01-10 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

In D116835#3228296 , @arlosi wrote:

> I submitted a change last year to hook up the /ZH option, but it was never 
> completed. https://reviews.llvm.org/D98438

I just put some comments on that. I'm happy to provide review if you think you 
have time to complete it?

(I'll break out the toHex() related changes here and try to get those landed 
separately.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116835

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


[PATCH] D98438: Clang: Allow selecting the hash algorithm for file checksums in debug info.

2022-01-10 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

Sorry for not seeing this sooner.

I think this looks great, just a few comments, and it also needs tests.




Comment at: clang/include/clang/Basic/CodeGenOptions.def:303
+/// Set debug info source file hashing algorithm
+ENUM_CODEGENOPT(DebugSrcHashAlgorithm, SrcHashAlgorithm, 4, CSK_MD5)
+

Why does it need 4 bits? Wouldn't 2 be enough?



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:368
 
-Optional
-CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
+Optional>
+CGDebugInfo::computeChecksum(FileID FID, SmallString<64> &Checksum) const {

I'm not sure changing the return type helps that much? I suppose it makes the 
calling code a little cleaner, but I think it makes the function itself a 
little more confusing.



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:398
+StringRef Result = Hash.final();
+llvm::raw_svector_ostream Res(Checksum);
+for (int i = 0; i < 20; ++i)

toHex() from StringExtras.h is much nicer, and MD5 should be using that 
internally too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D98438

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


[PATCH] D72940: Add a support for clang tidy to import another configurations files from .clang-tidy

2022-01-10 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood requested changes to this revision.
LegalizeAdulthood added a comment.
This revision now requires changes to proceed.
Herald added a subscriber: carlosgalvezp.

Please upload a full context diff so that the changes can be properly viewed.  
Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72940

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


[PATCH] D97625: fix check-clang-tools tests that fail due to Windows CRLF line endings

2022-01-10 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood added a comment.

I have run into this line ending problem with python scripts as well.
If you follow the advice on the "getting started" pages, then you will
have checked out the entire repo with Unix line endings, but when you
run python scripts like add_new_check.py for clang-tidy, it writes out
the files with native line endings and ends up flagging the entirety of
the modified file as changing due to the flip-flopping of line endings.

I have an open bug  on this,
but I think we need to have a wider discussion in order to reach a
more global fix.

Your limited scope fix looks good to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97625

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


[PATCH] D116774: AST: Move __va_list tag to the top level on ARM architectures.

2022-01-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D116774#3227280 , @jrtc27 wrote:

> The fact that va_list is in the std namespace does leak out into 
> __builtin_dump_struct, possibly the odd other place, and of course to 
> external AST consumers.

It can also leak out in funny places like AST dumping (to text, but more 
interestingly, to JSON). But the one place that may be observable and really 
matters (that I can think of) are AST matchers that get used by clang-tidy.

> I think it'd make sense to keep ASTContext as putting it in the std namespace 
> for C++ (like it does for Arm, and used to for AArch64) but also have 
> ItaniumMangle override it to the std namespace so that non-C++ gets the right 
> mangling? Otherwise the AST and __builtin_dump_struct won't match the Arm 
> spec.

I think this could make some sense. We typically try to have the AST reflect 
the reality of the program, and from that perspective, I think I would expect 
there to be a `std` namespace component for this in the AST if the spec calls 
for one even when obtaining the type through `stdarg.h` instead of `cstdarg`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116774

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


[PATCH] D116577: [clang-tidy] Added "boost-use-range-based-for-loop" check

2022-01-10 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood added inline comments.



Comment at: clang-tools-extra/clang-tidy/boost/UseRangeBasedForLoopCheck.cpp:68
+ ColToken->getLocation()),
+   (llvm::Twine("for(") + VariableString + " : ").str());
+  }

Now that this is chained, you might need to `clang-format` on it again.

Probably best to just `clang-format` the whole file before you submit.



Comment at: clang-tools-extra/clang-tidy/boost/UseRangeBasedForLoopCheck.h:28
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+return LangOpts.CPlusPlus11;
+  }

This is an implicit conversion from `unsigned` to `bool`,
an explicit comparison against `!= 0` would be preferable IMO.

However, my bigger question is what happens when someone
runs this check with `-std=c++14` or some other later version of C++?

I looked at the header for `LangOptions` and it isn't clear whether
the bits are set to indicate supported portions of the standard or
if they simply reflect the command-line options used when invoking
the compiler.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/boost-use-range-based-for-loop.rst:30
+-
+* Client code that use ``BOOST_FOREACH`` with "``std::pair`` of iterators" or 
with "Null-terminated strings (``char`` and ``wchar_t``)" or some other 
sequence types (everything that is not declared in the list "convertible 
correctly" above) will produce broken code (compilation error).
+

denzor200 wrote:
> LegalizeAdulthood wrote:
> > Eugene.Zelenko wrote:
> > > Please separate with newline and follow 80 character limit. Also closing 
> > > quote for `Null-terminated strings` is missing.
> > It would be better to detect known failure cases in the matcher and not 
> > issue a fixit but perhaps issue a diagnostic.
> I do not understand how I can determine type of expression `list_int` (for 
> example) at the preprocessing stage. This trick was not found in any of the 
> existing checks.
Ah, yes, ugh.  I forgot that this is all done by looking at macros.

We really need a bit of infrastructure in clang-tidy to associate macro
expansions with AST nodes for preprocessor related checks.

I suppose you could match for loops and try to correlate them to
the BOOST_FOREACH macros.  Then you could reason more about
the arguments to BOOST_FOREACH via the AST, but this is probably
fragile because it depends on the implementation of BOOST_FOREACH,
which may change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116577

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


Re: [clang] 80e2c58 - [clang] Remove redundant member initialization (NFC)

2022-01-10 Thread Kazu Hirata via cfe-commits
Hi Martin,

I've reverted the patch as 7485e6c7e9c7d484ba1faf2dc53c9b598286455b.  Thank
you for reporting the problem!

Kazu Hirata


On Mon, Jan 10, 2022 at 3:35 AM Martin Storsjö  wrote:

> On Sun, 9 Jan 2022, Kazu Hirata via cfe-commits wrote:
>
> >
> > Author: Kazu Hirata
> > Date: 2022-01-09T00:19:51-08:00
> > New Revision: 80e2c587498a7b2bf14dde47a33a058da6e88a9a
> >
> > URL:
> https://github.com/llvm/llvm-project/commit/80e2c587498a7b2bf14dde47a33a058da6e88a9a
> > DIFF:
> https://github.com/llvm/llvm-project/commit/80e2c587498a7b2bf14dde47a33a058da6e88a9a.diff
> >
> > LOG: [clang] Remove redundant member initialization (NFC)
> >
> > Identified with readability-redundant-member-init.
>
> While technically NFC, this causes lots of build warnings (689 warnings)
> when built with GCC, like this:
>
> In file included from
> llvm-project/clang/include/clang/Basic/SourceManager.h:37:0,
>   from
> llvm-project/clang/lib/Lex/ScratchBuffer.cpp:14:
> llvm-project/clang/include/clang/Basic/Diagnostic.h: In
> copy constructor ‘clang::DiagnosticBuilder::DiagnosticBuilder(const
> clang::DiagnosticBuilder&)’:
> llvm-project/clang/include/clang/Basic/Diagnostic.h:1329:3:
> warning: base class ‘class clang::StreamingDiagnostic’ should be
> explicitly initialized in the copy constructor [-Wextra]
> DiagnosticBuilder(const DiagnosticBuilder &D) {
> ^
>
>
> With that in mind, I would like to revert this commit - is that ok with
> you?
>
> // Martin
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D115183: [clang][HeaderSearch] Support framework includes in suggestPath...

2022-01-10 Thread David Goldman 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 rG0cf7e61a42c7: [clang][HeaderSearch] Support framework 
includes in suggestPath... (authored by dgoldman).

Changed prior to commit:
  https://reviews.llvm.org/D115183?vs=398178&id=398677#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115183

Files:
  clang/include/clang/Lex/HeaderSearch.h
  clang/lib/Lex/HeaderSearch.cpp
  clang/test/Modules/double-quotes.m
  clang/unittests/Lex/HeaderSearchTest.cpp

Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -47,6 +47,15 @@
 Search.AddSearchPath(DL, /*isAngled=*/false);
   }
 
+  void addSystemFrameworkSearchDir(llvm::StringRef Dir) {
+VFS->addFile(Dir, 0, llvm::MemoryBuffer::getMemBuffer(""), /*User=*/None,
+ /*Group=*/None, llvm::sys::fs::file_type::directory_file);
+auto DE = FileMgr.getOptionalDirectoryRef(Dir);
+assert(DE);
+auto DL = DirectoryLookup(*DE, SrcMgr::C_System, /*isFramework=*/true);
+Search.AddSystemSearchPath(DL);
+  }
+
   void addHeaderMap(llvm::StringRef Filename,
 std::unique_ptr Buf,
 bool isAngled = false) {
@@ -155,6 +164,29 @@
 "y/z/t.h");
 }
 
+TEST_F(HeaderSearchTest, SdkFramework) {
+  addSystemFrameworkSearchDir(
+  "/Platforms/MacOSX.platform/Developer/SDKs/MacOSX11.3.sdk/Frameworks/");
+  bool IsSystem = false;
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics(
+"/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/"
+"Frameworks/AppKit.framework/Headers/NSView.h",
+/*WorkingDir=*/"",
+/*MainFile=*/"", &IsSystem),
+"AppKit/NSView.h");
+  EXPECT_TRUE(IsSystem);
+}
+
+TEST_F(HeaderSearchTest, NestedFramework) {
+  addSystemFrameworkSearchDir("/Platforms/MacOSX/Frameworks");
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics(
+"/Platforms/MacOSX/Frameworks/AppKit.framework/Frameworks/"
+"Sub.framework/Headers/Sub.h",
+/*WorkingDir=*/"",
+/*MainFile=*/""),
+"Sub/Sub.h");
+}
+
 // Helper struct with null terminator character to make MemoryBuffer happy.
 template 
 struct NullTerminatedFile : public FileTy {
Index: clang/test/Modules/double-quotes.m
===
--- clang/test/Modules/double-quotes.m
+++ clang/test/Modules/double-quotes.m
@@ -24,8 +24,17 @@
 // because they only show up under the module A building context.
 // RUN: FileCheck --input-file=%t/stderr %s
 // CHECK: double-quoted include "A0.h" in framework header, expected angle-bracketed instead
+// CHECK: #include "A0.h"
+// CHECK:  ^~
+// CHECK: 
 // CHECK: double-quoted include "B.h" in framework header, expected angle-bracketed instead
+// CHECK: #include "B.h"
+// CHECK:  ^
+// CHECK: 
 // CHECK: double-quoted include "B.h" in framework header, expected angle-bracketed instead
+// CHECK: #import "B.h" // Included from Z.h & A.h
+// CHECK: ^
+// CHECK: 
 
 #import "A.h"
 #import 
Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -745,7 +745,8 @@
 }
 
 static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
- SmallVectorImpl &FrameworkName) {
+ SmallVectorImpl &FrameworkName,
+ SmallVectorImpl &IncludeSpelling) {
   using namespace llvm::sys;
   path::const_iterator I = path::begin(Path);
   path::const_iterator E = path::end(Path);
@@ -761,15 +762,22 @@
   // and some other variations among these lines.
   int FoundComp = 0;
   while (I != E) {
-if (*I == "Headers")
+if (*I == "Headers") {
   ++FoundComp;
-if (I->endswith(".framework")) {
-  FrameworkName.append(I->begin(), I->end());
-  ++FoundComp;
-}
-if (*I == "PrivateHeaders") {
+} else if (*I == "PrivateHeaders") {
   ++FoundComp;
   IsPrivateHeader = true;
+} else if (I->endswith(".framework")) {
+  StringRef Name = I->drop_back(10); // Drop .framework
+  // Need to reset the strings and counter to support nested frameworks.
+  FrameworkName.clear();
+  FrameworkName.append(Name.begin(), Name.end());
+  IncludeSpelling.clear();
+  IncludeSpelling.append(Name.begin(), Name.end());
+  FoundComp = 1;
+} else if (FoundComp >= 2) {
+  IncludeSpelling.push_back('/');
+  IncludeSpelling.append(I->begin(), I->end());
 }
 ++I;
   }
@@ -784,20 +792,24 @@
 

[clang] 0cf7e61 - [clang][HeaderSearch] Support framework includes in suggestPath...

2022-01-10 Thread David Goldman via cfe-commits

Author: David Goldman
Date: 2022-01-10T12:25:53-05:00
New Revision: 0cf7e61a42c7a08b0332204f1b60aa9fd1562089

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

LOG: [clang][HeaderSearch] Support framework includes in suggestPath...

Clang will now search through the framework includes to identify
the framework include path to a file, and then suggest a framework
style include spelling for the file.

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

Added: 


Modified: 
clang/include/clang/Lex/HeaderSearch.h
clang/lib/Lex/HeaderSearch.cpp
clang/test/Modules/double-quotes.m
clang/unittests/Lex/HeaderSearchTest.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/HeaderSearch.h 
b/clang/include/clang/Lex/HeaderSearch.h
index 0482bf6c053f..e056f009eae9 100644
--- a/clang/include/clang/Lex/HeaderSearch.h
+++ b/clang/include/clang/Lex/HeaderSearch.h
@@ -286,6 +286,12 @@ class HeaderSearch {
   /// Add an additional search path.
   void AddSearchPath(const DirectoryLookup &dir, bool isAngled);
 
+  /// Add an additional system search path.
+  void AddSystemSearchPath(const DirectoryLookup &dir) {
+SearchDirs.push_back(dir);
+SearchDirsUsage.push_back(false);
+  }
+
   /// Set the list of system header prefixes.
   void SetSystemHeaderPrefixes(ArrayRef> P) {
 SystemHeaderPrefixes.assign(P.begin(), P.end());

diff  --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index f9d61ecef796..d4de4ed156b6 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -745,7 +745,8 @@ static const char *copyString(StringRef Str, 
llvm::BumpPtrAllocator &Alloc) {
 }
 
 static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
- SmallVectorImpl &FrameworkName) {
+ SmallVectorImpl &FrameworkName,
+ SmallVectorImpl &IncludeSpelling) {
   using namespace llvm::sys;
   path::const_iterator I = path::begin(Path);
   path::const_iterator E = path::end(Path);
@@ -761,15 +762,22 @@ static bool isFrameworkStylePath(StringRef Path, bool 
&IsPrivateHeader,
   // and some other variations among these lines.
   int FoundComp = 0;
   while (I != E) {
-if (*I == "Headers")
+if (*I == "Headers") {
   ++FoundComp;
-if (I->endswith(".framework")) {
-  FrameworkName.append(I->begin(), I->end());
-  ++FoundComp;
-}
-if (*I == "PrivateHeaders") {
+} else if (*I == "PrivateHeaders") {
   ++FoundComp;
   IsPrivateHeader = true;
+} else if (I->endswith(".framework")) {
+  StringRef Name = I->drop_back(10); // Drop .framework
+  // Need to reset the strings and counter to support nested frameworks.
+  FrameworkName.clear();
+  FrameworkName.append(Name.begin(), Name.end());
+  IncludeSpelling.clear();
+  IncludeSpelling.append(Name.begin(), Name.end());
+  FoundComp = 1;
+} else if (FoundComp >= 2) {
+  IncludeSpelling.push_back('/');
+  IncludeSpelling.append(I->begin(), I->end());
 }
 ++I;
   }
@@ -784,20 +792,24 @@ diagnoseFrameworkInclude(DiagnosticsEngine &Diags, 
SourceLocation IncludeLoc,
  bool FoundByHeaderMap = false) {
   bool IsIncluderPrivateHeader = false;
   SmallString<128> FromFramework, ToFramework;
-  if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework))
+  SmallString<128> FromIncludeSpelling, ToIncludeSpelling;
+  if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework,
+FromIncludeSpelling))
 return;
   bool IsIncludeePrivateHeader = false;
-  bool IsIncludeeInFramework = isFrameworkStylePath(
-  IncludeFE->getName(), IsIncludeePrivateHeader, ToFramework);
+  bool IsIncludeeInFramework =
+  isFrameworkStylePath(IncludeFE->getName(), IsIncludeePrivateHeader,
+   ToFramework, ToIncludeSpelling);
 
   if (!isAngled && !FoundByHeaderMap) {
 SmallString<128> NewInclude("<");
 if (IsIncludeeInFramework) {
-  NewInclude += ToFramework.str().drop_back(10); // drop .framework
-  NewInclude += "/";
+  NewInclude += ToIncludeSpelling;
+  NewInclude += ">";
+} else {
+  NewInclude += IncludeFilename;
+  NewInclude += ">";
 }
-NewInclude += IncludeFilename;
-NewInclude += ">";
 Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
 << IncludeFilename
 << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
@@ -1865,9 +1877,9 @@ std::string HeaderSearch::suggestPathToFileForDiagnostics(
   using namespace llvm::sys;
 
   unsigned BestPrefixLength = 0;
-  // Checks whether Dir and File shares a common prefix, if they do and t

  1   2   3   >