504 Commits

Author SHA1 Message Date
Momchil Velikov
6303563b40
Simplify MS mangling of bultin types (NFC) (#125051)
Saves including 4 files, reduces the number of switch cases, less error
prone when adding new types,
at the "cost" of adding a` default:`.
2025-02-03 09:38:33 +00:00
Momchil Velikov
7939ce6295
[AArch64] Add MSVC mangling for the __mfp8 type (#124968)
Fixes #124907
2025-01-30 10:42:12 +00:00
Kazu Hirata
32b821cab3 [AST] Fix a warning
This patch fixes:

  clang/lib/AST/MicrosoftMangle.cpp:1006:11: error: enumeration value
  'S_PPCDoubleDoubleLegacy' not handled in switch [-Werror,-Wswitch]
2024-12-04 16:03:14 -08:00
Max Winkler
95566af789
[Clang][AST] Fix MS Mangle concept uneval context template instantiation crash (#117845)
Fixes https://github.com/llvm/llvm-project/issues/115990.

MSVC mangling got inadvertently broken here,
https://github.com/llvm/llvm-project/pull/83997, when it was fixed what
decl context a lambda is apart of for uneval contexts.

https://godbolt.org/z/K6jb5v145 for reference.

Given the following code snippet
```
template <typename T>
concept C = requires(const T& t)
{
    { T::test([](){}) };
};

template<typename T, typename = void>
struct Widget;

template <C T>
struct Widget<T> {};

struct Baz
{
    template<typename F>
    static constexpr decltype(auto) test(F&& f) {}
};

void test()
{
    Widget<Baz> w;
}
```
`Baz::test` has a deduced return type which means we must instantiate
that template even in an unevaluated context.
The lambda inside the concept is within the decl context of `struct
Widget<T> {};`. So we end up needing to mangle a name of
`Baz::test<Widget<template-type-0-0>::lambda()>>()` since the lambda
isn't apart of an instantiated substituted class `Widget` yet at the
point the lambda is instantiated.

Upon template instantation of `test` we end up asking for the mangled
name so we can add this instantiation to `CodeGenModule::DefferredDecls`
since `test` is now referenced but not yet used.

I think the longer term more correct solution is to key `DefferedDecls`
off of something else than the mangled name to avoid having to mangle
names for instantations that are referenced but will never be used since
they are only instantiated from an unevaluated context.

As a fix for the regression I just created a custom mangling scheme for
this case since MSVC has no comparable naming scheme as such a template
will never be emitted into the resulting obj as it will never be used.
2024-12-03 20:18:16 -08:00
Kazu Hirata
dec6324cb0
[AST] Remove unused includes (NFC) (#116549)
Identified with misc-include-cleaner.
2024-11-17 09:36:48 -08:00
Jay Foad
4dd55c567a
[clang] Use {} instead of std::nullopt to initialize empty ArrayRef (#109399)
Follow up to #109133.
2024-10-24 10:23:40 +01:00
Helena Kotas
3b4512074e
[HLSL] Make HLSLAttributedResourceType canonical and add code paths to convert HLSL types to DirectX target types (#110327)
Translates `RWBuffer` and `StructuredBuffer` resources buffer types to
DirectX target types `dx.TypedBuffer` and `dx.RawBuffer`.

Includes a change of `HLSLAttributesResourceType` from 'sugar' type to
full canonical type. This is required for codegen and other clang
infrastructure to work property on HLSL resource types.

Fixes #95952 (part 2/2)
2024-10-15 13:38:15 -07:00
Kazu Hirata
87a2413614 [AST] Fix a warning
This patch fixes:

  clang/lib/AST/MicrosoftMangle.cpp:1008:11: error: enumeration value
  'S_Float8E8M0FNU' not handled in switch [-Werror,-Wswitch]
2024-10-02 12:21:23 -07:00
Jay Foad
fe61dbf1d3
[AMDGPU] Specify width and align for all AMDGPU builtin types. NFC. (#109656)
This will be used in ASTContext::getTypeInfo which needs this
information for all builtin types, not just pointers.
2024-10-01 14:12:34 +01:00
JOE1994
223e2efa5e [clang] Nits on uses of raw_string_ostream (NFC)
* Don't call raw_string_ostream::flush(), which is essentially a no-op.
* Strip unneeded calls to raw_string_ostream::str(), to avoid extra indirection.
2024-09-14 05:29:40 -04:00
Max Winkler
2579b411a1
[clang-cl] [AST] Fix MS 1920+ placeholder return type mangling for lambdas (#105999)
Fixes https://github.com/llvm/llvm-project/pull/104722.

Missed handling `decltype(auto)` trailing return types for lambdas.
This was a mistake and regression on my part with my PR,
https://github.com/llvm/llvm-project/pull/104722.

Added some missing unit tests to test for the various placeholder
trailing return types in lambdas.
2024-08-25 20:48:07 -07:00
Max Winkler
43b88851ce
[clang-cl] [AST] Reapply #102848 Fix placeholder return type name mangling for MSVC 1920+ / VS2019+ (#104722)
Reapply https://github.com/llvm/llvm-project/pull/102848.

The description in this PR will detail the changes from the reverted
original PR above.

For `auto&&` return types that can partake in reference collapsing we
weren't properly handling that mangling that can arise.
When collapsing occurs an inner reference is created with the collapsed
reference type. If we return `int&` from such a function then an inner
reference of `int&` is created within the `auto&&` return type.
`getPointeeType` on a reference type goes through all inner references
before returning the pointee type which ends up being a builtin type,
`int`, which is unexpected.

We can use `getPointeeTypeAsWritten` to get the `AutoType` as expected
however for the instantiated template declaration reference collapsing
already occurred on the return type. This means `auto&&` is turned into
`auto&` in our example above.
We end up mangling an lvalue reference type.
This is unintended as MSVC mangles on the declaration of the return
type, `auto&&` in this case, which is treated as an rvalue reference.
```
template<class T>
auto&& AutoReferenceCollapseT(int& x) { return static_cast<int&>(x); }

void test() 
{
    int x = 1;
    auto&& rref = AutoReferenceCollapseT<void>(x); // "??$AutoReferenceCollapseT@X@@YA$$QEA_PAEAH@Z"
    // Mangled as an rvalue reference to auto
}
```

If we are mangling a template with a placeholder return type we want to
get the first template declaration and use its return type to do the
mangling of any instantiations.

This fixes the bug reported in the original PR that caused the revert
with libcxx `std::variant`.
I also tested locally with libcxx and the following test code which
fails in the original PR but now works in this PR.
```
#include <variant>

void test()
{
    std::variant<int> v{ 1 };
    int& r = std::get<0>(v);
    (void)r;
}
```
2024-08-24 12:25:46 -07:00
Hans Wennborg
05f6630815 Revert "[Clang] [AST] Fix placeholder return type name mangling for MSVC 1920+ / VS2019+ (#102848)"
It cause builds to start failing with

  Invalid type expected
  UNREACHABLE executed at clang/lib/AST/MicrosoftMangle.cpp:2551!

see comments on the PR.

> Partial fix for https://github.com/llvm/llvm-project/issues/92204.
> This PR just fixes VS2019+ since that is the suite of compilers that I
> require link compatibility with at the moment.
> I still intend to fix VS2017 and to update llvm-undname in future PRs.
> Once those are also finished and merged I'll close out
> https://github.com/llvm/llvm-project/issues/92204.
> I am hoping to get the llvm-undname PR up in a couple of weeks to be
> able to demangle the VS2019+ name mangling.
>
> MSVC 1920+ mangles placeholder return types for non-templated functions
> with "@".
> For example `auto foo() { return 0; }` is mangled as `?foo@@YA@XZ`.
>
> MSVC 1920+ mangles placeholder return types for templated functions as
> the qualifiers of the AutoType followed by "_P" for `auto` and "_T" for
> `decltype(auto)`.
> For example `template<class T> auto foo() { return 0; }` is mangled as
> `??$foo@H@@YA?A_PXZ` when `foo` is instantiated as follows `foo<int>()`.
>
> Lambdas with placeholder return types are still mangled with clang's
> custom mangling since MSVC lambda mangling hasn't been deciphered yet.
> Similarly any pointers in the return type with an address space are
> mangled with clang's custom mangling since that is a clang extension.
>
> We cannot augment `mangleType` to support this mangling scheme as the
> mangling schemes for variables and functions differ.
> auto variables are encoded with the fully deduced type where auto return
> types are not.
> The following two functions with a static variable are mangled the same
> ```
> template<class T>
> int test()
> {
>     static int i = 0; // "?i@?1???$test@H@@YAHXZ@4HA"
>     return i;
> }
>
> template<class T>
> int test()
> {
>     static auto i = 0; // "?i@?1???$test@H@@YAHXZ@4HA"
>     return i;
> }
> ```
> Inside `mangleType` once we get to mangling the `AutoType` we have no
> context if we are from a variable encoding or some other encoding.
> Therefore it was easier to handle any special casing for `AutoType`
> return types with a separate function instead of using the `mangleType`
> infrastructure.

This reverts commit e0d173d44161bf9b68243845666d58999e74f759
and the wollow-up fa343be414f9364911b947f109f3df5539e23068.
2024-08-15 11:48:28 +02:00
NAKAMURA Takumi
fa343be414 Fix warnings in #102848 [-Wunused-but-set-variable] 2024-08-15 16:12:05 +09:00
Max Winkler
e0d173d441
[Clang] [AST] Fix placeholder return type name mangling for MSVC 1920+ / VS2019+ (#102848)
Partial fix for https://github.com/llvm/llvm-project/issues/92204.
This PR just fixes VS2019+ since that is the suite of compilers that I
require link compatibility with at the moment.
I still intend to fix VS2017 and to update llvm-undname in future PRs.
Once those are also finished and merged I'll close out
https://github.com/llvm/llvm-project/issues/92204.
I am hoping to get the llvm-undname PR up in a couple of weeks to be
able to demangle the VS2019+ name mangling.

MSVC 1920+ mangles placeholder return types for non-templated functions
with "@".
For example `auto foo() { return 0; }` is mangled as `?foo@@YA@XZ`.

MSVC 1920+ mangles placeholder return types for templated functions as
the qualifiers of the AutoType followed by "_P" for `auto` and "_T" for
`decltype(auto)`.
For example `template<class T> auto foo() { return 0; }` is mangled as
`??$foo@H@@YA?A_PXZ` when `foo` is instantiated as follows `foo<int>()`.

Lambdas with placeholder return types are still mangled with clang's
custom mangling since MSVC lambda mangling hasn't been deciphered yet.
Similarly any pointers in the return type with an address space are
mangled with clang's custom mangling since that is a clang extension.

We cannot augment `mangleType` to support this mangling scheme as the
mangling schemes for variables and functions differ.
auto variables are encoded with the fully deduced type where auto return
types are not.
The following two functions with a static variable are mangled the same
```
template<class T>
int test()
{
    static int i = 0; // "?i@?1???$test@H@@YAHXZ@4HA"
    return i;
}

template<class T>
int test()
{
    static auto i = 0; // "?i@?1???$test@H@@YAHXZ@4HA"
    return i;
}
```
Inside `mangleType` once we get to mangling the `AutoType` we have no
context if we are from a variable encoding or some other encoding.
Therefore it was easier to handle any special casing for `AutoType`
return types with a separate function instead of using the `mangleType`
infrastructure.
2024-08-14 21:51:57 -07:00
Helena Kotas
52956b0f70
[HLSL] Implement intangible AST type (#97362)
HLSL has a set of intangible types which are described in in the
[draft HLSL Specification
(**[Basic.types]**)](https://microsoft.github.io/hlsl-specs/specs/hlsl.pdf):
  There are special implementation-defined types such as handle types,
  which fall into a category of standard intangible types. Intangible
  types are types that have no defined object representation or value
  representation, as such the size is unknown at compile time.
    
  A class type T is an intangible class type if it contains an base
  classes or members of intangible class type, standard intangible type,
  or arrays of such types. Standard intangible types and intangible class
  types are collectively called intangible
  types([9](https://microsoft.github.io/hlsl-specs/specs/hlsl.html#Intangible)).

This PR implements one standard intangible type `__hlsl_resource_t`
and sets up the infrastructure that will make it easier to add more
in the future, such as samplers or raytracing payload handles. The
HLSL intangible types are declared in
`clang/include/clang/Basic/HLSLIntangibleTypes.def` and this file is
included with related macro definition in most places that require edits
when a new type is added.

The new types are added as keywords and not typedefs to make sure they
cannot be redeclared, and they can only be declared in builtin implicit
headers. The `__hlsl_resource_t` type represents a handle to a memory
resource and it is going to be used in builtin HLSL buffer types like this:

        template <typename T>
        class RWBuffer {
          [[hlsl::contained_type(T)]]
          [[hlsl::is_rov(false)]]
          [[hlsl::resource_class(uav)]]  
          __hlsl_resource_t Handle;
        };

Part 1/3 of llvm/llvm-project#90631.

---------

Co-authored-by: Justin Bogner <mail@justinbogner.com>
2024-08-05 10:50:34 -07:00
Alexander Pivovarov
abc2fe31fc
[APFloat] Add support for f8E3M4 IEEE 754 type (#99698)
This PR adds `f8E4M3` type to APFloat.

`f8E3M4` type  follows IEEE 754 convention

```c
f8E3M4 (IEEE 754)
- Exponent bias: 3
- Maximum stored exponent value: 6 (binary 110)
- Maximum unbiased exponent value: 6 - 3 = 3
- Minimum stored exponent value: 1 (binary 001)
- Minimum unbiased exponent value: 1 − 3 = −2
- Precision specifies the total number of bits used for the significand (mantissa), 
    including implicit leading integer bit = 4 + 1 = 5
- Follows IEEE 754 conventions for representation of special values
- Has Positive and Negative zero
- Has Positive and Negative infinity
- Has NaNs

Additional details:
- Max exp (unbiased): 3
- Min exp (unbiased): -2
- Infinities (+/-): S.111.0000
- Zeros (+/-): S.000.0000
- NaNs: S.111.{0,1}⁴ except S.111.0000
- Max normal number: S.110.1111 = +/-2^(6-3) x (1 + 15/16) = +/-2^3 x 31 x 2^(-4) = +/-15.5
- Min normal number: S.001.0000 = +/-2^(1-3) x (1 + 0) = +/-2^(-2)
- Max subnormal number: S.000.1111 = +/-2^(-2) x 15/16 = +/-2^(-2) x 15 x 2^(-4) = +/-15 x 2^(-6)
- Min subnormal number: S.000.0001 = +/-2^(-2) x 1/16 =  +/-2^(-2) x 2^(-4) = +/-2^(-6)
```

Related PRs:
- [PR-97179](https://github.com/llvm/llvm-project/pull/97179) [APFloat]
Add support for f8E4M3 IEEE 754 type
2024-07-30 00:11:10 -07:00
memory-thrasher
83fb0643f7
Adds a pseudonym to clang's windows mangler... (#97792)
…to handle template argument values that are pointers one-past-the-end
of a non-array symbol. Also improves error messages in other template
argument scenarios where clang bails.

https://github.com/llvm/llvm-project/issues/97756

I don't think I hooked up the unit test right. I'm not sure one is
really needed for what boils down to a tweaked if statement. Please
advise.
2024-07-24 09:38:47 -07:00
Alexander Pivovarov
f363317702
[APFloat] Add support for f8E4M3 IEEE 754 type (#97179)
This PR adds `f8E4M3` type to APFloat.

`f8E4M3` type  follows IEEE 754 convention

```c
f8E4M3 (IEEE 754)
- Exponent bias: 7
- Maximum stored exponent value: 14 (binary 1110)
- Maximum unbiased exponent value: 14 - 7 = 7
- Minimum stored exponent value: 1 (binary 0001)
- Minimum unbiased exponent value: 1 − 7 = −6
- Precision specifies the total number of bits used for the significand (mantisa), 
    including implicit leading integer bit = 3 + 1 = 4
- Follows IEEE 754 conventions for representation of special values
- Has Positive and Negative zero
- Has Positive and Negative infinity
- Has NaNs

Additional details:
- Max exp (unbiased): 7
- Min exp (unbiased): -6
- Infinities (+/-): S.1111.000
- Zeros (+/-): S.0000.000
- NaNs: S.1111.{001, 010, 011, 100, 101, 110, 111}
- Max normal number: S.1110.111 = +/-2^(7) x (1 + 0.875) = +/-240
- Min normal number: S.0001.000 = +/-2^(-6)
- Max subnormal number: S.0000.111 = +/-2^(-6) x 0.875 = +/-2^(-9) x 7
- Min subnormal number: S.0000.001 = +/-2^(-6) x 0.125 = +/-2^(-9)
```

Related PRs:
- [PR-97118](https://github.com/llvm/llvm-project/pull/97118) Add f8E4M3
IEEE 754 type to mlir
2024-07-17 23:33:52 -07:00
Max Winkler
d1dc416983
Fix MSVC 1920+ auto NTTP mangling for pointers to members (#97007)
Fixes https://github.com/llvm/llvm-project/issues/70899.

This is a continuation of
https://github.com/llvm/llvm-project/pull/92477 for pointers to member
data and pointers to member functions.

The mangled name must be prefixed with `$M <mangled-type>` for the
deduced type of the nttp parameter.
2024-07-04 10:17:32 -07:00
Oliver Hunt
1b8ab2f089
[clang] Implement pointer authentication for C++ virtual functions, v-tables, and VTTs (#94056)
Virtual function pointer entries in v-tables are signed with address
discrimination in addition to declaration-based discrimination, where an
integer discriminator the string hash (see
`ptrauth_string_discriminator`) of the mangled name of the overridden
method. This notably provides diversity based on the full signature of
the overridden method, including the method name and parameter types.
This patch introduces ItaniumVTableContext logic to find the original
declaration of the overridden method.
On AArch64, these pointers are signed using the `IA` key (the
process-independent code key.)

V-table pointers can be signed with either no discrimination, or a
similar scheme using address and decl-based discrimination. In this
case, the integer discriminator is the string hash of the mangled
v-table identifier of the class that originally introduced the vtable
pointer.
On AArch64, these pointers are signed using the `DA` key (the
process-independent data key.)

Not using discrimination allows attackers to simply copy valid v-table
pointers from one object to another. However, using a uniform
discriminator of 0 does have positive performance and code-size
implications on AArch64, and diversity for the most important v-table
access pattern (virtual dispatch) is already better assured by the
signing schemas used on the virtual functions. It is also known that
some code in practice copies objects containing v-tables with `memcpy`,
and while this is not permitted formally, it is something that may be
invasive to eliminate.

This is controlled by:
```
  -fptrauth-vtable-pointer-type-discrimination
  -fptrauth-vtable-pointer-address-discrimination
```

In addition, this provides fine-grained controls in the
ptrauth_vtable_pointer attribute, which allows overriding the default
ptrauth schema for vtable pointers on a given class hierarchy, e.g.:
```
  [[clang::ptrauth_vtable_pointer(no_authentication, no_address_discrimination, 
                                  no_extra_discrimination)]]
  [[clang::ptrauth_vtable_pointer(default_key, default_address_discrimination,
                                  custom_discrimination, 0xf00d)]]
```

The override is then mangled as a parametrized vendor extension:
```
"__vtptrauth" I
 <key>
 <addressDiscriminated>
 <extraDiscriminator>
E
```

To support this attribute, this patch adds a small extension to the
attribute-emitter tablegen backend.

Note that there are known areas where signing is either missing
altogether or can be strengthened. Some will be addressed in later
changes (e.g., member function pointers, some RTTI).
`dynamic_cast` in particular is handled by emitting an artificial
v-table pointer load (in a way that always authenticates it) before the
runtime call itself, as the runtime doesn't have enough information
today to properly authenticate it. Instead, the runtime is currently
expected to strip the v-table pointer.

---------

Co-authored-by: John McCall <rjmccall@apple.com>
Co-authored-by: Ahmed Bougacha <ahmed@bougacha.org>
2024-06-26 18:35:10 -07:00
antangelo
5dcf3d5335
[MS ABI]: Support preserve_none in MS ABI (#96487)
Fixes ICE when compiling preserve_nonecc functions on Windows and adds
support for the calling convention on AArch64 for Windows targets.
2024-06-26 18:54:41 -04:00
Max Winkler
7b906d46f6
[clang-cl][AST] Fix auto NTTP MSVC 1920+ mangling for pointer types (#92477)
https://godbolt.org/z/G1K8Wszn9 for reference.

Starting with MSVC 1920+, VS2019, C++17 auto NTTP now adds `M <type>` to
the mangled name to avoid name collisions with different deduced types.
This PR fixes pointers. Pointers to members will be fixed in an upcoming
PR.

Here is a small example. The godbolt has more thorough examples.
```
template<auto>
struct AutoParmTemplate
{
    AutoParmTemplate() {}
};

int i;

int main()
{
    // MSVC 1916: ??0?$AutoParmTemplate@$1?i@@3HA@@QEAA@XZ
    // MSVC 1929: ??0?$AutoParmTemplate@$MPEAH1?i@@3HA@@QEAA@XZ
    // Clang: ??0?$AutoParmTemplate@$1?i@@3HA@@QEAA@XZ
    AutoParmTemplate<&i> x;
}
```
2024-06-20 19:49:17 -07:00
Shilei Tian
ad599211a7
[Clang][AMDGPU] Add a new builtin type for buffer rsrc (#94830)
This patch adds a new builtin type for AMDGPU's buffer rsrc data type,
which is effectively an AS 8 pointer. This is needed because we'd like
to expose certain intrinsics to users via builtins which take buffer
rsrc as argument.
2024-06-18 20:46:53 -04:00
Durgadoss R
880d37038c
[APFloat] Add APFloat support for FP4 data type (#95392)
This patch adds APFloat type support for the E2M1
FP4 datatype. The definitions for this format are
detailed in section 5.3.3 of the OCP specification,
which can be accessed here:

https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf

Signed-off-by: Durgadoss R <durgadossr@nvidia.com>
2024-06-14 14:17:37 +05:30
Durgadoss R
b1fe03f084
[APFloat] Add APFloat support for FP6 data types (#94735)
This patch adds APFloat type support for two FP6 data types,
E2M3 and E3M2. The definitions for the two formats are detailed
in section 5.3.2 of the OCP specification, which can be accessed here:

https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf

Signed-off-by: Durgadoss R <durgadossr@nvidia.com>
2024-06-11 13:16:51 +05:30
Pavel Samolysov
69e9e779b7
[clang] Replace X && isa<Y>(X) with isa_and_nonnull<Y>(X). NFC (#94987)
This addresses a clang-tidy suggestion.
2024-06-11 05:30:50 +03:00
Timm Baeder
3d56ea05b6
[clang][NFC] Fix FieldDecl::isUnnamedBitfield() capitalization (#89048)
We always capitalize bitfield as "BitField".
2024-04-18 07:39:29 +02:00
Chris B
9434c08347
[HLSL] Implement array temporary support (#79382)
HLSL constant sized array function parameters do not decay to pointers.
Instead constant sized array types are preserved as unique types for
overload resolution, template instantiation and name mangling.

This implements the change by adding a new `ArrayParameterType` which
represents a non-decaying `ConstantArrayType`. The new type behaves the
same as `ConstantArrayType` except that it does not decay to a pointer.

Values of `ConstantArrayType` in HLSL decay during overload resolution
via a new `HLSLArrayRValue` cast to `ArrayParameterType`.

`ArrayParamterType` values are passed indirectly by-value to functions
in IR generation resulting in callee generated memcpy instructions.

The behavior of HLSL function calls is documented in the [draft language
specification](https://microsoft.github.io/hlsl-specs/specs/hlsl.pdf)
under the Expr.Post.Call heading.

Additionally the design of this implementation approach is documented in
[Clang's
documentation](https://clang.llvm.org/docs/HLSL/FunctionCalls.html)

Resolves #70123
2024-04-01 12:10:10 -05:00
Chris B
28ddbd4a86
[NFC] Refactor ConstantArrayType size storage (#85716)
In PR #79382, I need to add a new type that derives from
ConstantArrayType. This means that ConstantArrayType can no longer use
`llvm::TrailingObjects` to store the trailing optional Expr*.

This change refactors ConstantArrayType to store a 60-bit integer and
4-bits for the integer size in bytes. This replaces the APInt field
previously in the type but preserves enough information to recreate it
where needed.

To reduce the number of places where the APInt is re-constructed I've
also added some helper methods to the ConstantArrayType to allow some
common use cases that operate on either the stored small integer or the
APInt as appropriate.

Resolves #85124.
2024-03-26 14:15:56 -05:00
Tom Honermann
bea17ff652
[clang] Correct Microsoft mangling of lifetime extended temporary objects. (#85529)
Lifetime extended temporary objects that are bound to references with
static storage duration may have external linkage and therefore require
mangled symbol names. Clang uses an extension of the Microsoft ABI to
give these symbols an implicit name of '$RT' followed by a discriminator
and then mangles them similarly to the variable they are bound to.
Clang's mangling scheme differs from the one used by MSVC.

Previously, the `$RT<discriminator>` portion of the name was not
registered as a back reference candidate and this resulted in incorrect
back references for enclosing class and/or namespace scopes that might
be referenced in the type of the object.

This is an ABI change and has the potential to cause backward
compatibility issues with previous Clang releases. Since MSVC uses a
different mangling scheme, this change does not affect compatibility
with MSVC.

This fixes one of the name mangling concerns reported in #85423.
2024-03-25 10:39:05 -04:00
Tom Honermann
f128607b89
[clang][MSVC] Correct mangling of thread-safe static initialization variables. (#85300)
Static local variables with dynamic initializers depend on implicitly defined
guard variables to synchronize thread-safe initialization.  These guard
variables may have external linkage and therefore require a stable name for
linkage purposes.  The Microsoft ABI assigns these variables a local name of
'$TSS' followed by a discriminator and mangles them as a static local variable
of type 'int'.  Previously, the '$TSS<discriminator>' portion of the name was
not registered as a back reference candidate and this resulted in incorrect
back references for enclosing class and/or namespace scopes that might be
referenced in the signature of the enclosing function.  This change adds the
previously missing back reference registration.  This matches the mangling
performed by MSVC and resolves incompatibilities when inline functions with
static local variables are inlined across DLL boundaries.

This is an ABI change and has the potential to cause backward compatibility
issues with previous Clang releases.

Fixes #83616
2024-03-15 19:12:19 -04:00
cor3ntin
ad1a65fcac
[Clang][C++26] Implement Pack Indexing (P2662R3). (#72644)
Implements https://isocpp.org/files/papers/P2662R3.pdf

The feature is exposed as an extension in older language modes.
Mangling is not yet supported and that is something we will have to do before release.
2024-01-27 10:23:38 +01:00
Andrey Ali Khan Bolshakov
5518a9d767
[c++20] P1907R1: Support for generalized non-type template arguments of scalar type. (#78041)
Previously committed as 9e08e51a20d0d2b1c5724bb17e969d036fced4cd, and
reverted because a dependency commit was reverted, then committed again
as 4b574008aef5a7235c1f894ab065fe300d26e786 and reverted again because
"dependency commit" 5a391d38ac6c561ba908334d427f26124ed9132e was
reverted. But it doesn't seem that 5a391d38ac6c was a real dependency
for this.

This commit incorporates 4b574008aef5a7235c1f894ab065fe300d26e786 and
18e093faf726d15f210ab4917142beec51848258 by Richard Smith (@zygoloid),
with some minor fixes, most notably:

- `UncommonValue` renamed to `StructuralValue`

- `VK_PRValue` instead of `VK_RValue` as default kind in lvalue and
member pointer handling branch in
`BuildExpressionFromNonTypeTemplateArgumentValue`;

- handling of `StructuralValue` in `IsTypeDeclaredInsideVisitor`;

- filling in `SugaredConverted` along with `CanonicalConverted`
parameter in `Sema::CheckTemplateArgument`;

- minor cleanup in
`TemplateInstantiator::transformNonTypeTemplateParmRef`;

- `TemplateArgument` constructors refactored;

- `ODRHash` calculation for `UncommonValue`;

- USR generation for `UncommonValue`;

- more correct MS compatibility mangling algorithm (tested on MSVC ver.
19.35; toolset ver. 143);

- IR emitting fixed on using a subobject as a template argument when the
corresponding template parameter is used in an lvalue context;

- `noundef` attribute and opaque pointers in `template-arguments` test;

- analysis for C++17 mode is turned off for templates in
`warn-bool-conversion` test; in C++17 and C++20 mode, array reference
used as a template argument of pointer type produces template argument
of UncommonValue type, and
`BuildExpressionFromNonTypeTemplateArgumentValue` makes
`OpaqueValueExpr` for it, and `DiagnoseAlwaysNonNullPointer` cannot see
through it; despite of "These cases should not warn" comment, I'm not
sure about correct behavior; I'd expect a suggestion to replace `if` by
`if constexpr`;

- `temp.arg.nontype/p1.cpp` and `dr18xx.cpp` tests fixed.
2024-01-21 21:28:57 +01:00
Kazu Hirata
f3dcc2351c
[clang] Use StringRef::{starts,ends}_with (NFC) (#75149)
This patch replaces uses of StringRef::{starts,ends}with with
StringRef::{starts,ends}_with for consistency with
std::{string,string_view}::{starts,ends}_with in C++20.

I'm planning to deprecate and eventually remove
StringRef::{starts,ends}with.
2023-12-13 08:54:13 -08:00
Kazu Hirata
cc4ecfd68b
[ADT] Rename SmallString::{starts,ends}with to {starts,ends}_with (#74916)
This patch renames {starts,ends}with to {starts,ends}_with for
consistency with std::{string,string_view}::{starts,ends}_with in
C++20.  Since there are only a handful of occurrences, this patch
skips the deprecation phase and simply renames them.
2023-12-09 14:28:45 -08:00
Vlad Serebrennikov
edd690b02e
[clang][NFC] Refactor TagTypeKind (#71160)
This patch converts TagTypeKind into scoped enum. Among other benefits,
this allows us to forward-declare it where necessary.
2023-11-03 21:45:39 +04:00
Vlad Serebrennikov
8775947633
[clang][NFC] Refactor clang::Linkage (#71049)
This patch introduces a new enumerator `Invalid = 0`, shifting other enumerators by +1. Contrary to how it might sound, this actually affirms status quo of how this enum is stored in `clang::Decl`:
```
  /// If 0, we have not computed the linkage of this declaration.
  /// Otherwise, it is the linkage + 1.
  mutable unsigned CacheValidAndLinkage : 3;
```
This patch makes debuggers to not be mistaken about enumerator stored in this bit-field. It also converts `clang::Linkage` to a scoped enum.
2023-11-02 20:57:29 +04:00
Matheus Izvekov
9c89b29555
-fsanitize=function: fix MSVC hashing to sugared type (#66816)
Hashing the sugared type instead of the canonical type meant that
a simple example like this would always fail under MSVC:

```
static auto l() {}
int main() {
  auto a = l;
  a();
}
```
`clang --target=x86_64-pc-windows-msvc -fno-exceptions
-fsanitize=function -g -O0 -fuse-ld=lld -o test.exe test.cc`

produces:
```
test.cc:4:3: runtime error: call to function l through pointer to incorrect function type 'void (*)()'
```
2023-10-02 19:09:39 +02:00
Corentin Jabot
af4751738d [C++] Implement "Deducing this" (P0847R7)
This patch implements P0847R7 (partially),
CWG2561 and CWG2653.

Reviewed By: aaron.ballman, #clang-language-wg

Differential Revision: https://reviews.llvm.org/D140828
2023-10-02 14:33:02 +02:00
Jan Svoboda
523c471250 Reapply "[clang] NFCI: Adopt SourceManager::getFileEntryRefForID()"
This reapplies ddbcc10b9e26b18f6a70e23d0611b9da75ffa52f, except for a tiny part that was reverted separately: 65331da0032ab4253a4bc0ddcb2da67664bd86a9. That will be reapplied later on, since it turned out to be more involved.

This commit is enabled by 5523fefb01c282c4cbcaf6314a9aaf658c6c145f and f0f548a65a215c450d956dbcedb03656449705b9, specifically the part that makes 'clang-tidy/checkers/misc/header-include-cycle.cpp' separator agnostic.
2023-09-08 19:04:01 -07:00
Jan Svoboda
0a9611fd8d Revert "[clang] NFCI: Adopt SourceManager::getFileEntryRefForID()"
This reverts commit ddbcc10b9e26b18f6a70e23d0611b9da75ffa52f.

The 'clang-tidy/checkers/misc/header-include-cycle.cpp' test started failing on Windows: https://lab.llvm.org/buildbot/#/builders/216/builds/26855.
2023-09-06 13:23:23 -07:00
Jan Svoboda
ddbcc10b9e [clang] NFCI: Adopt SourceManager::getFileEntryRefForID()
This commit replaces some calls to the deprecated `FileEntry::getName()` with `FileEntryRef::getName()` by swapping current usages of `SourceManager::getFileEntryForID()` with `SourceManager::getFileEntryRefForID()`. This lowers the number of usages of the deprecated `FileEntry::getName()` from 95 to 50.
2023-09-06 10:49:48 -07:00
Bing1 Yu
6ee497aa0b [X86][Regcall] Add an option to respect regcall ABI v.4 in win64&win32
Reviewed By: pengfei

Differential Revision: https://reviews.llvm.org/D155863
2023-08-03 13:58:33 +08:00
Fangrui Song
aa972f607c -fsanitize=function,MicrosoftMangle: Switch to xxh3_64bits
Following recent changes switching from xxh64 to xxh32 for better
hashing performance (e.g., D154813). These particular instances likely
have negligible time, but this change moves us toward removing xxHash64.

The type hash for -fsanitize=function will change, following a recent
change D148785 (not in any release yet) to the type hash scheme, though
sanitizers don't sign up for cross-version compatibility anyway.

The MicrosoftMangle instance is for internal symbols that need no
compatibility guarantee, as emphasized by the comment.
2023-07-19 15:20:50 -07:00
Jeremy Furtek
55c2211a23 [APFloat] Add APFloat semantic support for TF32
This diff adds APFloat support for a semantic that matches the TF32 data type
used by some accelerators (most notably GPUs from both NVIDIA and AMD).

For more information on the TF32 data type, see https://blogs.nvidia.com/blog/2020/05/14/tensorfloat-32-precision-format/.
Some intrinsics that support the TF32 data type were added in https://reviews.llvm.org/D122044.

For some discussion on supporting common semantics in `APFloat`, see similar
efforts for 8-bit formats at https://reviews.llvm.org/D146441, as well as
https://discourse.llvm.org/t/rfc-adding-the-amd-graphcore-maybe-others-float8-formats-to-apfloat/67969.

A subsequent diff will extend MLIR to use this data type. (Those changes are
not part of this diff to simplify the review process.)

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D151923
2023-06-23 10:54:49 +02:00
Manna, Soumi
982a87ab74 [CLANG] Fix potential null pointer dereference bugs
This patch uses castAs instead of getAs which will assert if the type doesn't match and adds nullptr check if needed.

Also this patch improves the codes and passes I.getData() instead of doing a lookup in dumpVarDefinitionName()
since we're iterating over the same map in LocalVariableMap::dumpContex().

Reviewed By: aaron.ballman, aaronpuchert

Differential Revision: https://reviews.llvm.org/D153033
2023-06-22 12:58:38 -07:00
Kazu Hirata
9932eb083a [AST] Use DenseMapBase::lookup (NFC) 2023-06-18 11:52:59 -07:00
Bolshakov
cd93532dfc [MS ABI] Fix C++ mangling references to declarations.
Several issues have been discovered and (hopefully) fixed here:

- Reference NTTPs should be mangled in the same manner as pointer
ones.

-  Pointer fields of class type NTTPs should be treated in the same
manner as reference ones.

- Pointer-to-member fields of class type NTTPs should be treated
differently compared to pointer-to-member NTTPs. Tests on
pointer-to-member-function NTTP class fields added.

- Correct mangling of pointers to anonymous union members.

- A bug in mangling references to subobjects fixed.

- Mangling array subscripts and base class members in references
to subobjects.

Reference NTTP mangling was done back in 2013
in e8fdc06e0dab2e7b98339425dbe369e27e2092a3, and Microsoft might change
mangling algorithm since then. But class type NTTPs are introduced only
in C++20, and the test was written in
b637148ecb62b900872b34eedd78b923bb43c378.
It is strange if the MS ABI had been realy changed, because Microsoft
claims that they maintain ABI stability since VS 2015. I've tested both
on v142 and v143 MSVC toolsets, and they show the same behavior
on the test cases which are changed in this PR. But
pointer-to-member-function NTTP class field mangling has been actually
changed, because it was erroneous in v142, leading to name collisions.

Moreover, pointer-to-member mangling with conversions across class
hierarchy has been enabled.

Differential Revision: https://reviews.llvm.org/D146386
2023-05-03 18:20:16 -07:00
Michael Liao
3c83480ae9 [clang][AST] Fix -Wuninitialized. NFC
- Adjust the declaration order as non-static member are initialized in
  order of declaration in the class definition.
2023-04-09 15:58:10 -04:00