Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,13 @@ TEST_F(OverlayCDBTest, GetCompileCommand) {
EXPECT_EQ(CDB.getCompileCommand(testPath("missing.cc")), std::nullopt);

auto Override = cmd(testPath("foo.cc"), "-DA=3");
CDB.setCompileCommand(testPath("foo.cc"), Override);
EXPECT_TRUE(CDB.setCompileCommand(testPath("foo.cc"), Override));
EXPECT_FALSE(CDB.setCompileCommand(testPath("foo.cc"), Override));
EXPECT_THAT(CDB.getCompileCommand(testPath("foo.cc"))->CommandLine,
Contains("-DA=3"));
EXPECT_EQ(CDB.getCompileCommand(testPath("missing.cc")), std::nullopt);
CDB.setCompileCommand(testPath("missing.cc"), Override);
EXPECT_TRUE(CDB.setCompileCommand(testPath("missing.cc"), Override));
EXPECT_FALSE(CDB.setCompileCommand(testPath("missing.cc"), Override));
EXPECT_THAT(CDB.getCompileCommand(testPath("missing.cc"))->CommandLine,
Contains("-DA=3"));
}
Expand All @@ -111,7 +113,7 @@ TEST_F(OverlayCDBTest, NoBase) {
OverlayCDB CDB(nullptr, {"-DA=6"});
EXPECT_EQ(CDB.getCompileCommand(testPath("bar.cc")), std::nullopt);
auto Override = cmd(testPath("bar.cc"), "-DA=5");
CDB.setCompileCommand(testPath("bar.cc"), Override);
EXPECT_TRUE(CDB.setCompileCommand(testPath("bar.cc"), Override));
EXPECT_THAT(CDB.getCompileCommand(testPath("bar.cc"))->CommandLine,
Contains("-DA=5"));

Expand All @@ -128,10 +130,10 @@ TEST_F(OverlayCDBTest, Watch) {
Changes.push_back(ChangedFiles);
});

Inner.setCompileCommand("A.cpp", tooling::CompileCommand());
Outer.setCompileCommand("B.cpp", tooling::CompileCommand());
Inner.setCompileCommand("A.cpp", std::nullopt);
Outer.setCompileCommand("C.cpp", std::nullopt);
EXPECT_TRUE(Inner.setCompileCommand("A.cpp", tooling::CompileCommand()));
EXPECT_TRUE(Outer.setCompileCommand("B.cpp", tooling::CompileCommand()));
EXPECT_TRUE(Inner.setCompileCommand("A.cpp", std::nullopt));
EXPECT_TRUE(Outer.setCompileCommand("C.cpp", std::nullopt));
EXPECT_THAT(Changes, ElementsAre(ElementsAre("A.cpp"), ElementsAre("B.cpp"),
ElementsAre("A.cpp"), ElementsAre("C.cpp")));
}
Expand All @@ -151,7 +153,7 @@ TEST_F(OverlayCDBTest, Adjustments) {
tooling::CompileCommand BarCommand;
BarCommand.Filename = testPath("bar.cc");
BarCommand.CommandLine = {"clang++", "-DB=1", testPath("bar.cc")};
CDB.setCompileCommand(testPath("bar.cc"), BarCommand);
EXPECT_TRUE(CDB.setCompileCommand(testPath("bar.cc"), BarCommand));
Cmd = *CDB.getCompileCommand(testPath("bar.cc"));
EXPECT_THAT(
Cmd.CommandLine,
Expand Down Expand Up @@ -412,7 +414,7 @@ TEST(GlobalCompilationDatabaseTest, NonCanonicalFilenames) {

llvm::SmallString<128> Root(testRoot());
llvm::sys::path::append(Root, "build", "..", "a.cc");
DB.setCompileCommand(Root.str(), tooling::CompileCommand());
EXPECT_TRUE(DB.setCompileCommand(Root.str(), tooling::CompileCommand()));
EXPECT_THAT(DiscoveredFiles, UnorderedElementsAre(testPath("a.cc")));
DiscoveredFiles.clear();

Expand All @@ -432,7 +434,7 @@ TEST_F(OverlayCDBTest, GetProjectInfo) {
EXPECT_EQ(DB.getProjectInfo(Header)->SourceRoot, testRoot());

// Shouldn't change after an override.
DB.setCompileCommand(File, tooling::CompileCommand());
EXPECT_TRUE(DB.setCompileCommand(File, tooling::CompileCommand()));
EXPECT_EQ(DB.getProjectInfo(File)->SourceRoot, testRoot());
EXPECT_EQ(DB.getProjectInfo(Header)->SourceRoot, testRoot());
}
Expand Down
59 changes: 59 additions & 0 deletions clang-tools-extra/clangd/unittests/tweaks/ExtractFunctionTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,18 @@ F (extracted();)
}]]
)cpp";
EXPECT_EQ(apply(CompoundFailInput), "unavailable");

ExtraArgs.push_back("-std=c++14");
// FIXME: Expressions are currently not extracted
EXPECT_EQ(apply(R"cpp(
void call() { [[1+1]]; }
)cpp"),
"unavailable");
// FIXME: Single expression statements are currently not extracted
EXPECT_EQ(apply(R"cpp(
void call() { [[1+1;]] }
)cpp"),
"unavailable");
}

TEST_F(ExtractFunctionTest, DifferentHeaderSourceTest) {
Expand Down Expand Up @@ -571,6 +583,53 @@ int getNum(bool Superstitious, int Min, int Max) {
EXPECT_EQ(apply(Before), After);
}

TEST_F(ExtractFunctionTest, OverloadedOperators) {
Context = File;
std::string Before = R"cpp(struct A {
int operator+(int x) { return x; }
};
A &operator<<(A &, int);
A &operator|(A &, int);
A stream{};
void foo(int, int);
int main() {
[[foo(1, 2);
foo(3, 4);
stream << 42;
stream + 42;
stream | 42;
foo(1, 2);
foo(3, 4);]]
})cpp";
std::string After =
R"cpp(struct A {
int operator+(int x) { return x; }
};
A &operator<<(A &, int);
A &operator|(A &, int);
A stream{};
void foo(int, int);
void extracted() {
foo(1, 2);
foo(3, 4);
stream << 42;
stream + 42;
stream | 42;
foo(1, 2);
foo(3, 4);
}
int main() {
extracted();
})cpp";
EXPECT_EQ(apply(Before), After);
}

} // namespace
} // namespace clangd
} // namespace clang
8 changes: 8 additions & 0 deletions clang-tools-extra/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ Code actions

- Added `Swap operands` tweak for certain binary operators.

- Improved the extract-to-function code action to allow extracting statements
with overloaded operators like ``<<`` of ``std::ostream``.

Signature help
^^^^^^^^^^^^^^

