[clang] [Clang][SYCL] Introduce clang-sycl-linker to link SYCL offloading device code (Part 1 of many) (PR #112245)

2024-10-28 Thread Alexey Bader via cfe-commits


@@ -0,0 +1,500 @@
+//= clang-sycl-linker/ClangSYCLLinker.cpp - SYCL Linker util ---=//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===-===//
+//
+// This tool executes a sequence of steps required to link device code in SYCL
+// fat objects. SYCL device code linking requires a complex sequence of steps
+// that include linking of llvm bitcode files, linking device library files
+// with the fully linked source bitcode file(s), running several SYCL specific
+// post-link steps on the fully linked bitcode file(s), and finally generating
+// target-specific device code.
+//===-===//
+
+#include "clang/Basic/Version.h"
+
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/BinaryFormat/Magic.h"
+#include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/CommandFlags.h"
+#include "llvm/IR/DiagnosticPrinter.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"
+#include "llvm/Object/ELFObjectFile.h"
+#include "llvm/Object/IRObjectFile.h"
+#include "llvm/Object/ObjectFile.h"
+#include "llvm/Object/OffloadBinary.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Option/OptTable.h"
+#include "llvm/Option/Option.h"
+#include "llvm/Remarks/HotnessThresholdParser.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/FileOutputBuffer.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/InitLLVM.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/StringSaver.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/TimeProfiler.h"
+#include "llvm/Support/WithColor.h"
+
+using namespace llvm;
+using namespace llvm::opt;
+using namespace llvm::object;
+
+/// Save intermediary results.
+static bool SaveTemps = false;
+
+/// Print arguments without executing.
+static bool DryRun = false;
+
+/// Print verbose output.
+static bool Verbose = false;
+
+/// Filename of the output being created.
+static StringRef OutputFile;
+
+/// Directory to dump SPIR-V IR if requested by user.
+static SmallString<128> SPIRVDumpDir;
+
+static void printVersion(raw_ostream &OS) {
+  OS << clang::getClangToolFullVersion("clang-sycl-linker") << '\n';
+}
+
+/// The value of `argv[0]` when run.
+static const char *Executable;
+
+/// Temporary files to be cleaned up.
+static SmallVector> TempFiles;
+
+namespace {
+// Must not overlap with llvm::opt::DriverFlag.
+enum WrapperFlags { WrapperOnlyOption = (1 << 4) };
+
+enum ID {
+  OPT_INVALID = 0, // This is not an option ID.
+#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
+#include "SYCLLinkOpts.inc"
+  LastOption
+#undef OPTION
+};
+
+#define PREFIX(NAME, VALUE)
\
+  static constexpr StringLiteral NAME##_init[] = VALUE;
\
+  static constexpr ArrayRef NAME(NAME##_init,   
\
+std::size(NAME##_init) - 1);
+#include "SYCLLinkOpts.inc"
+#undef PREFIX
+
+static constexpr OptTable::Info InfoTable[] = {
+#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
+#include "SYCLLinkOpts.inc"
+#undef OPTION
+};
+
+class WrapperOptTable : public opt::GenericOptTable {

bader wrote:

```suggestion
class LinkerOptTable : public opt::GenericOptTable {
```

https://github.com/llvm/llvm-project/pull/112245
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][SYCL] Introduce clang-sycl-linker to link SYCL offloading device code (Part 1 of many) (PR #112245)

2024-10-28 Thread Alexey Bader via cfe-commits


@@ -0,0 +1,42 @@
+// Tests the clang-sycl-linker tool.
+//
+// Test a simple case without arguments.
+// RUN: %clangxx -fsycl -emit-llvm -c %s -o %t.bc
+// RUN: clang-sycl-linker --dry-run -triple spirv64 %t.bc -o a.spv 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=SIMPLE
+// SIMPLE: "{{.*}}llvm-link{{.*}}" {{.*}}.bc -o [[FIRSTLLVMLINKOUT:.*]].bc 
--suppress-warnings
+// SIMPLE-NEXT: "{{.*}}llvm-spirv{{.*}}" {{.*}}-o a.spv [[FIRSTLLVMLINKOUT]].bc
+//
+// Test a simple case with device library files specified.
+// RUN: echo ' ' > %T/lib1.bc
+// RUN: echo ' ' > %T/lib2.bc
+// RUN: clang-sycl-linker --dry-run -triple spirv64 %t.bc --library-path=%T 
--device-libs=lib1.bc,lib2.bc -o a.spv 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=DEVLIBS
+// DEVLIBS: "{{.*}}llvm-link{{.*}}" {{.*}}.bc -o [[FIRSTLLVMLINKOUT:.*]].bc 
--suppress-warnings
+// DEVLIBS-NEXT: "{{.*}}llvm-link{{.*}}" -only-needed [[FIRSTLLVMLINKOUT]].bc 
{{.*}}lib1.bc {{.*}}lib2.bc -o [[SECONDLLVMLINKOUT:.*]].bc --suppress-warnings
+// DEVLIBS-NEXT: "{{.*}}llvm-spirv{{.*}}" {{.*}}-o a.spv 
[[SECONDLLVMLINKOUT]].bc
+//
+// Test a simple case with .o (fat object) as input.
+// TODO: Remove this test once fat object support is added.
+// RUN: %clangxx -fsycl -c %s -o %t.o
+// RUN: not clang-sycl-linker --dry-run -triple spirv64 %t.o -o a.spv 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=FILETYPEERROR
+// FILETYPEERROR: Unsupported file type
+//
+// Test to see if device library related errors are emitted.
+// RUN: not clang-sycl-linker --dry-run -triple spirv64 %t.bc 
--library-path=%T --device-libs= -o a.spv 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=DEVLIBSERR1
+// DEVLIBSERR1: Number of device library files cannot be zero
+// RUN: not clang-sycl-linker --dry-run -triple spirv64 %t.bc 
--library-path=%T --device-libs=lib3.bc -o a.spv 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=DEVLIBSERR2
+// DEVLIBSERR2: SYCL device library file is not found

bader wrote:

```suggestion
// DEVLIBSERR2: lib3.bc SYCL device library file is not found
```
Please, check that error message contains the name of the library file, we 
can't find.

https://github.com/llvm/llvm-project/pull/112245
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][SYCL] Introduce clang-sycl-linker to link SYCL offloading device code (Part 1 of many) (PR #112245)

2024-10-28 Thread Alexey Bader via cfe-commits


@@ -0,0 +1,42 @@
+// Tests the clang-sycl-linker tool.
+//
+// Test a simple case without arguments.
+// RUN: %clangxx -fsycl -emit-llvm -c %s -o %t.bc
+// RUN: clang-sycl-linker --dry-run -triple spirv64 %t.bc -o a.spv 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=SIMPLE
+// SIMPLE: "{{.*}}llvm-link{{.*}}" {{.*}}.bc -o [[FIRSTLLVMLINKOUT:.*]].bc 
--suppress-warnings
+// SIMPLE-NEXT: "{{.*}}llvm-spirv{{.*}}" {{.*}}-o a.spv [[FIRSTLLVMLINKOUT]].bc
+//
+// Test a simple case with device library files specified.
+// RUN: echo ' ' > %T/lib1.bc
+// RUN: echo ' ' > %T/lib2.bc

bader wrote:

```suggestion
// RUN: touch %T/lib1.bc
// RUN: touch %T/lib2.bc
```
Can we leave these files empty?

https://github.com/llvm/llvm-project/pull/112245
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][SYCL] Introduce clang-sycl-linker to link SYCL offloading device code (Part 1 of many) (PR #112245)

2024-10-28 Thread Alexey Bader via cfe-commits


@@ -0,0 +1,42 @@
+// Tests the clang-sycl-linker tool.
+//
+// Test a simple case without arguments.
+// RUN: %clangxx -fsycl -emit-llvm -c %s -o %t.bc

bader wrote:

```suggestion
// RUN: %clangxx -emit-llvm -c %s -o %t.bc
```
`-fsycl` is useless here. We just need to create a file with LLVM magic number 
to make this test work.

https://github.com/llvm/llvm-project/pull/112245
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][SYCL] Introduce clang-sycl-linker to link SYCL offloading device code (Part 1 of many) (PR #112245)

2024-10-28 Thread Alexey Bader via cfe-commits


@@ -0,0 +1,13 @@
+// Tests the driver when linking LLVM IR bitcode files and targeting SPIR-V
+// architecture.
+//
+// RUN: touch %t.bc
+// RUN: %clangxx --target=spirv64 --sycl-link -### %t.bc 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=LINK
+// LINK: "{{.*}}clang-sycl-linker{{.*}}" "{{.*}}.bc" "-o" "a.out"
+//
+// Test that -Xlinker options are being passed to clang-sycl-linker.
+// RUN: %clangxx -### --target=spirv64 --sycl-link -Xlinker 
--llvm-spirv-path=/tmp \
+// RUN:   -Xlinker --library-path=/tmp -Xlinker --device-libs=lib1.bc,lib2.bc 
%t.bc 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=XLINKEROPTS
+// XLINKEROPTS: "{{.*}}clang-sycl-linker{{.*}}" "--llvm-spirv-path=/tmp" 
"--library-path=/tmp" "--device-libs=lib1.bc,lib2.bc" "{{.*}}.bc" "-o" "a.out"

bader wrote:

This test case seems to cover everything that's checked in the previous test 
case. Can we drop the previous test case and leave only this one?
```suggestion
// RUN: %clangxx -### --target=spirv64 --sycl-link -Xlinker 
--llvm-spirv-path=/tmp \
// RUN:   -Xlinker --library-path=/tmp -Xlinker --device-libs=lib1.bc,lib2.bc 
%t.bc 2>&1 \
// RUN:   | FileCheck %s
// CHECK: "{{.*}}clang-sycl-linker{{.*}}" "--llvm-spirv-path=/tmp" 
"--library-path=/tmp" "--device-libs=lib1.bc,lib2.bc" "{{.*}}.bc" "-o" "a.out"
```

https://github.com/llvm/llvm-project/pull/112245
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][SYCL] Introduce clang-sycl-linker to link SYCL offloading device code (Part 1 of many) (PR #112245)

2024-10-28 Thread Alexey Bader via cfe-commits


@@ -0,0 +1,500 @@
+//= clang-sycl-linker/ClangSYCLLinker.cpp - SYCL Linker util ---=//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===-===//
+//
+// This tool executes a sequence of steps required to link device code in SYCL
+// fat objects. SYCL device code linking requires a complex sequence of steps
+// that include linking of llvm bitcode files, linking device library files
+// with the fully linked source bitcode file(s), running several SYCL specific
+// post-link steps on the fully linked bitcode file(s), and finally generating
+// target-specific device code.
+//===-===//
+
+#include "clang/Basic/Version.h"
+
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/BinaryFormat/Magic.h"
+#include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/CommandFlags.h"
+#include "llvm/IR/DiagnosticPrinter.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"
+#include "llvm/Object/ELFObjectFile.h"
+#include "llvm/Object/IRObjectFile.h"
+#include "llvm/Object/ObjectFile.h"
+#include "llvm/Object/OffloadBinary.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Option/OptTable.h"
+#include "llvm/Option/Option.h"
+#include "llvm/Remarks/HotnessThresholdParser.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/FileOutputBuffer.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/InitLLVM.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/StringSaver.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/TimeProfiler.h"
+#include "llvm/Support/WithColor.h"
+
+using namespace llvm;
+using namespace llvm::opt;
+using namespace llvm::object;
+
+/// Save intermediary results.
+static bool SaveTemps = false;
+
+/// Print arguments without executing.
+static bool DryRun = false;
+
+/// Print verbose output.
+static bool Verbose = false;
+
+/// Filename of the output being created.
+static StringRef OutputFile;
+
+/// Directory to dump SPIR-V IR if requested by user.
+static SmallString<128> SPIRVDumpDir;
+
+static void printVersion(raw_ostream &OS) {
+  OS << clang::getClangToolFullVersion("clang-sycl-linker") << '\n';
+}
+
+/// The value of `argv[0]` when run.
+static const char *Executable;
+
+/// Temporary files to be cleaned up.
+static SmallVector> TempFiles;
+
+namespace {
+// Must not overlap with llvm::opt::DriverFlag.
+enum WrapperFlags { WrapperOnlyOption = (1 << 4) };
+
+enum ID {
+  OPT_INVALID = 0, // This is not an option ID.
+#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
+#include "SYCLLinkOpts.inc"
+  LastOption
+#undef OPTION
+};
+
+#define PREFIX(NAME, VALUE)
\
+  static constexpr StringLiteral NAME##_init[] = VALUE;
\
+  static constexpr ArrayRef NAME(NAME##_init,   
\
+std::size(NAME##_init) - 1);
+#include "SYCLLinkOpts.inc"
+#undef PREFIX
+
+static constexpr OptTable::Info InfoTable[] = {
+#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
+#include "SYCLLinkOpts.inc"
+#undef OPTION
+};
+
+class WrapperOptTable : public opt::GenericOptTable {
+public:
+  WrapperOptTable() : opt::GenericOptTable(InfoTable) {}
+};
+
+const OptTable &getOptTable() {
+  static const WrapperOptTable *Table = []() {
+auto Result = std::make_unique();
+return Result.release();
+  }();
+  return *Table;
+}
+
+[[noreturn]] void reportError(Error E) {
+  outs().flush();
+  logAllUnhandledErrors(std::move(E), WithColor::error(errs(), Executable));
+  exit(EXIT_FAILURE);
+}
+
+std::string getMainExecutable(const char *Name) {
+  void *Ptr = (void *)(intptr_t)&getMainExecutable;
+  auto COWPath = sys::fs::getMainExecutable(Name, Ptr);
+  return sys::path::parent_path(COWPath).str();
+}
+
+Expected createTempFile(const ArgList &Args, const Twine &Prefix,
+   StringRef Extension) {
+  SmallString<128> OutputFile;
+  if (Args.hasArg(OPT_save_temps)) {
+// Generate a unique path name without creating a file
+sys::fs::createUniquePath(Prefix + "-%%." + Extension, OutputFile,
+  /*MakeAbsolute=*/false);
+  } else {
+if (std::error_code EC =
+sys::fs::createTemporaryFile(Prefix, Extension, OutputFile))
+  return createFileError(OutputFile, EC);
+  }
+
+  TempFiles.emplace_back(std::move(OutputFile));
+  return TempFiles.back();
+}
+
+Expected findProgram(const ArgList &Args, Strin

[clang] [clang][Driver] Allow -fuse-lld=lld-link when lto is enabled on *windows-msvc targets (PR #113966)

2024-10-28 Thread Fangrui Song via cfe-commits

MaskRay wrote:

Windows should use `-fuse-ld=lld` as well, not `-fuse-ld=lld-link`

https://github.com/llvm/llvm-project/pull/113966
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Driver] Remove ignored Flag form of -fauto-profile/-fprofile-sample-use (PR #113528)

2024-10-28 Thread Fangrui Song via cfe-commits

MaskRay wrote:

> Regarding the default filename extension, it doesn't have to be `.profdata` 
> for `fprofile-sample-use`, it can be the `.afdo`, or any other extension 
> deemed proper. `fprofile-sample-use` and `fprofile-use` would behave 
> similarly then: they would look for a `default` file with appropriate 
> extension, which seems like a reasonable behavior to me

I respectively disagree. The sample PGO framework is quite different from 
instrumentation PGO. There is no `-fprofile-sample-generate`. While the naming 
`-fprofile-sample-use=` is similar to `-fprofile-use=`, it's a very weak 
argument to have a default filename, when the filename in the wild has many 
uses of very different extensions.

The deployment experience has shown that we don't really need a default 
filename.

https://github.com/llvm/llvm-project/pull/113528
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] Avoid allocations when reading blob paths (PR #113984)

2024-10-28 Thread Chuanqi Xu via cfe-commits


@@ -1341,9 +1341,22 @@ class ASTReader
   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
 bool Complain = true);
 
+  /// Buffer we use as temporary storage backing resolved paths.
+  SmallString<256> PathBuf;

ChuanqiXu9 wrote:

Sounds... not too bad?

If we really want it, can we make the so-called global buffer to be a static 
local variable?

https://github.com/llvm/llvm-project/pull/113984
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [Clang][CMake] Add CSSPGO support to LLVM_BUILD_INSTRUMENTED (PR #79942)

2024-10-28 Thread Amir Ayupov via cfe-commits

aaupov wrote:

Ping @wlei-llvm @WenleiHe 

https://github.com/llvm/llvm-project/pull/79942
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Driver] Allow -fuse-lld=lld-link when lto is enabled on *windows-msvc targets (PR #113966)

2024-10-28 Thread Max Winkler via cfe-commits

MaxEW707 wrote:

> Windows should use `-fuse-ld=lld` as well, not `-fuse-ld=lld-link`

Is `-fuse-ld=lld-link` intended to be an allowable option?

Right now we don't issue any error if a user passes in `lld-link`.

I am interpreting your statement as suggesting we should do something like 
following?
```
const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ);
if (A->getValue() == "lld-link") {
D.Diag(diag::err_drv_unsupported_option_argument) << A->getSpelling() << 
A->getValue();
}
```

https://github.com/llvm/llvm-project/pull/113966
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] clang: Remove requires system-linux from some driver tests (PR #111976)

2024-10-28 Thread Matt Arsenault via cfe-commits

https://github.com/arsenm updated 
https://github.com/llvm/llvm-project/pull/111976

>From 91c2f46274f83603552b12317c2fb87a8633ccc3 Mon Sep 17 00:00:00 2001
From: Matt Arsenault 
Date: Fri, 11 Oct 2024 14:33:32 +0400
Subject: [PATCH 1/7] clang: Remove requires system-linux from some driver
 tests

Works for me on macos.
---
 clang/test/Driver/amdgpu-hip-system-arch.c | 1 -
 clang/test/Driver/amdgpu-openmp-system-arch-fail.c | 1 -
 clang/test/Driver/hip-partial-link.hip | 2 +-
 clang/test/Driver/hip-temps-linux.hip  | 1 -
 clang/test/Driver/linker-wrapper.c | 6 ++
 clang/test/Driver/nvptx-cuda-system-arch.c | 1 -
 clang/test/Driver/openmp-system-arch.c | 1 -
 7 files changed, 3 insertions(+), 10 deletions(-)

diff --git a/clang/test/Driver/amdgpu-hip-system-arch.c 
b/clang/test/Driver/amdgpu-hip-system-arch.c
index f25a4087080f6d..7be7b9cad1be02 100644
--- a/clang/test/Driver/amdgpu-hip-system-arch.c
+++ b/clang/test/Driver/amdgpu-hip-system-arch.c
@@ -1,4 +1,3 @@
-// REQUIRES: system-linux
 // REQUIRES: shell
 
 // RUN: mkdir -p %t
diff --git a/clang/test/Driver/amdgpu-openmp-system-arch-fail.c 
b/clang/test/Driver/amdgpu-openmp-system-arch-fail.c
index 85c82e4598cb10..b7e1d0b2c56659 100644
--- a/clang/test/Driver/amdgpu-openmp-system-arch-fail.c
+++ b/clang/test/Driver/amdgpu-openmp-system-arch-fail.c
@@ -1,4 +1,3 @@
-// REQUIRES: system-linux
 // REQUIRES: shell
 
 // RUN: mkdir -p %t
diff --git a/clang/test/Driver/hip-partial-link.hip 
b/clang/test/Driver/hip-partial-link.hip
index 8b27f78f3bdd12..5580e569780194 100644
--- a/clang/test/Driver/hip-partial-link.hip
+++ b/clang/test/Driver/hip-partial-link.hip
@@ -1,4 +1,4 @@
-// REQUIRES: x86-registered-target, amdgpu-registered-target, lld, system-linux
+// REQUIRES: x86-registered-target, amdgpu-registered-target, lld
 
 // RUN: %clang -x hip --target=x86_64-unknown-linux-gnu 
--no-offload-new-driver \
 // RUN:   --offload-arch=gfx906 -c -nostdinc -nogpuinc -nohipwrapperinc \
diff --git a/clang/test/Driver/hip-temps-linux.hip 
b/clang/test/Driver/hip-temps-linux.hip
index 83a7528dd4560a..3fb8a94a3463c8 100644
--- a/clang/test/Driver/hip-temps-linux.hip
+++ b/clang/test/Driver/hip-temps-linux.hip
@@ -1,6 +1,5 @@
 // REQUIRES: x86-registered-target
 // REQUIRES: amdgpu-registered-target
-// REQUIRES: system-linux
 
 // Check no temporary files or directores are left after compilation.
 // RUN: rm -rf %t/mytmp
diff --git a/clang/test/Driver/linker-wrapper.c 
b/clang/test/Driver/linker-wrapper.c
index 470af4d5d70cac..5d20fc413e485d 100644
--- a/clang/test/Driver/linker-wrapper.c
+++ b/clang/test/Driver/linker-wrapper.c
@@ -2,8 +2,6 @@
 // REQUIRES: nvptx-registered-target
 // REQUIRES: amdgpu-registered-target
 
-// REQUIRES: system-linux
-
 // An externally visible variable so static libraries extract.
 __attribute__((visibility("protected"), used)) int x;
 
@@ -30,7 +28,7 @@ __attribute__((visibility("protected"), used)) int x;
 // RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run 
--device-debug -O0 \
 // RUN:   --linker-path=/usr/bin/ld %t.o -o a.out 2>&1 | FileCheck %s 
--check-prefix=NVPTX-LINK-DEBUG
 
-// NVPTX-LINK-DEBUG: clang{{.*}} -o {{.*}}.img --target=nvptx64-nvidia-cuda 
-march=sm_70 -O2 -flto {{.*}}.o {{.*}}.o -g 
+// NVPTX-LINK-DEBUG: clang{{.*}} -o {{.*}}.img --target=nvptx64-nvidia-cuda 
-march=sm_70 -O2 -flto {{.*}}.o {{.*}}.o -g
 
 // RUN: clang-offload-packager -o %t.out \
 // RUN:   
--image=file=%t.elf.o,kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx908 \
@@ -93,7 +91,7 @@ __attribute__((visibility("protected"), used)) int x;
 
 // CUDA: clang{{.*}} -o [[IMG_SM70:.+]] --target=nvptx64-nvidia-cuda 
-march=sm_70
 // CUDA: clang{{.*}} -o [[IMG_SM52:.+]] --target=nvptx64-nvidia-cuda 
-march=sm_52
-// CUDA: fatbinary{{.*}}-64 --create {{.*}}.fatbin 
--image=profile=sm_70,file=[[IMG_SM70]] --image=profile=sm_52,file=[[IMG_SM52]] 
+// CUDA: fatbinary{{.*}}-64 --create {{.*}}.fatbin 
--image=profile=sm_70,file=[[IMG_SM70]] --image=profile=sm_52,file=[[IMG_SM52]]
 // CUDA: usr/bin/ld{{.*}} {{.*}}.openmp.image.{{.*}}.o 
{{.*}}.cuda.image.{{.*}}.o
 
 // RUN: clang-offload-packager -o %t.out \
diff --git a/clang/test/Driver/nvptx-cuda-system-arch.c 
b/clang/test/Driver/nvptx-cuda-system-arch.c
index 6a8a218406d139..b6a7617930fc19 100644
--- a/clang/test/Driver/nvptx-cuda-system-arch.c
+++ b/clang/test/Driver/nvptx-cuda-system-arch.c
@@ -1,4 +1,3 @@
-// REQUIRES: system-linux
 // REQUIRES: shell
 
 // RUN: mkdir -p %t
diff --git a/clang/test/Driver/openmp-system-arch.c 
b/clang/test/Driver/openmp-system-arch.c
index cd49f460099666..75322dae69de46 100644
--- a/clang/test/Driver/openmp-system-arch.c
+++ b/clang/test/Driver/openmp-system-arch.c
@@ -1,4 +1,3 @@
-// REQUIRES: system-linux
 // REQUIRES: shell
 
 // RUN: mkdir -p %t

>From dff52cca382a9578208ef4ed688f5b277d1557a9 Mon Sep 17 00:00:00 2001
From: Matt Arsenault 
Date: Tue, 15 Oct 2024 21:57:26 +

[clang] [rtsan][NFC] Add documentation link to Function Effects (PR #113979)

2024-10-28 Thread Florian Mayer via cfe-commits


@@ -11,11 +11,16 @@ RealtimeSanitizer (a.k.a. RTSan) is a real-time safety 
testing tool for C and C+
 projects. RTSan can be used to detect real-time violations, i.e. calls to 
methods
 that are not safe for use in functions with deterministic run time 
requirements.
 RTSan considers any function marked with the ``[[clang::nonblocking]]`` 
attribute
-to be a real-time function. If RTSan detects a call to ``malloc``, ``free``,
-``pthread_mutex_lock``, or anything else that could have a non-deterministic
-execution time in a function marked ``[[clang::nonblocking]]``
+to be a real-time function. At run-time, if RTSan detects a call to 
``malloc``, 
+``free``, ``pthread_mutex_lock``, or anything else that could have a 
+non-deterministic execution time in a function marked 
``[[clang::nonblocking]]``

fmayer wrote:

> or anything else that could have a non-deterministic execution time

that sounds like a guarantee. Isn't it more things that we _know_ to have a 
non-deterministic runtime

https://github.com/llvm/llvm-project/pull/113979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-28 Thread Rashmi Mudduluru via cfe-commits


@@ -48,6 +48,64 @@ bool isRefcountedStringsHack(const VarDecl *V) {
   return false;
 }
 
+struct GuardianVisitor : public RecursiveASTVisitor {
+  using Base = RecursiveASTVisitor;
+
+  const VarDecl *Guardian{nullptr};
+
+public:
+  explicit GuardianVisitor(const VarDecl *Guardian) : Guardian(Guardian) {
+assert(Guardian);
+  }
+
+  bool VisitBinaryOperator(const BinaryOperator *BO) {
+if (BO->isAssignmentOp()) {
+  if (auto *VarRef = dyn_cast(BO->getLHS())) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXConstructExpr(const CXXConstructExpr *CE) {
+if (auto *Ctor = CE->getConstructor()) {
+  if (Ctor->isMoveConstructor() && CE->getNumArgs() == 1) {
+auto *Arg = CE->getArg(0)->IgnoreParenCasts();
+if (auto *VarRef = dyn_cast(Arg)) {
+  if (VarRef->getDecl() == Guardian)
+return false;
+}
+  }
+}
+return true;
+  }
+
+  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) {
+auto MethodName = safeGetName(MCE->getMethodDecl());
+if (MethodName == "swap" || MethodName == "leakRef" ||
+MethodName == "releaseNonNull") {
+  auto *ThisArg = MCE->getImplicitObjectArgument()->IgnoreParenCasts();
+  if (auto *VarRef = dyn_cast(ThisArg)) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE) {
+if (OCE->isAssignmentOp() && OCE->getNumArgs() == 2) {

t-rasmud wrote:

Is the check `OCE->getNumArgs() == 2` necessary here? What are the cases in 
which `CXXOperatorCallExpr` is an assignment op but has a different number of 
args?

https://github.com/llvm/llvm-project/pull/113859
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-28 Thread Ryosuke Niwa via cfe-commits


@@ -48,6 +48,64 @@ bool isRefcountedStringsHack(const VarDecl *V) {
   return false;
 }
 
+struct GuardianVisitor : public RecursiveASTVisitor {
+  using Base = RecursiveASTVisitor;
+
+  const VarDecl *Guardian{nullptr};
+
+public:
+  explicit GuardianVisitor(const VarDecl *Guardian) : Guardian(Guardian) {
+assert(Guardian);
+  }
+
+  bool VisitBinaryOperator(const BinaryOperator *BO) {
+if (BO->isAssignmentOp()) {
+  if (auto *VarRef = dyn_cast(BO->getLHS())) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXConstructExpr(const CXXConstructExpr *CE) {
+if (auto *Ctor = CE->getConstructor()) {
+  if (Ctor->isMoveConstructor() && CE->getNumArgs() == 1) {
+auto *Arg = CE->getArg(0)->IgnoreParenCasts();
+if (auto *VarRef = dyn_cast(Arg)) {
+  if (VarRef->getDecl() == Guardian)
+return false;
+}
+  }
+}
+return true;
+  }
+
+  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) {
+auto MethodName = safeGetName(MCE->getMethodDecl());
+if (MethodName == "swap" || MethodName == "leakRef" ||
+MethodName == "releaseNonNull") {
+  auto *ThisArg = MCE->getImplicitObjectArgument()->IgnoreParenCasts();
+  if (auto *VarRef = dyn_cast(ThisArg)) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE) {
+if (OCE->isAssignmentOp() && OCE->getNumArgs() == 2) {

rniwa wrote:

That's a good point. It's probably redundant here.

https://github.com/llvm/llvm-project/pull/113859
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-28 Thread Ryosuke Niwa via cfe-commits


@@ -83,6 +83,65 @@ void foo7(RefCountable* obj) {
   bar.obj->method();
 }
 
+void foo8(RefCountable* obj) {
+  RefPtr foo;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo = nullptr;
+bar->method();
+  }
+  RefPtr baz;
+  {
+RefCountable *bar = baz.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+baz = obj;
+bar->method();
+  }
+  foo = nullptr;
+  {
+RefCountable *bar = foo.get();
+// No warning. It's okay to mutate RefPtr in an outer scope.
+bar->method();
+  }
+  foo = obj;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo.releaseNonNull();
+bar->method();
+  }
+}
+
+void foo9(RefCountable& o) {
+  Ref guardian(o);
+  {
+RefCountable &bar = guardian.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian = o; // We don't detect that we're setting it to the same value.
+bar.method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(*bar); // We don't detect other has the same value 
as guardian.
+guardian.swap(other);
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(static_cast&&>(guardian));
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian.leakRef();
+bar->method();
+  }
+}

rniwa wrote:

I think so. Should we add it as a test case?

https://github.com/llvm/llvm-project/pull/113859
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-28 Thread Rashmi Mudduluru via cfe-commits


@@ -83,6 +83,65 @@ void foo7(RefCountable* obj) {
   bar.obj->method();
 }
 
+void foo8(RefCountable* obj) {
+  RefPtr foo;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo = nullptr;
+bar->method();
+  }
+  RefPtr baz;
+  {
+RefCountable *bar = baz.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+baz = obj;
+bar->method();
+  }
+  foo = nullptr;
+  {
+RefCountable *bar = foo.get();
+// No warning. It's okay to mutate RefPtr in an outer scope.
+bar->method();
+  }
+  foo = obj;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo.releaseNonNull();
+bar->method();
+  }
+}
+
+void foo9(RefCountable& o) {
+  Ref guardian(o);
+  {
+RefCountable &bar = guardian.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian = o; // We don't detect that we're setting it to the same value.
+bar.method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(*bar); // We don't detect other has the same value 
as guardian.
+guardian.swap(other);
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(static_cast&&>(guardian));
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian.leakRef();
+bar->method();
+  }
+}

t-rasmud wrote:

Adding a test case would be great!

https://github.com/llvm/llvm-project/pull/113859
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 7bd8a16 - [X86] Don't allow '+f' as an inline asm constraint. (#113871)

2024-10-28 Thread via cfe-commits

Author: Craig Topper
Date: 2024-10-28T13:20:46-07:00
New Revision: 7bd8a165f95123e390f9cbb0a6a5e60d835a4461

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

LOG: [X86] Don't allow '+f' as an inline asm constraint. (#113871)

f cannot be used as an output constraint. We already errored for '=f'
but not '+f'.

Fixes #113692.

Added: 


Modified: 
clang/lib/Basic/Targets/X86.cpp
clang/test/Sema/asm.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index d067ec218b5270..700c2f9a5dbd18 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -1465,7 +1465,7 @@ bool X86TargetInfo::validateAsmConstraint(
 }
   case 'f': // Any x87 floating point stack register.
 // Constraint 'f' cannot be used for output operands.
-if (Info.ConstraintStr[0] == '=')
+if (Info.ConstraintStr[0] == '=' || Info.ConstraintStr[0] == '+')
   return false;
 Info.setAllowsRegister();
 return true;

diff  --git a/clang/test/Sema/asm.c b/clang/test/Sema/asm.c
index 6cd95c71604d44..28ef3ec6ce09c2 100644
--- a/clang/test/Sema/asm.c
+++ b/clang/test/Sema/asm.c
@@ -204,6 +204,12 @@ double f_output_constraint(void) {
   return result;
 }
 
+double f_output_constraint_2(void) {
+  double result;
+  __asm("foo1": "+f" (result)); // expected-error {{invalid output constraint 
'+f' in asm}}
+  return result;
+}
+
 void fn1(void) {
   int l;
   __asm__(""



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


[clang] Add clang/docs/FunctionEffectAnalysis.rst. (PR #109855)

2024-10-28 Thread Chris Apple via cfe-commits

https://github.com/cjappl closed 
https://github.com/llvm/llvm-project/pull/109855
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [CIR] Call code gen; create empty cir.func op (PR #113483)

2024-10-28 Thread Shoaib Meenai via cfe-commits


@@ -24,9 +27,149 @@ CIRGenModule::CIRGenModule(mlir::MLIRContext &context,
clang::ASTContext &astctx,
const clang::CodeGenOptions &cgo,
DiagnosticsEngine &diags)
-: astCtx(astctx), langOpts(astctx.getLangOpts()),
-  theModule{mlir::ModuleOp::create(mlir::UnknownLoc())},
-  target(astCtx.getTargetInfo()) {}
+: builder(&context), astCtx(astctx), langOpts(astctx.getLangOpts()),
+  theModule{mlir::ModuleOp::create(mlir::UnknownLoc::get(&context))},
+  diags(diags), target(astCtx.getTargetInfo()) {}
+
+mlir::Location CIRGenModule::getLoc(SourceLocation cLoc) {
+  assert(cLoc.isValid() && "expected valid source location");
+  const SourceManager &sm = astCtx.getSourceManager();
+  PresumedLoc pLoc = sm.getPresumedLoc(cLoc);
+  StringRef filename = pLoc.getFilename();
+  return mlir::FileLineColLoc::get(builder.getStringAttr(filename),
+   pLoc.getLine(), pLoc.getColumn());
+}
+
+mlir::Location CIRGenModule::getLoc(SourceRange cRange) {
+  assert(cRange.isValid() && "expected a valid source range");
+  mlir::Location begin = getLoc(cRange.getBegin());
+  mlir::Location end = getLoc(cRange.getEnd());
+  SmallVector locs = {begin, end};
+  mlir::Attribute metadata;
+  return mlir::FusedLoc::get(locs, metadata, builder.getContext());
+}
+
+void CIRGenModule::buildGlobal(clang::GlobalDecl gd) {
+

smeenai wrote:

Nit: extra newline

https://github.com/llvm/llvm-project/pull/113483
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Emit constrained atan2 intrinsic for clang builtin (PR #113636)

2024-10-28 Thread Tex Riddell via cfe-commits

https://github.com/tex3d updated 
https://github.com/llvm/llvm-project/pull/113636

>From 7c7b72b48e07e0f34c2ee65e11e70db37f8c88b3 Mon Sep 17 00:00:00 2001
From: Tex Riddell 
Date: Tue, 15 Oct 2024 16:18:44 -0700
Subject: [PATCH 1/3] Emit constrained atan2 intrinsic for clang builtin

This change is part of this proposal: 
https://discourse.llvm.org/t/rfc-all-the-math-intrinsics/78294

- `Builtins.td` - Add f16 support for libm atan2 builtin
- `CGBuiltin.cpp` - Emit constraint atan2 intrinsic for clang builtin

Part of Implement the atan2 HLSL Function #70096.
---
 clang/include/clang/Basic/Builtins.td |  6 +++---
 clang/lib/CodeGen/CGBuiltin.cpp   | 11 ++
 clang/test/CodeGen/X86/math-builtins.c| 14 ++---
 .../test/CodeGen/constrained-math-builtins.c  |  7 +++
 clang/test/CodeGen/libcalls.c |  7 +++
 clang/test/CodeGen/math-libcalls.c| 20 +--
 .../test/CodeGenCXX/builtin-calling-conv.cpp  | 10 +-
 clang/test/CodeGenOpenCL/builtins-f16.cl  |  3 +++
 8 files changed, 49 insertions(+), 29 deletions(-)

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 90475a361bb8f8..0d77f4105bb757 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -227,10 +227,10 @@ def FminimumNumF16F128 : Builtin, F16F128MathTemplate {
   let Prototype = "T(T, T)";
 }
 
-def Atan2F128 : Builtin {
-  let Spellings = ["__builtin_atan2f128"];
+def Atan2F16F128 : Builtin, F16F128MathTemplate {
+  let Spellings = ["__builtin_atan2"];
   let Attributes = [FunctionWithBuiltinPrefix, NoThrow, 
ConstIgnoringErrnoAndExceptions];
-  let Prototype = "__float128(__float128, __float128)";
+  let Prototype = "T(T, T)";
 }
 
 def CopysignF16 : Builtin {
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index a57c95d5b96672..012097e5bd72ee 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -2724,6 +2724,17 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(
   *this, E, Intrinsic::atan, 
Intrinsic::experimental_constrained_atan));
 
+case Builtin::BIatan2:
+case Builtin::BIatan2f:
+case Builtin::BIatan2l:
+case Builtin::BI__builtin_atan2:
+case Builtin::BI__builtin_atan2f:
+case Builtin::BI__builtin_atan2f16:
+case Builtin::BI__builtin_atan2l:
+case Builtin::BI__builtin_atan2f128:
+  return RValue::get(emitBinaryMaybeConstrainedFPBuiltin(
+  *this, E, Intrinsic::atan2, 
Intrinsic::experimental_constrained_atan2));
+
 case Builtin::BIceil:
 case Builtin::BIceilf:
 case Builtin::BIceill:
diff --git a/clang/test/CodeGen/X86/math-builtins.c 
b/clang/test/CodeGen/X86/math-builtins.c
index 48465df21cca19..bf107437fc63a3 100644
--- a/clang/test/CodeGen/X86/math-builtins.c
+++ b/clang/test/CodeGen/X86/math-builtins.c
@@ -45,10 +45,10 @@ void foo(double *d, float f, float *fp, long double *l, int 
*i, const char *c) {
 
   __builtin_atan2(f,f);__builtin_atan2f(f,f) ;  __builtin_atan2l(f, f); 
__builtin_atan2f128(f,f);
 
-// NO__ERRNO: declare double @atan2(double noundef, double noundef) 
[[READNONE:#[0-9]+]]
-// NO__ERRNO: declare float @atan2f(float noundef, float noundef) [[READNONE]]
-// NO__ERRNO: declare x86_fp80 @atan2l(x86_fp80 noundef, x86_fp80 noundef) 
[[READNONE]]
-// NO__ERRNO: declare fp128 @atan2f128(fp128 noundef, fp128 noundef) 
[[READNONE]]
+// NO__ERRNO: declare double @llvm.atan2.f64(double, double) 
[[READNONE_INTRINSIC:#[0-9]+]]
+// NO__ERRNO: declare float @llvm.atan2.f32(float, float) 
[[READNONE_INTRINSIC]]
+// NO__ERRNO: declare x86_fp80 @llvm.atan2.f80(x86_fp80, x86_fp80) 
[[READNONE_INTRINSIC]]
+// NO__ERRNO: declare fp128 @llvm.atan2.f128(fp128, fp128) 
[[READNONE_INTRINSIC]]
 // HAS_ERRNO: declare double @atan2(double noundef, double noundef) 
[[NOT_READNONE]]
 // HAS_ERRNO: declare float @atan2f(float noundef, float noundef) 
[[NOT_READNONE]]
 // HAS_ERRNO: declare x86_fp80 @atan2l(x86_fp80 noundef, x86_fp80 noundef) 
[[NOT_READNONE]]
@@ -56,7 +56,7 @@ void foo(double *d, float f, float *fp, long double *l, int 
*i, const char *c) {
 
   __builtin_copysign(f,f); __builtin_copysignf(f,f); __builtin_copysignl(f,f); 
__builtin_copysignf128(f,f);
 
-// NO__ERRNO: declare double @llvm.copysign.f64(double, double) 
[[READNONE_INTRINSIC:#[0-9]+]]
+// NO__ERRNO: declare double @llvm.copysign.f64(double, double) 
[[READNONE_INTRINSIC]]
 // NO__ERRNO: declare float @llvm.copysign.f32(float, float) 
[[READNONE_INTRINSIC]]
 // NO__ERRNO: declare x86_fp80 @llvm.copysign.f80(x86_fp80, x86_fp80) 
[[READNONE_INTRINSIC]]
 // NO__ERRNO: declare fp128 @llvm.copysign.f128(fp128, fp128) 
[[READNONE_INTRINSIC]]
@@ -179,7 +179,7 @@ void foo(double *d, float f, float *fp, long double *l, int 
*i, const char *c) {
 
   __builtin_acosh(f

[clang] 8e6856e - [Clang][TableGen] Use StringRef::str() instead of std::string() cast (#113645)

2024-10-28 Thread via cfe-commits

Author: Rahul Joshi
Date: 2024-10-28T16:15:39-07:00
New Revision: 8e6856e27859c90c5337a8328848b0959fe409fe

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

LOG: [Clang][TableGen] Use StringRef::str() instead of std::string() cast 
(#113645)

Use `StringRef::str()` instead of std::string(StringRef) to cast from
StringRef to std::string.

Added: 


Modified: 
clang/utils/TableGen/ClangAttrEmitter.cpp
clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp

Removed: 




diff  --git a/clang/utils/TableGen/ClangAttrEmitter.cpp 
b/clang/utils/TableGen/ClangAttrEmitter.cpp
index cf9c70a93e5db2..3031d81b3df731 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -122,9 +122,7 @@ GetFlattenedSpellings(const Record &Attr) {
 
 static std::string ReadPCHRecord(StringRef type) {
   return StringSwitch(type)
-  .EndsWith("Decl *", "Record.readDeclAs<" +
-  std::string(type.data(), 0, type.size() - 1) +
-  ">()")
+  .EndsWith("Decl *", "Record.readDeclAs<" + type.drop_back().str() + 
">()")
   .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
   .Case("Expr *", "Record.readExpr()")
   .Case("IdentifierInfo *", "Record.readIdentifier()")
@@ -145,18 +143,16 @@ static StringRef getStorageType(StringRef type) {
 static std::string WritePCHRecord(StringRef type, StringRef name) {
   return "Record." +
  StringSwitch(type)
- .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
+ .EndsWith("Decl *", "AddDeclRef(" + name.str() + ");\n")
  .Case("TypeSourceInfo *",
-   "AddTypeSourceInfo(" + std::string(name) + ");\n")
- .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
+   "AddTypeSourceInfo(" + name.str() + ");\n")
+ .Case("Expr *", "AddStmt(" + name.str() + ");\n")
  .Case("IdentifierInfo *",
-   "AddIdentifierRef(" + std::string(name) + ");\n")
- .Case("StringRef", "AddString(" + std::string(name) + ");\n")
- .Case("ParamIdx",
-   "push_back(" + std::string(name) + ".serialize());\n")
- .Case("OMPTraitInfo *",
-   "writeOMPTraitInfo(" + std::string(name) + ");\n")
- .Default("push_back(" + std::string(name) + ");\n");
+   "AddIdentifierRef(" + name.str() + ");\n")
+ .Case("StringRef", "AddString(" + name.str() + ");\n")
+ .Case("ParamIdx", "push_back(" + name.str() + ".serialize());\n")
+ .Case("OMPTraitInfo *", "writeOMPTraitInfo(" + name.str() + 
");\n")
+ .Default("push_back(" + name.str() + ");\n");
 }
 
 // Normalize attribute name by removing leading and trailing
@@ -197,7 +193,7 @@ static ParsedAttrMap getParsedAttrList(const RecordKeeper 
&Records,
   std::string AN;
   if (Attr->isSubClassOf("TargetSpecificAttr") &&
   !Attr->isValueUnset("ParseKind")) {
-AN = std::string(Attr->getValueAsString("ParseKind"));
+AN = Attr->getValueAsString("ParseKind").str();
 
 // If this attribute has already been handled, it does not need to be
 // handled again.
@@ -225,7 +221,7 @@ namespace {
 
   public:
 Argument(StringRef Arg, StringRef Attr)
-: lowerName(std::string(Arg)), upperName(lowerName), attrName(Attr),
+: lowerName(Arg.str()), upperName(lowerName), attrName(Attr),
   isOpt(false), Fake(false) {
   if (!lowerName.empty()) {
 lowerName[0] = std::tolower(lowerName[0]);
@@ -331,8 +327,7 @@ namespace {
 
 void writePCHWrite(raw_ostream &OS) const override {
   OS << ""
- << WritePCHRecord(type,
-   "SA->get" + std::string(getUpperName()) + "()");
+ << WritePCHRecord(type, "SA->get" + getUpperName().str() + "()");
 }
 
 std::string getIsOmitted() const override {
@@ -698,12 +693,12 @@ namespace {
 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
 : Argument(Arg, Attr), Type(std::move(T)),
   ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
-  RangeName(std::string(getLowerName())) {}
+  RangeName(getLowerName().str()) {}
 
 VariadicArgument(StringRef Arg, StringRef Attr, std::string T)
 : Argument(Arg, Attr), Type(std::move(T)),
   ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
-  RangeName(std::string(getLowerName())) {}
+  RangeName(getLowerName().str()) {}
 
 co

[clang] [rtsan][NFC] Add documentation link to Function Effects (PR #113979)

2024-10-28 Thread Chris Apple via cfe-commits

https://github.com/cjappl created 
https://github.com/llvm/llvm-project/pull/113979

None

>From d2a311863881486fbed6097d6358b096f305377a Mon Sep 17 00:00:00 2001
From: Chris Apple 
Date: Mon, 28 Oct 2024 16:17:48 -0700
Subject: [PATCH] [rtsan][NFC] Add documentation link to Function Effects

---
 clang/docs/RealtimeSanitizer.rst | 11 ---
 1 file changed, 8 insertions(+), 3 deletions(-)

diff --git a/clang/docs/RealtimeSanitizer.rst b/clang/docs/RealtimeSanitizer.rst
index 41b8bbb33baf14..e5f5abfcd9b47e 100644
--- a/clang/docs/RealtimeSanitizer.rst
+++ b/clang/docs/RealtimeSanitizer.rst
@@ -11,11 +11,16 @@ RealtimeSanitizer (a.k.a. RTSan) is a real-time safety 
testing tool for C and C+
 projects. RTSan can be used to detect real-time violations, i.e. calls to 
methods
 that are not safe for use in functions with deterministic run time 
requirements.
 RTSan considers any function marked with the ``[[clang::nonblocking]]`` 
attribute
-to be a real-time function. If RTSan detects a call to ``malloc``, ``free``,
-``pthread_mutex_lock``, or anything else that could have a non-deterministic
-execution time in a function marked ``[[clang::nonblocking]]``
+to be a real-time function. At run-time, if RTSan detects a call to 
``malloc``, 
+``free``, ``pthread_mutex_lock``, or anything else that could have a 
+non-deterministic execution time in a function marked 
``[[clang::nonblocking]]``
 RTSan raises an error.
 
+RTSan performs its analysis at run-time but shares the 
``[[clang::nonblocking]]`` 
+attribute with the :doc:`FunctionEffectAnalysis` system, which operates at 
+compile-time to detect potential real-time safety violations. For 
comprehensive 
+detection of real-time safety issues, it is recommended to use both systems 
together.
+
 The runtime slowdown introduced by RealtimeSanitizer is negligible.
 
 How to build

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


[clang] [rtsan][NFC] Add documentation link to Function Effects (PR #113979)

2024-10-28 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Chris Apple (cjappl)


Changes



---
Full diff: https://github.com/llvm/llvm-project/pull/113979.diff


1 Files Affected:

- (modified) clang/docs/RealtimeSanitizer.rst (+8-3) 


``diff
diff --git a/clang/docs/RealtimeSanitizer.rst b/clang/docs/RealtimeSanitizer.rst
index 41b8bbb33baf14..e5f5abfcd9b47e 100644
--- a/clang/docs/RealtimeSanitizer.rst
+++ b/clang/docs/RealtimeSanitizer.rst
@@ -11,11 +11,16 @@ RealtimeSanitizer (a.k.a. RTSan) is a real-time safety 
testing tool for C and C+
 projects. RTSan can be used to detect real-time violations, i.e. calls to 
methods
 that are not safe for use in functions with deterministic run time 
requirements.
 RTSan considers any function marked with the ``[[clang::nonblocking]]`` 
attribute
-to be a real-time function. If RTSan detects a call to ``malloc``, ``free``,
-``pthread_mutex_lock``, or anything else that could have a non-deterministic
-execution time in a function marked ``[[clang::nonblocking]]``
+to be a real-time function. At run-time, if RTSan detects a call to 
``malloc``, 
+``free``, ``pthread_mutex_lock``, or anything else that could have a 
+non-deterministic execution time in a function marked 
``[[clang::nonblocking]]``
 RTSan raises an error.
 
+RTSan performs its analysis at run-time but shares the 
``[[clang::nonblocking]]`` 
+attribute with the :doc:`FunctionEffectAnalysis` system, which operates at 
+compile-time to detect potential real-time safety violations. For 
comprehensive 
+detection of real-time safety issues, it is recommended to use both systems 
together.
+
 The runtime slowdown introduced by RealtimeSanitizer is negligible.
 
 How to build

``




https://github.com/llvm/llvm-project/pull/113979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [rtsan][NFC] Add documentation link to Function Effects (PR #113979)

2024-10-28 Thread Chris Apple via cfe-commits

cjappl wrote:

CC for review @dougsonos 

https://github.com/llvm/llvm-project/pull/113979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-28 Thread Rashmi Mudduluru via cfe-commits


@@ -83,6 +83,65 @@ void foo7(RefCountable* obj) {
   bar.obj->method();
 }
 
+void foo8(RefCountable* obj) {
+  RefPtr foo;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo = nullptr;
+bar->method();
+  }
+  RefPtr baz;
+  {
+RefCountable *bar = baz.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+baz = obj;
+bar->method();
+  }
+  foo = nullptr;
+  {
+RefCountable *bar = foo.get();
+// No warning. It's okay to mutate RefPtr in an outer scope.
+bar->method();
+  }
+  foo = obj;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo.releaseNonNull();
+bar->method();
+  }
+}
+
+void foo9(RefCountable& o) {
+  Ref guardian(o);
+  {
+RefCountable &bar = guardian.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian = o; // We don't detect that we're setting it to the same value.
+bar.method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(*bar); // We don't detect other has the same value 
as guardian.
+guardian.swap(other);
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(static_cast&&>(guardian));
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian.leakRef();
+bar->method();
+  }
+}

t-rasmud wrote:

What is the expected behavior for conditional assignments?
For example:
```
{
RefCountable *bar = cond? foo.get() : nullptr;
 }
```
Should the checker produce a warning here?

https://github.com/llvm/llvm-project/pull/113859
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][TableGen] Use StringRef::str() instead of std::string() cast (PR #113645)

2024-10-28 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul closed 
https://github.com/llvm/llvm-project/pull/113645
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [WIP][Wunsafe-buffer-usage] False positives for & expression indexing constant size array (arr[anything & 0]) (PR #112284)

2024-10-28 Thread Malavika Samak via cfe-commits

https://github.com/malavikasamak updated 
https://github.com/llvm/llvm-project/pull/112284

>From 7e00765481784324450982e4789bf61bf66dbfdf Mon Sep 17 00:00:00 2001
From: MalavikaSamak 
Date: Fri, 11 Oct 2024 12:24:58 -0700
Subject: [PATCH 1/2] [Wunsafe-buffer-usage] False positives for & expression
 indexing constant size array (arr[anything & 0])

Do not warn when a constant sized array is indexed with an expression that 
contains bitwise and operation
involving constants and it always results in a bound safe access.

(rdar://136684050)
---
 clang/lib/Analysis/UnsafeBufferUsage.cpp  | 127 --
 .../warn-unsafe-buffer-usage-array.cpp|  43 ++
 2 files changed, 162 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 97f1c4f16b8f4c..1ee1657e90d7aa 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -420,6 +420,118 @@ AST_MATCHER(CXXConstructExpr, 
isSafeSpanTwoParamConstruct) {
   return false;
 }
 
+class MaxValueEval : public RecursiveASTVisitor {
+
+  std::vector val;
+  ASTContext &Context;
+  llvm::APInt Max;
+  unsigned bit_width;
+
+public:
+  typedef RecursiveASTVisitor VisitorBase;
+
+  explicit MaxValueEval(ASTContext &Ctx, const Expr *exp) : Context(Ctx) {
+bit_width = Ctx.getIntWidth(exp->getType());
+Max = llvm::APInt::getSignedMaxValue(bit_width);
+val.clear();
+  }
+
+  bool findMatch(Expr *exp) {
+TraverseStmt(exp);
+return true;
+  }
+
+  bool VisitDeclRefExpr(DeclRefExpr *dre) {
+val.push_back(Max);
+return false;
+  }
+
+  bool VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
+val.push_back(Max);
+return false;
+  }
+
+  bool EvaluateExpression(Expr *exp) {
+Expr::EvalResult EVResult;
+if (exp->EvaluateAsInt(EVResult, Context)) {
+  llvm::APSInt Result = EVResult.Val.getInt();
+  val.push_back(Result);
+  return true;
+}
+return false;
+  }
+
+  bool VisitBinaryOperator(BinaryOperator *E) {
+
+if (EvaluateExpression(E)) {
+  return false;
+} else {
+  TraverseStmt(E->getLHS());
+  llvm::APInt LHS = val.back();
+  val.pop_back();
+
+  TraverseStmt(E->getRHS());
+  llvm::APInt RHS = val.back();
+  val.pop_back();
+  llvm::APInt Result = Max;
+
+  switch (E->getOpcode()) {
+  case BO_And:
+  case BO_AndAssign:
+Result = LHS & RHS;
+break;
+
+  case BO_Or:
+  case BO_OrAssign:
+Result = LHS | RHS;
+break;
+
+  case BO_Shl:
+  case BO_ShlAssign:
+if (RHS != Max.getLimitedValue())
+  Result = LHS << RHS.getLimitedValue();
+break;
+
+  case BO_Shr:
+  case BO_ShrAssign:
+if (RHS == Max.getLimitedValue())
+  Result = LHS;
+else
+  Result = LHS.getLimitedValue() >> RHS.getLimitedValue();
+break;
+
+  case BO_Rem:
+  case BO_RemAssign:
+if (LHS.getLimitedValue() < RHS.getLimitedValue())
+  Result = LHS;
+else
+  Result = --RHS;
+break;
+
+  default:
+break;
+  }
+  val.push_back(Result);
+  return false;
+}
+return true;
+  }
+
+  bool VisitExpr(Expr *E) {
+if (EvaluateExpression(E)) {
+  return false;
+}
+return VisitorBase::VisitExpr(E);
+  }
+
+  APInt getValue() {
+if (val.size() == 1)
+  return val[0];
+else // A pattern we didn't consider was encountered
+  return Max;
+  }
+};
+
 AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
   // FIXME: Proper solution:
   //  - refactor Sema::CheckArrayAccess
@@ -439,14 +551,13 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
   if (!CATy)
 return false;
 
-  if (const auto *IdxLit = dyn_cast(Node.getIdx())) {
-const APInt ArrIdx = IdxLit->getValue();
-// FIXME: ArrIdx.isNegative() we could immediately emit an error as that's 
a
-// bug
-if (ArrIdx.isNonNegative() &&
-ArrIdx.getLimitedValue() < CATy->getLimitedSize())
-  return true;
-  }
+  MaxValueEval Vis(Finder->getASTContext(), Node.getIdx());
+  Vis.findMatch(const_cast(Node.getIdx()));
+  APInt result = Vis.getValue();
+
+  if (result.isNonNegative() &&
+  result.getLimitedValue() < CATy->getLimitedSize())
+return true;
 
   return false;
 }
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
index 8b2f103ec66708..6f0a974e45d9c6 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
@@ -33,6 +33,49 @@ void constant_idx_safe0(unsigned idx) {
   buffer[0] = 0;
 }
 
+int array[10]; // expected-warning 3{{'array' is an unsafe buffer that does 
not perform bounds checks}}
+
+void masked_idx1(unsigned long long idx) {
+  // Bitwise and operation
+  array[idx & 5] = 10; // no warning
+  array[idx & 11 & 

[clang] [Wunsafe-buffer-usage] False positives for & expression indexing constant size array (arr[anything & 0]) (PR #112284)

2024-10-28 Thread Malavika Samak via cfe-commits

https://github.com/malavikasamak edited 
https://github.com/llvm/llvm-project/pull/112284
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [HLSL] Re-implement countbits with the correct return type (PR #113189)

2024-10-28 Thread Sarah Spall via cfe-commits

https://github.com/spall updated 
https://github.com/llvm/llvm-project/pull/113189

>From 23d62026c8338e6ad92495cfcaa54ff1fa5d08f0 Mon Sep 17 00:00:00 2001
From: Sarah Spall 
Date: Wed, 16 Oct 2024 19:00:08 +
Subject: [PATCH 1/5] implement countbits correctly

---
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  | 126 +++---
 .../test/CodeGenHLSL/builtins/countbits.hlsl  |  42 +++---
 .../SemaHLSL/BuiltIns/countbits-errors.hlsl   |  14 +-
 llvm/lib/Target/DirectX/DXIL.td   |   5 +-
 llvm/lib/Target/DirectX/DXILOpLowering.cpp|  64 +
 llvm/test/CodeGen/DirectX/countbits.ll|  39 --
 6 files changed, 202 insertions(+), 88 deletions(-)

diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h 
b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
index 8ade4b27f360fb..7936506a0461b6 100644
--- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -723,66 +723,90 @@ float4 cosh(float4);
 
 #ifdef __HLSL_ENABLE_16_BIT
 _HLSL_AVAILABILITY(shadermodel, 6.2)
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-int16_t countbits(int16_t);
+constexpr uint countbits(int16_t x) {
+  return __builtin_elementwise_popcount(x);
+}
 _HLSL_AVAILABILITY(shadermodel, 6.2)
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-int16_t2 countbits(int16_t2);
+constexpr uint2 countbits(int16_t2 x) {
+  return __builtin_elementwise_popcount(x);
+}
 _HLSL_AVAILABILITY(shadermodel, 6.2)
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-int16_t3 countbits(int16_t3);
+constexpr uint3 countbits(int16_t3 x) {
+  return __builtin_elementwise_popcount(x);
+}
 _HLSL_AVAILABILITY(shadermodel, 6.2)
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-int16_t4 countbits(int16_t4);
+constexpr uint4 countbits(int16_t4 x) {
+  return __builtin_elementwise_popcount(x);
+}
 _HLSL_AVAILABILITY(shadermodel, 6.2)
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-uint16_t countbits(uint16_t);
+constexpr uint countbits(uint16_t x) {
+  return __builtin_elementwise_popcount(x);
+}
 _HLSL_AVAILABILITY(shadermodel, 6.2)
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-uint16_t2 countbits(uint16_t2);
+constexpr uint2 countbits(uint16_t2 x) {
+  return __builtin_elementwise_popcount(x);
+}
 _HLSL_AVAILABILITY(shadermodel, 6.2)
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-uint16_t3 countbits(uint16_t3);
+constexpr uint3 countbits(uint16_t3 x) {
+  return __builtin_elementwise_popcount(x);
+}
 _HLSL_AVAILABILITY(shadermodel, 6.2)
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-uint16_t4 countbits(uint16_t4);
+constexpr uint4 countbits(uint16_t4 x) {
+  return __builtin_elementwise_popcount(x);
+}
 #endif
 
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-int countbits(int);
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-int2 countbits(int2);
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-int3 countbits(int3);
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-int4 countbits(int4);
-
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-uint countbits(uint);
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-uint2 countbits(uint2);
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-uint3 countbits(uint3);
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-uint4 countbits(uint4);
-
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-int64_t countbits(int64_t);
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-int64_t2 countbits(int64_t2);
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-int64_t3 countbits(int64_t3);
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-int64_t4 countbits(int64_t4);
-
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-uint64_t countbits(uint64_t);
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-uint64_t2 countbits(uint64_t2);
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-uint64_t3 countbits(uint64_t3);
-_HLSL_BUILTIN_ALIAS(__builtin_elementwise_popcount)
-uint64_t4 countbits(uint64_t4);
+constexpr uint countbits(int x) {
+  return __builtin_elementwise_popcount(x);
+}  
+constexpr uint2 countbits(int2 x) {
+  return __builtin_elementwise_popcount(x);
+}
+constexpr uint3 countbits(int3 x) {
+  return __builtin_elementwise_popcount(x);
+}
+constexpr uint4 countbits(int4 x) {
+  return __builtin_elementwise_popcount(x);
+}
+
+constexpr uint countbits(uint x) {
+  return __builtin_elementwise_popcount(x);
+}
+constexpr uint2 countbits(uint2 x) {
+  return __builtin_elementwise_popcount(x);
+}
+constexpr uint3 countbits(uint3 x) {
+  return __builtin_elementwise_popcount(x);
+}
+constexpr uint4 countbits(uint4 x) {
+  return __builtin_elementwise_popcount(x);
+}
+
+constexpr uint countbits(int64_t x) {
+  return __builtin_elementwise_popcount(x);
+}
+constexpr uint2 countbits(int64_t2 x) {
+  return __builtin_elementwise_popcount(x);
+}
+constexpr uint3 countbits(int64_t3 x) {
+  return __builtin_elementwise_popcount(x);
+}
+constexpr uint4 countbits(int64_t4 x) {
+  return 

[clang] [Wunsafe-buffer-usage] False positives for & expression indexing constant size array (arr[anything & 0]) (PR #112284)

2024-10-28 Thread Malavika Samak via cfe-commits


@@ -427,6 +427,48 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
   //-  e. g. "Try harder to find a NamedDecl to point at in the note."
   //already duplicated
   //  - call both from Sema and from here
+  std::function
+  SafeMaskedAccess;
+  unsigned int RecLimit = 5;
+
+  SafeMaskedAccess = [&](const Expr *exp, unsigned int RecLimit) -> 
llvm::APInt {
+llvm::APInt Max = 
llvm::APInt::getMaxValue(Finder->getASTContext().getIntWidth(exp->getType()));
+Max.setAllBits();
+
+if (RecLimit == 0)
+  return Max;
+
+//RecLimit--;
+
+if (const auto *IntLit = dyn_cast(exp)) {
+  const APInt ArrIdx = IntLit->getValue();
+  return ArrIdx;
+}
+
+if (const auto *BinEx = dyn_cast(exp)) {
+  llvm::APInt LHS = SafeMaskedAccess(BinEx->getLHS()->IgnoreParenCasts(), 
RecLimit);
+  llvm::APInt RHS = SafeMaskedAccess(BinEx->getRHS()->IgnoreParenCasts(), 
RecLimit);

malavikasamak wrote:

The code has now re-organized with ASTVisitors. I don't think casts should pose 
a major challenges anymore, but please let me know if you think otherwise. Also 
have added more type cast tests to cover all bases. 

https://github.com/llvm/llvm-project/pull/112284
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [rtsan][NFC] Add documentation link to Function Effects (PR #113979)

2024-10-28 Thread via cfe-commits

https://github.com/Sirraide commented:

Effects paragraph lgtm. I’m not really familiar w/ rtsan, so I can’t comment on 
the rest.

https://github.com/llvm/llvm-project/pull/113979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Add clang/docs/FunctionEffectAnalysis.rst. (PR #109855)

2024-10-28 Thread via cfe-commits

Sirraide wrote:

@dougsonos Now that this document exists, we should also update the function 
effects release note that the part 2 pr added to include a link to it. đź‘€

https://github.com/llvm/llvm-project/pull/109855
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [InstrPGO] Instrument sampling profile based cold function v2 (PR #110330)

2024-10-28 Thread Lei Wang via cfe-commits

https://github.com/wlei-llvm closed 
https://github.com/llvm/llvm-project/pull/110330
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [rtsan][NFC] Add documentation link to Function Effects (PR #113979)

2024-10-28 Thread Chris Apple via cfe-commits


@@ -11,11 +11,16 @@ RealtimeSanitizer (a.k.a. RTSan) is a real-time safety 
testing tool for C and C+
 projects. RTSan can be used to detect real-time violations, i.e. calls to 
methods
 that are not safe for use in functions with deterministic run time 
requirements.
 RTSan considers any function marked with the ``[[clang::nonblocking]]`` 
attribute
-to be a real-time function. If RTSan detects a call to ``malloc``, ``free``,
-``pthread_mutex_lock``, or anything else that could have a non-deterministic
-execution time in a function marked ``[[clang::nonblocking]]``
+to be a real-time function. At run-time, if RTSan detects a call to 
``malloc``, 
+``free``, ``pthread_mutex_lock``, or anything else that could have a 
+non-deterministic execution time in a function marked 
``[[clang::nonblocking]]``

cjappl wrote:

I agree, let me fix this in a future PR if that is alright - I want to keep 
this one focused.

The only non-whitespace change in this paragraph is the addition of "At 
run-time" the rest is git having problems with the new line breaks

https://github.com/llvm/llvm-project/pull/113979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC] Delete unused clang-formatted-file.txt/ClangFormattedStatus.rst files (PR #109220)

2024-10-28 Thread Rahul Joshi via cfe-commits

jurahul wrote:

@AaronBallman can you PTAL?

https://github.com/llvm/llvm-project/pull/109220
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-28 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated 
https://github.com/llvm/llvm-project/pull/113859

>From 8fce7f69eb5e28f6ec648ee0dc4cc23c793f64c0 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 27 Oct 2024 21:43:24 -0700
Subject: [PATCH 1/3] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of
 a raw pointer/reference when the guardian variable gets mutated.

This checker has a notion of a guardian variable which is a variable and keeps 
the object pointed to by a raw pointer /
reference in an inner scope alive long enough to "guard" it from 
use-after-free. But such a guardian variable fails to
flawed to keep the object alive if it ever gets mutated within the scope of a 
raw pointer / reference.

This PR fixes this bug by introducing a new AST visitor class, GuardianVisitor, 
which traverses the compound statements
of a guarded variable (raw pointer / reference) and looks for any operator=, 
move constructor, or calls to "swap",
"leakRef", or "releaseNonNull" functions.
---
 .../WebKit/UncountedLocalVarsChecker.cpp  | 72 +--
 .../Analysis/Checkers/WebKit/mock-types.h | 34 -
 .../Checkers/WebKit/uncounted-local-vars.cpp  | 59 +++
 3 files changed, 159 insertions(+), 6 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
index 5cdf047738abcb..5f5fb6e2bf1f87 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
@@ -48,6 +48,65 @@ bool isRefcountedStringsHack(const VarDecl *V) {
   return false;
 }
 
+struct GuardianVisitor : public RecursiveASTVisitor {
+  using Base = RecursiveASTVisitor;
+
+  const VarDecl *Guardian { nullptr };
+
+public:
+  explicit GuardianVisitor(const VarDecl *Guardian)
+  : Guardian(Guardian) {
+assert(Guardian);
+  }
+
+  bool VisitBinaryOperator(const BinaryOperator *BO) {
+if (BO->isAssignmentOp()) {
+  if (auto *VarRef = dyn_cast(BO->getLHS())) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXConstructExpr(const CXXConstructExpr* CE) {
+if (auto *Ctor = CE->getConstructor()) {
+  if (Ctor->isMoveConstructor() && CE->getNumArgs() == 1) {
+auto *Arg = CE->getArg(0)->IgnoreParenCasts();
+if (auto *VarRef = dyn_cast(Arg)) {
+  if (VarRef->getDecl() == Guardian)
+return false;
+}
+  }
+}
+return true;
+  }
+
+  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr* MCE) {
+auto MethodName = safeGetName(MCE->getMethodDecl());
+if (MethodName == "swap" || MethodName == "leakRef" ||
+MethodName == "releaseNonNull") {
+  auto *ThisArg = MCE->getImplicitObjectArgument()->IgnoreParenCasts();
+  if (auto *VarRef = dyn_cast(ThisArg)) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr* OCE) {
+if (OCE->isAssignmentOp() && OCE->getNumArgs() == 2) {
+  auto *ThisArg = OCE->getArg(0)->IgnoreParenCasts();
+  if (auto *VarRef = dyn_cast(ThisArg)) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+};
+
 bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl *Guarded,
const VarDecl *MaybeGuardian) {
   assert(Guarded);
@@ -81,7 +140,7 @@ bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl 
*Guarded,
 
   // We need to skip the first CompoundStmt to avoid situation when guardian is
   // defined in the same scope as guarded variable.
-  bool HaveSkippedFirstCompoundStmt = false;
+  const CompoundStmt *FirstCompondStmt = nullptr;
   for (DynTypedNodeList guardedVarAncestors = ctx.getParents(*Guarded);
!guardedVarAncestors.empty();
guardedVarAncestors = ctx.getParents(
@@ -90,12 +149,15 @@ bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl 
*Guarded,
   ) {
 for (auto &guardedVarAncestor : guardedVarAncestors) {
   if (auto *CStmtAncestor = guardedVarAncestor.get()) {
-if (!HaveSkippedFirstCompoundStmt) {
-  HaveSkippedFirstCompoundStmt = true;
+if (!FirstCompondStmt) {
+  FirstCompondStmt = CStmtAncestor;
   continue;
 }
-if (CStmtAncestor == guardiansClosestCompStmtAncestor)
-  return true;
+if (CStmtAncestor == guardiansClosestCompStmtAncestor) {
+  GuardianVisitor guardianVisitor(MaybeGuardian);
+  auto *GuardedScope = const_cast(FirstCompondStmt);
+  return guardianVisitor.TraverseCompoundStmt(GuardedScope);
+}
   }
 }
   }
diff --git a/clang/test/Analysis/Checkers/WebKit/mock-types.h 
b/clang/test/Analysis/Checkers/WebKit/mock-types.h
index 8d8a90f0afae0e..82c79c97a83de6 100644

[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-28 Thread Ryosuke Niwa via cfe-commits


@@ -83,6 +83,65 @@ void foo7(RefCountable* obj) {
   bar.obj->method();
 }
 
+void foo8(RefCountable* obj) {
+  RefPtr foo;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo = nullptr;
+bar->method();
+  }
+  RefPtr baz;
+  {
+RefCountable *bar = baz.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+baz = obj;
+bar->method();
+  }
+  foo = nullptr;
+  {
+RefCountable *bar = foo.get();
+// No warning. It's okay to mutate RefPtr in an outer scope.
+bar->method();
+  }
+  foo = obj;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo.releaseNonNull();
+bar->method();
+  }
+}
+
+void foo9(RefCountable& o) {
+  Ref guardian(o);
+  {
+RefCountable &bar = guardian.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian = o; // We don't detect that we're setting it to the same value.
+bar.method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(*bar); // We don't detect other has the same value 
as guardian.
+guardian.swap(other);
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(static_cast&&>(guardian));
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian.leakRef();
+bar->method();
+  }
+}

rniwa wrote:

Added

https://github.com/llvm/llvm-project/pull/113859
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [rtsan][NFC] Add documentation link to Function Effects (PR #113979)

2024-10-28 Thread Florian Mayer via cfe-commits

https://github.com/fmayer approved this pull request.


https://github.com/llvm/llvm-project/pull/113979
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-28 Thread Ryosuke Niwa via cfe-commits


@@ -48,6 +48,64 @@ bool isRefcountedStringsHack(const VarDecl *V) {
   return false;
 }
 
+struct GuardianVisitor : public RecursiveASTVisitor {
+  using Base = RecursiveASTVisitor;
+
+  const VarDecl *Guardian{nullptr};
+
+public:
+  explicit GuardianVisitor(const VarDecl *Guardian) : Guardian(Guardian) {
+assert(Guardian);
+  }
+
+  bool VisitBinaryOperator(const BinaryOperator *BO) {
+if (BO->isAssignmentOp()) {
+  if (auto *VarRef = dyn_cast(BO->getLHS())) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXConstructExpr(const CXXConstructExpr *CE) {
+if (auto *Ctor = CE->getConstructor()) {
+  if (Ctor->isMoveConstructor() && CE->getNumArgs() == 1) {
+auto *Arg = CE->getArg(0)->IgnoreParenCasts();
+if (auto *VarRef = dyn_cast(Arg)) {
+  if (VarRef->getDecl() == Guardian)
+return false;
+}
+  }
+}
+return true;
+  }
+
+  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) {
+auto MethodName = safeGetName(MCE->getMethodDecl());
+if (MethodName == "swap" || MethodName == "leakRef" ||
+MethodName == "releaseNonNull") {
+  auto *ThisArg = MCE->getImplicitObjectArgument()->IgnoreParenCasts();
+  if (auto *VarRef = dyn_cast(ThisArg)) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE) {
+if (OCE->isAssignmentOp() && OCE->getNumArgs() == 2) {

rniwa wrote:

Removed and added an assertion instead.

https://github.com/llvm/llvm-project/pull/113859
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Remove Linux search paths on Windows (PR #113628)

2024-10-28 Thread David Salinas via cfe-commits

https://github.com/david-salinas updated 
https://github.com/llvm/llvm-project/pull/113628

>From 44f610ead0ec6e497f16771234067e7d96460666 Mon Sep 17 00:00:00 2001
From: David Salinas 
Date: Tue, 22 Oct 2024 18:58:47 +
Subject: [PATCH] Remove Linux search paths on Windows

Change-Id: Ia0b44eb1069fa631a6d5156cf5881c978e23b62d
---
 clang/lib/Driver/Driver.cpp  |  6 ++---
 clang/lib/Driver/ToolChains/AMDGPU.cpp   | 27 
 clang/lib/Driver/ToolChains/AMDGPU.h |  2 +-
 clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp |  2 +-
 clang/lib/Driver/ToolChains/Gnu.cpp  |  1 +
 clang/lib/Driver/ToolChains/HIPAMD.cpp   |  8 +-
 clang/lib/Driver/ToolChains/MSVC.cpp |  5 
 clang/lib/Driver/ToolChains/ROCm.h   | 12 +
 clang/test/Driver/rocm-detect-linux.hip  |  9 +++
 clang/test/Driver/rocm-detect-windows.hip|  9 +++
 10 files changed, 65 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/Driver/rocm-detect-linux.hip
 create mode 100644 clang/test/Driver/rocm-detect-windows.hip

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 9878a9dad78d40..2be0d04d1c5ddf 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -6440,7 +6440,7 @@ const ToolChain &Driver::getToolChain(const ArgList &Args,
   TC = std::make_unique(*this, Target, Args);
   break;
 case llvm::Triple::AMDHSA:
-  TC = std::make_unique(*this, Target, Args);
+  TC = std::make_unique(*this, Target, Args, 
Target.isWindowsMSVCEnvironment());
   break;
 case llvm::Triple::AMDPAL:
 case llvm::Triple::Mesa3D:
@@ -6582,8 +6582,8 @@ const ToolChain &Driver::getOffloadingDeviceToolChain(
 TC = std::make_unique(*this, Target,
HostTC, Args);
   else if (Target.getArch() == llvm::Triple::spirv64 &&
-   Target.getVendor() == llvm::Triple::UnknownVendor &&
-   Target.getOS() == llvm::Triple::UnknownOS)
+ Target.getVendor() == llvm::Triple::UnknownVendor &&
+ Target.getOS() == llvm::Triple::UnknownOS)
 TC = std::make_unique(*this, Target,
HostTC, Args);
   break;
diff --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index 2c85d21ebd738c..07f340ea425127 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -306,15 +306,18 @@ RocmInstallationDetector::getInstallationPathCandidates() 
{
   LatestVer = Ver;
 }
   }
+
+ if (!isHostWindows()) {
   if (!LatestROCm.empty())
 ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/" + LatestROCm,
 /*StrictChecking=*/true);
 
-  ROCmSearchDirs.emplace_back(D.SysRoot + "/usr/local",
-  /*StrictChecking=*/true);
-  ROCmSearchDirs.emplace_back(D.SysRoot + "/usr",
-  /*StrictChecking=*/true);
-
+ROCmSearchDirs.emplace_back(D.SysRoot + "/usr/local",
+/*StrictChecking=*/true);
+ROCmSearchDirs.emplace_back(D.SysRoot + "/usr",
+/*StrictChecking=*/true);
+ }
+  
   DoPrintROCmSearchDirs();
   return ROCmSearchDirs;
 }
@@ -376,10 +379,10 @@ RocmInstallationDetector::RocmInstallationDetector(
   .str();
   }
 
-  if (DetectHIPRuntime)
-detectHIPRuntime();
-  if (DetectDeviceLib)
-detectDeviceLibrary();
+  // Windows needs to exclude linux style paths from the list of paths to 
search,
+  // so delay these detection functions until after the constructor
+
+
 }
 
 void RocmInstallationDetector::detectDeviceLibrary() {
@@ -703,6 +706,7 @@ AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const 
llvm::Triple &Triple,
 : Generic_ELF(D, Triple, Args),
   OptionsDefault(
   {{options::OPT_O, "3"}, {options::OPT_cl_std_EQ, "CL1.2"}}) {
+  RocmInstallation->init();
   // Check code object version options. Emit warnings for legacy options
   // and errors for the last invalid code object version options.
   // It is done here to avoid repeated warning or error messages for
@@ -835,8 +839,11 @@ bool AMDGPUToolChain::isWave64(const llvm::opt::ArgList 
&DriverArgs,
 
 /// ROCM Toolchain
 ROCMToolChain::ROCMToolChain(const Driver &D, const llvm::Triple &Triple,
- const ArgList &Args)
+ const ArgList &Args, bool isHostTCMSVC)
 : AMDGPUToolChain(D, Triple, Args) {
+  RocmInstallation->setHostWindows(isHostTCMSVC);
+  if (isHostTCMSVC) 
+RocmInstallation->init(true, false);
   RocmInstallation->detectDeviceLibrary();
 }
 
diff --git a/clang/lib/Driver/ToolChains/AMDGPU.h 
b/clang/lib/Driver/ToolChains/AMDGPU.h
index a9b4552a1f91a4..db08529f955168 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.h
+++ b/clang/lib/Driver/

[clang] b46a048 - [clang][bytecode] Implement __builtin_arithmetic_fence (#113937)

2024-10-28 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-10-29T00:56:03+01:00
New Revision: b46a0482f9e4c0ee82b38da794b20f8f1a76f044

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

LOG: [clang][bytecode] Implement __builtin_arithmetic_fence (#113937)

Added: 


Modified: 
clang/lib/AST/ByteCode/InterpBuiltin.cpp
clang/test/Sema/arithmetic-fence-builtin.c

Removed: 




diff  --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 10e33c14f4b455..b00d2a1768b6b7 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1670,6 +1670,15 @@ static bool interp__builtin_operator_delete(InterpState 
&S, CodePtr OpPC,
   S, OpPC, *AllocForm, DynamicAllocator::Form::Operator, BlockDesc, 
Source);
 }
 
+static bool interp__builtin_arithmetic_fence(InterpState &S, CodePtr OpPC,
+ const InterpFrame *Frame,
+ const Function *Func,
+ const CallExpr *Call) {
+  const Floating &Arg0 = S.Stk.peek();
+  S.Stk.push(Arg0);
+  return true;
+}
+
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call, uint32_t BuiltinID) {
   const InterpFrame *Frame = S.Current;
@@ -2111,6 +2120,11 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, 
const Function *F,
   return false;
 break;
 
+  case Builtin::BI__arithmetic_fence:
+if (!interp__builtin_arithmetic_fence(S, OpPC, Frame, F, Call))
+  return false;
+break;
+
   default:
 S.FFDiag(S.Current->getLocation(OpPC),
  diag::note_invalid_subexpr_in_const_expr)

diff  --git a/clang/test/Sema/arithmetic-fence-builtin.c 
b/clang/test/Sema/arithmetic-fence-builtin.c
index a1941970edb53c..55867ffb5e012c 100644
--- a/clang/test/Sema/arithmetic-fence-builtin.c
+++ b/clang/test/Sema/arithmetic-fence-builtin.c
@@ -1,8 +1,13 @@
 // RUN: %clang_cc1 -triple i386-pc-linux-gnu -emit-llvm -o - -verify -x c++ %s
+// RUN: %clang_cc1 -triple i386-pc-linux-gnu -emit-llvm -o - -verify -x c++ %s 
-fexperimental-new-constant-interpreter
 // RUN: %clang_cc1 -triple ppc64le -DPPC -emit-llvm -o - -verify -x c++ %s
+// RUN: %clang_cc1 -triple ppc64le -DPPC -emit-llvm -o - -verify -x c++ %s 
-fexperimental-new-constant-interpreter
 // RUN: not %clang_cc1 -triple ppc64le -DPPC -emit-llvm -o - -x c++ %s \
 // RUN:-fprotect-parens 2>&1 | FileCheck -check-prefix=PPC %s
+// RUN: not %clang_cc1 -triple ppc64le -DPPC -emit-llvm -o - -x c++ %s 
-fexperimental-new-constant-interpreter \
+// RUN:-fprotect-parens 2>&1 | FileCheck -check-prefix=PPC %s
 // RUN: %clang_cc1 -triple spir64 -emit-llvm -o - -verify -x c++ %s
+// RUN: %clang_cc1 -triple spir64 -emit-llvm -o - -verify -x c++ %s 
-fexperimental-new-constant-interpreter
 #ifndef PPC
 int v;
 template  T addT(T a, T b) {



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


[clang] [clang][bytecode] Implement __builtin_arithmetic_fence (PR #113937)

2024-10-28 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr closed 
https://github.com/llvm/llvm-project/pull/113937
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-28 Thread Rashmi Mudduluru via cfe-commits


@@ -83,6 +83,77 @@ void foo7(RefCountable* obj) {
   bar.obj->method();
 }
 
+void foo8(RefCountable* obj) {
+  RefPtr foo;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo = nullptr;
+bar->method();
+  }
+  RefPtr baz;
+  {
+RefCountable *bar = baz.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+baz = obj;
+bar->method();
+  }
+  foo = nullptr;
+  {
+RefCountable *bar = foo.get();
+// No warning. It's okay to mutate RefPtr in an outer scope.
+bar->method();
+  }
+  foo = obj;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo.releaseNonNull();
+bar->method();
+  }
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo = obj ? obj : nullptr;
+bar->method();
+  }
+}
+
+void foo9(RefCountable& o) {
+  Ref guardian(o);
+  {
+RefCountable &bar = guardian.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian = o; // We don't detect that we're setting it to the same value.
+bar.method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(*bar); // We don't detect other has the same value 
as guardian.
+guardian.swap(other);
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(static_cast&&>(guardian));
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian.leakRef();
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian = o.trivial() ? o : *bar;

t-rasmud wrote:

Since `guardian` is mutated here, should we also have an `// expected-warning` 
on this line too?

https://github.com/llvm/llvm-project/pull/113859
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [HLSL][SPIRV] Added clamp intrinsic (PR #113394)

2024-10-28 Thread Adam Yang via cfe-commits


@@ -83,12 +83,210 @@ entry:
   ret i64 %0
 }
 
-declare half @llvm.dx.clamp.f16(half, half, half)
-declare float @llvm.dx.clamp.f32(float, float, float)
-declare double @llvm.dx.clamp.f64(double, double, double)
-declare i16 @llvm.dx.clamp.i16(i16, i16, i16)
-declare i32 @llvm.dx.clamp.i32(i32, i32, i32)
-declare i64 @llvm.dx.clamp.i64(i64, i64, i64)
+declare half @llvm.dx.nclamp.f16(half, half, half)

adam-yang wrote:

Done.

https://github.com/llvm/llvm-project/pull/113394
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] First run at removing the linked-list for decls. Tests not run, but … (PR #113983)

2024-10-28 Thread Erich Keane via cfe-commits

https://github.com/erichkeane created 
https://github.com/llvm/llvm-project/pull/113983

…it builds

Note: this is a Draft until i can pass testing, clean this up, and figure out 
if this is of perf benefit.  This is #2 here: 
https://github.com/llvm/llvm-project/issues/113950


>From 09c1c890394ecaa66b20cd933ba0d85c2141e34f Mon Sep 17 00:00:00 2001
From: erichkeane 
Date: Mon, 28 Oct 2024 17:00:38 -0700
Subject: [PATCH] First run at removing the linked-list for decls.  Tests not
 run, but it builds

---
 clang/include/clang/AST/Decl.h |   4 +-
 clang/include/clang/AST/DeclBase.h |  70 +++-
 clang/include/clang/AST/DeclCXX.h  |   2 +-
 clang/lib/AST/Decl.cpp |  37 --
 clang/lib/AST/DeclBase.cpp | 173 ++---
 clang/lib/AST/DeclPrinter.cpp  |   6 +-
 6 files changed, 188 insertions(+), 104 deletions(-)

diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 7ff35d73df5997..641f790c67824f 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -4893,7 +4893,9 @@ class ExportDecl final : public Decl, public DeclContext {
   return RBraceLoc;
 // No braces: get the end location of the (only) declaration in context
 // (if present).
-return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
+// TODO: ERICH: is this going to be a problem?  Previous iterator did a
+// double-dereference, which doesn't seem right.
+return decls_empty() ? getLocation() : (*decls_begin())->getEndLoc();
   }
 
   SourceRange getSourceRange() const override LLVM_READONLY {
diff --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index a3447d19909752..3c53658ecd41af 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -240,14 +240,6 @@ class alignas(8) Decl {
 ModulePrivate
   };
 
-protected:
-  /// The next declaration within the same lexical
-  /// DeclContext. These pointers form the linked list that is
-  /// traversed via DeclContext's decls_begin()/decls_end().
-  ///
-  /// The extra three bits are used for the ModuleOwnershipKind.
-  llvm::PointerIntPair NextInContextAndBits;
-
 private:
   friend class DeclContext;
 
@@ -351,6 +343,13 @@ class alignas(8) Decl {
   LLVM_PREFERRED_TYPE(Linkage)
   mutable unsigned CacheValidAndLinkage : 3;
 
+  // TODO: ERICH: Does this have to be protected? The PointerIntPair was, but 
it
+  // isn't clear that is necessary.
+  /// Kind of ownership the declaration has, for visibility purposes. See
+  /// declaration of `ModuleOwnershipKind`.
+  LLVM_PREFERRED_TYPE(ModuleOwnershipKind)
+  unsigned ModuleOwnership : 3;
+
   /// Allocate memory for a deserialized declaration.
   ///
   /// This routine must be used to allocate memory for any declaration that is
@@ -394,12 +393,12 @@ class alignas(8) Decl {
 
 protected:
   Decl(Kind DK, DeclContext *DC, SourceLocation L)
-  : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
-DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
+  : DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
 Implicit(false), Used(false), Referenced(false),
 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
-CacheValidAndLinkage(llvm::to_underlying(Linkage::Invalid)) {
+CacheValidAndLinkage(llvm::to_underlying(Linkage::Invalid)),
+
ModuleOwnership(static_cast(getModuleOwnershipKindForChildOf(DC))) {
 if (StatisticsEnabled) add(DK);
   }
 
@@ -449,8 +448,9 @@ class alignas(8) Decl {
   Kind getKind() const { return static_cast(DeclKind); }
   const char *getDeclKindName() const;
 
-  Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
-  const Decl *getNextDeclInContext() const {return 
NextInContextAndBits.getPointer();}
+  //TODO: ERICH: figure out how necessary these are? Can be implemented 
'dumb-ly'
+  //Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
+  //const Decl *getNextDeclInContext() const {return 
NextInContextAndBits.getPointer();}
 
   DeclContext *getDeclContext() {
 if (isInSemaDC())
@@ -867,7 +867,7 @@ class alignas(8) Decl {
 
   /// Get the kind of module ownership for this declaration.
   ModuleOwnershipKind getModuleOwnershipKind() const {
-return NextInContextAndBits.getInt();
+return static_cast(ModuleOwnership);
   }
 
   /// Set whether this declaration is hidden from name lookup.
@@ -876,7 +876,7 @@ class alignas(8) Decl {
  MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&
  !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration");
-NextInContextAndBits.setInt(MOK);
+ModuleOwnership = static_cast(MOK);
   }
 
   unsigned getIdentifierNamespace() const {
@@ -2060,19 +20

[clang] First run at removing the linked-list for decls. Tests not run, but … (PR #113983)

2024-10-28 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff 19131c7f36e047898ea954ee5a187ac62f2ab09b 
09c1c890394ecaa66b20cd933ba0d85c2141e34f --extensions h,cpp -- 
clang/include/clang/AST/Decl.h clang/include/clang/AST/DeclBase.h 
clang/include/clang/AST/DeclCXX.h clang/lib/AST/Decl.cpp 
clang/lib/AST/DeclBase.cpp clang/lib/AST/DeclPrinter.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index 3c53658ecd..f58f4f21bb 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -398,7 +398,8 @@ protected:
 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
 CacheValidAndLinkage(llvm::to_underlying(Linkage::Invalid)),
-
ModuleOwnership(static_cast(getModuleOwnershipKindForChildOf(DC))) {
+ModuleOwnership(
+static_cast(getModuleOwnershipKindForChildOf(DC))) {
 if (StatisticsEnabled) add(DK);
   }
 
@@ -448,9 +449,10 @@ public:
   Kind getKind() const { return static_cast(DeclKind); }
   const char *getDeclKindName() const;
 
-  //TODO: ERICH: figure out how necessary these are? Can be implemented 
'dumb-ly'
-  //Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
-  //const Decl *getNextDeclInContext() const {return 
NextInContextAndBits.getPointer();}
+  // TODO: ERICH: figure out how necessary these are? Can be implemented
+  // 'dumb-ly' Decl *getNextDeclInContext() { return
+  // NextInContextAndBits.getPointer(); } const Decl *getNextDeclInContext()
+  // const {return NextInContextAndBits.getPointer();}
 
   DeclContext *getDeclContext() {
 if (isInSemaDC())
@@ -2060,21 +2062,21 @@ protected:
 
   /// FirstDecl - The first declaration stored within this declaration
   /// context.
-  ///mutable Decl *FirstDecl = nullptr;
+  /// mutable Decl *FirstDecl = nullptr;
 
   /// LastDecl - The last declaration stored within this declaration
   /// context. FIXME: We could probably cache this value somewhere
   /// outside of the DeclContext, to reduce the size of DeclContext by
   /// another pointer.
-  ///mutable Decl *LastDecl = nullptr;
+  /// mutable Decl *LastDecl = nullptr;
 
   /// Build up a chain of declarations.
   ///
   /// \returns the first/last pair of declarations.
   // TODO: ERICH: this ends up being just a filter if it doesn't need to update
   // next decl.
-  //static std::pair
-  //BuildDeclChain(ArrayRef Decls, bool FieldsAlreadyLoaded);
+  // static std::pair
+  // BuildDeclChain(ArrayRef Decls, bool FieldsAlreadyLoaded);
 
   DeclContext(Decl::Kind K);
 
@@ -2308,63 +2310,62 @@ public:
   void collectAllContexts(SmallVectorImpl &Contexts);
 
   // TODO: ERICH: Remove
-/*
-  /// decl_iterator - Iterates through the declarations stored
-  /// within this context.
-  class decl_iterator {
-/// Current - The current declaration.
-Decl *Current = nullptr;
-
-  public:
-using value_type = Decl *;
-using reference = const value_type &;
-using pointer = const value_type *;
-using iterator_category = std::forward_iterator_tag;
-using difference_type = std::ptrdiff_t;
-
-decl_iterator() = default;
-explicit decl_iterator(Decl *C) : Current(C) {}
-
-reference operator*() const { return Current; }
-
-// This doesn't meet the iterator requirements, but it's convenient
-value_type operator->() const { return Current; }
-
-decl_iterator& operator++() {
-  Current = Current->getNextDeclInContext();
-  return *this;
-}
-
-decl_iterator operator++(int) {
-  decl_iterator tmp(*this);
-  ++(*this);
-  return tmp;
-}
-
-friend bool operator==(decl_iterator x, decl_iterator y) {
-  return x.Current == y.Current;
-}
-
-friend bool operator!=(decl_iterator x, decl_iterator y) {
-  return x.Current != y.Current;
-}
-  };
-  */
+  /*
+/// decl_iterator - Iterates through the declarations stored
+/// within this context.
+class decl_iterator {
+  /// Current - The current declaration.
+  Decl *Current = nullptr;
+
+public:
+  using value_type = Decl *;
+  using reference = const value_type &;
+  using pointer = const value_type *;
+  using iterator_category = std::forward_iterator_tag;
+  using difference_type = std::ptrdiff_t;
+
+  decl_iterator() = default;
+  explicit decl_iterator(Decl *C) : Current(C) {}
+
+  reference operator*() const { return Current; }
+
+  // This doesn't meet the iterator requirements, but it's convenient
+  value_type operator->() const { return Current; }
+
+  decl_iterator& operator++() {
+Current = Current->getNextDeclInContext();
+return *this;

[clang] First run at removing the linked-list for decls. Tests not run, but … (PR #113983)

2024-10-28 Thread Erich Keane via cfe-commits

erichkeane wrote:

Clang format fails, I expected this, there is a ton of TODOs, commented out 
code, etc anyway, so I'll fix that after this 'proof of concept' shows promise.

https://github.com/llvm/llvm-project/pull/113983
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][ExprConst] Reject field access with nullptr base (PR #113885)

2024-10-28 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr edited 
https://github.com/llvm/llvm-project/pull/113885
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Clang tooling generated visibility macros for Clang (PR #109702)

2024-10-28 Thread Tom Stellard via cfe-commits

tstellar wrote:

Is there any reason why the tool should be in the monorepo and not some other 
repository?

Also, as for keeping the annotations up-to-date.  My recommendation is to add a 
github action job that runs the ids tool and then submits a pull request for 
any necessary changes.   We could run it automatically once a day to start.

https://github.com/llvm/llvm-project/pull/109702
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] Avoid allocations when reading blob paths (PR #113984)

2024-10-28 Thread Jan Svoboda via cfe-commits

https://github.com/jansvoboda11 created 
https://github.com/llvm/llvm-project/pull/113984

When reading a path from a bitstream blob, `ASTReader` performs up to three 
allocations:
 1. Conversion of the `StringRef` blob into `std::string` to conform to the 
`ASTReader::ResolveImportedPath()` API that takes `std::string &`.
 2. Concatenation of the module file prefix directory and the relative path 
into a fresh `SmallString<128>` buffer in `ASTReader::ResolveImportedPath()`.
 3. Propagating the result out of `ASTReader::ResolveImportedPath()` by calling 
`std::string::assign()` on the out-parameter.

 This patch makes is so that we avoid allocations altogether (amortized) by:
 1. Avoiding conversion of the `StringRef` blob into `std::string` and changing 
the `ASTReader::ResolveImportedPath()` API.
 2. Using one "global" buffer to hold the concatenation.
 3. Returning `StringRef` pointing into the buffer and being careful to not 
store this anywhere where it can outlive the underlying global buffer contents.

Note that in some places of the bitstream we don't store paths as blobs, but 
rather as records that get VBR-encoded. This makes the allocation in (1) 
unavoidable. I plan to fix this in a follow-up PR by changing the PCM format.

Moreover, there are some data structures (e.g. `serialization::InputFileInfo`) 
that store deserialized and resolved paths as `std::string`. If we don't access 
them frequently, it would be more efficient to store just the unresolved 
`StringRef` and resolve them on demand (within some kind of shared buffer to 
prevent allocations).

 This PR alone improves `clang-scan-deps` performance on my workload by _TBD_%.

>From 709cc1c8c41603c4d9eb637cb0453521029af201 Mon Sep 17 00:00:00 2001
From: Jan Svoboda 
Date: Mon, 28 Oct 2024 16:59:13 -0700
Subject: [PATCH] [clang][modules] Avoid allocations when reading blob paths

When reading paths from bitstream blobs, `ASTReader` always performs up to 
three allocations:
 1. Convert the `StringRef` blob to `std::string` right away.
 2. Concatenate the module file prefix directory and the relative path within 
`ASTReader::ResolveImportedPath()`.
 3. Call `std::string::assign()` on the allocated blob with the concatenation 
result.

 This patch makes is so that we avoid allocations altogether (amortized). This 
works by:
 1. Avoiding conversion of the `StringRef` blob into `std::string`.
 2. Keeping one "global" buffer to perform the concatenation with.
 3. Returning `StringRef` pointing into the global buffer and being careful to 
not store this anywhere where it can outlive the underlying global buffer 
allocation.

 Note that in some places, we don't store paths as blobs, but rather as records 
that get VBR-encoded. This makes the allocation in (1) unavoidable. I plan to 
fix this in a follow-up PR by changing the PCM format to store those as offsets 
into the blob part of the record.

 Similarly, there are some data structures that store the deserialized paths as 
`std::string`. If we don't access them frequently, it might be better to store 
just the unresolved `StringRef` and resolve it on demand, again using some kind 
of shared buffer to prevent allocations.

 This improves `clang-scan-deps` performance on my workload by %.
---
 clang/include/clang/Serialization/ASTReader.h | 17 -
 clang/lib/Serialization/ASTReader.cpp | 70 ---
 2 files changed, 44 insertions(+), 43 deletions(-)

diff --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 070c1c9a54f48c..3c8bef484d0133 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -1341,9 +1341,22 @@ class ASTReader
   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
 bool Complain = true);
 
+  /// Buffer we use as temporary storage backing resolved paths.
+  SmallString<256> PathBuf;
+
 public:
-  void ResolveImportedPath(ModuleFile &M, std::string &Filename);
-  static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
+  StringRef ResolveImportedPath(StringRef Path, ModuleFile &M) {
+return ResolveImportedPath(PathBuf, Path, M);
+  }
+  StringRef ResolveImportedPath(StringRef Path, StringRef Prefix) {
+return ResolveImportedPath(PathBuf, Path, Prefix);
+  }
+  static StringRef ResolveImportedPath(SmallVectorImpl &Buffer,
+   StringRef Path, ModuleFile &M) {
+return ResolveImportedPath(Buffer, Path, M.BaseDirectory);
+  }
+  static StringRef ResolveImportedPath(SmallVectorImpl &Buffer,
+   StringRef Path, StringRef Prefix);
 
   /// Returns the first key declaration for the given declaration. This
   /// is one that is formerly-canonical (or still canonical) and whose module
diff --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 8d8f9378cfeabe..19f7f2

[clang] [clang][modules] Avoid allocations when reading blob paths (PR #113984)

2024-10-28 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-modules

Author: Jan Svoboda (jansvoboda11)


Changes

When reading a path from a bitstream blob, `ASTReader` performs up to three 
allocations:
 1. Conversion of the `StringRef` blob into `std::string` to conform to the 
`ASTReader::ResolveImportedPath()` API that takes `std::string &`.
 2. Concatenation of the module file prefix directory and the relative path 
into a fresh `SmallString<128>` buffer in 
`ASTReader::ResolveImportedPath()`.
 3. Propagating the result out of `ASTReader::ResolveImportedPath()` by calling 
`std::string::assign()` on the out-parameter.

 This patch makes is so that we avoid allocations altogether (amortized) by:
 1. Avoiding conversion of the `StringRef` blob into `std::string` and changing 
the `ASTReader::ResolveImportedPath()` API.
 2. Using one "global" buffer to hold the concatenation.
 3. Returning `StringRef` pointing into the buffer and being careful to not 
store this anywhere where it can outlive the underlying global buffer contents.

Note that in some places of the bitstream we don't store paths as blobs, but 
rather as records that get VBR-encoded. This makes the allocation in (1) 
unavoidable. I plan to fix this in a follow-up PR by changing the PCM format.

Moreover, there are some data structures (e.g. `serialization::InputFileInfo`) 
that store deserialized and resolved paths as `std::string`. If we don't access 
them frequently, it would be more efficient to store just the unresolved 
`StringRef` and resolve them on demand (within some kind of shared buffer to 
prevent allocations).

 This PR alone improves `clang-scan-deps` performance on my workload by _TBD_%.

---
Full diff: https://github.com/llvm/llvm-project/pull/113984.diff


2 Files Affected:

- (modified) clang/include/clang/Serialization/ASTReader.h (+15-2) 
- (modified) clang/lib/Serialization/ASTReader.cpp (+29-41) 


``diff
diff --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 070c1c9a54f48c..3c8bef484d0133 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -1341,9 +1341,22 @@ class ASTReader
   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
 bool Complain = true);
 
+  /// Buffer we use as temporary storage backing resolved paths.
+  SmallString<256> PathBuf;
+
 public:
-  void ResolveImportedPath(ModuleFile &M, std::string &Filename);
-  static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
+  StringRef ResolveImportedPath(StringRef Path, ModuleFile &M) {
+return ResolveImportedPath(PathBuf, Path, M);
+  }
+  StringRef ResolveImportedPath(StringRef Path, StringRef Prefix) {
+return ResolveImportedPath(PathBuf, Path, Prefix);
+  }
+  static StringRef ResolveImportedPath(SmallVectorImpl &Buffer,
+   StringRef Path, ModuleFile &M) {
+return ResolveImportedPath(Buffer, Path, M.BaseDirectory);
+  }
+  static StringRef ResolveImportedPath(SmallVectorImpl &Buffer,
+   StringRef Path, StringRef Prefix);
 
   /// Returns the first key declaration for the given declaration. This
   /// is one that is formerly-canonical (or still canonical) and whose module
diff --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 8d8f9378cfeabe..19f7f2be7f9011 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -2050,8 +2050,7 @@ const FileEntry *HeaderFileInfoTrait::getFile(const 
internal_key_type &Key) {
 return nullptr;
   }
 
-  std::string Resolved = std::string(Key.Filename);
-  Reader.ResolveImportedPath(M, Resolved);
+  StringRef Resolved = Reader.ResolveImportedPath(Key.Filename, M);
   if (auto File = FileMgr.getOptionalFileRef(Resolved))
 return *File;
   return nullptr;
@@ -2150,9 +2149,9 @@ HeaderFileInfoTrait::ReadData(internal_key_ref key, const 
unsigned char *d,
 ModuleMap &ModMap =
 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
 
-std::string Filename = std::string(key.Filename);
+StringRef Filename = key.Filename;
 if (key.Imported)
-  Reader.ResolveImportedPath(M, Filename);
+  Filename = Reader.ResolveImportedPath(Filename, M);
 if (auto FE = FileMgr.getOptionalFileRef(Filename)) {
   // FIXME: NameAsWritten
   Module::Header H = {std::string(key.Filename), "", *FE};
@@ -2520,11 +2519,10 @@ InputFileInfo ASTReader::getInputFileInfo(ModuleFile 
&F, unsigned ID) {
   std::tie(R.FilenameAsRequested, R.Filename) = [&]() {
 uint16_t AsRequestedLength = Record[7];
 
-std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str();
-std::string Name = Blob.substr(AsRequestedLength).str();
-
-ResolveImportedPath(F, NameAsRequested);
-ResolveImportedPath(F, Name);
+std::string NameAsRequested

[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-28 Thread Ryosuke Niwa via cfe-commits


@@ -83,6 +83,77 @@ void foo7(RefCountable* obj) {
   bar.obj->method();
 }
 
+void foo8(RefCountable* obj) {
+  RefPtr foo;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo = nullptr;
+bar->method();
+  }
+  RefPtr baz;
+  {
+RefCountable *bar = baz.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+baz = obj;
+bar->method();
+  }
+  foo = nullptr;
+  {
+RefCountable *bar = foo.get();
+// No warning. It's okay to mutate RefPtr in an outer scope.
+bar->method();
+  }
+  foo = obj;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo.releaseNonNull();
+bar->method();
+  }
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo = obj ? obj : nullptr;
+bar->method();
+  }
+}
+
+void foo9(RefCountable& o) {
+  Ref guardian(o);
+  {
+RefCountable &bar = guardian.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian = o; // We don't detect that we're setting it to the same value.
+bar.method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(*bar); // We don't detect other has the same value 
as guardian.
+guardian.swap(other);
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(static_cast&&>(guardian));
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian.leakRef();
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian = o.trivial() ? o : *bar;

rniwa wrote:

No, the warning is for the unsafe local variable "bar", not about guardian 
variable. Here, we're saying that the use of "bar" is unsafe due to the lack of 
a valid guardian variable.

https://github.com/llvm/llvm-project/pull/113859
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 19131c7 - [clang][modules][lldb] Fix build after #113391

2024-10-28 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2024-10-28T12:50:53-07:00
New Revision: 19131c7f36e047898ea954ee5a187ac62f2ab09b

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

LOG: [clang][modules][lldb] Fix build after #113391

Instead of changing the return type of `ModuleMap::findOrCreateModule`, this 
patch adds a counterpart that only returns `Module *` and thus has the same 
signature as `createModule()`, which is important in `ASTReader`.

Added: 


Modified: 
clang/include/clang/Lex/ModuleMap.h
clang/lib/Lex/ModuleMap.cpp
clang/lib/Serialization/ASTReader.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/ModuleMap.h 
b/clang/include/clang/Lex/ModuleMap.h
index 5ee152e4213abf..53e9e0ec83ddb1 100644
--- a/clang/include/clang/Lex/ModuleMap.h
+++ b/clang/include/clang/Lex/ModuleMap.h
@@ -541,9 +541,17 @@ class ModuleMap {
   ///
   /// \param IsExplicit Whether this is an explicit submodule.
   ///
-  /// \returns The found or newly-created module.
-  Module *findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,
- bool IsExplicit);
+  /// \returns The found or newly-created module, along with a boolean value
+  /// that will be true if the module is newly-created.
+  std::pair findOrCreateModule(StringRef Name, Module *Parent,
+   bool IsFramework,
+   bool IsExplicit);
+  /// Call \c ModuleMap::findOrCreateModule and throw away the information
+  /// whether the module was found or created.
+  Module *findOrCreateModuleFirst(StringRef Name, Module *Parent,
+  bool IsFramework, bool IsExplicit) {
+return findOrCreateModule(Name, Parent, IsFramework, IsExplicit).first;
+  }
   /// Create new submodule, assuming it does not exist. This function can only
   /// be called when it is guaranteed that this submodule does not exist yet.
   /// The parameters have same semantics as \c ModuleMap::findOrCreateModule.

diff  --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index 10774429a2177b..dc9d2bfd5629c9 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -655,8 +655,8 @@ 
ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(FileEntryRef File) {
 SmallString<32> NameBuf;
 StringRef Name = sanitizeFilenameAsIdentifier(
 llvm::sys::path::stem(SkippedDir.getName()), NameBuf);
-Result =
-findOrCreateModule(Name, Result, /*IsFramework=*/false, Explicit);
+Result = findOrCreateModuleFirst(Name, Result, /*IsFramework=*/false,
+ Explicit);
 setInferredModuleAllowedBy(Result, UmbrellaModuleMap);
 
 // Associate the module and the directory.
@@ -672,8 +672,8 @@ 
ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(FileEntryRef File) {
   SmallString<32> NameBuf;
   StringRef Name = sanitizeFilenameAsIdentifier(
  llvm::sys::path::stem(File.getName()), NameBuf);
-  Result =
-  findOrCreateModule(Name, Result, /*IsFramework=*/false, Explicit);
+  Result = findOrCreateModuleFirst(Name, Result, /*IsFramework=*/false,
+   Explicit);
   setInferredModuleAllowedBy(Result, UmbrellaModuleMap);
   Result->addTopHeader(File);
 
@@ -857,14 +857,17 @@ Module *ModuleMap::lookupModuleQualified(StringRef Name, 
Module *Context) const{
   return Context->findSubmodule(Name);
 }
 
-Module *ModuleMap::findOrCreateModule(StringRef Name, Module *Parent,
-  bool IsFramework, bool IsExplicit) {
+std::pair ModuleMap::findOrCreateModule(StringRef Name,
+Module *Parent,
+bool IsFramework,
+bool IsExplicit) {
   // Try to find an existing module with this name.
   if (Module *Sub = lookupModuleQualified(Name, Parent))
-return Sub;
+return std::make_pair(Sub, false);
 
   // Create a new module with this name.
-  return createModule(Name, Parent, IsFramework, IsExplicit);
+  Module *M = createModule(Name, Parent, IsFramework, IsExplicit);
+  return std::make_pair(M, true);
 }
 
 Module *ModuleMap::createModule(StringRef Name, Module *Parent,
@@ -2129,8 +2132,8 @@ void ModuleMapParser::parseModuleDecl() {
 ActiveModule =
 Map.createShadowedModule(ModuleName, Framework, ShadowingModule);
   } else {
-ActiveModule =
-Map.findOrCreateModule(ModuleName, ActiveModule, Framework, Explicit);
+ActiveModule = Map.findOrCreateModuleFirst(ModuleName, ActiveModule,
+ 

[clang] Add clang/docs/FunctionEffectAnalysis.rst. (PR #109855)

2024-10-28 Thread via cfe-commits


@@ -0,0 +1,544 @@
+
+Function Effect Analysis
+
+
+.. contents::
+  :depth: 3
+  :local:
+
+
+Introduction
+
+
+Clang Function Effect Analysis is a language extension which can warn about 
"unsafe"
+constructs. The feature is currently tailored for the Performance Constraint 
attributes,
+``nonblocking`` and ``nonallocating``; functions with these attributes are 
verified as not
+containing any language constructs or calls to other functions which violate 
the constraint.
+(See :doc:`AttributeReference`.)
+
+
+The ``nonblocking`` and ``nonallocating`` attributes
+
+
+Attribute syntax
+
+
+The ``nonblocking`` and ``nonallocating`` attributes apply to function types, 
allowing them to be
+attached to functions, blocks, function pointers, lambdas, and member 
functions.
+
+.. code-block:: c++
+
+  // Functions
+  void nonblockingFunction() [[clang::nonblocking]];
+  void nonallocatingFunction() [[clang::nonallocating]];
+
+  // Function pointers
+  void (*nonblockingFunctionPtr)() [[clang::nonblocking]];
+
+  // Typedefs, type aliases.
+  typedef void (*NBFunctionPtrTypedef)() [[clang::nonblocking]];
+  using NBFunctionPtrTypeAlias_gnu = __attribute__((nonblocking)) void (*)();
+  using NBFunctionPtrTypeAlias_std = void (*)() [[clang::nonblocking]];
+
+  // C++ methods
+  struct Struct {
+void NBMethod() [[clang::nonblocking]];
+  };
+
+  // C++ lambdas
+  auto nbLambda = []() [[clang::nonblocking]] {};
+
+  // Blocks
+  void (^nbBlock)() = ^() [[clang::nonblocking]] {};
+
+The attribute applies only to the function itself. In particular, it does not 
apply to any nested
+functions or declarations, such as blocks, lambdas, and local classes.
+
+This document uses the C++/C23 syntax ``[[clang::nonblocking]]``, since it 
parallels the placement 
+of the ``noexcept`` specifier, and the attributes have other similarities to 
``noexcept``. The GNU
+``__attribute__((nonblocking))`` syntax is also supported. Note that it 
requires a different 
+placement on a C++ type alias.
+
+Like ``noexcept``, ``nonblocking`` and ``nonallocating`` have an optional 
argument, a compile-time
+constant boolean expression. By default, the argument is ``true``, so 
``[[clang::nonblocking]]``
+is equivalent to ``[[clang::nonblocking(true)]]``, and declares the function 
type as never locking.
+
+
+Attribute semantics
+---
+
+Together with ``noexcept``, the ``nonallocating`` and ``nonblocking`` 
attributes define an ordered
+series of performance constraints. From weakest to strongest:
+
+- ``noexcept`` (as per the C++ standard): The function type will never throw 
an exception.
+- ``nonallocating``: The function type will never allocate memory on the heap, 
and never throw an
+  exception.
+- ``nonblocking``: The function type will never block on a lock, never 
allocate memory on the heap,
+  and never throw an exception.
+
+``nonblocking`` includes the ``nonallocating`` guarantee. 
+
+While ``nonblocking`` and ``nonallocating`` are conceptually a superset of 
``noexcept``, neither
+attribute implicitly specifies ``noexcept``. Further, ``noexcept`` has a 
specified runtime behavior of 
+aborting if an exception is thrown, while the ``nonallocating`` and 
``nonblocking`` attributes are
+purely for compile-time analysis and have no potential runtime behavior. 
Nonetheless, Clang emits a
+warning if, in C++, a function is declared ``nonblocking`` or 
``nonallocating`` without
+``noexcept``. This diagnostic is controlled by 
``-Wperf-constraint-implies-noexcept``.
+
+Also, the ``nonblocking`` and ``blocking`` attributes do have special runtime 
behavior in code built
+with Clang's :doc:`RealtimeSanitizer`.
+
+``nonblocking(true)`` and ``nonallocating(true)`` apply to function *types*, 
and by extension, to
+function-like declarations. When applied to a declaration with a body, the 
compiler verifies the
+function, as described in the section "Analysis and warnings", below. 
Functions without an explicit
+performance constraint are not verified.
+
+``blocking`` and ``allocating`` are synonyms for ``nonblocking(false)`` and
+``nonallocating(false)``, respectively. They can be used on a function-like 
declaration to
+explicitly disable any potential inference of ``nonblocking`` or 
``nonallocating`` during
+verification. (Inference is described later in this document). 
``nonblocking(false)`` and
+``nonallocating(false)`` are legal, but superfluous  when applied to a 
function *type*.
+``float (int) [[nonblocking(false)]]`` and ``float (int)`` are identical types.
+
+For functions with no explicit performance constraint, the worst is assumed: 
the function
+allocates memory and potentially blocks, unless it can be inferred otherwise. 
This is detailed in the
+discussion of verification.
+
+The following example describes the meanings of all permutations of the two 
attributes and

[clang] [compiler-rt] [RISCV][compiler-rt] Update __init_riscv_feature_bits prototype (PR #101472)

2024-10-28 Thread Craig Topper via cfe-commits


@@ -280,14 +280,18 @@ static void initRISCVFeature(struct riscv_hwprobe 
Hwprobes[]) {
 
 static int FeaturesBitCached = 0;
 
-void __init_riscv_feature_bits() CONSTRUCTOR_ATTRIBUTE;
+void __init_riscv_feature_bits(void *) CONSTRUCTOR_ATTRIBUTE;
 
 // A constructor function that sets __riscv_feature_bits, and
 // __riscv_vendor_feature_bits to the right values.  This needs to run
 // only once.  This constructor is given the highest priority and it should
 // run before constructors without the priority set.  However, it still runs
 // after ifunc initializers and needs to be called explicitly there.
-void CONSTRUCTOR_ATTRIBUTE __init_riscv_feature_bits() {
+
+// PlatformArgs allows the platform to provide pre-computed data and access it
+// without extra effort. For example, Linux could pass the vDSO object to avoid
+// an extra system call.
+void CONSTRUCTOR_ATTRIBUTE __init_riscv_feature_bits(void *PlatformArgs) {

topperc wrote:

I think clang needs to call it because ifunc resolvers may run before 
constructors?

But I agree having an argument doesn't make sense.

https://github.com/llvm/llvm-project/pull/101472
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] Optimize construction and usage of the submodule index (PR #113391)

2024-10-28 Thread Jan Svoboda via cfe-commits


@@ -541,11 +541,14 @@ class ModuleMap {
   ///
   /// \param IsExplicit Whether this is an explicit submodule.
   ///
-  /// \returns The found or newly-created module, along with a boolean value
-  /// that will be true if the module is newly-created.
-  std::pair findOrCreateModule(StringRef Name, Module *Parent,
-   bool IsFramework,
-   bool IsExplicit);
+  /// \returns The found or newly-created module.
+  Module *findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework,

jansvoboda11 wrote:

Fixed in 19131c7f.

https://github.com/llvm/llvm-project/pull/113391
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC] Delete unused clang-formatted-file.txt/ClangFormattedStatus.rst files (PR #109220)

2024-10-28 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul edited 
https://github.com/llvm/llvm-project/pull/109220
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [BPF] Add load-acquire and store-release instructions under -mcpu=v4 (PR #108636)

2024-10-28 Thread Peilin Ye via cfe-commits


@@ -48,6 +48,24 @@ def BPF_END  : BPFArithOp<0xd>;
 def BPF_XCHG: BPFArithOp<0xe>;
 def BPF_CMPXCHG : BPFArithOp<0xf>;
 
+class BPFAtomicLoadStoreOp val> {
+  bits<4> Value = val;
+}
+
+def BPF_ATOMIC_LOAD : BPFAtomicLoadStoreOp<0x1>;
+def BPF_ATOMIC_STORE : BPFAtomicLoadStoreOp<0x2>;
+
+class BPFAtomicOrdering val> {
+  bits<4> Value = val;
+}
+
+def BPF_RELAXED : BPFAtomicOrdering<0x0>;
+def BPF_CONSUME : BPFAtomicOrdering<0x1>;

peilin-ye wrote:

Sure, let me delete it.

https://github.com/llvm/llvm-project/pull/108636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] fix range calculation for conditionals with throw expressions (PR #112081)

2024-10-28 Thread Oleksandr T. via cfe-commits


@@ -9827,6 +9827,9 @@ static IntRange GetExprRange(ASTContext &C, const Expr 
*E, unsigned MaxWidth,
 return IntRange(BitField->getBitWidthValue(C),
 BitField->getType()->isUnsignedIntegerOrEnumerationType());
 
+  if (GetExprType(E)->isVoidType())
+return IntRange{0, true};

a-tarasyuk wrote:

@AaronBallman @shafik if these changes look good to you, would you mind 
proceeding with the merge? thanks

https://github.com/llvm/llvm-project/pull/112081
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [BPF] Add load-acquire and store-release instructions under -mcpu=v4 (PR #108636)

2024-10-28 Thread Peilin Ye via cfe-commits

https://github.com/peilin-ye updated 
https://github.com/llvm/llvm-project/pull/108636

>From 885d5141f6707a0fdf4be363351083f8fdf8fd54 Mon Sep 17 00:00:00 2001
From: Peilin Ye 
Date: Sat, 5 Oct 2024 06:44:21 +
Subject: [PATCH 1/3] [BPF] Rename isST*() and isLD*() functions in
 BPFMISimplifyPatchable.cpp (NFC)

We are planning to add load (specifically, atomic acquiring load, or
"load-acquire") instructions under the STX instruction class.  To make
that easier, rename the isST*() and isLD*() helper functions based on
what the instructions actually do, rather than their instruction class.
---
 .../lib/Target/BPF/BPFMISimplifyPatchable.cpp | 22 +--
 1 file changed, 11 insertions(+), 11 deletions(-)

diff --git a/llvm/lib/Target/BPF/BPFMISimplifyPatchable.cpp 
b/llvm/lib/Target/BPF/BPFMISimplifyPatchable.cpp
index 39390e8c38f8c1..4a1684ccebb793 100644
--- a/llvm/lib/Target/BPF/BPFMISimplifyPatchable.cpp
+++ b/llvm/lib/Target/BPF/BPFMISimplifyPatchable.cpp
@@ -94,35 +94,35 @@ void BPFMISimplifyPatchable::initialize(MachineFunction 
&MFParm) {
   LLVM_DEBUG(dbgs() << "*** BPF simplify patchable insts pass ***\n\n");
 }
 
-static bool isST(unsigned Opcode) {
+static bool isStoreImm(unsigned Opcode) {
   return Opcode == BPF::STB_imm || Opcode == BPF::STH_imm ||
  Opcode == BPF::STW_imm || Opcode == BPF::STD_imm;
 }
 
-static bool isSTX32(unsigned Opcode) {
+static bool isStore32(unsigned Opcode) {
   return Opcode == BPF::STB32 || Opcode == BPF::STH32 || Opcode == BPF::STW32;
 }
 
-static bool isSTX64(unsigned Opcode) {
+static bool isStore64(unsigned Opcode) {
   return Opcode == BPF::STB || Opcode == BPF::STH || Opcode == BPF::STW ||
  Opcode == BPF::STD;
 }
 
-static bool isLDX32(unsigned Opcode) {
+static bool isLoad32(unsigned Opcode) {
   return Opcode == BPF::LDB32 || Opcode == BPF::LDH32 || Opcode == BPF::LDW32;
 }
 
-static bool isLDX64(unsigned Opcode) {
+static bool isLoad64(unsigned Opcode) {
   return Opcode == BPF::LDB || Opcode == BPF::LDH || Opcode == BPF::LDW ||
  Opcode == BPF::LDD;
 }
 
-static bool isLDSX(unsigned Opcode) {
+static bool isLoadSext(unsigned Opcode) {
   return Opcode == BPF::LDBSX || Opcode == BPF::LDHSX || Opcode == BPF::LDWSX;
 }
 
 bool BPFMISimplifyPatchable::isLoadInst(unsigned Opcode) {
-  return isLDX32(Opcode) || isLDX64(Opcode) || isLDSX(Opcode);
+  return isLoad32(Opcode) || isLoad64(Opcode) || isLoadSext(Opcode);
 }
 
 void BPFMISimplifyPatchable::checkADDrr(MachineRegisterInfo *MRI,
@@ -143,11 +143,11 @@ void 
BPFMISimplifyPatchable::checkADDrr(MachineRegisterInfo *MRI,
 MachineInstr *DefInst = MO.getParent();
 unsigned Opcode = DefInst->getOpcode();
 unsigned COREOp;
-if (isLDX64(Opcode) || isLDSX(Opcode))
+if (isLoad64(Opcode) || isLoadSext(Opcode))
   COREOp = BPF::CORE_LD64;
-else if (isLDX32(Opcode))
+else if (isLoad32(Opcode))
   COREOp = BPF::CORE_LD32;
-else if (isSTX64(Opcode) || isSTX32(Opcode) || isST(Opcode))
+else if (isStore64(Opcode) || isStore32(Opcode) || isStoreImm(Opcode))
   COREOp = BPF::CORE_ST;
 else
   continue;
@@ -160,7 +160,7 @@ void BPFMISimplifyPatchable::checkADDrr(MachineRegisterInfo 
*MRI,
 // Reject the form:
 //   %1 = ADD_rr %2, %3
 //   *(type *)(%2 + 0) = %1
-if (isSTX64(Opcode) || isSTX32(Opcode)) {
+if (isStore64(Opcode) || isStore32(Opcode)) {
   const MachineOperand &Opnd = DefInst->getOperand(0);
   if (Opnd.isReg() && Opnd.getReg() == MO.getReg())
 continue;

>From 77807685b76607db97c18bb5dd146203c675ab98 Mon Sep 17 00:00:00 2001
From: Peilin Ye 
Date: Sat, 5 Oct 2024 07:31:54 +
Subject: [PATCH 2/3] [BPF] Add load-acquire and store-release instructions
 under -mcpu=v4

As discussed in [1], introduce BPF instructions with load-acquire and
store-release semantics under -mcpu=v4.

The following new flags are defined:

  BPF_ATOMIC_LOAD   0x10
  BPF_ATOMIC_STORE  0x20

  BPF_RELAXED:   0x0
  BPF_ACQUIRE:   0x1
  BPF_RELEASE:   0x2
  BPF_ACQ_REL:   0x3
  BPF_SEQ_CST:   0x4

A "load-acquire" is a BPF_STX | BPF_ATOMIC instruction with the 'imm'
field set to BPF_ATOMIC_LOAD | BPF_ACQUIRE (0x11).

Similarly, a "store-release" is a BPF_STX | BPF_ATOMIC instruction with
the 'imm' field set to BPF_ATOMIC_STORE | BPF_RELEASE (0x22).

Unlike existing atomic operations that only support BPF_W (32-bit) and
BPF_DW (64-bit) size modifiers, load-acquires and store-releases also
support BPF_B (8-bit) and BPF_H (16-bit).  An 8- or 16-bit load-acquire
zero-extends the value before writing it to a 32-bit register, just like
ARM64 instruction LDAPRH and friends.

As an example, for -march=bpfel (big-endian):

  long foo(long *ptr) {
  return __atomic_load_n(ptr, __ATOMIC_ACQUIRE);
  }

foo() can be compiled to:

  db 10 00 00 11 00 00 00  r0 = load_acquire((u64 *)(r1 + 0x0))
  95 00 00 00 00 00 00 00  exit

  opcode (0xdb): BPF_ATOMIC | BPF_DW | BPF_STX
  imm (0x0011): BPF_ATOMIC_L

[clang] 7131569 - [clang] Warn about memset/memcpy to NonTriviallyCopyable types (#111434)

2024-10-28 Thread via cfe-commits

Author: serge-sans-paille
Date: 2024-10-28T20:40:52Z
New Revision: 71315698c91d0cda054b903da0594ca6f072c350

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

LOG: [clang] Warn about memset/memcpy to NonTriviallyCopyable types (#111434)

This implements a warning that's similar to what GCC does in that
context: both memcpy and memset require their first and second operand
to be trivially copyable, let's warn if that's not the case.

Added: 
clang/test/SemaCXX/warn-memaccess.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaChecking.cpp
clang/test/SemaCXX/constexpr-string.cpp
libcxx/include/__memory/uninitialized_algorithms.h
libcxx/test/std/utilities/expected/types.h
libcxx/test/support/min_allocator.h

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9515e96ffd01c1..424f02ef08d70e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -322,6 +322,11 @@ Modified Compiler Flags
   to utilize these vector libraries. The behavior for all other vector function
   libraries remains unchanged.
 
+- The ``-Wnontrivial-memaccess`` warning has been updated to also warn about
+  passing non-trivially-copyable destrination parameter to ``memcpy``,
+  ``memset`` and similar functions for which it is a documented undefined
+  behavior.
+
 Removed Compiler Flags
 -
 

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 9b9bdd7c800e37..34ff49d7238a7f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -795,6 +795,10 @@ def warn_cstruct_memaccess : Warning<
   "%1 call is a pointer to record %2 that is not trivial to "
   "%select{primitive-default-initialize|primitive-copy}3">,
   InGroup;
+def warn_cxxstruct_memaccess : Warning<
+  "first argument in call to "
+  "%0 is a pointer to non-trivially copyable type %1">,
+  InGroup;
 def note_nontrivial_field : Note<
   "field is non-trivial to %select{copy|default-initialize}0">;
 def err_non_trivial_c_union_in_invalid_context : Error<

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 27b274d74ce716..d027e4c6dfdb4d 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -8899,18 +8899,36 @@ void Sema::CheckMemaccessArguments(const CallExpr *Call,
   << ArgIdx << FnName << PointeeTy
   << Call->getCallee()->getSourceRange());
 else if (const auto *RT = PointeeTy->getAs()) {
+
+  bool IsTriviallyCopyableCXXRecord =
+  RT->desugar().isTriviallyCopyableType(Context);
+
   if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
   RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
 PDiag(diag::warn_cstruct_memaccess)
 << ArgIdx << FnName << PointeeTy << 0);
 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
+  } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
+ !IsTriviallyCopyableCXXRecord && ArgIdx == 0) {
+// FIXME: Limiting this warning to dest argument until we decide
+// whether it's valid for source argument too.
+DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
+PDiag(diag::warn_cxxstruct_memaccess)
+<< FnName << PointeeTy);
   } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
 PDiag(diag::warn_cstruct_memaccess)
 << ArgIdx << FnName << PointeeTy << 1);
 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
+  } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
+ !IsTriviallyCopyableCXXRecord && ArgIdx == 0) {
+// FIXME: Limiting this warning to dest argument until we decide
+// whether it's valid for source argument too.
+DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
+PDiag(diag::warn_cxxstruct_memaccess)
+<< FnName << PointeeTy);
   } else {
 continue;
   }

diff  --git a/clang/test/SemaCXX/constexpr-string.cpp 
b/clang/test/SemaCXX/constexpr-string.cpp
index c456740ef7551f..5448365489a514 100644
--- a/clang/test/SemaCXX/constexpr-string.cpp
+++ b/clang/test/SemaCXX/constexpr-string.cpp
@@ -670,6 +670,8 @@ nam

[clang] [libcxx] [clang] Warn about memset/memcpy to NonTriviallyCopyable types (PR #111434)

2024-10-28 Thread via cfe-commits

https://github.com/serge-sans-paille closed 
https://github.com/llvm/llvm-project/pull/111434
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] Optimize construction and usage of the submodule index (PR #113391)

2024-10-28 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `llvm-x86_64-debian-dylib` 
running on `gribozavr4` while building `clang` at step 5 "build-unified-tree".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/60/builds/11233


Here is the relevant piece of the build log for the reference

```
Step 5 (build-unified-tree) failure: build (failure)
...
575.236 [115/21/6881] Building CXX object 
tools/lldb/source/Plugins/Language/CPlusPlus/CMakeFiles/lldbPluginCPlusPlusLanguage.dir/BlockPointer.cpp.o
575.412 [115/20/6882] Building CXX object 
tools/lldb/source/Plugins/ExpressionParser/Clang/CMakeFiles/lldbPluginExpressionParserClang.dir/ClangUtilityFunction.cpp.o
575.722 [115/19/6883] Building CXX object 
tools/lldb/source/Plugins/ExpressionParser/Clang/CMakeFiles/lldbPluginExpressionParserClang.dir/ASTStructExtractor.cpp.o
576.310 [115/18/6884] Building CXX object 
tools/lldb/source/Plugins/ExpressionParser/Clang/CMakeFiles/lldbPluginExpressionParserClang.dir/ClangFunctionCaller.cpp.o
576.595 [115/17/6885] Building CXX object 
tools/lldb/source/Plugins/ExpressionParser/Clang/CMakeFiles/lldbPluginExpressionParserClang.dir/ASTResultSynthesizer.cpp.o
577.216 [115/16/6886] Building CXX object 
tools/lldb/source/Plugins/ExpressionParser/Clang/CMakeFiles/lldbPluginExpressionParserClang.dir/ClangUserExpression.cpp.o
577.314 [115/15/6887] Building CXX object 
tools/lldb/source/Plugins/SymbolFile/NativePDB/CMakeFiles/lldbPluginSymbolFileNativePDB.dir/UdtRecordCompleter.cpp.o
577.400 [115/14/6888] Building CXX object 
tools/lldb/source/Plugins/SymbolFile/PDB/CMakeFiles/lldbPluginSymbolFilePDB.dir/PDBASTParser.cpp.o
577.541 [115/13/6889] Building CXX object 
tools/lldb/source/Plugins/ExpressionParser/Clang/CMakeFiles/lldbPluginExpressionParserClang.dir/IRForTarget.cpp.o
577.696 [115/12/6890] Building CXX object 
tools/lldb/source/Plugins/TypeSystem/Clang/CMakeFiles/lldbPluginTypeSystemClang.dir/TypeSystemClang.cpp.o
FAILED: 
tools/lldb/source/Plugins/TypeSystem/Clang/CMakeFiles/lldbPluginTypeSystemClang.dir/TypeSystemClang.cpp.o
 
CCACHE_CPP2=yes CCACHE_HASHDIR=yes /usr/bin/ccache /usr/bin/clang++ 
-DGTEST_HAS_RTTI=0 -DHAVE_ROUND -D_DEBUG -D_GLIBCXX_ASSERTIONS -D_GNU_SOURCE 
-D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS 
-I/b/1/llvm-x86_64-debian-dylib/build/tools/lldb/source/Plugins/TypeSystem/Clang
 
-I/b/1/llvm-x86_64-debian-dylib/llvm-project/lldb/source/Plugins/TypeSystem/Clang
 -I/b/1/llvm-x86_64-debian-dylib/llvm-project/lldb/include 
-I/b/1/llvm-x86_64-debian-dylib/build/tools/lldb/include 
-I/b/1/llvm-x86_64-debian-dylib/build/include 
-I/b/1/llvm-x86_64-debian-dylib/llvm-project/llvm/include 
-I/b/1/llvm-x86_64-debian-dylib/llvm-project/llvm/../clang/include 
-I/b/1/llvm-x86_64-debian-dylib/build/tools/lldb/../clang/include 
-I/b/1/llvm-x86_64-debian-dylib/llvm-project/lldb/source 
-I/b/1/llvm-x86_64-debian-dylib/build/tools/lldb/source -isystem 
/usr/include/libxml2 -fPIC -fvisibility-inlines-hidden -Werror=date-time 
-Werror=unguarded-availability-new -Wall -Wextra -Wno-unused-parameter 
-Wwrite-strings -Wcast-qual -Wmissing-field-initializers -pedantic 
-Wno-long-long -Wc++98-compat-extra-semi -Wimplicit-fallthrough 
-Wcovered-switch-default -Wno-noexcept-type -Wnon-virtual-dtor 
-Wdelete-non-virtual-dtor -Wsuggest-override -Wstring-conversion 
-Wmisleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color 
-ffunction-sections -fdata-sections -Wno-unknown-pragmas -Wno-strict-aliasing 
-Wno-vla-extension -O3 -DNDEBUG  -fno-exceptions -funwind-tables -fno-rtti 
-UNDEBUG -std=c++17 -MD -MT 
tools/lldb/source/Plugins/TypeSystem/Clang/CMakeFiles/lldbPluginTypeSystemClang.dir/TypeSystemClang.cpp.o
 -MF 
tools/lldb/source/Plugins/TypeSystem/Clang/CMakeFiles/lldbPluginTypeSystemClang.dir/TypeSystemClang.cpp.o.d
 -o 
tools/lldb/source/Plugins/TypeSystem/Clang/CMakeFiles/lldbPluginTypeSystemClang.dir/TypeSystemClang.cpp.o
 -c 
/b/1/llvm-x86_64-debian-dylib/llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
/b/1/llvm-x86_64-debian-dylib/llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp:1233:29:
 error: no viable overloaded '='
  std::tie(module, created) = m_module_map_up->findOrCreateModule(
  ~ ^ 
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/tuple:1173:7:
 note: candidate function not viable: no known conversion from 'clang::Module 
*' to 'const std::tuple' for 1st argument
  operator=(typename conditional<__assignable(),
  ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/tuple:1184:7:
 note: candidate function not viable: no known conversion from 'clang::Module 
*' to 'std::tuple' for 1st argument
  operator=(typename conditional<__assignable<_T1, _T2>(),
  ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/tuple:1196:2:
 note: candidate template ignored: could not match 't

[clang] [clang][CodeGen][OpenCL] Fix `alloca` handling & `sret`when compiling for (PR #113930)

2024-10-28 Thread Matt Arsenault via cfe-commits


@@ -108,11 +108,15 @@ RawAddress CodeGenFunction::CreateTempAlloca(llvm::Type 
*Ty, CharUnits Align,
   if (AllocaAddr)
 *AllocaAddr = Alloca;
   llvm::Value *V = Alloca.getPointer();
+  assert((!getLangOpts().OpenCL ||
+  CGM.getTarget().getTargetAddressSpace(getASTAllocaAddressSpace()) ==
+  CGM.getTarget().getTargetAddressSpace(LangAS::opencl_private)) &&
+ "For OpenCL allocas must allocate in the private address space!");
   // Alloca always returns a pointer in alloca address space, which may
   // be different from the type defined by the language. For example,
   // in C++ the auto variables are in the default address space. Therefore
   // cast alloca to the default address space when necessary.
-  if (getASTAllocaAddressSpace() != LangAS::Default) {
+  if (!getLangOpts().OpenCL && getASTAllocaAddressSpace() != LangAS::Default) {

arsenm wrote:

Don't see why the language mode would factor in. The below code also seems more 
complex than necessary. I would expect there to be a language typed value, and 
there to be an IR value. You would simply insert the cast if they didn't match, 
so not sure what the performAddrSpaceCast hook is for. Is that a holdover from 
before addrspacecast existed? 

https://github.com/llvm/llvm-project/pull/113930
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Driver] Allow -fuse-lld=lld-link when lto is enabled on *windows-msvc targets (PR #113966)

2024-10-28 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Zhaoshi Zheng (zhaoshiz)


Changes

Follow-up on https://github.com/llvm/llvm-project/pull/109607, we have a use 
case on WoA where `cmake -G "Unix Makefiles"` generates -fuse-ld=lld-link, 
which is disallowed by PR#109607.

---
Full diff: https://github.com/llvm/llvm-project/pull/113966.diff


3 Files Affected:

- (modified) clang/lib/Driver/Driver.cpp (+1-1) 
- (modified) clang/test/Driver/clang_f_opts.c (+1) 
- (added) clang/test/Driver/woa-lto.c (+15) 


``diff
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 9878a9dad78d40..c1c581e6c6df7c 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4035,7 +4035,7 @@ void Driver::handleArguments(Compilation &C, 
DerivedArgList &Args,
 if (C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment() &&
 LTOMode != LTOK_None &&
 !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
- .equals_insensitive("lld"))
+ .starts_with_insensitive("lld"))
   Diag(clang::diag::err_drv_lto_without_lld);
 
 // If -dumpdir is not specified, give a default prefix derived from the 
link
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index fd15552715cb35..2cfbe256bc7456 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -606,6 +606,7 @@
 // RUN: %clang -### -S -fjmc -g --target=x86_64-unknown-linux %s 2>&1 | 
FileCheck -check-prefix=CHECK_JMC %s
 // RUN: %clang -### -S -fjmc -g -fno-jmc --target=x86_64-unknown-linux %s 2>&1 
| FileCheck -check-prefix=CHECK_NOJMC %s
 // RUN: %clang -### -fjmc -g -flto -fuse-ld=lld 
--target=x86_64-pc-windows-msvc %s 2>&1 | FileCheck 
-check-prefix=CHECK_NOJMC_LTO %s
+// RUN: %clang -### -fjmc -g -flto -fuse-ld=lld-link 
--target=x86_64-pc-windows-msvc %s 2>&1 | FileCheck 
-check-prefix=CHECK_NOJMC_LTO %s
 // RUN: %clang -### -fjmc -g -flto --target=x86_64-unknown-linux %s 2>&1 | 
FileCheck -check-prefix=CHECK_JMC_LTO %s
 // RUN: %clang -### -fjmc -g -flto -fno-jmc --target=x86_64-unknown-linux %s 
2>&1 | FileCheck -check-prefix=CHECK_NOJMC_LTO %s
 // CHECK_JMC_WARN: -fjmc requires debug info. Use -g or debug options that 
enable debugger's stepping function; option ignored
diff --git a/clang/test/Driver/woa-lto.c b/clang/test/Driver/woa-lto.c
new file mode 100644
index 00..25c42374c4d449
--- /dev/null
+++ b/clang/test/Driver/woa-lto.c
@@ -0,0 +1,15 @@
+// REQUIRES: aarch64-registered-target
+//
+// RUN: echo "int main() {} " > %t.c
+//
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld -c %t.c 
-o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld -### 
%t.o 2>&1 | FileCheck %s
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin -fuse-ld=lld -c 
%t.c -o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin -fuse-ld=lld 
-### %t.o 2>&1 | FileCheck %s
+//
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld-link -c 
%t.c -o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld-link 
-### %t.o 2>&1 | FileCheck %s
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin 
-fuse-ld=lld-link -c %t.c -o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin 
-fuse-ld=lld-link -### %t.o 2>&1 | FileCheck %s
+//
+// CHECK: "{{.*}}lld-link" "-out:a.exe" "-defaultlib:libcmt" 
"-defaultlib:oldnames"

``




https://github.com/llvm/llvm-project/pull/113966
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Driver] Allow -fuse-lld=lld-link when lto is enabled on *windows-msvc targets (PR #113966)

2024-10-28 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Zhaoshi Zheng (zhaoshiz)


Changes

Follow-up on https://github.com/llvm/llvm-project/pull/109607, we have a use 
case on WoA where `cmake -G "Unix Makefiles"` generates -fuse-ld=lld-link, 
which is disallowed by PR#109607.

---
Full diff: https://github.com/llvm/llvm-project/pull/113966.diff


3 Files Affected:

- (modified) clang/lib/Driver/Driver.cpp (+1-1) 
- (modified) clang/test/Driver/clang_f_opts.c (+1) 
- (added) clang/test/Driver/woa-lto.c (+15) 


``diff
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 9878a9dad78d40..c1c581e6c6df7c 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4035,7 +4035,7 @@ void Driver::handleArguments(Compilation &C, 
DerivedArgList &Args,
 if (C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment() &&
 LTOMode != LTOK_None &&
 !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
- .equals_insensitive("lld"))
+ .starts_with_insensitive("lld"))
   Diag(clang::diag::err_drv_lto_without_lld);
 
 // If -dumpdir is not specified, give a default prefix derived from the 
link
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index fd15552715cb35..2cfbe256bc7456 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -606,6 +606,7 @@
 // RUN: %clang -### -S -fjmc -g --target=x86_64-unknown-linux %s 2>&1 | 
FileCheck -check-prefix=CHECK_JMC %s
 // RUN: %clang -### -S -fjmc -g -fno-jmc --target=x86_64-unknown-linux %s 2>&1 
| FileCheck -check-prefix=CHECK_NOJMC %s
 // RUN: %clang -### -fjmc -g -flto -fuse-ld=lld 
--target=x86_64-pc-windows-msvc %s 2>&1 | FileCheck 
-check-prefix=CHECK_NOJMC_LTO %s
+// RUN: %clang -### -fjmc -g -flto -fuse-ld=lld-link 
--target=x86_64-pc-windows-msvc %s 2>&1 | FileCheck 
-check-prefix=CHECK_NOJMC_LTO %s
 // RUN: %clang -### -fjmc -g -flto --target=x86_64-unknown-linux %s 2>&1 | 
FileCheck -check-prefix=CHECK_JMC_LTO %s
 // RUN: %clang -### -fjmc -g -flto -fno-jmc --target=x86_64-unknown-linux %s 
2>&1 | FileCheck -check-prefix=CHECK_NOJMC_LTO %s
 // CHECK_JMC_WARN: -fjmc requires debug info. Use -g or debug options that 
enable debugger's stepping function; option ignored
diff --git a/clang/test/Driver/woa-lto.c b/clang/test/Driver/woa-lto.c
new file mode 100644
index 00..25c42374c4d449
--- /dev/null
+++ b/clang/test/Driver/woa-lto.c
@@ -0,0 +1,15 @@
+// REQUIRES: aarch64-registered-target
+//
+// RUN: echo "int main() {} " > %t.c
+//
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld -c %t.c 
-o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld -### 
%t.o 2>&1 | FileCheck %s
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin -fuse-ld=lld -c 
%t.c -o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin -fuse-ld=lld 
-### %t.o 2>&1 | FileCheck %s
+//
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld-link -c 
%t.c -o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld-link 
-### %t.o 2>&1 | FileCheck %s
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin 
-fuse-ld=lld-link -c %t.c -o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin 
-fuse-ld=lld-link -### %t.o 2>&1 | FileCheck %s
+//
+// CHECK: "{{.*}}lld-link" "-out:a.exe" "-defaultlib:libcmt" 
"-defaultlib:oldnames"

``




https://github.com/llvm/llvm-project/pull/113966
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Driver] Allow -fuse-lld=lld-link when lto is enabled on *windows-msvc targets (PR #113966)

2024-10-28 Thread Zhaoshi Zheng via cfe-commits

https://github.com/zhaoshiz created 
https://github.com/llvm/llvm-project/pull/113966

Follow-up on https://github.com/llvm/llvm-project/pull/109607, we have a use 
case on WoA where `cmake -G "Unix Makefiles"` generates -fuse-ld=lld-link, 
which is disallowed by PR#109607.

>From 5259a3b00fe1b841e8548443036a943b169970dc Mon Sep 17 00:00:00 2001
From: Zhaoshi Zheng 
Date: Mon, 28 Oct 2024 14:35:35 -0700
Subject: [PATCH] [clang][Driver] Allow -fuse-lld=lld-link when lto is enabled
 on *windows-msvc targets

Follow-up on https://github.com/llvm/llvm-project/pull/109607, we have a use
case on WoA where `cmake -G "Unix Makefiles"` generates -fuse-ld=lld-link,
which is disallowed by PR#109607.
---
 clang/lib/Driver/Driver.cpp  |  2 +-
 clang/test/Driver/clang_f_opts.c |  1 +
 clang/test/Driver/woa-lto.c  | 15 +++
 3 files changed, 17 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Driver/woa-lto.c

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 9878a9dad78d40..c1c581e6c6df7c 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4035,7 +4035,7 @@ void Driver::handleArguments(Compilation &C, 
DerivedArgList &Args,
 if (C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment() &&
 LTOMode != LTOK_None &&
 !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
- .equals_insensitive("lld"))
+ .starts_with_insensitive("lld"))
   Diag(clang::diag::err_drv_lto_without_lld);
 
 // If -dumpdir is not specified, give a default prefix derived from the 
link
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index fd15552715cb35..2cfbe256bc7456 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -606,6 +606,7 @@
 // RUN: %clang -### -S -fjmc -g --target=x86_64-unknown-linux %s 2>&1 | 
FileCheck -check-prefix=CHECK_JMC %s
 // RUN: %clang -### -S -fjmc -g -fno-jmc --target=x86_64-unknown-linux %s 2>&1 
| FileCheck -check-prefix=CHECK_NOJMC %s
 // RUN: %clang -### -fjmc -g -flto -fuse-ld=lld 
--target=x86_64-pc-windows-msvc %s 2>&1 | FileCheck 
-check-prefix=CHECK_NOJMC_LTO %s
+// RUN: %clang -### -fjmc -g -flto -fuse-ld=lld-link 
--target=x86_64-pc-windows-msvc %s 2>&1 | FileCheck 
-check-prefix=CHECK_NOJMC_LTO %s
 // RUN: %clang -### -fjmc -g -flto --target=x86_64-unknown-linux %s 2>&1 | 
FileCheck -check-prefix=CHECK_JMC_LTO %s
 // RUN: %clang -### -fjmc -g -flto -fno-jmc --target=x86_64-unknown-linux %s 
2>&1 | FileCheck -check-prefix=CHECK_NOJMC_LTO %s
 // CHECK_JMC_WARN: -fjmc requires debug info. Use -g or debug options that 
enable debugger's stepping function; option ignored
diff --git a/clang/test/Driver/woa-lto.c b/clang/test/Driver/woa-lto.c
new file mode 100644
index 00..25c42374c4d449
--- /dev/null
+++ b/clang/test/Driver/woa-lto.c
@@ -0,0 +1,15 @@
+// REQUIRES: aarch64-registered-target
+//
+// RUN: echo "int main() {} " > %t.c
+//
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld -c %t.c 
-o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld -### 
%t.o 2>&1 | FileCheck %s
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin -fuse-ld=lld -c 
%t.c -o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin -fuse-ld=lld 
-### %t.o 2>&1 | FileCheck %s
+//
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld-link -c 
%t.c -o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld-link 
-### %t.o 2>&1 | FileCheck %s
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin 
-fuse-ld=lld-link -c %t.c -o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin 
-fuse-ld=lld-link -### %t.o 2>&1 | FileCheck %s
+//
+// CHECK: "{{.*}}lld-link" "-out:a.exe" "-defaultlib:libcmt" 
"-defaultlib:oldnames"

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


[clang-tools-extra] [clang-tidy] Create bugprone-incorrect-enable-shared-from-this check (PR #102299)

2024-10-28 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti edited 
https://github.com/llvm/llvm-project/pull/102299
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [BPF] Add load-acquire and store-release instructions under -mcpu=v4 (PR #108636)

2024-10-28 Thread Peilin Ye via cfe-commits

peilin-ye wrote:

Changes in v7:

1. Change encoding to make it easier to support `SEQ_CST` in the future 
(Yingchi)
```
 (before)  | imm{7-4}| imm{3-0} |
 - | --- |  |
 load-acquire  | BPF_LOAD_ACQ (0x1)  | 0x0  |
 store-release | BPF_STORE_REL (0x2) | 0x0  |
```
```
 (after)   | imm{7-4}| imm{3-0}  |
 - | --- | - |
 load-acquire  | BPF_LOAD (0x1)  | BPF_ACQUIRE (0x1) |
 store-release | BPF_STORE (0x2) | BPF_RELEASE (0x2) |
```
Introduce the following new flags for memory orders:
```
def BPF_RELAXED : BPFAtomicOrdering<0x0>;
def BPF_ACQUIRE : BPFAtomicOrdering<0x1>;
def BPF_RELEASE : BPFAtomicOrdering<0x2>;
def BPF_ACQ_REL : BPFAtomicOrdering<0x3>;
def BPF_SEQ_CST : BPFAtomicOrdering<0x4>;
```
Include all orders defined by the C++ standard except `CONSUME` (Yonghong)

2. `BPFISelLowering.cpp` changes (Matt)
   - Avoid unnecessarily setting `MVT::i{8,16}` `ATOMIC_{LOAD,STORE}` to 
`Custom`
   - Coding style change

3. `acquire-release.ll` changes (Yingchi)
   - Move `; CHECK` labels into their corresponding function bodies
   - Delete the `; Source:` section

4. Update `bpf-predefined-macros.c`

https://github.com/llvm/llvm-project/pull/108636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [CIR] Call code gen; create empty cir.func op (PR #113483)

2024-10-28 Thread Shoaib Meenai via cfe-commits

https://github.com/smeenai commented:

Very minor nits :)

Is it at all possible to write a test to exercise the new functionality, or 
will it just run into an NYI?

https://github.com/llvm/llvm-project/pull/113483
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [CIR] Call code gen; create empty cir.func op (PR #113483)

2024-10-28 Thread Shoaib Meenai via cfe-commits

https://github.com/smeenai edited 
https://github.com/llvm/llvm-project/pull/113483
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [CIR] Call code gen; create empty cir.func op (PR #113483)

2024-10-28 Thread Shoaib Meenai via cfe-commits


@@ -37,14 +40,39 @@ class CIRGenConsumer : public clang::ASTConsumer {
  const LangOptions &LangOptions,
  const FrontendOptions &FEOptions,
  std::unique_ptr OS)
-  : OutputStream(std::move(OS)), FS(VFS),
+  : Action(Action), OutputStream(std::move(OS)), FS(VFS),
 Gen(std::make_unique(DiagnosticsEngine, std::move(VFS),
CodeGenOptions)) {}
 
+  void Initialize(ASTContext &Ctx) override {
+assert(!Context && "initialized multiple times");
+
+Context = &Ctx;
+

smeenai wrote:

The newlines seem superfluous, unless there's more to be filled in here later.

https://github.com/llvm/llvm-project/pull/113483
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] Reland "[LLVM] Add IRNormalizer Pass" (PR #113780)

2024-10-28 Thread Vladimir Vereschaka via cfe-commits

vvereschaka wrote:

@justinfargnoli ,

I wasn't able to build and check your branch (`TheManWithTheGoldenCanon:main`) 
locally on the builder because of these linker  errors:
```
 
/home/buildbot/worker/temp/llvm-project/llvm/include/llvm/IR/PassManager.h:111: 
error: undefined reference to 'llvm::PreservedFunctionHashAnalysis::Key'
/home/buildbot/worker/temp/llvm-project/llvm/include/llvm/IR/PassManager.h:111: 
error: undefined reference to 'llvm::PreservedModuleHashAnalysis::Key'
collect2: error: ld returned 1 exit status
```

Would you check your changes once again? Probably you need to sync your branch 
with the `llvm-project:main` top-of-the-tree.

https://github.com/llvm/llvm-project/pull/113780
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Driver] Allow -fuse-lld=lld-link when lto is enabled on *windows-msvc targets (PR #113966)

2024-10-28 Thread Zhaoshi Zheng via cfe-commits

https://github.com/zhaoshiz updated 
https://github.com/llvm/llvm-project/pull/113966

>From 5259a3b00fe1b841e8548443036a943b169970dc Mon Sep 17 00:00:00 2001
From: Zhaoshi Zheng 
Date: Mon, 28 Oct 2024 14:35:35 -0700
Subject: [PATCH 1/2] [clang][Driver] Allow -fuse-lld=lld-link when lto is
 enabled on *windows-msvc targets

Follow-up on https://github.com/llvm/llvm-project/pull/109607, we have a use
case on WoA where `cmake -G "Unix Makefiles"` generates -fuse-ld=lld-link,
which is disallowed by PR#109607.
---
 clang/lib/Driver/Driver.cpp  |  2 +-
 clang/test/Driver/clang_f_opts.c |  1 +
 clang/test/Driver/woa-lto.c  | 15 +++
 3 files changed, 17 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Driver/woa-lto.c

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 9878a9dad78d40..c1c581e6c6df7c 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4035,7 +4035,7 @@ void Driver::handleArguments(Compilation &C, 
DerivedArgList &Args,
 if (C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment() &&
 LTOMode != LTOK_None &&
 !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
- .equals_insensitive("lld"))
+ .starts_with_insensitive("lld"))
   Diag(clang::diag::err_drv_lto_without_lld);
 
 // If -dumpdir is not specified, give a default prefix derived from the 
link
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index fd15552715cb35..2cfbe256bc7456 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -606,6 +606,7 @@
 // RUN: %clang -### -S -fjmc -g --target=x86_64-unknown-linux %s 2>&1 | 
FileCheck -check-prefix=CHECK_JMC %s
 // RUN: %clang -### -S -fjmc -g -fno-jmc --target=x86_64-unknown-linux %s 2>&1 
| FileCheck -check-prefix=CHECK_NOJMC %s
 // RUN: %clang -### -fjmc -g -flto -fuse-ld=lld 
--target=x86_64-pc-windows-msvc %s 2>&1 | FileCheck 
-check-prefix=CHECK_NOJMC_LTO %s
+// RUN: %clang -### -fjmc -g -flto -fuse-ld=lld-link 
--target=x86_64-pc-windows-msvc %s 2>&1 | FileCheck 
-check-prefix=CHECK_NOJMC_LTO %s
 // RUN: %clang -### -fjmc -g -flto --target=x86_64-unknown-linux %s 2>&1 | 
FileCheck -check-prefix=CHECK_JMC_LTO %s
 // RUN: %clang -### -fjmc -g -flto -fno-jmc --target=x86_64-unknown-linux %s 
2>&1 | FileCheck -check-prefix=CHECK_NOJMC_LTO %s
 // CHECK_JMC_WARN: -fjmc requires debug info. Use -g or debug options that 
enable debugger's stepping function; option ignored
diff --git a/clang/test/Driver/woa-lto.c b/clang/test/Driver/woa-lto.c
new file mode 100644
index 00..25c42374c4d449
--- /dev/null
+++ b/clang/test/Driver/woa-lto.c
@@ -0,0 +1,15 @@
+// REQUIRES: aarch64-registered-target
+//
+// RUN: echo "int main() {} " > %t.c
+//
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld -c %t.c 
-o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld -### 
%t.o 2>&1 | FileCheck %s
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin -fuse-ld=lld -c 
%t.c -o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin -fuse-ld=lld 
-### %t.o 2>&1 | FileCheck %s
+//
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld-link -c 
%t.c -o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld-link 
-### %t.o 2>&1 | FileCheck %s
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin 
-fuse-ld=lld-link -c %t.c -o %t.o
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin 
-fuse-ld=lld-link -### %t.o 2>&1 | FileCheck %s
+//
+// CHECK: "{{.*}}lld-link" "-out:a.exe" "-defaultlib:libcmt" 
"-defaultlib:oldnames"

>From 70454559165840f7c4e261bf5ed24b1c317d5b86 Mon Sep 17 00:00:00 2001
From: Zhaoshi Zheng 
Date: Mon, 28 Oct 2024 20:38:43 -0700
Subject: [PATCH 2/2] Update test case to allow possible '.exe' extension

---
 clang/test/Driver/woa-lto.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/Driver/woa-lto.c b/clang/test/Driver/woa-lto.c
index 25c42374c4d449..7f4ecefd6b4b37 100644
--- a/clang/test/Driver/woa-lto.c
+++ b/clang/test/Driver/woa-lto.c
@@ -12,4 +12,4 @@
 // RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin 
-fuse-ld=lld-link -c %t.c -o %t.o
 // RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin 
-fuse-ld=lld-link -### %t.o 2>&1 | FileCheck %s
 //
-// CHECK: "{{.*}}lld-link" "-out:a.exe" "-defaultlib:libcmt" 
"-defaultlib:oldnames"
+// CHECK: "{{.*}}lld-link{{(.exe)?}}" "-out:a.exe" "-defaultlib:libcmt" 
"-defaultlib:oldnames"

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


[clang-tools-extra] [clangd] [Modules] Use ASTReader directly in IsModuleFileUpToDate (PR #113879)

2024-10-28 Thread Chuanqi Xu via cfe-commits


@@ -127,50 +128,64 @@ struct ModuleFile {
   std::string ModuleFilePath;
 };
 
-bool IsModuleFileUpToDate(
-PathRef ModuleFilePath,
-const PrerequisiteModules &RequisiteModules) {
-IntrusiveRefCntPtr Diags =
-  CompilerInstance::createDiagnostics(new DiagnosticOptions());
-
+bool IsModuleFileUpToDate(PathRef ModuleFilePath,
+  const PrerequisiteModules &RequisiteModules,
+  llvm::IntrusiveRefCntPtr VFS) 
{
   auto HSOpts = std::make_shared();
   RequisiteModules.adjustHeaderSearchOptions(*HSOpts);
   HSOpts->ForceCheckCXX20ModulesInputFiles = true;
   HSOpts->ValidateASTInputFilesContent = true;
 
+  IntrusiveRefCntPtr Diags =
+  CompilerInstance::createDiagnostics(new DiagnosticOptions());
+
+  LangOptions LangOpts;
+  LangOpts.SkipODRCheckInGMF = true;
+
+  FileManager FileMgr(FileSystemOptions(), VFS);
+
+  SourceManager SourceMgr(*Diags, FileMgr);
+
+  HeaderSearch HeaderInfo(HSOpts, SourceMgr, *Diags, LangOpts,
+  /*Target=*/nullptr);
+
+  TrivialModuleLoader ModuleLoader;
+  Preprocessor PP(std::make_shared(), *Diags, LangOpts,
+  SourceMgr, HeaderInfo, ModuleLoader);
+
+  IntrusiveRefCntPtr ModuleCache = new 
InMemoryModuleCache;

ChuanqiXu9 wrote:

This was the defect on the clang side. The module manager will store the 
`ModuleCache` as `IntrusiveRefCntPtr`: 
https://github.com/llvm/llvm-project/blob/0c1c37bfbed08c9d4e414a10f46cbed9a3e4c870/clang/include/clang/Serialization/ModuleManager.h#L67-L68
 while it was not required by the constructor.

And if I make the `ModuleCache` as a local variable, then it crashes with 
invalid pointer.

https://github.com/llvm/llvm-project/pull/113879
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clangd] [Modules] Use ASTReader directly in IsModuleFileUpToDate (PR #113879)

2024-10-28 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 updated 
https://github.com/llvm/llvm-project/pull/113879

>From 99e1989c3b2fad7702795a707d130fe96a93f42f Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Mon, 28 Oct 2024 15:54:37 +0800
Subject: [PATCH 1/2] [clangd] [Modules] Use ASTReader directly in
 IsModuleFileUpToDate

---
 clang-tools-extra/clangd/ModulesBuilder.cpp | 59 +
 1 file changed, 37 insertions(+), 22 deletions(-)

diff --git a/clang-tools-extra/clangd/ModulesBuilder.cpp 
b/clang-tools-extra/clangd/ModulesBuilder.cpp
index 1eeff468ef1236..1566ec8d9d900d 100644
--- a/clang-tools-extra/clangd/ModulesBuilder.cpp
+++ b/clang-tools-extra/clangd/ModulesBuilder.cpp
@@ -12,6 +12,7 @@
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Serialization/ASTReader.h"
+#include "clang/Serialization/InMemoryModuleCache.h"
 
 namespace clang {
 namespace clangd {
@@ -127,50 +128,64 @@ struct ModuleFile {
   std::string ModuleFilePath;
 };
 
-bool IsModuleFileUpToDate(
-PathRef ModuleFilePath,
-const PrerequisiteModules &RequisiteModules) {
-IntrusiveRefCntPtr Diags =
-  CompilerInstance::createDiagnostics(new DiagnosticOptions());
-
+bool IsModuleFileUpToDate(PathRef ModuleFilePath,
+  const PrerequisiteModules &RequisiteModules,
+  llvm::IntrusiveRefCntPtr VFS) 
{
   auto HSOpts = std::make_shared();
   RequisiteModules.adjustHeaderSearchOptions(*HSOpts);
   HSOpts->ForceCheckCXX20ModulesInputFiles = true;
   HSOpts->ValidateASTInputFilesContent = true;
 
+  IntrusiveRefCntPtr Diags =
+  CompilerInstance::createDiagnostics(new DiagnosticOptions());
+
+  LangOptions LangOpts;
+  LangOpts.SkipODRCheckInGMF = true;
+
+  FileManager FileMgr(FileSystemOptions(), VFS);
+
+  SourceManager SourceMgr(*Diags, FileMgr);
+
+  HeaderSearch HeaderInfo(HSOpts, SourceMgr, *Diags, LangOpts,
+  /*Target=*/nullptr);
+
+  TrivialModuleLoader ModuleLoader;
+  Preprocessor PP(std::make_shared(), *Diags, LangOpts,
+  SourceMgr, HeaderInfo, ModuleLoader);
+
+  IntrusiveRefCntPtr ModuleCache = new 
InMemoryModuleCache;
   PCHContainerOperations PCHOperations;
-  std::unique_ptr Unit = ASTUnit::LoadFromASTFile(
-  ModuleFilePath.str(), PCHOperations.getRawReader(), ASTUnit::LoadASTOnly,
-  Diags, FileSystemOptions(), std::move(HSOpts));
+  ASTReader Reader(PP, *ModuleCache, /*ASTContext=*/nullptr,
+   PCHOperations.getRawReader(), {});
 
-  if (!Unit)
-return false;
+  Reader.setListener(std::make_unique(PP));
 
-  auto Reader = Unit->getASTReader();
-  if (!Reader)
+  if (Reader.ReadAST(ModuleFilePath, serialization::MK_MainFile,
+ SourceLocation(),
+ ASTReader::ARR_None) != ASTReader::Success)
 return false;
 
   bool UpToDate = true;
-  Reader->getModuleManager().visit([&](serialization::ModuleFile &MF) -> bool {
-Reader->visitInputFiles(
+  Reader.getModuleManager().visit([&](serialization::ModuleFile &MF) -> bool {
+Reader.visitInputFiles(
 MF, /*IncludeSystem=*/false, /*Complain=*/false,
 [&](const serialization::InputFile &IF, bool isSystem) {
   if (!IF.getFile() || IF.isOutOfDate())
 UpToDate = false;
 });
-
 return !UpToDate;
   });
-
   return UpToDate;
 }
 
 bool IsModuleFilesUpToDate(
 llvm::SmallVector ModuleFilePaths,
-const PrerequisiteModules &RequisiteModules) {
-  return llvm::all_of(ModuleFilePaths, [&RequisiteModules](auto 
ModuleFilePath) {
-return IsModuleFileUpToDate(ModuleFilePath, RequisiteModules);
-  });
+const PrerequisiteModules &RequisiteModules,
+llvm::IntrusiveRefCntPtr VFS) {
+  return llvm::all_of(
+  ModuleFilePaths, [&RequisiteModules, VFS](auto ModuleFilePath) {
+return IsModuleFileUpToDate(ModuleFilePath, RequisiteModules, VFS);
+  });
 }
 
 // StandalonePrerequisiteModules - stands for PrerequisiteModules for which all
@@ -347,7 +362,7 @@ bool StandalonePrerequisiteModules::canReuse(
   SmallVector BMIPaths;
   for (auto &MF : RequiredModules)
 BMIPaths.push_back(MF.ModuleFilePath);
-  return IsModuleFilesUpToDate(BMIPaths, *this);
+  return IsModuleFilesUpToDate(BMIPaths, *this, VFS);
 }
 
 } // namespace clangd

>From 61a2c9adf302c49bb91eb81a86ffa2d399e6615e Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Tue, 29 Oct 2024 10:51:06 +0800
Subject: [PATCH 2/2] Update

---
 clang-tools-extra/clangd/ModulesBuilder.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/ModulesBuilder.cpp 
b/clang-tools-extra/clangd/ModulesBuilder.cpp
index 1566ec8d9d900d..c4ed7869d7d1e0 100644
--- a/clang-tools-extra/clangd/ModulesBuilder.cpp
+++ b/clang-tools-extra/clangd/ModulesBuilder.cpp
@@ -136,8 +136,9 @@ bool IsModuleFileUpToDate(PathRef ModuleFilePath,
   HSOpts->ForceCheckCXX20ModulesInputFiles = true;
   HSOpts->ValidateASTInputFilesConten

[clang-tools-extra] [clang-tidy] Fix crash in modernize-use-designated-initializers check (PR #113688)

2024-10-28 Thread via cfe-commits

z1nke wrote:

Hi, I don’t have write access to merge code, and this is my first commit to 
clang-tidy. What else needs to be done to merge this PR? Thanks!

https://github.com/llvm/llvm-project/pull/113688
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Fix crash in modernize-use-designated-initializers check (PR #113688)

2024-10-28 Thread Nicolas van Kempen via cfe-commits

https://github.com/nicovank edited 
https://github.com/llvm/llvm-project/pull/113688
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Fix crash in modernize-use-designated-initializers check (PR #113688)

2024-10-28 Thread via cfe-commits

https://github.com/z1nke updated 
https://github.com/llvm/llvm-project/pull/113688

>From a2184027393c9e9605aaa08f1d1eef4b11cd9be1 Mon Sep 17 00:00:00 2001
From: czn 
Date: Fri, 25 Oct 2024 21:48:50 +0800
Subject: [PATCH 1/3] [clang-tidy] Fix crash in
 modernize-use-designated-initializers check

---
 .../modernize/UseDesignatedInitializersCheck.cpp  | 8 ++--
 .../checkers/modernize/use-designated-initializers.cpp| 8 
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp
index 2a0cc403b726e8..3132067f3d5ece 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp
@@ -80,9 +80,13 @@ unsigned getNumberOfDesignated(const InitListExpr 
*SyntacticInitList) {
   });
 }
 
-AST_MATCHER(CXXRecordDecl, isAggregate) { return Node.isAggregate(); }
+AST_MATCHER(CXXRecordDecl, isAggregate) {
+  return Node.hasDefinition() && Node.isAggregate();
+}
 
-AST_MATCHER(CXXRecordDecl, isPOD) { return Node.isPOD(); }
+AST_MATCHER(CXXRecordDecl, isPOD) {
+  return Node.hasDefinition() && Node.isPOD();
+}
 
 AST_MATCHER(InitListExpr, isFullyDesignated) {
   if (const InitListExpr *SyntacticForm =
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-designated-initializers.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-designated-initializers.cpp
index 9b769ad0be23ca..db1fe3baa99d7c 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-designated-initializers.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-designated-initializers.cpp
@@ -201,3 +201,11 @@ DECLARE_S93;
 // CHECK-MESSAGES-MACROS: :[[@LINE-1]]:1: warning: use designated initializer 
list to initialize 'S9' [modernize-use-designated-initializers]
 // CHECK-MESSAGES-MACROS: :[[@LINE-4]]:28: note: expanded from macro 
'DECLARE_S93'
 // CHECK-MESSAGES-MACROS: :[[@LINE-71]]:1: note: aggregate type is defined here
+
+// Issus #113652.
+struct S14;
+
+struct S15{
+  S15(S14& d):d{d}{}
+  S14& d;
+};
\ No newline at end of file

>From 2bff90592868f3ecd728510408d8c78dbd5f605e Mon Sep 17 00:00:00 2001
From: czn 
Date: Fri, 25 Oct 2024 23:55:20 +0800
Subject: [PATCH 2/3] [clang-tidy] Fix typo

---
 .../checkers/modernize/use-designated-initializers.cpp| 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-designated-initializers.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-designated-initializers.cpp
index db1fe3baa99d7c..048665b2e54ac5 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-designated-initializers.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-designated-initializers.cpp
@@ -202,10 +202,10 @@ DECLARE_S93;
 // CHECK-MESSAGES-MACROS: :[[@LINE-4]]:28: note: expanded from macro 
'DECLARE_S93'
 // CHECK-MESSAGES-MACROS: :[[@LINE-71]]:1: note: aggregate type is defined here
 
-// Issus #113652.
+// Issue #113652.
 struct S14;
 
 struct S15{
   S15(S14& d):d{d}{}
   S14& d;
-};
\ No newline at end of file
+};

>From f2d16fe4d84b3aa09d2e9b055eb891c80dcef8e7 Mon Sep 17 00:00:00 2001
From: czn 
Date: Sat, 26 Oct 2024 08:34:10 +0800
Subject: [PATCH 3/3] Add release note

---
 clang-tools-extra/docs/ReleaseNotes.rst | 4 
 1 file changed, 4 insertions(+)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 876689c40fcdb2..0bea4be6e9e239 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -210,6 +210,10 @@ Changes in existing checks
   a false positive when only an implicit conversion happened inside an
   initializer list.
 
+- Improved :doc:`modernize-use-designated-initializers
+  ` check to fix a
+  crash when a class is declared but not defined.
+
 - Improved :doc:`modernize-use-nullptr
   ` check to also recognize
   ``NULL``/``__null`` (but not ``0``) when used with a templated type.

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


[clang] [clang][CodeGen][OpenCL] Fix `alloca` handling & `sret`when compiling for (PR #113930)

2024-10-28 Thread Matt Arsenault via cfe-commits


@@ -108,11 +108,15 @@ RawAddress CodeGenFunction::CreateTempAlloca(llvm::Type 
*Ty, CharUnits Align,
   if (AllocaAddr)
 *AllocaAddr = Alloca;
   llvm::Value *V = Alloca.getPointer();
+  assert((!getLangOpts().OpenCL ||
+  CGM.getTarget().getTargetAddressSpace(getASTAllocaAddressSpace()) ==
+  CGM.getTarget().getTargetAddressSpace(LangAS::opencl_private)) &&
+ "For OpenCL allocas must allocate in the private address space!");

arsenm wrote:

That is the nature of the PTX hack. They pretend everything is 0, and then fix 
up stack later. The backend then runs NVPTXLowerAlloca to introduce a bunch of 
casts to show that it really was an addrspace(5) pointer to begin with around 
most use contexts 

https://github.com/llvm/llvm-project/pull/113930
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] Avoid allocations when reading blob paths (PR #113984)

2024-10-28 Thread Jan Svoboda via cfe-commits


@@ -1341,9 +1341,22 @@ class ASTReader
   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
 bool Complain = true);
 
+  /// Buffer we use as temporary storage backing resolved paths.
+  SmallString<256> PathBuf;

jansvoboda11 wrote:

Do you have any suggestions?

https://github.com/llvm/llvm-project/pull/113984
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Remove Linux search paths on Windows (PR #113628)

2024-10-28 Thread David Salinas via cfe-commits

https://github.com/david-salinas updated 
https://github.com/llvm/llvm-project/pull/113628

>From 307e0abed8387b0bffa4b7e24e995ad7ec402749 Mon Sep 17 00:00:00 2001
From: David Salinas 
Date: Tue, 22 Oct 2024 18:58:47 +
Subject: [PATCH] Remove Linux search paths on Windows

Change-Id: Ia0b44eb1069fa631a6d5156cf5881c978e23b62d
---
 clang/lib/Driver/Driver.cpp  |  7 ++---
 clang/lib/Driver/ToolChains/AMDGPU.cpp   | 27 ++--
 clang/lib/Driver/ToolChains/AMDGPU.h |  2 +-
 clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp |  3 ++-
 clang/lib/Driver/ToolChains/Gnu.cpp  |  1 +
 clang/lib/Driver/ToolChains/HIPAMD.cpp   |  9 ++-
 clang/lib/Driver/ToolChains/MSVC.cpp |  6 +
 clang/lib/Driver/ToolChains/ROCm.h   | 12 +
 clang/test/Driver/rocm-detect-linux.hip  |  9 +++
 clang/test/Driver/rocm-detect-windows.hip|  9 +++
 10 files changed, 66 insertions(+), 19 deletions(-)
 create mode 100644 clang/test/Driver/rocm-detect-linux.hip
 create mode 100644 clang/test/Driver/rocm-detect-windows.hip

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 9878a9dad78d40..6fb743a8349fae 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -6440,7 +6440,8 @@ const ToolChain &Driver::getToolChain(const ArgList &Args,
   TC = std::make_unique(*this, Target, Args);
   break;
 case llvm::Triple::AMDHSA:
-  TC = std::make_unique(*this, Target, Args);
+  TC = std::make_unique(*this, Target, Args, 
+   Target.isOSWindows());
   break;
 case llvm::Triple::AMDPAL:
 case llvm::Triple::Mesa3D:
@@ -6582,8 +6583,8 @@ const ToolChain &Driver::getOffloadingDeviceToolChain(
 TC = std::make_unique(*this, Target,
HostTC, Args);
   else if (Target.getArch() == llvm::Triple::spirv64 &&
-   Target.getVendor() == llvm::Triple::UnknownVendor &&
-   Target.getOS() == llvm::Triple::UnknownOS)
+ Target.getVendor() == llvm::Triple::UnknownVendor &&
+ Target.getOS() == llvm::Triple::UnknownOS)
 TC = std::make_unique(*this, Target,
HostTC, Args);
   break;
diff --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index 2c85d21ebd738c..969c2e289f7fa0 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -306,15 +306,17 @@ RocmInstallationDetector::getInstallationPathCandidates() 
{
   LatestVer = Ver;
 }
   }
-  if (!LatestROCm.empty())
-ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/" + LatestROCm,
-/*StrictChecking=*/true);
 
-  ROCmSearchDirs.emplace_back(D.SysRoot + "/usr/local",
-  /*StrictChecking=*/true);
-  ROCmSearchDirs.emplace_back(D.SysRoot + "/usr",
-  /*StrictChecking=*/true);
+  if (!isHostWindows()) {
+if (!LatestROCm.empty())
+  ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/" + LatestROCm,
+  /*StrictChecking=*/true);
 
+ROCmSearchDirs.emplace_back(D.SysRoot + "/usr/local",
+/*StrictChecking=*/true);
+ROCmSearchDirs.emplace_back(D.SysRoot + "/usr",
+/*StrictChecking=*/true);
+  }
   DoPrintROCmSearchDirs();
   return ROCmSearchDirs;
 }
@@ -375,11 +377,6 @@ RocmInstallationDetector::RocmInstallationDetector(
Twine(DefaultVersionMinor) + "." + VersionPatch)
   .str();
   }
-
-  if (DetectHIPRuntime)
-detectHIPRuntime();
-  if (DetectDeviceLib)
-detectDeviceLibrary();
 }
 
 void RocmInstallationDetector::detectDeviceLibrary() {
@@ -703,6 +700,7 @@ AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const 
llvm::Triple &Triple,
 : Generic_ELF(D, Triple, Args),
   OptionsDefault(
   {{options::OPT_O, "3"}, {options::OPT_cl_std_EQ, "CL1.2"}}) {
+  RocmInstallation->init();
   // Check code object version options. Emit warnings for legacy options
   // and errors for the last invalid code object version options.
   // It is done here to avoid repeated warning or error messages for
@@ -835,8 +833,11 @@ bool AMDGPUToolChain::isWave64(const llvm::opt::ArgList 
&DriverArgs,
 
 /// ROCM Toolchain
 ROCMToolChain::ROCMToolChain(const Driver &D, const llvm::Triple &Triple,
- const ArgList &Args)
+ const ArgList &Args, bool isHostTCMSVC)
 : AMDGPUToolChain(D, Triple, Args) {
+  RocmInstallation->setHostWindows(isHostTCMSVC);
+  if (isHostTCMSVC)
+RocmInstallation->init(true, false);
   RocmInstallation->detectDeviceLibrary();
 }
 
diff --git a/clang/lib/Driver/ToolChains/AMDGPU.h 
b/clang/lib/Driver/ToolChains/AMD

[clang] [clang][modules] Avoid allocations when reading blob paths (PR #113984)

2024-10-28 Thread Jan Svoboda via cfe-commits


@@ -1341,9 +1341,22 @@ class ASTReader
   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
 bool Complain = true);
 
+  /// Buffer we use as temporary storage backing resolved paths.
+  SmallString<256> PathBuf;

jansvoboda11 wrote:

Allocations during path reading account for 5+% of wall time of the entire 
dependency scan, so I have to disagree that this isn't so bad. I'm curious, how 
is static local better than member variable?

https://github.com/llvm/llvm-project/pull/113984
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-28 Thread Ryosuke Niwa via cfe-commits


@@ -83,6 +83,77 @@ void foo7(RefCountable* obj) {
   bar.obj->method();
 }
 
+void foo8(RefCountable* obj) {
+  RefPtr foo;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo = nullptr;
+bar->method();
+  }
+  RefPtr baz;
+  {
+RefCountable *bar = baz.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+baz = obj;
+bar->method();
+  }
+  foo = nullptr;
+  {
+RefCountable *bar = foo.get();
+// No warning. It's okay to mutate RefPtr in an outer scope.
+bar->method();
+  }
+  foo = obj;
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo.releaseNonNull();
+bar->method();
+  }
+  {
+RefCountable *bar = foo.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+foo = obj ? obj : nullptr;
+bar->method();
+  }
+}
+
+void foo9(RefCountable& o) {
+  Ref guardian(o);
+  {
+RefCountable &bar = guardian.get();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian = o; // We don't detect that we're setting it to the same value.
+bar.method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(*bar); // We don't detect other has the same value 
as guardian.
+guardian.swap(other);
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+Ref other(static_cast&&>(guardian));
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian.leakRef();
+bar->method();
+  }
+  {
+RefCountable *bar = guardian.ptr();
+// expected-warning@-1{{Local variable 'bar' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+guardian = o.trivial() ? o : *bar;

rniwa wrote:

To put it another way, the issue isn't so much that the guardian variable is 
getting mutated but rather that we're using a raw pointer in such a way there 
is no guardian variable which keeps the same object alive.

https://github.com/llvm/llvm-project/pull/113859
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] convert path to Windows path if user is using a MSYS2 shell (PR #111526)

2024-10-28 Thread Gary Wang via cfe-commits

BLumia wrote:

@HazardyKnusperkeks @owenca @cor3ntin sorry for the ping, kindly asking for a 
review. Thanks in advance!

https://github.com/llvm/llvm-project/pull/111526
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] Avoid allocations when reading blob paths (PR #113984)

2024-10-28 Thread Chuanqi Xu via cfe-commits


@@ -1341,9 +1341,22 @@ class ASTReader
   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
 bool Complain = true);
 
+  /// Buffer we use as temporary storage backing resolved paths.
+  SmallString<256> PathBuf;

ChuanqiXu9 wrote:

I think the static local variable makes it harder to be misused. As you said, 
we must be careful for the "global" variable. Then I feel better if we can 
reduce the mind burden.

https://github.com/llvm/llvm-project/pull/113984
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][ExprConst] Reject field access with nullptr base (PR #113885)

2024-10-28 Thread Richard Smith via cfe-commits


@@ -1703,7 +1703,7 @@ namespace {
 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
   if (Designator.Invalid)
 return false;
-  if (IsNullPtr) {
+  if (getLValueBase().isNull()) {

zygoloid wrote:

Why was the old check not good enough here? In the added testcase, `nb` is a 
null pointer.

https://github.com/llvm/llvm-project/pull/113885
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][ExprConst] Reject field access with nullptr base (PR #113885)

2024-10-28 Thread Richard Smith via cfe-commits


@@ -1703,7 +1703,7 @@ namespace {
 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
   if (Designator.Invalid)
 return false;
-  if (IsNullPtr) {
+  if (getLValueBase().isNull()) {

zygoloid wrote:

Oh, I see. We're adjusting the offset *before* we call `addDecl`. I think this 
would be better fixed by reversing the order in which we do those steps -- 
first `addDecl` and then adjust the offset. A null base isn't necessarily a 
null pointer, so checking for a null base here seems wrong (but only in the 
weird case of a zero integer cast to a non-null pointer value, which we should 
only accept in constant-folding mode, not when properly evaluating).

https://github.com/llvm/llvm-project/pull/113885
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][SYCL] Introduce clang-sycl-linker to link SYCL offloading device code (Part 1 of many) (PR #112245)

2024-10-28 Thread Alexey Bader via cfe-commits


@@ -0,0 +1,42 @@
+// Tests the clang-sycl-linker tool.
+//
+// Test a simple case without arguments.
+// RUN: %clangxx -fsycl -emit-llvm -c %s -o %t.bc
+// RUN: clang-sycl-linker --dry-run -triple spirv64 %t.bc -o a.spv 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=SIMPLE
+// SIMPLE: "{{.*}}llvm-link{{.*}}" {{.*}}.bc -o [[FIRSTLLVMLINKOUT:.*]].bc 
--suppress-warnings
+// SIMPLE-NEXT: "{{.*}}llvm-spirv{{.*}}" {{.*}}-o a.spv [[FIRSTLLVMLINKOUT]].bc
+//
+// Test a simple case with device library files specified.
+// RUN: echo ' ' > %T/lib1.bc
+// RUN: echo ' ' > %T/lib2.bc
+// RUN: clang-sycl-linker --dry-run -triple spirv64 %t.bc --library-path=%T 
--device-libs=lib1.bc,lib2.bc -o a.spv 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=DEVLIBS
+// DEVLIBS: "{{.*}}llvm-link{{.*}}" {{.*}}.bc -o [[FIRSTLLVMLINKOUT:.*]].bc 
--suppress-warnings
+// DEVLIBS-NEXT: "{{.*}}llvm-link{{.*}}" -only-needed [[FIRSTLLVMLINKOUT]].bc 
{{.*}}lib1.bc {{.*}}lib2.bc -o [[SECONDLLVMLINKOUT:.*]].bc --suppress-warnings
+// DEVLIBS-NEXT: "{{.*}}llvm-spirv{{.*}}" {{.*}}-o a.spv 
[[SECONDLLVMLINKOUT]].bc
+//
+// Test a simple case with .o (fat object) as input.
+// TODO: Remove this test once fat object support is added.

bader wrote:

Is `clang-sycl-linker` supposed to support fat objects? According to my 
understanding, this tool links the device code only. Some other tool (e.g. 
`clang-linker-wrapper`) is supposed to extract device code from fat objects and 
invoke `clang-sycl-linker` tool to link the device code. I think this tool is 
supposed to handle object files, but only 'lean'. @jhuber6, did I get it right?

https://github.com/llvm/llvm-project/pull/112245
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][SYCL] Introduce clang-sycl-linker to link SYCL offloading device code (Part 1 of many) (PR #112245)

2024-10-28 Thread Alexey Bader via cfe-commits


@@ -0,0 +1,500 @@
+//= clang-sycl-linker/ClangSYCLLinker.cpp - SYCL Linker util ---=//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===-===//
+//
+// This tool executes a sequence of steps required to link device code in SYCL
+// fat objects. SYCL device code linking requires a complex sequence of steps
+// that include linking of llvm bitcode files, linking device library files
+// with the fully linked source bitcode file(s), running several SYCL specific
+// post-link steps on the fully linked bitcode file(s), and finally generating
+// target-specific device code.
+//===-===//
+
+#include "clang/Basic/Version.h"
+
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/BinaryFormat/Magic.h"
+#include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/CommandFlags.h"
+#include "llvm/IR/DiagnosticPrinter.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"
+#include "llvm/Object/ELFObjectFile.h"
+#include "llvm/Object/IRObjectFile.h"
+#include "llvm/Object/ObjectFile.h"
+#include "llvm/Object/OffloadBinary.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Option/OptTable.h"
+#include "llvm/Option/Option.h"
+#include "llvm/Remarks/HotnessThresholdParser.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/FileOutputBuffer.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/InitLLVM.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/StringSaver.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/TimeProfiler.h"
+#include "llvm/Support/WithColor.h"
+
+using namespace llvm;
+using namespace llvm::opt;
+using namespace llvm::object;
+
+/// Save intermediary results.
+static bool SaveTemps = false;
+
+/// Print arguments without executing.
+static bool DryRun = false;
+
+/// Print verbose output.
+static bool Verbose = false;
+
+/// Filename of the output being created.
+static StringRef OutputFile;
+
+/// Directory to dump SPIR-V IR if requested by user.
+static SmallString<128> SPIRVDumpDir;
+
+static void printVersion(raw_ostream &OS) {
+  OS << clang::getClangToolFullVersion("clang-sycl-linker") << '\n';
+}
+
+/// The value of `argv[0]` when run.
+static const char *Executable;
+
+/// Temporary files to be cleaned up.
+static SmallVector> TempFiles;
+
+namespace {
+// Must not overlap with llvm::opt::DriverFlag.
+enum WrapperFlags { WrapperOnlyOption = (1 << 4) };
+
+enum ID {
+  OPT_INVALID = 0, // This is not an option ID.
+#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
+#include "SYCLLinkOpts.inc"
+  LastOption
+#undef OPTION
+};
+
+#define PREFIX(NAME, VALUE)
\
+  static constexpr StringLiteral NAME##_init[] = VALUE;
\
+  static constexpr ArrayRef NAME(NAME##_init,   
\
+std::size(NAME##_init) - 1);
+#include "SYCLLinkOpts.inc"
+#undef PREFIX
+
+static constexpr OptTable::Info InfoTable[] = {
+#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
+#include "SYCLLinkOpts.inc"
+#undef OPTION
+};
+
+class WrapperOptTable : public opt::GenericOptTable {
+public:
+  WrapperOptTable() : opt::GenericOptTable(InfoTable) {}
+};
+
+const OptTable &getOptTable() {
+  static const WrapperOptTable *Table = []() {
+auto Result = std::make_unique();
+return Result.release();
+  }();
+  return *Table;
+}
+
+[[noreturn]] void reportError(Error E) {
+  outs().flush();
+  logAllUnhandledErrors(std::move(E), WithColor::error(errs(), Executable));
+  exit(EXIT_FAILURE);
+}
+
+std::string getMainExecutable(const char *Name) {
+  void *Ptr = (void *)(intptr_t)&getMainExecutable;
+  auto COWPath = sys::fs::getMainExecutable(Name, Ptr);
+  return sys::path::parent_path(COWPath).str();
+}
+
+Expected createTempFile(const ArgList &Args, const Twine &Prefix,
+   StringRef Extension) {
+  SmallString<128> OutputFile;
+  if (Args.hasArg(OPT_save_temps)) {
+// Generate a unique path name without creating a file
+sys::fs::createUniquePath(Prefix + "-%%." + Extension, OutputFile,
+  /*MakeAbsolute=*/false);
+  } else {
+if (std::error_code EC =
+sys::fs::createTemporaryFile(Prefix, Extension, OutputFile))
+  return createFileError(OutputFile, EC);
+  }
+
+  TempFiles.emplace_back(std::move(OutputFile));
+  return TempFiles.back();
+}
+
+Expected findProgram(const ArgList &Args, Strin

[libclc] [libclc] Create an internal 'clc' builtins library (PR #109985)

2024-10-28 Thread Matt Arsenault via cfe-commits

https://github.com/arsenm approved this pull request.


https://github.com/llvm/llvm-project/pull/109985
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][SYCL] Introduce clang-sycl-linker to link SYCL offloading device code (Part 1 of many) (PR #112245)

2024-10-28 Thread Alexey Bader via cfe-commits


@@ -0,0 +1,42 @@
+// Tests the clang-sycl-linker tool.
+//
+// Test a simple case without arguments.
+// RUN: %clangxx -fsycl -emit-llvm -c %s -o %t.bc
+// RUN: clang-sycl-linker --dry-run -triple spirv64 %t.bc -o a.spv 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=SIMPLE
+// SIMPLE: "{{.*}}llvm-link{{.*}}" {{.*}}.bc -o [[FIRSTLLVMLINKOUT:.*]].bc 
--suppress-warnings
+// SIMPLE-NEXT: "{{.*}}llvm-spirv{{.*}}" {{.*}}-o a.spv [[FIRSTLLVMLINKOUT]].bc
+//
+// Test a simple case with device library files specified.
+// RUN: echo ' ' > %T/lib1.bc
+// RUN: echo ' ' > %T/lib2.bc
+// RUN: clang-sycl-linker --dry-run -triple spirv64 %t.bc --library-path=%T 
--device-libs=lib1.bc,lib2.bc -o a.spv 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=DEVLIBS
+// DEVLIBS: "{{.*}}llvm-link{{.*}}" {{.*}}.bc -o [[FIRSTLLVMLINKOUT:.*]].bc 
--suppress-warnings
+// DEVLIBS-NEXT: "{{.*}}llvm-link{{.*}}" -only-needed [[FIRSTLLVMLINKOUT]].bc 
{{.*}}lib1.bc {{.*}}lib2.bc -o [[SECONDLLVMLINKOUT:.*]].bc --suppress-warnings
+// DEVLIBS-NEXT: "{{.*}}llvm-spirv{{.*}}" {{.*}}-o a.spv 
[[SECONDLLVMLINKOUT]].bc
+//
+// Test a simple case with .o (fat object) as input.
+// TODO: Remove this test once fat object support is added.
+// RUN: %clangxx -fsycl -c %s -o %t.o
+// RUN: not clang-sycl-linker --dry-run -triple spirv64 %t.o -o a.spv 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=FILETYPEERROR
+// FILETYPEERROR: Unsupported file type
+//
+// Test to see if device library related errors are emitted.
+// RUN: not clang-sycl-linker --dry-run -triple spirv64 %t.bc 
--library-path=%T --device-libs= -o a.spv 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=DEVLIBSERR1
+// DEVLIBSERR1: Number of device library files cannot be zero
+// RUN: not clang-sycl-linker --dry-run -triple spirv64 %t.bc 
--library-path=%T --device-libs=lib3.bc -o a.spv 2>&1 \

bader wrote:

```suggestion
// RUN: not clang-sycl-linker --dry-run -triple spirv64 %t.bc --library-path=%T 
--device-libs=lib1.bc,lib2.bc,lib3.bc -o a.spv 2>&1 \
```

https://github.com/llvm/llvm-project/pull/112245
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][SYCL] Introduce clang-sycl-linker to link SYCL offloading device code (Part 1 of many) (PR #112245)

2024-10-28 Thread Alexey Bader via cfe-commits


@@ -0,0 +1,55 @@
+include "llvm/Option/OptParser.td"
+
+def WrapperOnlyOption : OptionFlag;
+
+def help : Flag<["-", "--"], "help">,
+  HelpText<"Display available options (--help-hidden for more)">;
+
+def help_hidden : Flag<["-", "--"], "help-hidden">,
+  HelpText<"Display all available options">;
+
+def verbose : Flag<["-"], "v">, HelpText<"Print verbose information">;
+def version : Flag<["--"], "version">,
+  HelpText<"Display the version number and exit">;
+
+def o : JoinedOrSeparate<["-"], "o">, MetaVarName<"">,
+  HelpText<"Path to file to write output">;
+def output : Separate<["--"], "output-file">, Alias, Flags<[HelpHidden]>,
+  HelpText<"Alias for -o">;
+
+def library_path_EQ : Joined<["--", "-"], "library-path=">,
+  Flags<[HelpHidden]>, HelpText<"Add  to the library search path">;
+
+def device_libs_EQ : CommaJoined<["--", "-"], "device-libs=">,
+  Flags<[WrapperOnlyOption]>,
+  HelpText<"A comma separated list of device libraries that are linked during 
the device link.">;
+
+def triple : Joined<["--"], "triple">,
+  HelpText<"The device target triple">;
+def arch : Separate<["--", "-"], "arch">,
+  HelpText<"Specify the name of the target architecture.">;
+
+def g : Flag<["-"], "g">, HelpText<"Specify that this was a debug compile.">;
+def debug : Flag<["--"], "debug">, Alias;

bader wrote:

Why would we need to specify that? I see that this option is not used. I would 
expect the linker to inspect the object file to identify if "this was a debug 
compile" rather than rely on command line option.

https://github.com/llvm/llvm-project/pull/112245
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Remove Linux search paths on Windows (PR #113628)

2024-10-28 Thread David Salinas via cfe-commits

https://github.com/david-salinas updated 
https://github.com/llvm/llvm-project/pull/113628

>From ee17fe072310a55e004134bb793a18b8089b4020 Mon Sep 17 00:00:00 2001
From: David Salinas 
Date: Tue, 22 Oct 2024 18:58:47 +
Subject: [PATCH] Remove Linux search paths on Windows

Change-Id: Ia0b44eb1069fa631a6d5156cf5881c978e23b62d
---
 clang/lib/Driver/Driver.cpp  |  6 ++---
 clang/lib/Driver/ToolChains/AMDGPU.cpp   | 27 ++--
 clang/lib/Driver/ToolChains/AMDGPU.h |  2 +-
 clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp |  2 +-
 clang/lib/Driver/ToolChains/Gnu.cpp  |  1 +
 clang/lib/Driver/ToolChains/HIPAMD.cpp   |  9 ++-
 clang/lib/Driver/ToolChains/MSVC.cpp |  6 +
 clang/lib/Driver/ToolChains/ROCm.h   | 12 +
 clang/test/Driver/rocm-detect-linux.hip  |  9 +++
 clang/test/Driver/rocm-detect-windows.hip|  9 +++
 10 files changed, 64 insertions(+), 19 deletions(-)
 create mode 100644 clang/test/Driver/rocm-detect-linux.hip
 create mode 100644 clang/test/Driver/rocm-detect-windows.hip

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 9878a9dad78d40..d9b75c814c6bc5 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -6440,7 +6440,7 @@ const ToolChain &Driver::getToolChain(const ArgList &Args,
   TC = std::make_unique(*this, Target, Args);
   break;
 case llvm::Triple::AMDHSA:
-  TC = std::make_unique(*this, Target, Args);
+  TC = std::make_unique(*this, Target, Args, 
Target.isOSWindows());
   break;
 case llvm::Triple::AMDPAL:
 case llvm::Triple::Mesa3D:
@@ -6582,8 +6582,8 @@ const ToolChain &Driver::getOffloadingDeviceToolChain(
 TC = std::make_unique(*this, Target,
HostTC, Args);
   else if (Target.getArch() == llvm::Triple::spirv64 &&
-   Target.getVendor() == llvm::Triple::UnknownVendor &&
-   Target.getOS() == llvm::Triple::UnknownOS)
+ Target.getVendor() == llvm::Triple::UnknownVendor &&
+ Target.getOS() == llvm::Triple::UnknownOS)
 TC = std::make_unique(*this, Target,
HostTC, Args);
   break;
diff --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index 2c85d21ebd738c..f150abd2b5c285 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -306,15 +306,17 @@ RocmInstallationDetector::getInstallationPathCandidates() 
{
   LatestVer = Ver;
 }
   }
-  if (!LatestROCm.empty())
-ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/" + LatestROCm,
-/*StrictChecking=*/true);
 
-  ROCmSearchDirs.emplace_back(D.SysRoot + "/usr/local",
-  /*StrictChecking=*/true);
-  ROCmSearchDirs.emplace_back(D.SysRoot + "/usr",
-  /*StrictChecking=*/true);
+  if (!isHostWindows()) {
+   if (!LatestROCm.empty())
+ ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/" + LatestROCm,
+ /*StrictChecking=*/true);
 
+   ROCmSearchDirs.emplace_back(D.SysRoot + "/usr/local",
+   /*StrictChecking=*/true);
+   ROCmSearchDirs.emplace_back(D.SysRoot + "/usr",
+   /*StrictChecking=*/true);
+  }
   DoPrintROCmSearchDirs();
   return ROCmSearchDirs;
 }
@@ -375,11 +377,6 @@ RocmInstallationDetector::RocmInstallationDetector(
Twine(DefaultVersionMinor) + "." + VersionPatch)
   .str();
   }
-
-  if (DetectHIPRuntime)
-detectHIPRuntime();
-  if (DetectDeviceLib)
-detectDeviceLibrary();
 }
 
 void RocmInstallationDetector::detectDeviceLibrary() {
@@ -703,6 +700,7 @@ AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const 
llvm::Triple &Triple,
 : Generic_ELF(D, Triple, Args),
   OptionsDefault(
   {{options::OPT_O, "3"}, {options::OPT_cl_std_EQ, "CL1.2"}}) {
+  RocmInstallation->init();
   // Check code object version options. Emit warnings for legacy options
   // and errors for the last invalid code object version options.
   // It is done here to avoid repeated warning or error messages for
@@ -835,8 +833,11 @@ bool AMDGPUToolChain::isWave64(const llvm::opt::ArgList 
&DriverArgs,
 
 /// ROCM Toolchain
 ROCMToolChain::ROCMToolChain(const Driver &D, const llvm::Triple &Triple,
- const ArgList &Args)
+ const ArgList &Args, bool isHostTCMSVC)
 : AMDGPUToolChain(D, Triple, Args) {
+  RocmInstallation->setHostWindows(isHostTCMSVC);
+  if (isHostTCMSVC) 
+RocmInstallation->init(true, false);
   RocmInstallation->detectDeviceLibrary();
 }
 
diff --git a/clang/lib/Driver/ToolChains/AMDGPU.h 
b/clang/lib/Driver/ToolChains/AMDGPU.h
index a9b4552a1f91a4..db08529f955168 100644
--- a/clang/l

[clang-tools-extra] [clangd] [Modules] Use ASTReader directly in IsModuleFileUpToDate (PR #113879)

2024-10-28 Thread Chuanqi Xu via cfe-commits


@@ -127,33 +127,39 @@ struct ModuleFile {
   std::string ModuleFilePath;
 };
 
-bool IsModuleFileUpToDate(PathRef ModuleFilePath,
-  const PrerequisiteModules &RequisiteModules,
-  llvm::IntrusiveRefCntPtr VFS) 
{
+bool IsModuleFileUpToDate(
+PathRef ModuleFilePath,
+const PrerequisiteModules &RequisiteModules,
+const CompilerInvocation &CI,
+llvm::IntrusiveRefCntPtr VFS) {
+  CompilerInstance Clang;

ChuanqiXu9 wrote:

We may not be able to do it since ASTReader is stateful. If the ASTReader reads 
multiple module files (BMIs), the ASTReader will check automatically if these 
module files conflicts with each other. It doesn't matter in an ideal world. 
But it is common that users wrote invalid codes especially during the process 
of editing.

https://github.com/llvm/llvm-project/pull/113879
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] Reapply " [XRay] Add support for instrumentation of DSOs on x86_64 (#90959)" (PR #113548)

2024-10-28 Thread Jordan Rupprecht via cfe-commits


@@ -0,0 +1,17 @@
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fPIC -fxray-instrument 
-fxray-shared -c %s -o /dev/null 2>&1 | FileCheck %s
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fpic -fxray-instrument 
-fxray-shared -c %s -o /dev/null 2>&1 | FileCheck %s
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fxray-instrument 
-fxray-shared -c %s -o /dev/null 2>&1 | FileCheck %s

rupprecht wrote:

This test case fails for builds where the `CLANG_DEFAULT_PIE_ON_LINUX` cmake 
option is not the default.

If this test line is important, we could move it to a separate test file 
guarded by the `default-pie-on-linux` lit feature, i.e. like 
https://github.com/llvm/llvm-project/blob/main/clang/test/Driver/linux-default-pie.c.

However, I'd argue this case is not worth keeping. The two test lines above 
verify `-fxray-shared` work w/ pic, and the two below verify it doesn't work w/ 
no-pic. With the tests surrounding this in place, the only thing this verifies 
is that pic is the default (which isn't always true), and linux-default-pie.c 
already covers that behavior.

Any objection to just removing this line? Or should I move it to a separate 
file? (btw, not asking for a revert -- I'm just ignoring this test failure)

https://github.com/llvm/llvm-project/pull/113548
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] Avoid allocations when reading blob paths (PR #113984)

2024-10-28 Thread Jan Svoboda via cfe-commits


@@ -1341,9 +1341,22 @@ class ASTReader
   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
 bool Complain = true);
 
+  /// Buffer we use as temporary storage backing resolved paths.
+  SmallString<256> PathBuf;

jansvoboda11 wrote:

Because if callers construct fresh buffers all the time, each call to 
`ResolveImportedPath()` allocates. If the buffer is global, the function never 
allocates again after the longest path has been resolved.

https://github.com/llvm/llvm-project/pull/113984
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][SYCL] Introduce clang-sycl-linker to link SYCL offloading device code (Part 1 of many) (PR #112245)

2024-10-28 Thread Joseph Huber via cfe-commits


@@ -0,0 +1,500 @@
+//= clang-sycl-linker/ClangSYCLLinker.cpp - SYCL Linker util ---=//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===-===//
+//
+// This tool executes a sequence of steps required to link device code in SYCL
+// fat objects. SYCL device code linking requires a complex sequence of steps
+// that include linking of llvm bitcode files, linking device library files
+// with the fully linked source bitcode file(s), running several SYCL specific
+// post-link steps on the fully linked bitcode file(s), and finally generating
+// target-specific device code.
+//===-===//
+
+#include "clang/Basic/Version.h"
+
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/BinaryFormat/Magic.h"
+#include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/CommandFlags.h"
+#include "llvm/IR/DiagnosticPrinter.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"
+#include "llvm/Object/ELFObjectFile.h"
+#include "llvm/Object/IRObjectFile.h"
+#include "llvm/Object/ObjectFile.h"
+#include "llvm/Object/OffloadBinary.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Option/OptTable.h"
+#include "llvm/Option/Option.h"
+#include "llvm/Remarks/HotnessThresholdParser.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/FileOutputBuffer.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/InitLLVM.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/StringSaver.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/TimeProfiler.h"
+#include "llvm/Support/WithColor.h"
+
+using namespace llvm;
+using namespace llvm::opt;
+using namespace llvm::object;
+
+/// Save intermediary results.
+static bool SaveTemps = false;
+
+/// Print arguments without executing.
+static bool DryRun = false;
+
+/// Print verbose output.
+static bool Verbose = false;
+
+/// Filename of the output being created.
+static StringRef OutputFile;
+
+/// Directory to dump SPIR-V IR if requested by user.
+static SmallString<128> SPIRVDumpDir;
+
+static void printVersion(raw_ostream &OS) {
+  OS << clang::getClangToolFullVersion("clang-sycl-linker") << '\n';
+}
+
+/// The value of `argv[0]` when run.
+static const char *Executable;
+
+/// Temporary files to be cleaned up.
+static SmallVector> TempFiles;
+
+namespace {
+// Must not overlap with llvm::opt::DriverFlag.
+enum WrapperFlags { WrapperOnlyOption = (1 << 4) };
+
+enum ID {
+  OPT_INVALID = 0, // This is not an option ID.
+#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
+#include "SYCLLinkOpts.inc"
+  LastOption
+#undef OPTION
+};
+
+#define PREFIX(NAME, VALUE)
\
+  static constexpr StringLiteral NAME##_init[] = VALUE;
\
+  static constexpr ArrayRef NAME(NAME##_init,   
\
+std::size(NAME##_init) - 1);
+#include "SYCLLinkOpts.inc"
+#undef PREFIX
+
+static constexpr OptTable::Info InfoTable[] = {
+#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
+#include "SYCLLinkOpts.inc"
+#undef OPTION
+};
+
+class WrapperOptTable : public opt::GenericOptTable {
+public:
+  WrapperOptTable() : opt::GenericOptTable(InfoTable) {}
+};
+
+const OptTable &getOptTable() {
+  static const WrapperOptTable *Table = []() {
+auto Result = std::make_unique();
+return Result.release();
+  }();
+  return *Table;
+}
+
+[[noreturn]] void reportError(Error E) {
+  outs().flush();
+  logAllUnhandledErrors(std::move(E), WithColor::error(errs(), Executable));
+  exit(EXIT_FAILURE);
+}
+
+std::string getMainExecutable(const char *Name) {
+  void *Ptr = (void *)(intptr_t)&getMainExecutable;
+  auto COWPath = sys::fs::getMainExecutable(Name, Ptr);
+  return sys::path::parent_path(COWPath).str();
+}
+
+Expected createTempFile(const ArgList &Args, const Twine &Prefix,
+   StringRef Extension) {
+  SmallString<128> OutputFile;
+  if (Args.hasArg(OPT_save_temps)) {
+// Generate a unique path name without creating a file
+sys::fs::createUniquePath(Prefix + "-%%." + Extension, OutputFile,
+  /*MakeAbsolute=*/false);
+  } else {
+if (std::error_code EC =
+sys::fs::createTemporaryFile(Prefix, Extension, OutputFile))
+  return createFileError(OutputFile, EC);
+  }
+
+  TempFiles.emplace_back(std::move(OutputFile));
+  return TempFiles.back();
+}
+
+Expected findProgram(const ArgList &Args, Strin

[clang] [Clang][SYCL] Introduce clang-sycl-linker to link SYCL offloading device code (Part 1 of many) (PR #112245)

2024-10-28 Thread Joseph Huber via cfe-commits


@@ -0,0 +1,55 @@
+include "llvm/Option/OptParser.td"
+
+def WrapperOnlyOption : OptionFlag;
+
+def help : Flag<["-", "--"], "help">,
+  HelpText<"Display available options (--help-hidden for more)">;
+
+def help_hidden : Flag<["-", "--"], "help-hidden">,
+  HelpText<"Display all available options">;
+
+def verbose : Flag<["-"], "v">, HelpText<"Print verbose information">;
+def version : Flag<["--"], "version">,
+  HelpText<"Display the version number and exit">;
+
+def o : JoinedOrSeparate<["-"], "o">, MetaVarName<"">,
+  HelpText<"Path to file to write output">;
+def output : Separate<["--"], "output-file">, Alias, Flags<[HelpHidden]>,
+  HelpText<"Alias for -o">;
+
+def library_path_EQ : Joined<["--", "-"], "library-path=">,
+  Flags<[HelpHidden]>, HelpText<"Add  to the library search path">;
+
+def device_libs_EQ : CommaJoined<["--", "-"], "device-libs=">,
+  Flags<[WrapperOnlyOption]>,
+  HelpText<"A comma separated list of device libraries that are linked during 
the device link.">;
+
+def triple : Joined<["--"], "triple">,
+  HelpText<"The device target triple">;
+def arch : Separate<["--", "-"], "arch">,
+  HelpText<"Specify the name of the target architecture.">;
+
+def g : Flag<["-"], "g">, HelpText<"Specify that this was a debug compile.">;
+def debug : Flag<["--"], "debug">, Alias;

jhuber6 wrote:

Probably not necessary here, probably copied from the NVPTX case where we 
needed to handle it separately because `-O2` is an error if the PTX was created 
with `-g`.

https://github.com/llvm/llvm-project/pull/112245
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   4   5   6   >