Expand Down Expand Up @@ -191,6 +194,11 @@ Changes in existing checks
<clang-tidy/checks/bugprone/unsafe-functions>` check to allow specifying
additional functions to match.

- Improved :doc:`bugprone-use-after-move
<clang-tidy/checks/bugprone/use-after-move>` to avoid triggering on
``reset()`` calls on moved-from ``std::optional`` and ``std::any`` objects,
similarly to smart pointers.

- Improved :doc:`cert-flp30-c <clang-tidy/checks/cert/flp30-c>` check to
fix false positive that floating point variable is only used in increment
expression.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,11 +196,13 @@ Any occurrence of the moved variable that is not a reinitialization (see below)
is considered to be a use.

An exception to this are objects of type ``std::unique_ptr``,
``std::shared_ptr`` and ``std::weak_ptr``, which have defined move behavior
(objects of these classes are guaranteed to be empty after they have been moved
from). Therefore, an object of these classes will only be considered to be used
if it is dereferenced, i.e. if ``operator*``, ``operator->`` or ``operator[]``
(in the case of ``std::unique_ptr<T []>``) is called on it.
``std::shared_ptr``, ``std::weak_ptr``, ``std::optional``, and ``std::any``.
An exception to this are objects of type ``std::unique_ptr``,
``std::shared_ptr``, ``std::weak_ptr``, ``std::optional``, and ``std::any``, which
can be reinitialized via ``reset``. For smart pointers specifically, the
moved-from objects have a well-defined state of being ``nullptr``s, and only
``operator*``, ``operator->`` and ``operator[]`` are considered bad accesses as
they would be dereferencing a ``nullptr``.

If multiple uses occur after a move, only the first of these is flagged.

Expand All @@ -222,7 +224,8 @@ The check considers a variable to be reinitialized in the following cases:
``unordered_multimap``.

- ``reset()`` is called on the variable and the variable is of type
``std::unique_ptr``, ``std::shared_ptr`` or ``std::weak_ptr``.
``std::unique_ptr``, ``std::shared_ptr``, ``std::weak_ptr``,
``std::optional``, or ``std::any``.

- A member function marked with the ``[[clang::reinitializes]]`` attribute is
called on the variable.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,19 @@ struct weak_ptr {
bool expired() const;
};

template <typename T>
struct optional {
optional();
T& operator*();
const T& operator*() const;
void reset();
};

struct any {
any();
void reset();
};

template <typename T1, typename T2>
struct pair {};

Expand Down Expand Up @@ -257,6 +270,14 @@ void standardSmartPtr() {
// CHECK-NOTES: [[@LINE-1]]:5: warning: 'ptr' used after it was moved
// CHECK-NOTES: [[@LINE-3]]:5: note: move occurred here
}
{
std::optional<A> opt;
std::move(opt);
A val = *opt;
(void)val;
// CHECK-NOTES: [[@LINE-2]]:14: warning: 'opt' used after it was moved
// CHECK-NOTES: [[@LINE-4]]:5: note: move occurred here
}
{
// std::weak_ptr<> cannot be dereferenced directly, so we only check that
// member functions may be called on it after a move.
Expand Down Expand Up @@ -994,10 +1015,10 @@ void standardContainerAssignIsReinit() {
}
}

// Resetting the standard smart pointer types using reset() is treated as a
// Resetting the standard smart owning types using reset() is treated as a
// re-initialization. (We don't test std::weak_ptr<> because it can't be
// dereferenced directly.)
void standardSmartPointerResetIsReinit() {
void resetIsReinit() {
{
std::unique_ptr<A> ptr;
std::move(ptr);
Expand All @@ -1010,6 +1031,20 @@ void standardSmartPointerResetIsReinit() {
ptr.reset(new A);
*ptr;
}
{
std::optional<A> opt;
std::move(opt);
opt.reset();
std::optional<A> opt2 = opt;
(void)opt2;
}
{
std::any a;
std::move(a);
a.reset();
std::any a2 = a;
(void)a2;
}
}

void reinitAnnotation() {
Expand Down
6 changes: 6 additions & 0 deletions clang/Maintainers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,12 @@ Constant Expressions
| mariya.podchishchaeva\@intel.com (email), Fznamznon (GitHub), fznamznon (Discord), Fznamznon (Discourse)

Thread Safety Analysis
~~~~~~~~~~~~~~~~~~~~~~
| Aaron Puchert
| aaron.puchert\@sap.com (email), aaronpuchert (GitHub), aaronpuchert (Discourse)

Tools
-----
These maintainers are responsible for user-facing tools under the Clang
Expand Down
14 changes: 11 additions & 3 deletions clang/cmake/caches/Fuchsia-stage2.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ if(FUCHSIA_SDK)
set(LLVM_RUNTIME_MULTILIB_hwasan+noexcept_TARGETS "aarch64-unknown-fuchsia;riscv64-unknown-fuchsia" CACHE STRING "")
endif()

foreach(target armv6m-none-eabi;armv7m-none-eabi;armv8m.main-none-eabi)
foreach(target armv6m-none-eabi;armv7m-none-eabi;armv8m.main-none-eabi;armv8.1m.main-none-eabi)
list(APPEND BUILTIN_TARGETS "${target}")
set(BUILTINS_${target}_CMAKE_SYSTEM_NAME Generic CACHE STRING "")
set(BUILTINS_${target}_CMAKE_SYSTEM_PROCESSOR arm CACHE STRING "")
Expand All @@ -313,6 +313,9 @@ foreach(target armv6m-none-eabi;armv7m-none-eabi;armv8m.main-none-eabi)
if(${target} STREQUAL "armv8m.main-none-eabi")
set(BUILTINS_${target}_CMAKE_${lang}_local_flags "${BUILTINS_${target}_CMAKE_${lang}_local_flags} -mfloat-abi=softfp -march=armv8m.main+fp+dsp -mcpu=cortex-m33" CACHE STRING "")
endif()
if(${target} STREQUAL "armv8.1m.main-none-eabi")
set(BUILTINS_${target}_CMAKE_${lang}_local_flags "${BUILTINS_${target}_CMAKE_${lang}_local_flags} -mfloat-abi=hard -march=armv8.1-m.main+mve.fp+fp.dp -mcpu=cortex-m55" CACHE STRING "")
endif()
set(BUILTINS_${target}_CMAKE_${lang}_FLAGS "${BUILTINS_${target}_CMAKE_${lang}_local_flags}" CACHE STRING "")
endforeach()
foreach(type SHARED;MODULE;EXE)
Expand All @@ -329,17 +332,21 @@ foreach(target armv6m-none-eabi;armv7m-none-eabi;armv8m.main-none-eabi)
foreach(lang C;CXX;ASM)
# TODO: The preprocessor defines workaround various issues in libc and libc++ integration.
# These should be addressed and removed over time.
set(RUNTIMES_${target}_CMAKE_${lang}_local_flags "--target=${target} -mthumb -Wno-atomic-alignment \"-Dvfprintf(stream, format, vlist)=vprintf(format, vlist)\" \"-Dfprintf(stream, format, ...)=printf(format)\" \"-Dgettimeofday(tv, tz)\" -D_LIBCPP_PRINT=1")
set(RUNTIMES_${target}_CMAKE_${lang}_local_flags "--target=${target} -mthumb -Wno-atomic-alignment \"-Dvfprintf(stream, format, vlist)=vprintf(format, vlist)\" \"-Dfprintf(stream, format, ...)=printf(format)\" \"-Dtimeval=struct timeval{int tv_sec; int tv_usec;}\" \"-Dgettimeofday(tv, tz)\" -D_LIBCPP_PRINT=1")
if(${target} STREQUAL "armv8m.main-none-eabi")
set(RUNTIMES_${target}_CMAKE_${lang}_local_flags "${RUNTIMES_${target}_CMAKE_${lang}_local_flags} -mfloat-abi=softfp -march=armv8m.main+fp+dsp -mcpu=cortex-m33" CACHE STRING "")
endif()
if(${target} STREQUAL "armv8.1m.main-none-eabi")
set(RUNTIMES_${target}_CMAKE_${lang}_local_flags "${RUNTIMES_${target}_CMAKE_${lang}_local_flags} -mfloat-abi=hard -march=armv8.1-m.main+mve.fp+fp.dp -mcpu=cortex-m55" CACHE STRING "")
endif()
set(RUNTIMES_${target}_CMAKE_${lang}_FLAGS "${RUNTIMES_${target}_CMAKE_${lang}_local_flags}" CACHE STRING "")
endforeach()
foreach(type SHARED;MODULE;EXE)
set(RUNTIMES_${target}_CMAKE_${type}_LINKER_FLAGS "-fuse-ld=lld" CACHE STRING "")
endforeach()
set(RUNTIMES_${target}_LLVM_LIBC_FULL_BUILD ON CACHE BOOL "")
set(RUNTIMES_${target}_LIBC_ENABLE_USE_BY_CLANG ON CACHE BOOL "")
set(RUNTIMES_${target}_LIBC_USE_NEW_HEADER_GEN OFF CACHE BOOL "")
set(RUNTIMES_${target}_LIBCXX_ABI_VERSION 2 CACHE STRING "")
set(RUNTIMES_${target}_LIBCXX_CXX_ABI none CACHE STRING "")
set(RUNTIMES_${target}_LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
Expand Down Expand Up @@ -384,13 +391,14 @@ foreach(target riscv32-unknown-elf)
foreach(lang C;CXX;ASM)
# TODO: The preprocessor defines workaround various issues in libc and libc++ integration.
# These should be addressed and removed over time.
set(RUNTIMES_${target}_CMAKE_${lang}_FLAGS "--target=${target} -march=rv32imafc -mabi=ilp32f -Wno-atomic-alignment \"-Dvfprintf(stream, format, vlist)=vprintf(format, vlist)\" \"-Dfprintf(stream, format, ...)=printf(format)\" \"-Dgettimeofday(tv, tz)\" -D_LIBCPP_PRINT=1" CACHE STRING "")
set(RUNTIMES_${target}_CMAKE_${lang}_FLAGS "--target=${target} -march=rv32imafc -mabi=ilp32f -Wno-atomic-alignment \"-Dvfprintf(stream, format, vlist)=vprintf(format, vlist)\" \"-Dfprintf(stream, format, ...)=printf(format)\" \"-Dtimeval=struct timeval{int tv_sec; int tv_usec;}\" \"-Dgettimeofday(tv, tz)\" -D_LIBCPP_PRINT=1" CACHE STRING "")
endforeach()
foreach(type SHARED;MODULE;EXE)
set(RUNTIMES_${target}_CMAKE_${type}_LINKER_FLAGS "-fuse-ld=lld" CACHE STRING "")
endforeach()
set(RUNTIMES_${target}_LLVM_LIBC_FULL_BUILD ON CACHE BOOL "")
set(RUNTIMES_${target}_LIBC_ENABLE_USE_BY_CLANG ON CACHE BOOL "")
set(RUNTIMES_${target}_LIBC_USE_NEW_HEADER_GEN OFF CACHE BOOL "")
set(RUNTIMES_${target}_LIBCXX_ABI_VERSION 2 CACHE STRING "")
set(RUNTIMES_${target}_LIBCXX_CXX_ABI none CACHE STRING "")
set(RUNTIMES_${target}_LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
Expand Down
14 changes: 6 additions & 8 deletions clang/docs/AddressSanitizer.rst
Original file line number Diff line number Diff line change
Expand Up @@ -326,15 +326,13 @@ Supported Platforms

AddressSanitizer is supported on:

* Linux i386/x86\_64 (tested on Ubuntu 12.04)
* macOS 10.7 - 10.11 (i386/x86\_64)
* Linux
* macOS
* iOS Simulator
* Android ARM
* NetBSD i386/x86\_64
* FreeBSD i386/x86\_64 (tested on FreeBSD 11-current)
* Windows 8.1+ (i386/x86\_64)

Ports to various other platforms are in progress.
* Android
* NetBSD
* FreeBSD
* Windows 8.1+

Current Status
==============
Expand Down
10 changes: 5 additions & 5 deletions clang/docs/LeakSanitizer.rst
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ constraints in mind and may compromise the security of the resulting executable.
Supported Platforms
===================

* Android aarch64/i386/x86_64
* Fuchsia aarch64/x86_64
* Linux arm/aarch64/mips64/ppc64/ppc64le/riscv64/s390x/i386/x86\_64
* macOS aarch64/i386/x86\_64
* NetBSD i386/x86_64
* Android
* Fuchsia
* Linux
* macOS
* NetBSD

More Information
================
Expand Down
16 changes: 16 additions & 0 deletions clang/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,8 @@ Resolutions to C++ Defect Reports
C Language Changes
------------------

- Extend clang's ``<limits.h>`` to define ``LONG_LONG_*`` macros for Android's bionic.

C2y Feature Support
^^^^^^^^^^^^^^^^^^^

Expand Down Expand Up @@ -553,6 +555,8 @@ Bug Fixes in This Version
the unsupported type instead of the ``register`` keyword (#GH109776).
- Fixed a crash when emit ctor for global variant with flexible array init (#GH113187).
- Fixed a crash when GNU statement expression contains invalid statement (#GH113468).
- Fixed a failed assertion when using ``__attribute__((noderef))`` on an
``_Atomic``-qualified type (#GH116124).

Bug Fixes to Compiler Builtins
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Expand Down Expand Up @@ -706,6 +710,17 @@ Target Specific Changes
AMDGPU Support
^^^^^^^^^^^^^^

- Added headers ``gpuintrin.h`` and ``amdgpuintrin.h`` that contains common
definitions for GPU builtin functions. This header can be included for OpenMP,
CUDA, HIP, OpenCL, and C/C++.

NVPTX Support
^^^^^^^^^^^^^^

- Added headers ``gpuintrin.h`` and ``nvptxintrin.h`` that contains common
definitions for GPU builtin functions. This header can be included for OpenMP,
CUDA, HIP, OpenCL, and C/C++.

X86 Support
^^^^^^^^^^^

Expand Down Expand Up @@ -752,6 +767,7 @@ X86 Support
- Support ISA of ``AMX-MOVRS``.
- Support ISA of ``AMX-AVX512``.
- Support ISA of ``AMX-TF32``.
- Support ISA of ``MOVRS``.

Arm and AArch64 Support
^^^^^^^^^^^^^^^^^^^^^^^
Expand Down
7 changes: 7 additions & 0 deletions clang/include/clang/AST/ASTNodeTraverser.h
Original file line number Diff line number Diff line change
Expand Up @@ -800,6 +800,13 @@ class ASTNodeTraverser
Visit(A);
}

void VisitLabelStmt(const LabelStmt *Node) {
if (Node->getDecl()->hasAttrs()) {
for (const auto *A : Node->getDecl()->getAttrs())
Visit(A);
}
}

void VisitCXXCatchStmt(const CXXCatchStmt *Node) {
Visit(Node->getExceptionDecl());
}
Expand Down
9 changes: 5 additions & 4 deletions clang/include/clang/AST/CanonicalType.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ namespace clang {

template<typename T> class CanProxy;
template<typename T> struct CanProxyAdaptor;
class ASTContext;
class CXXRecordDecl;
class EnumDecl;
class Expr;
Expand Down Expand Up @@ -164,14 +165,14 @@ class CanQual {

/// Determines whether this canonical type is more qualified than
/// the @p Other canonical type.
bool isMoreQualifiedThan(CanQual<T> Other) const {
return Stored.isMoreQualifiedThan(Other.Stored);
bool isMoreQualifiedThan(CanQual<T> Other, const ASTContext &Ctx) const {
return Stored.isMoreQualifiedThan(Other.Stored, Ctx);
}

/// Determines whether this canonical type is at least as qualified as
/// the @p Other canonical type.
bool isAtLeastAsQualifiedAs(CanQual<T> Other) const {
return Stored.isAtLeastAsQualifiedAs(Other.Stored);
bool isAtLeastAsQualifiedAs(CanQual<T> Other, const ASTContext &Ctx) const {
return Stored.isAtLeastAsQualifiedAs(Other.Stored, Ctx);
}

/// If the canonical type is a reference type, returns the type that
Expand Down
60 changes: 23 additions & 37 deletions clang/include/clang/AST/Type.h
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@ class PointerAuthQualifier {
/// * Objective C: the GC attributes (none, weak, or strong)
class Qualifiers {
public:
Qualifiers() = default;
enum TQ : uint64_t {
// NOTE: These flags must be kept in sync with DeclSpec::TQ.
Const = 0x1,
Expand Down Expand Up @@ -697,45 +698,27 @@ class Qualifiers {
/// every address space is a superset of itself.
/// CL2.0 adds:
/// __generic is a superset of any address space except for __constant.
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B,
const ASTContext &Ctx) {
// Address spaces must match exactly.
return A == B ||
// Otherwise in OpenCLC v2.0 s6.5.5: every address space except
// for __constant can be used as __generic.
(A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
// We also define global_device and global_host address spaces,
// to distinguish global pointers allocated on host from pointers
// allocated on device, which are a subset of __global.
(A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
B == LangAS::opencl_global_host)) ||
(A == LangAS::sycl_global && (B == LangAS::sycl_global_device ||
B == LangAS::sycl_global_host)) ||
// Consider pointer size address spaces to be equivalent to default.
((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
(isPtrSizeAddressSpace(B) || B == LangAS::Default)) ||
// Default is a superset of SYCL address spaces.
(A == LangAS::Default &&
(B == LangAS::sycl_private || B == LangAS::sycl_local ||
B == LangAS::sycl_global || B == LangAS::sycl_global_device ||
B == LangAS::sycl_global_host)) ||
// In HIP device compilation, any cuda address space is allowed
// to implicitly cast into the default address space.
(A == LangAS::Default &&
(B == LangAS::cuda_constant || B == LangAS::cuda_device ||
B == LangAS::cuda_shared));
return A == B || isTargetAddressSpaceSupersetOf(A, B, Ctx);
}

static bool isTargetAddressSpaceSupersetOf(LangAS A, LangAS B,
const ASTContext &Ctx);

/// Returns true if the address space in these qualifiers is equal to or
/// a superset of the address space in the argument qualifiers.
bool isAddressSpaceSupersetOf(Qualifiers other) const {
return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
bool isAddressSpaceSupersetOf(Qualifiers other, const ASTContext &Ctx) const {
return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace(),
Ctx);
}

/// Determines if these qualifiers compatibly include another set.
/// Generally this answers the question of whether an object with the other
/// qualifiers can be safely used as an object with these qualifiers.
bool compatiblyIncludes(Qualifiers other) const {
return isAddressSpaceSupersetOf(other) &&
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const {
return isAddressSpaceSupersetOf(other, Ctx) &&
// ObjC GC qualifiers can match, be added, or be removed, but can't
// be changed.
(getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
Expand Down Expand Up @@ -1273,11 +1256,11 @@ class QualType {

/// Determine whether this type is more qualified than the other
/// given type, requiring exact equality for non-CVR qualifiers.
bool isMoreQualifiedThan(QualType Other) const;
bool isMoreQualifiedThan(QualType Other, const ASTContext &Ctx) const;

/// Determine whether this type is at least as qualified as the other
/// given type, requiring exact equality for non-CVR qualifiers.
bool isAtLeastAsQualifiedAs(QualType Other) const;
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const;

QualType getNonReferenceType() const;

Expand Down Expand Up @@ -1425,11 +1408,12 @@ class QualType {
/// address spaces overlap iff they are they same.
/// OpenCL C v2.0 s6.5.5 adds:
/// __generic overlaps with any address space except for __constant.
bool isAddressSpaceOverlapping(QualType T) const {
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const {
Qualifiers Q = getQualifiers();
Qualifiers TQ = T.getQualifiers();
// Address spaces overlap if at least one of them is a superset of another
return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
return Q.isAddressSpaceSupersetOf(TQ, Ctx) ||
TQ.isAddressSpaceSupersetOf(Q, Ctx);
}

/// Returns gc attribute of this type.
Expand Down Expand Up @@ -8112,24 +8096,26 @@ inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
/// is more qualified than "const int", "volatile int", and
/// "int". However, it is not more qualified than "const volatile
/// int".
inline bool QualType::isMoreQualifiedThan(QualType other) const {
inline bool QualType::isMoreQualifiedThan(QualType other,
const ASTContext &Ctx) const {
Qualifiers MyQuals = getQualifiers();
Qualifiers OtherQuals = other.getQualifiers();
return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals, Ctx));
}

/// Determine whether this type is at last
/// as qualified as the Other type. For example, "const volatile
/// int" is at least as qualified as "const int", "volatile int",
/// "int", and "const volatile int".
inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
inline bool QualType::isAtLeastAsQualifiedAs(QualType other,
const ASTContext &Ctx) const {
Qualifiers OtherQuals = other.getQualifiers();

// Ignore __unaligned qualifier if this type is a void.
if (getUnqualifiedType()->isVoidType())
OtherQuals.removeUnaligned();

return getQualifiers().compatiblyIncludes(OtherQuals);
return getQualifiers().compatiblyIncludes(OtherQuals, Ctx);
}

/// If Type is a reference type (e.g., const
Expand Down
15 changes: 6 additions & 9 deletions clang/include/clang/Analysis/CallGraph.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
#define LLVM_CLANG_ANALYSIS_CALLGRAPH_H

#include "clang/AST/Decl.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DynamicRecursiveASTVisitor.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/GraphTraits.h"
#include "llvm/ADT/STLExtras.h"
Expand All @@ -39,7 +40,7 @@ class Stmt;
/// The call graph extends itself with the given declarations by implementing
/// the recursive AST visitor, which constructs the graph by visiting the given
/// declarations.
class CallGraph : public RecursiveASTVisitor<CallGraph> {
class CallGraph : public DynamicRecursiveASTVisitor {
friend class CallGraphNode;

using FunctionMapTy =
Expand Down Expand Up @@ -109,7 +110,7 @@ class CallGraph : public RecursiveASTVisitor<CallGraph> {

/// Part of recursive declaration visitation. We recursively visit all the
/// declarations to collect the root functions.
bool VisitFunctionDecl(FunctionDecl *FD) {
bool VisitFunctionDecl(FunctionDecl *FD) override {
// We skip function template definitions, as their semantics is
// only determined when they are instantiated.
if (includeInGraph(FD) && FD->isThisDeclarationADefinition()) {
Expand All @@ -124,7 +125,7 @@ class CallGraph : public RecursiveASTVisitor<CallGraph> {
}

/// Part of recursive declaration visitation.
bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
bool VisitObjCMethodDecl(ObjCMethodDecl *MD) override {
if (includeInGraph(MD)) {
addNodesForBlocks(MD);
addNodeForDecl(MD, true);
Expand All @@ -133,11 +134,7 @@ class CallGraph : public RecursiveASTVisitor<CallGraph> {
}

// We are only collecting the declarations, so do not step into the bodies.
bool TraverseStmt(Stmt *S) { return true; }

bool shouldWalkTypesOfTypeLocs() const { return false; }
bool shouldVisitTemplateInstantiations() const { return true; }
bool shouldVisitImplicitCode() const { return true; }
bool TraverseStmt(Stmt *S) override { return true; }

private:
/// Add the given declaration to the call graph.
Expand Down
31 changes: 16 additions & 15 deletions clang/include/clang/Analysis/FlowSensitive/ASTOps.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ASTOPS_H

#include "clang/AST/Decl.h"
#include "clang/AST/DynamicRecursiveASTVisitor.h"
#include "clang/AST/Expr.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/Type.h"
#include "clang/Analysis/FlowSensitive/StorageLocation.h"
#include "llvm/ADT/DenseSet.h"
Expand Down Expand Up @@ -88,14 +89,14 @@ class RecordInitListHelper {
/// the function to analyze. Don't call `TraverseDecl()` on the function itself;
/// this won't work as `TraverseDecl()` contains code to avoid traversing nested
/// functions.
template <class Derived>
class AnalysisASTVisitor : public RecursiveASTVisitor<Derived> {
class AnalysisASTVisitor : public DynamicRecursiveASTVisitor {
public:
bool shouldVisitImplicitCode() { return true; }

bool shouldVisitLambdaBody() const { return false; }
AnalysisASTVisitor() {
ShouldVisitImplicitCode = true;
ShouldVisitLambdaBody = false;
}

bool TraverseDecl(Decl *D) {
bool TraverseDecl(Decl *D) override {
// Don't traverse nested record or function declarations.
// - We won't be analyzing code contained in these anyway
// - We don't model fields that are used only in these nested declaration,
Expand All @@ -104,30 +105,30 @@ class AnalysisASTVisitor : public RecursiveASTVisitor<Derived> {
if (isa_and_nonnull<RecordDecl>(D) || isa_and_nonnull<FunctionDecl>(D))
return true;

return RecursiveASTVisitor<Derived>::TraverseDecl(D);
return DynamicRecursiveASTVisitor::TraverseDecl(D);
}

// Don't traverse expressions in unevaluated contexts, as we don't model
// fields that are only used in these.
// Note: The operand of the `noexcept` operator is an unevaluated operand, but
// nevertheless it appears in the Clang CFG, so we don't exclude it here.
bool TraverseDecltypeTypeLoc(DecltypeTypeLoc) { return true; }
bool TraverseTypeOfExprTypeLoc(TypeOfExprTypeLoc) { return true; }
bool TraverseCXXTypeidExpr(CXXTypeidExpr *TIE) {
bool TraverseDecltypeTypeLoc(DecltypeTypeLoc) override { return true; }
bool TraverseTypeOfExprTypeLoc(TypeOfExprTypeLoc) override { return true; }
bool TraverseCXXTypeidExpr(CXXTypeidExpr *TIE) override {
if (TIE->isPotentiallyEvaluated())
return RecursiveASTVisitor<Derived>::TraverseCXXTypeidExpr(TIE);
return DynamicRecursiveASTVisitor::TraverseCXXTypeidExpr(TIE);
return true;
}
bool TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *) {
bool TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *) override {
return true;
}

bool TraverseBindingDecl(BindingDecl *BD) {
bool TraverseBindingDecl(BindingDecl *BD) override {
// `RecursiveASTVisitor` doesn't traverse holding variables for
// `BindingDecl`s by itself, so we need to tell it to.
if (VarDecl *HoldingVar = BD->getHoldingVar())
TraverseDecl(HoldingVar);
return RecursiveASTVisitor<Derived>::TraverseBindingDecl(BD);
return DynamicRecursiveASTVisitor::TraverseBindingDecl(BD);
}
};

Expand Down
2 changes: 1 addition & 1 deletion clang/include/clang/Basic/AArch64SVEACLETypes.def
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ SVE_PREDICATE_TYPE_ALL("__clang_svboolx4_t", "svboolx4_t", SveBoolx4, SveBoolx4T

SVE_OPAQUE_TYPE("__SVCount_t", "__SVCount_t", SveCount, SveCountTy)

AARCH64_VECTOR_TYPE_MFLOAT("__MFloat8_t", "__MFloat8_t", MFloat8, MFloat8Ty, 1, 8, 1)
AARCH64_VECTOR_TYPE_MFLOAT("__mfp8", "__mfp8", MFloat8, MFloat8Ty, 1, 8, 1)
AARCH64_VECTOR_TYPE_MFLOAT("__MFloat8x8_t", "__MFloat8x8_t", MFloat8x8, MFloat8x8Ty, 8, 8, 1)
AARCH64_VECTOR_TYPE_MFLOAT("__MFloat8x16_t", "__MFloat8x16_t", MFloat8x16, MFloat8x16Ty, 16, 8, 1)

Expand Down
5 changes: 4 additions & 1 deletion clang/include/clang/Basic/Attr.td
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,9 @@ def TargetELF : TargetSpec {
def TargetELFOrMachO : TargetSpec {
let ObjectFormats = ["ELF", "MachO"];
}
def TargetIFuncSupport : TargetSpec {
let CustomCode = [{ Target.supportsIFunc() }];
}
def TargetWindowsArm64EC : TargetSpec {
let CustomCode = [{ Target.getTriple().isWindowsArm64EC() }];
}
Expand Down Expand Up @@ -1855,7 +1858,7 @@ def IBOutletCollection : InheritableAttr {
let Documentation = [Undocumented];
}

def IFunc : Attr, TargetSpecificAttr<TargetELFOrMachO> {
def IFunc : Attr, TargetSpecificAttr<TargetIFuncSupport> {
let Spellings = [GCC<"ifunc">];
let Args = [StringArgument<"Resolver">];
let Subjects = SubjectList<[Function]>;
Expand Down
19 changes: 13 additions & 6 deletions clang/include/clang/Basic/AttrDocs.td
Original file line number Diff line number Diff line change
Expand Up @@ -6051,12 +6051,19 @@ declared entity. The entity must not have weak linkage; for example, in C++,
it cannot be applied to a declaration if a definition at that location would be
considered inline.

Not all targets support this attribute. ELF target support depends on both the
linker and runtime linker, and is available in at least lld 4.0 and later,
binutils 2.20.1 and later, glibc v2.11.1 and later, and FreeBSD 9.1 and later.
Mach-O targets support it, but with slightly different semantics: the resolver
is run at first call, instead of at load time by the runtime linker. Targets
other than ELF and Mach-O currently do not support this attribute.
Not all targets support this attribute:

- ELF target support depends on both the linker and runtime linker, and is
available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc
v2.11.1 and later, and FreeBSD 9.1 and later.
- Mach-O targets support it, but with slightly different semantics: the resolver
is run at first call, instead of at load time by the runtime linker.
- Windows target supports it on AArch64, but with different semantics: the
``ifunc`` is replaced with a global function pointer, and the call is replaced
with an indirect call. The function pointer is initialized by a constructor
that calls the resolver.
- Baremetal target supports it on AVR.
- Other targets currently do not support this attribute.
}];
}

Expand Down
6 changes: 6 additions & 0 deletions clang/include/clang/Basic/Builtins.td
Original file line number Diff line number Diff line change
Expand Up @@ -4895,6 +4895,12 @@ def HLSLSplitDouble: LangBuiltin<"HLSL_LANG"> {
let Prototype = "void(...)";
}

def HLSLClip: LangBuiltin<"HLSL_LANG"> {
let Spellings = ["__builtin_hlsl_elementwise_clip"];
let Attributes = [NoThrow, Const];
let Prototype = "void(...)";
}

// Builtins for XRay.
def XRayCustomEvent : Builtin {
let Spellings = ["__xray_customevent"];
Expand Down
3 changes: 3 additions & 0 deletions clang/include/clang/Basic/BuiltinsX86.def
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,9 @@ TARGET_BUILTIN(__builtin_ia32_vpdpbuud256, "V8iV8iV8iV8i", "ncV:256:", "avxvnnii
TARGET_BUILTIN(__builtin_ia32_vpdpbuuds128, "V4iV4iV4iV4i", "ncV:128:", "avxvnniint8|avx10.2-256")
TARGET_BUILTIN(__builtin_ia32_vpdpbuuds256, "V8iV8iV8iV8i", "ncV:256:", "avxvnniint8|avx10.2-256")

// MOVRS
TARGET_BUILTIN(__builtin_ia32_prefetchrs, "vvC*", "nc", "movrs")

TARGET_BUILTIN(__builtin_ia32_gather3div2df, "V2dV2dvC*V2OiUcIi", "nV:128:", "avx512vl")
TARGET_BUILTIN(__builtin_ia32_gather3div2di, "V2OiV2OivC*V2OiUcIi", "nV:128:", "avx512vl")
TARGET_BUILTIN(__builtin_ia32_gather3div4df, "V4dV4dvC*V4OiUcIi", "nV:256:", "avx512vl")
Expand Down
18 changes: 18 additions & 0 deletions clang/include/clang/Basic/BuiltinsX86_64.def
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,12 @@ TARGET_BUILTIN(__builtin_ia32_t2rpntlvwz1rs_internal, "vUsUsUsV256i*V256i*vC*z",
TARGET_BUILTIN(__builtin_ia32_t2rpntlvwz1t1_internal, "vUsUsUsV256i*V256i*vC*z", "n", "amx-transpose")
TARGET_BUILTIN(__builtin_ia32_t2rpntlvwz1rst1_internal, "vUsUsUsV256i*V256i*vC*z", "n", "amx-movrs,amx-transpose")
TARGET_BUILTIN(__builtin_ia32_ttransposed_internal, "V256iUsUsV256i", "n", "amx-transpose")
TARGET_BUILTIN(__builtin_ia32_ttdpbf16ps_internal, "V256iUsUsUsV256iV256iV256i", "n", "amx-bf16,amx-transpose")
TARGET_BUILTIN(__builtin_ia32_ttdpfp16ps_internal, "V256iUsUsUsV256iV256iV256i", "n", "amx-fp16,amx-transpose")
TARGET_BUILTIN(__builtin_ia32_ttcmmimfp16ps_internal, "V256iUsUsUsV256iV256iV256i", "n", "amx-complex,amx-transpose")
TARGET_BUILTIN(__builtin_ia32_ttcmmrlfp16ps_internal, "V256iUsUsUsV256iV256iV256i", "n", "amx-complex,amx-transpose")
TARGET_BUILTIN(__builtin_ia32_tconjtcmmimfp16ps_internal, "V256iUsUsUsV256iV256iV256i", "n", "amx-complex,amx-transpose")
TARGET_BUILTIN(__builtin_ia32_tconjtfp16_internal, "V256iUsUsV256i", "n", "amx-complex,amx-transpose")

TARGET_BUILTIN(__builtin_ia32_tcvtrowd2ps_internal, "V16fUsUsV256iUi", "n", "amx-avx512,avx10.2-512")
TARGET_BUILTIN(__builtin_ia32_tcvtrowps2pbf16h_internal, "V32yUsUsV256iUi", "n", "amx-avx512,avx10.2-512")
Expand Down Expand Up @@ -185,6 +191,12 @@ TARGET_BUILTIN(__builtin_ia32_t2rpntlvwz0t1, "vIUcvC*z", "n","amx-transpose")
TARGET_BUILTIN(__builtin_ia32_t2rpntlvwz1, "vIUcvC*z", "n", "amx-transpose")
TARGET_BUILTIN(__builtin_ia32_t2rpntlvwz1t1, "vIUcvC*z", "n","amx-transpose")
TARGET_BUILTIN(__builtin_ia32_ttransposed, "vIUcIUc", "n", "amx-transpose")
TARGET_BUILTIN(__builtin_ia32_ttdpbf16ps, "vIUcIUcIUc", "n", "amx-bf16,amx-transpose")
TARGET_BUILTIN(__builtin_ia32_ttdpfp16ps, "vIUcIUcIUc", "n", "amx-fp16,amx-transpose")
TARGET_BUILTIN(__builtin_ia32_ttcmmimfp16ps, "vIUcIUcIUc", "n", "amx-complex,amx-transpose")
TARGET_BUILTIN(__builtin_ia32_ttcmmrlfp16ps, "vIUcIUcIUc", "n", "amx-complex,amx-transpose")
TARGET_BUILTIN(__builtin_ia32_tconjtcmmimfp16ps, "vIUcIUcIUc", "n", "amx-complex,amx-transpose")
TARGET_BUILTIN(__builtin_ia32_tconjtfp16, "vIUcIUc", "n", "amx-complex,amx-transpose")

TARGET_BUILTIN(__builtin_ia32_tcvtrowd2ps, "V16fIUcUi", "n", "amx-avx512,avx10.2-512")
TARGET_BUILTIN(__builtin_ia32_tcvtrowps2pbf16h, "V32yIUcUi", "n", "amx-avx512,avx10.2-512")
Expand Down Expand Up @@ -216,6 +228,12 @@ TARGET_BUILTIN(__builtin_ia32_aand64, "vv*SOi", "n", "raoint")
TARGET_BUILTIN(__builtin_ia32_aor64, "vv*SOi", "n", "raoint")
TARGET_BUILTIN(__builtin_ia32_axor64, "vv*SOi", "n", "raoint")

// MOVRS
TARGET_BUILTIN(__builtin_ia32_movrsqi, "ScvC*", "n", "movrs")
TARGET_BUILTIN(__builtin_ia32_movrshi, "SsvC*", "n", "movrs")
TARGET_BUILTIN(__builtin_ia32_movrssi, "SivC*", "n", "movrs")
TARGET_BUILTIN(__builtin_ia32_movrsdi, "SLLivC*", "n", "movrs")

// MOVRS and AVX10.2
TARGET_BUILTIN(__builtin_ia32_vmovrsb128, "V16cV16cC*", "nV:128:", "movrs,avx10.2-256")
TARGET_BUILTIN(__builtin_ia32_vmovrsb256, "V32cV32cC*", "nV:256:", "movrs,avx10.2-256")
Expand Down
1 change: 1 addition & 0 deletions clang/include/clang/Basic/CodeGenOptions.def
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ VALUE_CODEGENOPT(PatchableFunctionEntryOffset , 32, 0)
CODEGENOPT(HotPatch, 1, 0) ///< Supports the Microsoft /HOTPATCH flag and
///< generates a 'patchable-function' attribute.

CODEGENOPT(TlsGuards , 1, 1) ///< Controls emission of tls guards via -fms-tls-guards
CODEGENOPT(JMCInstrument, 1, 0) ///< Set when -fjmc is enabled.
CODEGENOPT(InstrumentForProfiling , 1, 0) ///< Set when -pg is enabled.
CODEGENOPT(CallFEntry , 1, 0) ///< Set when -mfentry is enabled.
Expand Down
11 changes: 11 additions & 0 deletions clang/include/clang/Basic/TargetInfo.h
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,13 @@ class TargetInfo : public TransferrableTargetInfo,
/// \param AddrSpace address space of pointee in source language.
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const { return 0; }

/// Returns true if an address space can be safely converted to another.
/// \param A address space of target in source language.
/// \param B address space of source in source language.
virtual bool isAddressSpaceSupersetOf(LangAS A, LangAS B) const {
return A == B;
}

/// Return the size of '_Bool' and C++ 'bool' for this target, in bits.
unsigned getBoolWidth() const { return BoolWidth; }

Expand Down Expand Up @@ -1497,6 +1504,10 @@ class TargetInfo : public TransferrableTargetInfo,
bool supportsIFunc() const {
if (getTriple().isOSBinFormatMachO())
return true;
if (getTriple().isOSWindows() && getTriple().isAArch64())
return true;
if (getTriple().getArch() == llvm::Triple::ArchType::avr)
return true;
return getTriple().isOSBinFormatELF() &&
((getTriple().isOSLinux() && !getTriple().isMusl()) ||
getTriple().isOSFreeBSD());
Expand Down
2 changes: 1 addition & 1 deletion clang/include/clang/Basic/arm_sve.td
Original file line number Diff line number Diff line change
Expand Up @@ -1964,7 +1964,7 @@ let SVETargetGuard = "sve2,lut,bf16", SMETargetGuard = "sme2,lut,bf16" in {
////////////////////////////////////////////////////////////////////////////////
// SVE2 - Optional

let SVETargetGuard = "sve2-aes", SMETargetGuard = InvalidMode in {
let SVETargetGuard = "sve2,sve-aes", SMETargetGuard = InvalidMode in {
def SVAESD : SInst<"svaesd[_{d}]", "ddd", "Uc", MergeNone, "aarch64_sve_aesd", [IsOverloadNone]>;
def SVAESIMC : SInst<"svaesimc[_{d}]", "dd", "Uc", MergeNone, "aarch64_sve_aesimc", [IsOverloadNone]>;
def SVAESE : SInst<"svaese[_{d}]", "ddd", "Uc", MergeNone, "aarch64_sve_aese", [IsOverloadNone]>;
Expand Down
11 changes: 11 additions & 0 deletions clang/include/clang/Driver/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -4072,6 +4072,11 @@ defm threadsafe_statics : BoolFOption<"threadsafe-statics",
NegFlag<SetFalse, [], [ClangOption, CC1Option],
"Do not emit code to make initialization of local statics thread safe">,
PosFlag<SetTrue>>;
defm ms_tls_guards : BoolFOption<"ms-tls-guards",
CodeGenOpts<"TlsGuards">, DefaultTrue,
NegFlag<SetFalse, [], [CC1Option],
"Do not emit code to perform on-demand initialization of thread-local variables">,
PosFlag<SetTrue>>;
def ftime_report : Flag<["-"], "ftime-report">, Group<f_Group>,
Visibility<[ClangOption, CC1Option]>,
MarshallingInfoFlag<CodeGenOpts<"TimePasses">>;
Expand Down Expand Up @@ -8635,6 +8640,12 @@ def _SLASH_Zc_threadSafeInit : CLFlag<"Zc:threadSafeInit">,
def _SLASH_Zc_threadSafeInit_ : CLFlag<"Zc:threadSafeInit-">,
HelpText<"Disable thread-safe initialization of static variables">,
Alias<fno_threadsafe_statics>;
def _SLASH_Zc_tlsGuards : CLFlag<"Zc:tlsGuards">,
HelpText<"Enable on-demand initialization of thread-local variables">,
Alias<fms_tls_guards>;
def _SLASH_Zc_tlsGuards_ : CLFlag<"Zc:tlsGuards-">,
HelpText<"Disable on-demand initialization of thread-local variables">,
Alias<fno_ms_tls_guards>;
def _SLASH_Zc_trigraphs : CLFlag<"Zc:trigraphs">,
HelpText<"Enable trigraphs">, Alias<ftrigraphs>;
def _SLASH_Zc_trigraphs_off : CLFlag<"Zc:trigraphs-">,
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/AST/ASTContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11405,7 +11405,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
// Blocks can't be an expression in a ternary operator (OpenCL v2.0
// 6.12.5) thus the following check is asymmetric.
if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
return {};
LHSPteeQual.removeAddressSpace();
RHSPteeQual.removeAddressSpace();
Expand Down
30 changes: 30 additions & 0 deletions clang/lib/AST/Type.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,36 @@ bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
(hasObjCLifetime() && !Other.hasObjCLifetime()));
}

bool Qualifiers::isTargetAddressSpaceSupersetOf(LangAS A, LangAS B,
const ASTContext &Ctx) {
// In OpenCLC v2.0 s6.5.5: every address space except for __constant can be
// used as __generic.
return (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
// We also define global_device and global_host address spaces,
// to distinguish global pointers allocated on host from pointers
// allocated on device, which are a subset of __global.
(A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
B == LangAS::opencl_global_host)) ||
(A == LangAS::sycl_global &&
(B == LangAS::sycl_global_device || B == LangAS::sycl_global_host)) ||
// Consider pointer size address spaces to be equivalent to default.
((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
(isPtrSizeAddressSpace(B) || B == LangAS::Default)) ||
// Default is a superset of SYCL address spaces.
(A == LangAS::Default &&
(B == LangAS::sycl_private || B == LangAS::sycl_local ||
B == LangAS::sycl_global || B == LangAS::sycl_global_device ||
B == LangAS::sycl_global_host)) ||
// In HIP device compilation, any cuda address space is allowed
// to implicitly cast into the default address space.
(A == LangAS::Default &&
(B == LangAS::cuda_constant || B == LangAS::cuda_device ||
B == LangAS::cuda_shared)) ||
// Conversions from target specific address spaces may be legal
// depending on the target information.
Ctx.getTargetInfo().isAddressSpaceSupersetOf(A, B);
}

const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
const Type* ty = getTypePtr();
NamedDecl *ND = nullptr;
Expand Down
3 changes: 3 additions & 0 deletions clang/lib/Analysis/CallGraph.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,9 @@ void CallGraph::addNodesForBlocks(DeclContext *D) {
}

CallGraph::CallGraph() {
ShouldWalkTypesOfTypeLocs = false;
ShouldVisitTemplateInstantiations = true;
ShouldVisitImplicitCode = true;
Root = getOrInsertNode(nullptr);
}

Expand Down
8 changes: 4 additions & 4 deletions clang/lib/Analysis/CalledOnceCheck.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DynamicRecursiveASTVisitor.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/ParentMap.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtObjC.h"
#include "clang/AST/StmtVisitor.h"
Expand Down Expand Up @@ -426,7 +426,7 @@ const Expr *getCondition(const Stmt *S) {
/// of the AST will end up in the results.
/// Results might have duplicate names, if this is a problem, convert to
/// string sets afterwards.
class NamesCollector : public RecursiveASTVisitor<NamesCollector> {
class NamesCollector : public DynamicRecursiveASTVisitor {
public:
static constexpr unsigned EXPECTED_NUMBER_OF_NAMES = 5;
using NameCollection =
Expand All @@ -438,12 +438,12 @@ class NamesCollector : public RecursiveASTVisitor<NamesCollector> {
return Impl.Result;
}

bool VisitDeclRefExpr(const DeclRefExpr *E) {
bool VisitDeclRefExpr(DeclRefExpr *E) override {
Result.push_back(E->getDecl()->getName());
return true;
}

bool VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *E) {
bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) override {
llvm::StringRef Name;

if (E->isImplicitProperty()) {
Expand Down
19 changes: 9 additions & 10 deletions clang/lib/Analysis/FlowSensitive/ASTOps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -198,13 +198,12 @@ static MemberExpr *getMemberForAccessor(const CXXMemberCallExpr &C) {
return nullptr;
}

class ReferencedDeclsVisitor
: public AnalysisASTVisitor<ReferencedDeclsVisitor> {
class ReferencedDeclsVisitor : public AnalysisASTVisitor {
public:
ReferencedDeclsVisitor(ReferencedDecls &Referenced)
: Referenced(Referenced) {}

void TraverseConstructorInits(const CXXConstructorDecl *Ctor) {
void traverseConstructorInits(const CXXConstructorDecl *Ctor) {
for (const CXXCtorInitializer *Init : Ctor->inits()) {
if (Init->isMemberInitializer()) {
Referenced.Fields.insert(Init->getMember());
Expand All @@ -225,21 +224,21 @@ class ReferencedDeclsVisitor
}
}

bool VisitDecl(Decl *D) {
bool VisitDecl(Decl *D) override {
insertIfGlobal(*D, Referenced.Globals);
insertIfLocal(*D, Referenced.Locals);
insertIfFunction(*D, Referenced.Functions);
return true;
}

bool VisitDeclRefExpr(DeclRefExpr *E) {
bool VisitDeclRefExpr(DeclRefExpr *E) override {
insertIfGlobal(*E->getDecl(), Referenced.Globals);
insertIfLocal(*E->getDecl(), Referenced.Locals);
insertIfFunction(*E->getDecl(), Referenced.Functions);
return true;
}

bool VisitCXXMemberCallExpr(CXXMemberCallExpr *C) {
bool VisitCXXMemberCallExpr(CXXMemberCallExpr *C) override {
// If this is a method that returns a member variable but does nothing else,
// model the field of the return value.
if (MemberExpr *E = getMemberForAccessor(*C))
Expand All @@ -248,7 +247,7 @@ class ReferencedDeclsVisitor
return true;
}

bool VisitMemberExpr(MemberExpr *E) {
bool VisitMemberExpr(MemberExpr *E) override {
// FIXME: should we be using `E->getFoundDecl()`?
const ValueDecl *VD = E->getMemberDecl();
insertIfGlobal(*VD, Referenced.Globals);
Expand All @@ -258,14 +257,14 @@ class ReferencedDeclsVisitor
return true;
}

bool VisitInitListExpr(InitListExpr *InitList) {
bool VisitInitListExpr(InitListExpr *InitList) override {
if (InitList->getType()->isRecordType())
for (const auto *FD : getFieldsForInitListExpr(InitList))
Referenced.Fields.insert(FD);
return true;
}

bool VisitCXXParenListInitExpr(CXXParenListInitExpr *ParenInitList) {
bool VisitCXXParenListInitExpr(CXXParenListInitExpr *ParenInitList) override {
if (ParenInitList->getType()->isRecordType())
for (const auto *FD : getFieldsForInitListExpr(ParenInitList))
Referenced.Fields.insert(FD);
Expand All @@ -281,7 +280,7 @@ ReferencedDecls getReferencedDecls(const FunctionDecl &FD) {
ReferencedDeclsVisitor Visitor(Result);
Visitor.TraverseStmt(FD.getBody());
if (const auto *CtorDecl = dyn_cast<CXXConstructorDecl>(&FD))
Visitor.TraverseConstructorInits(CtorDecl);
Visitor.traverseConstructorInits(CtorDecl);

return Result;
}
Expand Down
14 changes: 7 additions & 7 deletions clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ namespace {
// Visitor that builds a map from record prvalues to result objects.
// For each result object that it encounters, it propagates the storage location
// of the result object to all record prvalues that can initialize it.
class ResultObjectVisitor : public AnalysisASTVisitor<ResultObjectVisitor> {
class ResultObjectVisitor : public AnalysisASTVisitor {
public:
// `ResultObjectMap` will be filled with a map from record prvalues to result
// object. If this visitor will traverse a function that returns a record by
Expand All @@ -315,7 +315,7 @@ class ResultObjectVisitor : public AnalysisASTVisitor<ResultObjectVisitor> {
// called by `RecursiveASTVisitor`; it should be called manually if we are
// analyzing a constructor. `ThisPointeeLoc` is the storage location that
// `this` points to.
void TraverseConstructorInits(const CXXConstructorDecl *Ctor,
void traverseConstructorInits(const CXXConstructorDecl *Ctor,
RecordStorageLocation *ThisPointeeLoc) {
assert(ThisPointeeLoc != nullptr);
for (const CXXCtorInitializer *Init : Ctor->inits()) {
Expand All @@ -339,31 +339,31 @@ class ResultObjectVisitor : public AnalysisASTVisitor<ResultObjectVisitor> {
}
}

bool VisitVarDecl(VarDecl *VD) {
bool VisitVarDecl(VarDecl *VD) override {
if (VD->getType()->isRecordType() && VD->hasInit())
PropagateResultObject(
VD->getInit(),
&cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*VD)));
return true;
}

bool VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE) {
bool VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE) override {
if (MTE->getType()->isRecordType())
PropagateResultObject(
MTE->getSubExpr(),
&cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*MTE)));
return true;
}

bool VisitReturnStmt(ReturnStmt *Return) {
bool VisitReturnStmt(ReturnStmt *Return) override {
Expr *RetValue = Return->getRetValue();
if (RetValue != nullptr && RetValue->getType()->isRecordType() &&
RetValue->isPRValue())
PropagateResultObject(RetValue, LocForRecordReturnVal);
return true;
}

bool VisitExpr(Expr *E) {
bool VisitExpr(Expr *E) override {
// Clang's AST can have record-type prvalues without a result object -- for
// example as full-expressions contained in a compound statement or as
// arguments of call expressions. We notice this if we get here and a
Expand Down Expand Up @@ -1211,7 +1211,7 @@ Environment::PrValueToResultObject Environment::buildResultObjectMap(

ResultObjectVisitor Visitor(Map, LocForRecordReturnVal, *DACtx);
if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FuncDecl))
Visitor.TraverseConstructorInits(Ctor, ThisPointeeLoc);
Visitor.traverseConstructorInits(Ctor, ThisPointeeLoc);

return Map;
}
Expand Down
6 changes: 5 additions & 1 deletion clang/lib/Analysis/ProgramPoint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

#include "clang/Analysis/ProgramPoint.h"
#include "clang/AST/ASTContext.h"
#include "clang/Analysis/AnalysisDeclContext.h"
#include "clang/Basic/JsonSupport.h"

using namespace clang;
Expand Down Expand Up @@ -81,7 +82,10 @@ void ProgramPoint::printJson(llvm::raw_ostream &Out, const char *NL) const {
llvm_unreachable("BlockExitKind");
break;
case ProgramPoint::CallEnterKind:
Out << "CallEnter\"";
Out << "CallEnter\", \"callee_decl\": \"";
Out << AnalysisDeclContext::getFunctionName(
castAs<CallEnter>().getCalleeContext()->getDecl())
<< '\"';
break;
case ProgramPoint::CallExitBeginKind:
Out << "CallExitBegin\"";
Expand Down
14 changes: 8 additions & 6 deletions clang/lib/Analysis/ReachableCode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@

#include "clang/Analysis/Analyses/ReachableCode.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DynamicRecursiveASTVisitor.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ParentMap.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Analysis/AnalysisDeclContext.h"
#include "clang/Analysis/CFG.h"
Expand Down Expand Up @@ -476,17 +476,19 @@ static bool isInCoroutineStmt(const Stmt *DeadStmt, const CFGBlock *Block) {
}
if (!CoroStmt)
return false;
struct Checker : RecursiveASTVisitor<Checker> {
struct Checker : DynamicRecursiveASTVisitor {
const Stmt *DeadStmt;
bool CoroutineSubStmt = false;
Checker(const Stmt *S) : DeadStmt(S) {}
bool VisitStmt(const Stmt *S) {
Checker(const Stmt *S) : DeadStmt(S) {
// Statements captured in the CFG can be implicit.
ShouldVisitImplicitCode = true;
}

bool VisitStmt(Stmt *S) override {
if (S == DeadStmt)
CoroutineSubStmt = true;
return true;
}
// Statements captured in the CFG can be implicit.
bool shouldVisitImplicitCode() const { return true; }
};
Checker checker(DeadStmt);
checker.TraverseStmt(const_cast<Stmt *>(CoroStmt));
Expand Down
178 changes: 68 additions & 110 deletions clang/lib/Analysis/UnsafeBufferUsage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
#include "clang/Analysis/Analyses/UnsafeBufferUsage.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DynamicRecursiveASTVisitor.h"
#include "clang/AST/Expr.h"
#include "clang/AST/FormatString.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/AST/Type.h"
Expand Down Expand Up @@ -82,11 +82,8 @@ static std::string getDREAncestorString(const DeclRefExpr *DRE,
namespace clang::ast_matchers {
// A `RecursiveASTVisitor` that traverses all descendants of a given node "n"
// except for those belonging to a different callable of "n".
class MatchDescendantVisitor
: public RecursiveASTVisitor<MatchDescendantVisitor> {
class MatchDescendantVisitor : public DynamicRecursiveASTVisitor {
public:
typedef RecursiveASTVisitor<MatchDescendantVisitor> VisitorBase;

// Creates an AST visitor that matches `Matcher` on all
// descendants of a given node "n" except for the ones
// belonging to a different callable of "n".
Expand All @@ -96,7 +93,10 @@ class MatchDescendantVisitor
internal::ASTMatchFinder::BindKind Bind,
const bool ignoreUnevaluatedContext)
: Matcher(Matcher), Finder(Finder), Builder(Builder), Bind(Bind),
Matches(false), ignoreUnevaluatedContext(ignoreUnevaluatedContext) {}
Matches(false), ignoreUnevaluatedContext(ignoreUnevaluatedContext) {
ShouldVisitTemplateInstantiations = true;
ShouldVisitImplicitCode = false; // TODO: let's ignore implicit code for now
}

// Returns true if a match is found in a subtree of `DynNode`, which belongs
// to the same callable of `DynNode`.
Expand All @@ -117,7 +117,7 @@ class MatchDescendantVisitor
// For the matchers so far used in safe buffers, we only need to match
// `Stmt`s. To override more as needed.

bool TraverseDecl(Decl *Node) {
bool TraverseDecl(Decl *Node) override {
if (!Node)
return true;
if (!match(*Node))
Expand All @@ -126,69 +126,58 @@ class MatchDescendantVisitor
if (isa<FunctionDecl, BlockDecl, ObjCMethodDecl>(Node))
return true;
// Traverse descendants
return VisitorBase::TraverseDecl(Node);
return DynamicRecursiveASTVisitor::TraverseDecl(Node);
}

bool TraverseGenericSelectionExpr(GenericSelectionExpr *Node) {
bool TraverseGenericSelectionExpr(GenericSelectionExpr *Node) override {
// These are unevaluated, except the result expression.
if (ignoreUnevaluatedContext)
return TraverseStmt(Node->getResultExpr());
return VisitorBase::TraverseGenericSelectionExpr(Node);
return DynamicRecursiveASTVisitor::TraverseGenericSelectionExpr(Node);
}

bool TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node) {
bool
TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node) override {
// Unevaluated context.
if (ignoreUnevaluatedContext)
return true;
return VisitorBase::TraverseUnaryExprOrTypeTraitExpr(Node);
return DynamicRecursiveASTVisitor::TraverseUnaryExprOrTypeTraitExpr(Node);
}

bool TraverseTypeOfExprTypeLoc(TypeOfExprTypeLoc Node) {
bool TraverseTypeOfExprTypeLoc(TypeOfExprTypeLoc Node) override {
// Unevaluated context.
if (ignoreUnevaluatedContext)
return true;
return VisitorBase::TraverseTypeOfExprTypeLoc(Node);
return DynamicRecursiveASTVisitor::TraverseTypeOfExprTypeLoc(Node);
}

bool TraverseDecltypeTypeLoc(DecltypeTypeLoc Node) {
bool TraverseDecltypeTypeLoc(DecltypeTypeLoc Node) override {
// Unevaluated context.
if (ignoreUnevaluatedContext)
return true;
return VisitorBase::TraverseDecltypeTypeLoc(Node);
return DynamicRecursiveASTVisitor::TraverseDecltypeTypeLoc(Node);
}

bool TraverseCXXNoexceptExpr(CXXNoexceptExpr *Node) {
bool TraverseCXXNoexceptExpr(CXXNoexceptExpr *Node) override {
// Unevaluated context.
if (ignoreUnevaluatedContext)
return true;
return VisitorBase::TraverseCXXNoexceptExpr(Node);
return DynamicRecursiveASTVisitor::TraverseCXXNoexceptExpr(Node);
}

bool TraverseCXXTypeidExpr(CXXTypeidExpr *Node) {
bool TraverseCXXTypeidExpr(CXXTypeidExpr *Node) override {
// Unevaluated context.
if (ignoreUnevaluatedContext)
return true;
return VisitorBase::TraverseCXXTypeidExpr(Node);
}

bool TraverseCXXDefaultInitExpr(CXXDefaultInitExpr *Node) {
if (!TraverseStmt(Node->getExpr()))
return false;
return VisitorBase::TraverseCXXDefaultInitExpr(Node);
return DynamicRecursiveASTVisitor::TraverseCXXTypeidExpr(Node);
}

bool TraverseStmt(Stmt *Node, DataRecursionQueue *Queue = nullptr) {
bool TraverseStmt(Stmt *Node) override {
if (!Node)
return true;
if (!match(*Node))
return false;
return VisitorBase::TraverseStmt(Node);
}

bool shouldVisitTemplateInstantiations() const { return true; }
bool shouldVisitImplicitCode() const {
// TODO: let's ignore implicit code for now
return false;
return DynamicRecursiveASTVisitor::TraverseStmt(Node);
}

private:
Expand Down Expand Up @@ -1998,18 +1987,14 @@ class DerefSimplePtrArithFixableGadget : public FixableGadget {
};

/// Scan the function and return a list of gadgets found with provided kits.
static void findGadgets(const Stmt *S, ASTContext &Ctx,
const UnsafeBufferUsageHandler &Handler,
bool EmitSuggestions, FixableGadgetList &FixableGadgets,
WarningGadgetList &WarningGadgets,
DeclUseTracker &Tracker) {
static std::tuple<FixableGadgetList, WarningGadgetList, DeclUseTracker>
findGadgets(const Decl *D, const UnsafeBufferUsageHandler &Handler,
bool EmitSuggestions) {

struct GadgetFinderCallback : MatchFinder::MatchCallback {
GadgetFinderCallback(FixableGadgetList &FixableGadgets,
WarningGadgetList &WarningGadgets,
DeclUseTracker &Tracker)
: FixableGadgets(FixableGadgets), WarningGadgets(WarningGadgets),
Tracker(Tracker) {}
FixableGadgetList FixableGadgets;
WarningGadgetList WarningGadgets;
DeclUseTracker Tracker;

void run(const MatchFinder::MatchResult &Result) override {
// In debug mode, assert that we've found exactly one gadget.
Expand Down Expand Up @@ -2050,14 +2035,10 @@ static void findGadgets(const Stmt *S, ASTContext &Ctx,
assert(numFound >= 1 && "Gadgets not found in match result!");
assert(numFound <= 1 && "Conflicting bind tags in gadgets!");
}

FixableGadgetList &FixableGadgets;
WarningGadgetList &WarningGadgets;
DeclUseTracker &Tracker;
};

MatchFinder M;
GadgetFinderCallback CB{FixableGadgets, WarningGadgets, Tracker};
GadgetFinderCallback CB;

// clang-format off
M.addMatcher(
Expand Down Expand Up @@ -2102,7 +2083,9 @@ static void findGadgets(const Stmt *S, ASTContext &Ctx,
// clang-format on
}

M.match(*S, Ctx);
M.match(*D->getBody(), D->getASTContext());
return {std::move(CB.FixableGadgets), std::move(CB.WarningGadgets),
std::move(CB.Tracker)};
}

// Compares AST nodes by source locations.
Expand Down Expand Up @@ -3646,9 +3629,39 @@ class VariableGroupsManagerImpl : public VariableGroupsManager {
}
};

void applyGadgets(const Decl *D, FixableGadgetList FixableGadgets,
WarningGadgetList WarningGadgets, DeclUseTracker Tracker,
UnsafeBufferUsageHandler &Handler, bool EmitSuggestions) {
void clang::checkUnsafeBufferUsage(const Decl *D,
UnsafeBufferUsageHandler &Handler,
bool EmitSuggestions) {
#ifndef NDEBUG
Handler.clearDebugNotes();
#endif

assert(D && D->getBody());
// We do not want to visit a Lambda expression defined inside a method
// independently. Instead, it should be visited along with the outer method.
// FIXME: do we want to do the same thing for `BlockDecl`s?
if (const auto *fd = dyn_cast<CXXMethodDecl>(D)) {
if (fd->getParent()->isLambda() && fd->getParent()->isLocalClass())
return;
}

// Do not emit fixit suggestions for functions declared in an
// extern "C" block.
if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
for (FunctionDecl *FReDecl : FD->redecls()) {
if (FReDecl->isExternC()) {
EmitSuggestions = false;
break;
}
}
}

WarningGadgetSets UnsafeOps;
FixableGadgetSets FixablesForAllVars;

auto [FixableGadgets, WarningGadgets, Tracker] =
findGadgets(D, Handler, EmitSuggestions);

if (!EmitSuggestions) {
// Our job is very easy without suggestions. Just warn about
// every problematic operation and consider it done. No need to deal
Expand Down Expand Up @@ -3692,10 +3705,8 @@ void applyGadgets(const Decl *D, FixableGadgetList FixableGadgets,
if (WarningGadgets.empty())
return;

WarningGadgetSets UnsafeOps =
groupWarningGadgetsByVar(std::move(WarningGadgets));
FixableGadgetSets FixablesForAllVars =
groupFixablesByVar(std::move(FixableGadgets));
UnsafeOps = groupWarningGadgetsByVar(std::move(WarningGadgets));
FixablesForAllVars = groupFixablesByVar(std::move(FixableGadgets));

std::map<const VarDecl *, FixItList> FixItsForVariableGroup;

Expand Down Expand Up @@ -3916,56 +3927,3 @@ void applyGadgets(const Decl *D, FixableGadgetList FixableGadgets,
}
}
}

void clang::checkUnsafeBufferUsage(const Decl *D,
UnsafeBufferUsageHandler &Handler,
bool EmitSuggestions) {
#ifndef NDEBUG
Handler.clearDebugNotes();
#endif

assert(D);

SmallVector<Stmt *> Stmts;

if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
// We do not want to visit a Lambda expression defined inside a method
// independently. Instead, it should be visited along with the outer method.
// FIXME: do we want to do the same thing for `BlockDecl`s?
if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
if (MD->getParent()->isLambda() && MD->getParent()->isLocalClass())
return;
}

for (FunctionDecl *FReDecl : FD->redecls()) {
if (FReDecl->isExternC()) {
// Do not emit fixit suggestions for functions declared in an
// extern "C" block.
EmitSuggestions = false;
break;
}
}

Stmts.push_back(FD->getBody());

if (const auto *ID = dyn_cast<CXXConstructorDecl>(D)) {
for (const CXXCtorInitializer *CI : ID->inits()) {
Stmts.push_back(CI->getInit());
}
}
} else if (isa<BlockDecl>(D) || isa<ObjCMethodDecl>(D)) {
Stmts.push_back(D->getBody());
}

assert(!Stmts.empty());

FixableGadgetList FixableGadgets;
WarningGadgetList WarningGadgets;
DeclUseTracker Tracker;
for (Stmt *S : Stmts) {
findGadgets(S, D->getASTContext(), Handler, EmitSuggestions, FixableGadgets,
WarningGadgets, Tracker);
}
applyGadgets(D, std::move(FixableGadgets), std::move(WarningGadgets),
std::move(Tracker), Handler, EmitSuggestions);
}
10 changes: 4 additions & 6 deletions clang/lib/Basic/Targets/AArch64.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,7 @@ void AArch64TargetInfo::getTargetDefines(const LangOptions &Opts,
if (HasSVE2p1)
Builder.defineMacro("__ARM_FEATURE_SVE2p1", "1");

if (HasSVE2 && HasSVE2AES)
if (HasSVE2 && HasSVEAES)
Builder.defineMacro("__ARM_FEATURE_SVE2_AES", "1");

if (HasSVE2 && HasSVE2BitPerm)
Expand Down Expand Up @@ -769,7 +769,7 @@ bool AArch64TargetInfo::hasFeature(StringRef Feature) const {
.Case("f32mm", FPU & SveMode && HasMatmulFP32)
.Case("f64mm", FPU & SveMode && HasMatmulFP64)
.Case("sve2", FPU & SveMode && HasSVE2)
.Case("sve2-pmull128", FPU & SveMode && HasSVE2AES)
.Case("sve-aes", HasSVEAES)
.Case("sve2-bitperm", FPU & SveMode && HasSVE2BitPerm)
.Case("sve2-sha3", FPU & SveMode && HasSVE2SHA3)
.Case("sve2-sm4", FPU & SveMode && HasSVE2SM4)
Expand Down Expand Up @@ -861,12 +861,10 @@ bool AArch64TargetInfo::handleTargetFeatures(std::vector<std::string> &Features,
HasSVE2 = true;
HasSVE2p1 = true;
}
if (Feature == "+sve2-aes") {
if (Feature == "+sve-aes") {
FPU |= NeonMode;
FPU |= SveMode;
HasFullFP16 = true;
HasSVE2 = true;
HasSVE2AES = true;
HasSVEAES = true;
}
if (Feature == "+sve2-sha3") {
FPU |= NeonMode;
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/Basic/Targets/AArch64.h
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public TargetInfo {
bool HasBFloat16 = false;
bool HasSVE2 = false;
bool HasSVE2p1 = false;
bool HasSVE2AES = false;
bool HasSVEAES = false;
bool HasSVE2SHA3 = false;
bool HasSVE2SM4 = false;
bool HasSVEB16B16 = false;
Expand Down
12 changes: 12 additions & 0 deletions clang/lib/Basic/Targets/AMDGPU.h
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,18 @@ class LLVM_LIBRARY_VISIBILITY AMDGPUTargetInfo final : public TargetInfo {
return getPointerWidthV(AddrSpace);
}

virtual bool isAddressSpaceSupersetOf(LangAS A, LangAS B) const override {
// The flat address space AS(0) is a superset of all the other address
// spaces used by the backend target.
return A == B ||
((A == LangAS::Default ||
(isTargetAddressSpace(A) &&
toTargetAddressSpace(A) == llvm::AMDGPUAS::FLAT_ADDRESS)) &&
isTargetAddressSpace(B) &&
toTargetAddressSpace(B) >= llvm::AMDGPUAS::FLAT_ADDRESS &&
toTargetAddressSpace(B) <= llvm::AMDGPUAS::PRIVATE_ADDRESS);
}

uint64_t getMaxPointerWidth() const override {
return getTriple().getArch() == llvm::Triple::amdgcn ? 64 : 32;
}
Expand Down
15 changes: 15 additions & 0 deletions clang/lib/Basic/Targets/NVPTX.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/NVPTXAddrSpace.h"
#include "llvm/TargetParser/Triple.h"
#include <optional>

Expand Down Expand Up @@ -89,6 +90,20 @@ class LLVM_LIBRARY_VISIBILITY NVPTXTargetInfo : public TargetInfo {

bool hasFeature(StringRef Feature) const override;

virtual bool isAddressSpaceSupersetOf(LangAS A, LangAS B) const override {
// The generic address space AS(0) is a superset of all the other address
// spaces used by the backend target.
return A == B ||
((A == LangAS::Default ||
(isTargetAddressSpace(A) &&
toTargetAddressSpace(A) ==
llvm::NVPTXAS::ADDRESS_SPACE_GENERIC)) &&
isTargetAddressSpace(B) &&
toTargetAddressSpace(B) >= llvm::NVPTXAS::ADDRESS_SPACE_GENERIC &&
toTargetAddressSpace(B) <= llvm::NVPTXAS::ADDRESS_SPACE_LOCAL &&
toTargetAddressSpace(B) != 2);
}

ArrayRef<const char *> getGCCRegNames() const override;

ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
Expand Down
3 changes: 3 additions & 0 deletions clang/lib/CIR/Dialect/IR/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ add_clang_library(MLIRCIR
CIRDialect.cpp
CIRTypes.cpp

DEPENDS
MLIRCIROpsIncGen

LINK_LIBS PUBLIC
MLIRIR
)
5 changes: 0 additions & 5 deletions clang/lib/CodeGen/BackendUtil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,14 @@
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/Utils.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/SchedulerRegistry.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/Frontend/Driver/CodeGenOptions.h"
#include "llvm/IR/DataLayout.h"
Expand All @@ -39,7 +35,6 @@
#include "llvm/IR/Verifier.h"
#include "llvm/IRPrinter/IRPrintingPasses.h"
#include "llvm/LTO/LTOBackend.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Object/OffloadBinary.h"
#include "llvm/Passes/PassBuilder.h"
Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CGAtomic.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
#include "llvm/ADT/DenseMap.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Operator.h"

using namespace clang;
using namespace CodeGen;
Expand Down
15 changes: 6 additions & 9 deletions clang/lib/CodeGen/CGBlocks.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
#include "clang/AST/Attr.h"
#include "clang/AST/DeclObjC.h"
#include "clang/CodeGen/ConstantInitBuilder.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/ScopedPrinter.h"
Expand Down Expand Up @@ -2837,10 +2836,9 @@ llvm::FunctionCallee CodeGenModule::getBlockObjectDispose() {
if (BlockObjectDispose)
return BlockObjectDispose;

llvm::Type *args[] = { Int8PtrTy, Int32Ty };
llvm::FunctionType *fty
= llvm::FunctionType::get(VoidTy, args, false);
BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
QualType args[] = {Context.VoidPtrTy, Context.IntTy};
BlockObjectDispose =
CreateRuntimeFunction(Context.VoidTy, args, "_Block_object_dispose");
configureBlocksRuntimeObject(
*this, cast<llvm::Constant>(BlockObjectDispose.getCallee()));
return BlockObjectDispose;
Expand All @@ -2850,10 +2848,9 @@ llvm::FunctionCallee CodeGenModule::getBlockObjectAssign() {
if (BlockObjectAssign)
return BlockObjectAssign;

llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
llvm::FunctionType *fty
= llvm::FunctionType::get(VoidTy, args, false);
BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
QualType args[] = {Context.VoidPtrTy, Context.VoidPtrTy, Context.IntTy};
BlockObjectAssign =
CreateRuntimeFunction(Context.VoidTy, args, "_Block_object_assign");
configureBlocksRuntimeObject(
*this, cast<llvm::Constant>(BlockObjectAssign.getCallee()));
return BlockObjectAssign;
Expand Down
58 changes: 47 additions & 11 deletions clang/lib/CodeGen/CGBuiltin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@
#include "llvm/IR/IntrinsicsR600.h"
#include "llvm/IR/IntrinsicsRISCV.h"
#include "llvm/IR/IntrinsicsS390.h"
#include "llvm/IR/IntrinsicsVE.h"
#include "llvm/IR/IntrinsicsWebAssembly.h"
#include "llvm/IR/IntrinsicsX86.h"
#include "llvm/IR/MDBuilder.h"
Expand All @@ -69,7 +68,6 @@
#include "llvm/TargetParser/RISCVISAInfo.h"
#include "llvm/TargetParser/X86TargetParser.h"
#include <optional>
#include <sstream>
#include <utility>

using namespace clang;
Expand Down Expand Up @@ -99,6 +97,47 @@ static void initializeAlloca(CodeGenFunction &CGF, AllocaInst *AI, Value *Size,
I->addAnnotationMetadata("auto-init");
}

static Value *handleHlslClip(const CallExpr *E, CodeGenFunction *CGF) {
Value *Op0 = CGF->EmitScalarExpr(E->getArg(0));

Constant *FZeroConst = ConstantFP::getZero(CGF->FloatTy);
Value *CMP;
Value *LastInstr;

if (const auto *VecTy = E->getArg(0)->getType()->getAs<clang::VectorType>()) {
FZeroConst = ConstantVector::getSplat(
ElementCount::getFixed(VecTy->getNumElements()), FZeroConst);
auto *FCompInst = CGF->Builder.CreateFCmpOLT(Op0, FZeroConst);
CMP = CGF->Builder.CreateIntrinsic(
CGF->Builder.getInt1Ty(), CGF->CGM.getHLSLRuntime().getAnyIntrinsic(),
{FCompInst}, nullptr);
} else
CMP = CGF->Builder.CreateFCmpOLT(Op0, FZeroConst);

if (CGF->CGM.getTarget().getTriple().isDXIL())
LastInstr = CGF->Builder.CreateIntrinsic(
CGF->VoidTy, llvm::Intrinsic::dx_discard, {CMP}, nullptr);
else if (CGF->CGM.getTarget().getTriple().isSPIRV()) {
BasicBlock *LT0 = CGF->createBasicBlock("lt0", CGF->CurFn);
BasicBlock *End = CGF->createBasicBlock("end", CGF->CurFn);

CGF->Builder.CreateCondBr(CMP, LT0, End);

CGF->Builder.SetInsertPoint(LT0);

CGF->Builder.CreateIntrinsic(CGF->VoidTy, llvm::Intrinsic::spv_discard, {},
nullptr);

LastInstr = CGF->Builder.CreateBr(End);

CGF->Builder.SetInsertPoint(End);
} else {
llvm_unreachable("Backend Codegen not supported.");
}

return LastInstr;
}

static Value *handleHlslSplitdouble(const CallExpr *E, CodeGenFunction *CGF) {
Value *Op0 = CGF->EmitScalarExpr(E->getArg(0));
const auto *OutArg1 = dyn_cast<HLSLOutArgExpr>(E->getArg(1));
Expand Down Expand Up @@ -5944,15 +5983,8 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
llvm::Value *Block =
Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);

AttrBuilder B(Builder.getContext());
B.addByValAttr(NDRangeL.getAddress().getElementType());
llvm::AttributeList ByValAttrSet =
llvm::AttributeList::get(CGM.getModule().getContext(), 3U, B);

auto RTCall =
EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name, ByValAttrSet),
{Queue, Flags, Range, Kernel, Block});
RTCall->setAttributes(ByValAttrSet);
auto RTCall = EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
{Queue, Flags, Range, Kernel, Block});
return RValue::get(RTCall);
}
assert(NumArgs >= 5 && "Invalid enqueue_kernel signature");
Expand Down Expand Up @@ -19208,6 +19240,10 @@ case Builtin::BI__builtin_hlsl_elementwise_isinf: {
"asuint operands types mismatch");
return handleHlslSplitdouble(E, this);
}
case Builtin::BI__builtin_hlsl_elementwise_clip:
assert(E->getArg(0)->getType()->hasFloatingRepresentation() &&
"clip operands types mismatch");
return handleHlslClip(E, this);
}
return nullptr;
}
Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CGCUDARuntime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
#include "CGCUDARuntime.h"
#include "CGCall.h"
#include "CodeGenFunction.h"
#include "clang/AST/Decl.h"
#include "clang/AST/ExprCXX.h"

using namespace clang;
Expand Down
2 changes: 0 additions & 2 deletions clang/lib/CodeGen/CGCXX.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Basic/CodeGenOptions.h"
#include "llvm/ADT/StringExtras.h"
using namespace clang;
using namespace CodeGen;

Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CGCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/Path.h"
#include "llvm/Transforms/Utils/Local.h"
#include <optional>
using namespace clang;
Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CGClass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/TargetBuiltins.h"
#include "clang/CodeGen/CGFunctionInfo.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Metadata.h"
Expand Down
2 changes: 0 additions & 2 deletions clang/lib/CodeGen/CGDebugInfo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/VTableBuilder.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Version.h"
#include "clang/CodeGen/ModuleBuilder.h"
Expand All @@ -48,7 +47,6 @@
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MD5.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SHA1.h"
Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CGDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclOpenMP.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/CGFunctionInfo.h"
#include "clang/Sema/Sema.h"
Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CGException.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
#include "clang/AST/StmtObjC.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/DiagnosticSema.h"
#include "clang/Basic/TargetBuiltins.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicsWebAssembly.h"
Expand Down
4 changes: 0 additions & 4 deletions clang/lib/CodeGen/CGExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,22 +31,18 @@
#include "clang/Basic/Builtins.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicsWebAssembly.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/MatrixBuilder.h"
#include "llvm/Passes/OptimizationLevel.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/xxhash.h"
#include "llvm/Transforms/Utils/SanitizerStats.h"

Expand Down
2 changes: 0 additions & 2 deletions clang/lib/CodeGen/CGExprComplex.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,10 @@
#include "CodeGenModule.h"
#include "ConstantEmitter.h"
#include "clang/AST/StmtVisitor.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Metadata.h"
#include <algorithm>
using namespace clang;
using namespace CodeGen;

Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CGGPUBuiltin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
#include "clang/Basic/Builtins.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Instruction.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Transforms/Utils/AMDGPUEmitPrintf.h"

using namespace clang;
Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CGObjC.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
#include "clang/Basic/Diagnostic.h"
#include "clang/CodeGen/CGFunctionInfo.h"
#include "clang/CodeGen/CodeGenABITypes.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/ObjCARCUtil.h"
#include "llvm/BinaryFormat/MachO.h"
#include "llvm/IR/Constants.h"
Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CGObjCGNU.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
#include "clang/AST/DeclObjC.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtObjC.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/CodeGen/ConstantInitBuilder.h"
#include "llvm/ADT/SmallVector.h"
Expand Down
2 changes: 0 additions & 2 deletions clang/lib/CodeGen/CGObjCMac.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,12 @@
#include "clang/AST/StmtObjC.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/LangOptions.h"
#include "clang/CodeGen/CGFunctionInfo.h"
#include "clang/CodeGen/ConstantInitBuilder.h"
#include "llvm/ADT/CachedHashString.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/UniqueVector.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/IntrinsicInst.h"
Expand Down
5 changes: 0 additions & 5 deletions clang/lib/CodeGen/CGOpenMPRuntime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,10 @@
#include "clang/AST/OpenMPClause.h"
#include "clang/AST/StmtOpenMP.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/BitmaskEnum.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/SourceManager.h"
#include "clang/CodeGen/ConstantInitBuilder.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SetOperations.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Bitcode/BitcodeReader.h"
Expand All @@ -40,7 +36,6 @@
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/AtomicOrdering.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdint>
Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
#include "clang/Basic/Cuda.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Frontend/OpenMP/OMPGridValues.h"
#include "llvm/Support/MathExtras.h"

using namespace clang;
using namespace CodeGen;
Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CGVTables.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
#include "clang/CodeGen/CGFunctionInfo.h"
#include "clang/CodeGen/ConstantInitBuilder.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/Support/Format.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include <algorithm>
#include <cstdio>
Expand Down
2 changes: 0 additions & 2 deletions clang/lib/CodeGen/CodeGenABITypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/CodeGen/CGFunctionInfo.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/PreprocessorOptions.h"

using namespace clang;
using namespace CodeGen;
Expand Down
3 changes: 0 additions & 3 deletions clang/lib/CodeGen/CodeGenAction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/MultiplexConsumer.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Serialization/ASTWriter.h"
Expand All @@ -50,7 +48,6 @@
#include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/YAMLTraits.h"
#include "llvm/Transforms/IPO/Internalize.h"
#include "llvm/Transforms/Utils/Cloning.h"

Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CodeGenFunction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/CRC.h"
#include "llvm/Support/xxhash.h"
#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Expand Down
68 changes: 49 additions & 19 deletions clang/lib/CodeGen/CodeGenModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,10 @@
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Stack.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/CodeGen/BackendUtil.h"
Expand All @@ -55,7 +52,6 @@
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
#include "llvm/IR/AttributeMask.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/DataLayout.h"
Expand Down Expand Up @@ -4903,6 +4899,52 @@ GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
return nullptr;
}

static void setWindowsItaniumDLLImport(CodeGenModule &CGM, bool Local,
llvm::Function *F, StringRef Name) {
// In Windows Itanium environments, try to mark runtime functions
// dllimport. For Mingw and MSVC, don't. We don't really know if the user
// will link their standard library statically or dynamically. Marking
// functions imported when they are not imported can cause linker errors
// and warnings.
if (!Local && CGM.getTriple().isWindowsItaniumEnvironment() &&
!CGM.getCodeGenOpts().LTOVisibilityPublicStd) {
const FunctionDecl *FD = GetRuntimeFunctionDecl(CGM.getContext(), Name);
if (!FD || FD->hasAttr<DLLImportAttr>()) {
F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
F->setLinkage(llvm::GlobalValue::ExternalLinkage);
}
}
}

llvm::FunctionCallee CodeGenModule::CreateRuntimeFunction(
QualType ReturnTy, ArrayRef<QualType> ArgTys, StringRef Name,
llvm::AttributeList ExtraAttrs, bool Local, bool AssumeConvergent) {
if (AssumeConvergent) {
ExtraAttrs =
ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
}

QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
FunctionProtoType::ExtProtoInfo());
const CGFunctionInfo &Info = getTypes().arrangeFreeFunctionType(
Context.getCanonicalType(FTy).castAs<FunctionProtoType>());
auto *ConvTy = getTypes().GetFunctionType(Info);
llvm::Constant *C = GetOrCreateLLVMFunction(
Name, ConvTy, GlobalDecl(), /*ForVTable=*/false,
/*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);

if (auto *F = dyn_cast<llvm::Function>(C)) {
if (F->empty()) {
SetLLVMFunctionAttributes(GlobalDecl(), Info, F, /*IsThunk*/ false);
// FIXME: Set calling-conv properly in ExtProtoInfo
F->setCallingConv(getRuntimeCC());
setWindowsItaniumDLLImport(*this, Local, F, Name);
setDSOLocal(F);
}
}
return {ConvTy, C};
}

/// CreateRuntimeFunction - Create a new runtime function with the specified
/// type and name.
llvm::FunctionCallee
Expand All @@ -4922,24 +4964,12 @@ CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
if (auto *F = dyn_cast<llvm::Function>(C)) {
if (F->empty()) {
F->setCallingConv(getRuntimeCC());

// In Windows Itanium environments, try to mark runtime functions
// dllimport. For Mingw and MSVC, don't. We don't really know if the user
// will link their standard library statically or dynamically. Marking
// functions imported when they are not imported can cause linker errors
// and warnings.
if (!Local && getTriple().isWindowsItaniumEnvironment() &&
!getCodeGenOpts().LTOVisibilityPublicStd) {
const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
if (!FD || FD->hasAttr<DLLImportAttr>()) {
F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
F->setLinkage(llvm::GlobalValue::ExternalLinkage);
}
}
setWindowsItaniumDLLImport(*this, Local, F, Name);
setDSOLocal(F);
// FIXME: We should use CodeGenModule::SetLLVMFunctionAttributes() instead
// of trying to approximate the attributes using the LLVM function
// signature. This requires revising the API of CreateRuntimeFunction().
// signature. The other overload of CreateRuntimeFunction does this; it
// should be used for new code.
markRegisterParameterAttributes(F);
}
}
Expand Down
12 changes: 12 additions & 0 deletions clang/lib/CodeGen/CodeGenModule.h
Original file line number Diff line number Diff line change
Expand Up @@ -1247,11 +1247,23 @@ class CodeGenModule : public CodeGenTypeCache {
/// Create or return a runtime function declaration with the specified type
/// and name. If \p AssumeConvergent is true, the call will have the
/// convergent attribute added.
///
/// For new code, please use the overload that takes a QualType; it sets
/// function attributes more accurately.
llvm::FunctionCallee
CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
bool Local = false, bool AssumeConvergent = false);

/// Create or return a runtime function declaration with the specified type
/// and name. If \p AssumeConvergent is true, the call will have the
/// convergent attribute added.
llvm::FunctionCallee
CreateRuntimeFunction(QualType ReturnTy, ArrayRef<QualType> ArgTys,
StringRef Name,
llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
bool Local = false, bool AssumeConvergent = false);

/// Create a new runtime global variable with the specified type and name.
llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
StringRef Name);
Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/CodeGenPGO.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
#include "llvm/IR/MDBuilder.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MD5.h"
#include <optional>

Expand Down
2 changes: 0 additions & 2 deletions clang/lib/CodeGen/CodeGenTBAA.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@
#include "clang/AST/RecordLayout.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
Expand Down
3 changes: 0 additions & 3 deletions clang/lib/CodeGen/CoverageMappingGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,13 @@
#include "CodeGenFunction.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ProfileData/Coverage/CoverageMapping.h"
#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
#include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
#include "llvm/ProfileData/InstrProfReader.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include <optional>
Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/ItaniumCXXABI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
#include "CGVTables.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "ConstantEmitter.h"
#include "TargetInfo.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Mangle.h"
Expand Down
4 changes: 0 additions & 4 deletions clang/lib/CodeGen/LinkInModulesPass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@
#include "LinkInModulesPass.h"
#include "BackendConsumer.h"

#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"

using namespace llvm;

LinkInModulesPass::LinkInModulesPass(clang::BackendConsumer *BC) : BC(BC) {}
Expand Down
1 change: 1 addition & 0 deletions clang/lib/CodeGen/MicrosoftCXXABI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,7 @@ class MicrosoftCXXABI : public CGCXXABI {
bool usesThreadWrapperFunction(const VarDecl *VD) const override {
return getContext().getLangOpts().isCompatibleWithMSVC(
LangOptions::MSVC2019_5) &&
CGM.getCodeGenOpts().TlsGuards &&
(!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD));
}
LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
Expand Down
3 changes: 0 additions & 3 deletions clang/lib/CodeGen/ObjectFilePCHContainerWriter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,12 @@
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitstream/BitstreamReader.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/Path.h"
#include <memory>
#include <utility>
Expand Down
3 changes: 0 additions & 3 deletions clang/lib/CodeGen/SanitizerMetadata.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@
#include "CodeGenModule.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Type.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Constants.h"

using namespace clang;
using namespace CodeGen;
Expand Down
1 change: 0 additions & 1 deletion clang/lib/CodeGen/SwiftCallingConv.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
#include "CodeGenModule.h"
#include "TargetInfo.h"
#include "clang/Basic/TargetInfo.h"
#include <optional>

using namespace clang;
using namespace CodeGen;
Expand Down
3 changes: 0 additions & 3 deletions clang/lib/Driver/Compilation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,10 @@
#include "clang/Basic/LLVM.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/ToolChain.h"
#include "clang/Driver/Util.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptSpecifier.h"
#include "llvm/Option/Option.h"
Expand Down
1 change: 0 additions & 1 deletion clang/lib/Driver/Distro.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

#include "clang/Driver/Distro.h"
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorOr.h"
Expand Down
1 change: 0 additions & 1 deletion clang/lib/Driver/Driver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@
#include "clang/Config/config.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/InputInfo.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Options.h"
Expand Down
2 changes: 0 additions & 2 deletions clang/lib/Driver/DriverOptions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
//===----------------------------------------------------------------------===//

#include "clang/Driver/Options.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
#include <cassert>

using namespace clang::driver;
Expand Down
2 changes: 0 additions & 2 deletions clang/lib/Driver/Job.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
#include "clang/Driver/Job.h"
#include "clang/Basic/LLVM.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/InputInfo.h"
#include "clang/Driver/Tool.h"
#include "clang/Driver/ToolChain.h"
Expand All @@ -26,7 +25,6 @@
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <string>
Expand Down
4 changes: 0 additions & 4 deletions clang/lib/Driver/Multilib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,11 @@

#include "clang/Driver/Multilib.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/Driver.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/VersionTuple.h"
#include "llvm/Support/YAMLParser.h"
Expand Down
1 change: 0 additions & 1 deletion clang/lib/Driver/MultilibBuilder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

#include "clang/Driver/MultilibBuilder.h"
#include "ToolChains/CommonArgs.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Regex.h"
Expand Down
1 change: 0 additions & 1 deletion clang/lib/Driver/OffloadBundler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
#include "clang/Driver/OffloadBundler.h"
#include "clang/Basic/Cuda.h"
#include "clang/Basic/TargetID.h"
#include "clang/Basic/Version.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
Expand Down
3 changes: 0 additions & 3 deletions clang/lib/Driver/SanitizerArgs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,10 @@
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/SanitizerArgs.h"
#include "ToolChains/CommonArgs.h"
#include "clang/Basic/Sanitizers.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/ToolChain.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Path.h"
Expand Down
2 changes: 0 additions & 2 deletions clang/lib/Driver/ToolChain.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,11 @@
#include "clang/Config/config.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/InputInfo.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/SanitizerArgs.h"
#include "clang/Driver/XRayArgs.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
Expand Down
4 changes: 4 additions & 0 deletions clang/lib/Driver/ToolChains/Arch/ARM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -908,6 +908,10 @@ llvm::ARM::FPUKind arm::getARMTargetFeatures(const Driver &D,
if (VersionNum < 6 ||
Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
Features.push_back("+strict-align");
} else if (Triple.getVendor() == llvm::Triple::Apple &&
Triple.isOSBinFormatMachO()) {
// Firmwares on Apple platforms are strict-align by default.
Features.push_back("+strict-align");
} else if (VersionNum < 7 ||
Triple.getSubArch() ==
llvm::Triple::SubArchType::ARMSubArch_v6m ||
Expand Down
9 changes: 7 additions & 2 deletions clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,15 @@ void loongarch::getLoongArchTargetFeatures(const Driver &D,
Features.push_back("+lsx");

std::string ArchName;
if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
ArchName = A->getValue();
const Arg *MArch = Args.getLastArg(options::OPT_march_EQ);
if (MArch)
ArchName = MArch->getValue();
ArchName = postProcessTargetCPUString(ArchName, Triple);
llvm::LoongArch::getArchFeatures(ArchName, Features);
if (MArch && StringRef(MArch->getValue()) == "native")
for (auto &F : llvm::sys::getHostCPUFeatures())
Features.push_back(
Args.MakeArgString((F.second ? "+" : "-") + F.first()));

// Select floating-point features determined by -mdouble-float,
// -msingle-float, -msoft-float and -mfpu.
Expand Down
5 changes: 5 additions & 0 deletions clang/lib/Driver/ToolChains/Clang.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1341,6 +1341,7 @@ static bool isSignedCharDefault(const llvm::Triple &Triple) {
return false;

case llvm::Triple::hexagon:
case llvm::Triple::msp430:
case llvm::Triple::ppcle:
case llvm::Triple::ppc64le:
case llvm::Triple::riscv32:
Expand Down Expand Up @@ -7316,6 +7317,10 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
(!IsWindowsMSVC || IsMSVC2015Compatible)))
CmdArgs.push_back("-fno-threadsafe-statics");

if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
true))
CmdArgs.push_back("-fno-ms-tls-guards");

// Add -fno-assumptions, if it was specified.
if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
true))
Expand Down
66 changes: 55 additions & 11 deletions clang/lib/Driver/ToolChains/PS4CPU.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ void tools::PS4cpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
CmdArgs.push_back(
Args.MakeArgString(Twine("-lto-debug-options=") + LTOArgs));

// Sanitizer runtimes must be supplied before all other objects and libs.
if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
TC.addSanitizerArgs(Args, CmdArgs, "-l", "");

Expand Down Expand Up @@ -360,27 +361,70 @@ void tools::PS5cpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
if (StringRef Jobs = getLTOParallelism(Args, D); !Jobs.empty())
AddLTOFlag(Twine("jobs=") + Jobs);

if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
TC.addSanitizerArgs(Args, CmdArgs, "-l", "");

TC.AddFilePathLibArgs(Args, CmdArgs);
Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
options::OPT_s, options::OPT_t});

if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
CmdArgs.push_back("--no-demangle");

AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
// Sanitizer runtimes must be supplied before all other objects and libs.
if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
TC.addSanitizerArgs(Args, CmdArgs, "-l", "");

if (Args.hasArg(options::OPT_pthread)) {
CmdArgs.push_back("-lpthread");
const bool AddStartFiles =
!Relocatable &&
!Args.hasArg(options::OPT_nostartfiles, options::OPT_nostdlib);

auto AddCRTObject = [&](const char *Name) {
CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath(Name)));
};

if (AddStartFiles) {
if (!Shared)
AddCRTObject("crt1.o");
AddCRTObject("crti.o");
AddCRTObject(Shared ? "crtbeginS.o"
: Static ? "crtbeginT.o"
: "crtbegin.o");
}

if (UseJMC) {
CmdArgs.push_back("--push-state");
CmdArgs.push_back("--whole-archive");
CmdArgs.push_back("-lSceJmc_nosubmission");
CmdArgs.push_back("--pop-state");
AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);

if (!Relocatable &&
!Args.hasArg(options::OPT_nodefaultlibs, options::OPT_nostdlib)) {

if (UseJMC) {
CmdArgs.push_back("--push-state");
CmdArgs.push_back("--whole-archive");
CmdArgs.push_back("-lSceJmc_nosubmission");
CmdArgs.push_back("--pop-state");
}

if (Args.hasArg(options::OPT_pthread))
CmdArgs.push_back("-lpthread");

if (Static) {
if (!Args.hasArg(options::OPT_nostdlibxx))
CmdArgs.push_back("-lstdc++");
if (!Args.hasArg(options::OPT_nolibc)) {
CmdArgs.push_back("-lm");
CmdArgs.push_back("-lc");
}

CmdArgs.push_back("-lcompiler_rt");
CmdArgs.push_back("-lkernel");
} else {
// The C and C++ libraries are combined.
if (!Args.hasArg(options::OPT_nolibc, options::OPT_nostdlibxx))
CmdArgs.push_back("-lc_stub_weak");

CmdArgs.push_back("-lkernel_stub_weak");
}
}
if (AddStartFiles) {
AddCRTObject(Shared ? "crtendS.o" : "crtend.o");
AddCRTObject("crtn.o");
}

if (Args.hasArg(options::OPT_fuse_ld_EQ)) {
Expand Down
3 changes: 0 additions & 3 deletions clang/lib/Driver/Types.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,9 @@

#include "clang/Driver/Types.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include <cassert>
#include <cstring>

Expand Down
3 changes: 0 additions & 3 deletions clang/lib/Driver/XRayArgs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,10 @@
#include "clang/Driver/XRayArgs.h"
#include "ToolChains/CommonArgs.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/ToolChain.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Support/SpecialCaseList.h"
#include "llvm/Support/VirtualFileSystem.h"

Expand Down
4 changes: 4 additions & 0 deletions clang/lib/Headers/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,11 @@ set(x86_files
adxintrin.h
ammintrin.h
amxavx512intrin.h
amxbf16transposeintrin.h
amxcomplexintrin.h
amxcomplextransposeintrin.h
amxfp16intrin.h
amxfp16transposeintrin.h
amxfp8intrin.h
amxintrin.h
amxmovrsintrin.h
Expand Down Expand Up @@ -230,6 +233,7 @@ set(x86_files
movdirintrin.h
movrs_avx10_2_512intrin.h
movrs_avx10_2intrin.h
movrsintrin.h
mwaitxintrin.h
nmmintrin.h
pconfigintrin.h
Expand Down
18 changes: 9 additions & 9 deletions clang/lib/Headers/amdgpuintrin.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ _Pragma("omp begin declare target device_type(nohost)");
_Pragma("omp begin declare variant match(device = {arch(amdgcn)})");

// Type aliases to the address spaces used by the AMDGPU backend.
#define __gpu_private __attribute__((opencl_private))
#define __gpu_constant __attribute__((opencl_constant))
#define __gpu_local __attribute__((opencl_local))
#define __gpu_global __attribute__((opencl_global))
#define __gpu_generic __attribute__((opencl_generic))
#define __gpu_private __attribute__((address_space(5)))
#define __gpu_constant __attribute__((address_space(4)))
#define __gpu_local __attribute__((address_space(3)))
#define __gpu_global __attribute__((address_space(1)))
#define __gpu_generic __attribute__((address_space(0)))

// Attribute to declare a function as a kernel.
#define __gpu_kernel __attribute__((amdgpu_kernel, visibility("protected")))
Expand Down Expand Up @@ -160,14 +160,14 @@ __gpu_shuffle_idx_u64(uint64_t __lane_mask, uint32_t __idx, uint64_t __x) {

// Returns true if the flat pointer points to CUDA 'shared' memory.
_DEFAULT_FN_ATTRS static __inline__ bool __gpu_is_ptr_local(void *ptr) {
return __builtin_amdgcn_is_shared(
(void __attribute__((address_space(0))) *)((void __gpu_generic *)ptr));
return __builtin_amdgcn_is_shared((void __attribute__((address_space(0))) *)((
void [[clang::opencl_generic]] *)ptr));
}

// Returns true if the flat pointer points to CUDA 'local' memory.
_DEFAULT_FN_ATTRS static __inline__ bool __gpu_is_ptr_private(void *ptr) {
return __builtin_amdgcn_is_private(
(void __attribute__((address_space(0))) *)((void __gpu_generic *)ptr));
return __builtin_amdgcn_is_private((void __attribute__((
address_space(0))) *)((void [[clang::opencl_generic]] *)ptr));
}

// Terminates execution of the associated wavefront.
Expand Down
Loading