2118 Commits

Author SHA1 Message Date
Tom Honermann
1a590870b6
[SYCL] The sycl_kernel_entry_point attribute. (#111389)
The `sycl_kernel_entry_point` attribute is used to declare a function that
defines a pattern for an offload kernel to be emitted. The attribute requires
a single type argument that specifies the type used as a SYCL kernel name as
described in section 5.2, "Naming of kernels", of the SYCL 2020 specification.

Properties of the offload kernel are collected when a function declared with
the `sycl_kernel_entry_point` attribute is parsed or instantiated. These
properties, such as the kernel name type, are stored in the AST context where
they are (or will be) used for diagnostic purposes and to facilitate reflection
to a SYCL run-time library. These properties are not serialized with the AST
but are recreated upon deserialization.

The `sycl_kernel_entry_point` attribute is intended to replace the existing
`sycl_kernel` attribute which is intended to be deprecated in a future change
and removed following an appropriate deprecation period. The new attribute
differs in that it is enabled for both SYCL host and device compilation, may
be used with non-template functions, explicitly indicates the type used as
the kernel name type, and will impact AST generation.

This change adds the basic infrastructure for the new attribute. Future
changes will add diagnostics and new AST support that will be used to drive
generation of the corresponding offload kernel.
2024-11-05 11:09:32 -05:00
Justin Stitt
3dd1d888fb
[Clang] Implement labelled type filtering for overflow/truncation sanitizers w/ SSCLs (#107332)
[Related
RFC](https://discourse.llvm.org/t/rfc-support-globpattern-add-operator-to-invert-matches/80683/5?u=justinstitt)

### Summary

Implement type-based filtering via [Sanitizer Special Case
Lists](https://clang.llvm.org/docs/SanitizerSpecialCaseList.html) for
the arithmetic overflow and truncation sanitizers.

Currently, using the `type:` prefix with these sanitizers does nothing.
I've hooked up the SSCL parsing with Clang codegen so that we don't emit
the overflow/truncation checks if the arithmetic contains an ignored
type.

### Usefulness

You can craft ignorelists that ignore specific types that are expected
to overflow or wrap-around. For example, to ignore `my_type` from
`unsigned-integer-overflow` instrumentation:
```bash
$ cat ignorelist.txt
[unsigned-integer-overflow]
type:my_type=no_sanitize

$ cat foo.c
typedef unsigned long my_type;
void foo() {
  my_type a = ULONG_MAX;
  ++a;
}

$ clang foo.c -fsanitize=unsigned-integer-overflow -fsanitize-ignorelist=ignorelist.txt ; ./a.out
// --> no sanitizer error
```

If a type is functionally intended to overflow, like
[refcount_t](https://kernsec.org/wiki/index.php/Kernel_Protections/refcount_t)
and its associated APIs in the Linux kernel, then this type filtering
would prove useful for reducing sanitizer noise. Currently, the Linux
kernel dealt with this by
[littering](https://elixir.bootlin.com/linux/v6.10.8/source/include/linux/refcount.h#L139
) `__attribute__((no_sanitize("signed-integer-overflow")))` annotations
on all the `refcount_t` APIs. I think this serves as an example of how a
codebase could be made cleaner. We could make custom types that are
filtered out in an ignorelist, allowing for types to be more expressive
-- without the need for annotations. This accomplishes a similar goal to
https://github.com/llvm/llvm-project/pull/86618.


Yet another use case for this type filtering is whitelisting. We could
ignore _all_ types, save a few.

```bash
$ cat ignorelist.txt
[implicit-signed-integer-truncation]
type:*=no_sanitize # ignore literally all types
type:short=sanitize # except `short`

$ cat bar.c
// compile with -fsanitize=implicit-signed-integer-truncation
void bar(int toobig) {
  char a = toobig;  // not instrumented
  short b = toobig; // instrumented
}
```

### Other ways to accomplish the goal of sanitizer
allowlisting/whitelisting
* ignore list SSCL type support (this PR that you're reading)
* [my sanitize-allowlist
branch](https://github.com/llvm/llvm-project/compare/main...JustinStitt:llvm-project:sanitize-allowlist)
- this just implements a sibling flag `-fsanitize-allowlist=`, removing
some of the double negative logic present with `skip`/`ignore` when
trying to whitelist something.
* [Glob
Negation](https://discourse.llvm.org/t/rfc-support-globpattern-add-operator-to-invert-matches/80683)
- Implement a negation operator to the GlobPattern class so the
ignorelist query can use them to simulate allowlisting


Please let me know which of the three options we like best. They are not
necessarily mutually exclusive.

Here's [another related
PR](https://github.com/llvm/llvm-project/pull/86618) which implements a
`wraps` attribute. This can accomplish a similar goal to this PR but
requires in-source changes to codebases and also covers a wider variety
of integer definedness problems.

### CCs
@kees @vitalybuka @bwendling

---------

Signed-off-by: Justin Stitt <justinstitt@google.com>
2024-11-03 23:57:47 -08:00
Pavel Yaskevich
d3daa3c443
[clang/AST] Make it possible to use SwiftAttr in type context (#108631)
Swift ClangImporter now supports concurrency annotations on imported
declarations and their parameters/results, to make it possible to use
imported APIs in Swift safely there has to be a way to annotate
individual parameters and result types with relevant attributes that
indicate that e.g. a block is called on a particular actor or it accepts
a `Sendable` parameter.

To faciliate that `SwiftAttr` is switched from `InheritableAttr` which
is a declaration attribute to `DeclOrTypeAttr`. To support this
attribute in type context we need access to its "Attribute" argument
which requires `AttributedType` to be extended to include `Attr *` when
available instead of just `attr::Kind` otherwise it won't be possible to
determine what attribute should be imported.
2024-10-31 11:15:22 +00:00
Krystian Stasiowski
639a7ac648
[Clang][AST] Store injected template arguments in TemplateParameterList (#113579)
Currently, we store injected template arguments in
`RedeclarableTemplateDecl::CommonBase`. This approach has a couple
problems:
1. We can only access the injected template arguments of
`RedeclarableTemplateDecl` derived types, but other `Decl` kinds still
make use of the injected arguments (e.g.
`ClassTemplatePartialSpecializationDecl`,
`VarTemplatePartialSpecializationDecl`, and `TemplateTemplateParmDecl`).
2. Accessing the injected template arguments requires the common data
structure to be allocated. This may occur before we determine whether a
previous declaration exists (e.g. when comparing constraints), so if the
template _is_ a redeclaration, we end up discarding the common data
structure.

This patch moves the storage and access of injected template arguments
from `RedeclarableTemplateDecl` to `TemplateParameterList`.
2024-10-29 13:36:55 -04: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
CarolineConcatto
6dad29aebc
[CLANG][AArch64]Add Neon vectors for mfloat8_t (#99865)
This patch adds these new vector sizes for neon:
   mfloat8x16_t and mfloat8x8_t

    According to the ARM ACLE PR#323[1].

    [1] ARM-software/acle#323
2024-10-23 13:23:18 +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
Piyou Chen
f658c1bf4a
Recommit "[RISCV][FMV] Support target_version" (#111096)" (#111333)
Fix the buildbot failure caused by heap use-after-free error.

Origin message:

    This patch enable `target_version` attribute for RISC-V target.

    The proposal of `target_version` syntax can be found at the
    https://github.com/riscv-non-isa/riscv-c-api-doc/pull/48 (which has
    landed), as modified by the proposed
https://github.com/riscv-non-isa/riscv-c-api-doc/pull/85 (which adds the
    priority syntax).

`target_version` attribute will trigger the function multi-versioning
    feature and act like `target_clones` attribute. See
https://github.com/llvm/llvm-project/pull/85786 for the implementation
    of `target_clones`.
2024-10-08 16:26:55 +08:00
Piyou Chen
1e5e153485
Revert "[RISCV][FMV] Support target_version" (#111096)
Reverts llvm/llvm-project#99040 due to https://lab.llvm.org/buildbot/#/builders/190/builds/7052
2024-10-04 12:02:39 +08:00
Piyou Chen
7ab488e92c
[RISCV][FMV] Support target_version (#99040)
This patch enable `target_version` attribute for RISC-V target.

The proposal of `target_version` syntax can be found at the
https://github.com/riscv-non-isa/riscv-c-api-doc/pull/48 (which has
landed), as modified by the proposed
https://github.com/riscv-non-isa/riscv-c-api-doc/pull/85 (which adds the
priority syntax).

`target_version` attribute will trigger the function multi-versioning
feature and act like `target_clones` attribute. See
https://github.com/llvm/llvm-project/pull/85786 for the implementation
of `target_clones`.
2024-10-04 11:02:45 +08:00
Kazu Hirata
bf3deb17cb
[AST] Avoid repeated hash lookups (NFC) (#110947) 2024-10-03 08:27:54 -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
Helena Kotas
e20bf28987
[HLSL] Replace element_type* handles in HLSLExternalSemaSource with __hlsl_resource_t builtin type (#110079)
Replace `element_type*` handles in HLSLExternalSemaSource with
`__hlsl_resource_t` builtin type.

The handle used to be defined as `element_type*` which was used by the
provisional subscript operator implementation. Now that the handle is
`__hlsl_resource_t` the subscript placeholder implementation was updated
to add `element_type* e;` field to the resource struct. and return a
reference to that. This field is just a temporary workaround until the
indexing is implemented properly in llvm/llvm-project#95956, at which
point the field will be removed. This seemed like a better solution than
disabling many of the existing tests that already use the `[]` operator.
One test has to be disabled nevertheless because an error based on
interactions of const and template instantiation (potential bug that can
be investigated once indexing is implemented the right way).

Fixes #84824
2024-09-29 20:41:54 -07:00
Sirraide
f4fa16f14b
[Clang] Bugfixes and improved support for AttributedTypes in lambdas (#85325)
This fixes a crash when we attempt to instantiate a lambda with an
`AnnotatedType`, refactors the code that handles transforming the
function type of a lambda, and improves source fidelity for lambda
function types.

This fixes #85120 and fixes #85154.

---------

Co-authored-by: Yuxuan Chen <ych@meta.com>
Co-authored-by: Doug Wyatt <dwyatt@apple.com>
2024-09-26 03:24:53 +02:00
Kazu Hirata
d6a6e25c51
[AST] Avoid repeated hash lookups (NFC) (#109603) 2024-09-23 06:45:59 -07:00
Nikolas Klauser
f5be5cdaad
[Clang] Add __builtin_common_type (#99473)
This implements the logic of the `common_type` base template as a
builtin alias. If there should be no `type` member, an empty class is
returned. Otherwise a specialization of a `type_identity`-like class is
returned. The base template (i.e. `std::common_type`) as well as the
empty class and `type_identity`-like struct are given as arguments to
the builtin.
2024-09-22 09:25:52 +02:00
Nathan Ridge
ea578804c8
[AST] Ensure getRawCommentsForAnyRedecl() does not miss any redecl with a comment (#108475)
The previous implementation had a bug where, if it was called on a Decl
later in the redecl chain than `LastCheckedDecl`, it could incorrectly
skip and overlook a Decl with a comment.
    
The patch addresses this by only using `LastCheckedDecl` if the input
Decl `D` is on the path from the first (canonical) Decl to
`LastCheckedDecl`.
    
An alternative that was considered was to start the iteration from the
(canonical) Decl, however this ran into problems with the modelling of
explicit template specializations in the AST where the canonical Decl
can be unusual. With the current solution, if no Decls were checked yet,
we prefer to check the input Decl over the canonical one.

Fixes https://github.com/llvm/llvm-project/issues/108145
2024-09-20 02:23:58 -04:00
Jay Foad
24748339f5
[Clang][AMDGPU] Handle builtin types more generically. NFC. (#109004)
Tweak encodeTypeForFunctionPointerAuth to handle all AMDGPU builtin
types generically instead of just __amdgpu_buffer_rsrc_t which happens
to be the only one defined so far.
2024-09-18 09:32:37 +01:00
Jay Foad
f4172f6659
[Clang][AMDGPU] Simplify builtin type definitions. NFC. (#108968)
Remove the MangledName field since these types just use the normal Name
for mangling purposes.
2024-09-17 15:35:15 +01:00
Piyou Chen
9cd9377409
[RISCV][FMV] Support target_clones (#85786)
This patch enable the function multiversion(FMV) and `target_clones`
attribute for RISC-V target.

The proposal of `target_clones` syntax can be found at the
https://github.com/riscv-non-isa/riscv-c-api-doc/pull/48 (which has
landed), as modified by the proposed
https://github.com/riscv-non-isa/riscv-c-api-doc/pull/85 (which adds the
priority syntax).

It supports the `target_clones` function attribute and function
multiversioning feature for RISC-V target. It will generate the ifunc
resolver function for the function that declared with target_clones
attribute.

The resolver function will check the version support by runtime object
`__riscv_feature_bits`.

For example:

```
__attribute__((target_clones("default", "arch=+ver1", "arch=+ver2"))) int bar() {
    return 1;
}
```

the corresponding resolver will be like:

```
bar.resolver() {
    __init_riscv_feature_bits();
    // Check arch=+ver1
    if ((__riscv_feature_bits.features[0] & BITMASK_OF_VERSION1) == BITMASK_OF_VERSION1) {
        return bar.arch=+ver1;
    } else {
        // Check arch=+ver2
        if ((__riscv_feature_bits.features[0] & BITMASK_OF_VERSION2) == BITMASK_OF_VERSION2) {
            return bar.arch=+ver2;
        } else {
            // Default
            return bar.default;
        }
    }
}
```
2024-09-13 18:04:53 +08:00
Paul Walker
2a130f1a14
[NFC][Clang][SVE] Refactor AArch64SVEACLETypes.def to enabled more uses. (#107599)
Some switch statements require all SVE builtin types to be manually
specified. This patch refactors the SVE_*_TYPE macros so that such code
can be generated during preprocessing.

I've tried to establish a minimal interface that covers all types where
no special information is required and then created a set of macros that
are dedicated to specific datatypes (i.e. int, float).

This patch is groundwork to simplify the changing of SVE tuple types to
become struct based as well as work to support the FP8 ACLE.
2024-09-11 14:03:01 +01:00
Matheus Izvekov
fa65804705
[clang] Implement CWG2398 provisional TTP matching to class templates (#94981)
This extends default argument deduction to cover class templates as
well, applying only to partial ordering, adding to the provisional
wording introduced in https://github.com/llvm/llvm-project/pull/89807.

This solves some ambuguity introduced in P0522 regarding how template
template parameters are partially ordered, and should reduce the
negative impact of enabling `-frelaxed-template-template-args` by
default.

Given the following example:
```C++
template <class T1, class T2 = float> struct A;
template <class T3> struct B;

template <template <class T4> class TT1, class T5> struct B<TT1<T5>>;   // #1
template <class T6, class T7>                      struct B<A<T6, T7>>; // #2

template struct B<A<int>>;
```
Prior to P0522, `#2` was picked. Afterwards, this became ambiguous. This
patch restores the pre-P0522 behavior, `#2` is picked again.
2024-09-07 15:49:07 -03:00
Younan Zhang
aacdc657fc
[Clang] Preserve the ExpandsToEmpty flag in PackIndexingType (#107181)
Similar to PackIndexingExpr, we should avoid another round of
transformation of the pattern if the pattern has already turned out to
be an empty pack. As an outcome, the empty SubstTemplateTypeParmPackType
won't occur, and we don't need to collect any unexpanded packs.

Fixes https://github.com/llvm/llvm-project/issues/105903
2024-09-04 16:34:27 +08:00
Timm Baeder
38ae53da15
[clang][AST][NFC] Make ASTContext::UnwrapSimilar{Array,}Types const (#106992)
They don't mutate the context at all, so mark them const.
2024-09-02 19:03:52 +02:00
Chris B
89fb8490a9
[HLSL] Implement output parameter (#101083)
HLSL output parameters are denoted with the `inout` and `out` keywords
in the function declaration. When an argument to an output parameter is
constructed a temporary value is constructed for the argument.

For `inout` pamameters the argument is initialized via copy-initialization
from the argument lvalue expression to the parameter type. For `out`
parameters the argument is not initialized before the call.

In both cases on return of the function the temporary value is written
back to the argument lvalue expression through an implicit assignment
binary operator with casting as required.

This change introduces a new HLSLOutArgExpr ast node which represents
the output argument behavior. The OutArgExpr has three defined children:
- An OpaqueValueExpr of the argument lvalue expression.
- An OpaqueValueExpr of the copy-initialized parameter.
- A BinaryOpExpr assigning the first with the value of the second.

Fixes #87526

---------

Co-authored-by: Damyan Pepper <damyanp@microsoft.com>
Co-authored-by: John McCall <rjmccall@gmail.com>
2024-08-31 10:59:08 -05:00
Helena Kotas
e00e9a3f82
[HLSL] Add HLSLAttributedResourceType (#106181)
Introducing `HLSLAttributedResourceType` - a new type that is similar to
`AttributedType` but with additional data specific to HLSL resources.
`AttributeType` currently only stores an attribute kind and no
additional data from the type attribute parameters. This does not really
work for HLSL resources since its type attributes contain non-boolean
values that need to be retained as well.

For example:

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

The data `HLSLAttributedResourceType` needs to eventually store are:
- resource class (SRV, UAV, CBuffer, Sampler)
- texture dimension(1-3)
- flags is_rov, is_array, is_feedback and is_multisample
- contained type

All of these values except contained type will be stored in
`HLSLAttributedResourceType::Attributes` struct and accessed
individually via the fields. There is also `Data` alias that covers all
of these values as a `unsigned` which is used for hashing and the AST
type serialization.

During type attribute processing all HLSL type attributes will be
validated and collected by SemaHLSL (by
`SemaHLSL::handleResourceTypeAttr`) and in the end combined into a
single `HLSLAttributedResourceType` instance (in
`SemaHLSL::ProcessResourceTypeAttributes`). `SemaHLSL` will also need to
short-term store the `TypeLoc` information for the new type that will be
grabbed by `TypeSpecLocFiller` soon after the type is created.

Part 1/2 of #104861
2024-08-29 21:42:20 -07:00
smanna12
79f6ae05c1
[Clang][NFC] Fix potential null dereference in encodeTypeForFunctionPointerAuth (#104737)
This patch replaces getAs with castAs in
encodeTypeForFunctionPointerAuth to prevent dereferencing a potential
null pointer, enhancing type safety as reported by static analyzer tool.
2024-08-19 09:37:06 -05:00
Timm Baeder
a07aba5d44
[clang] Rename all AST/Interp stuff to AST/ByteCode (#104552)
"Interp" clashes with the clang interpreter and people often confuse
this.
2024-08-16 17:13:12 +02:00
Krystian Stasiowski
d52cc9de5a
[Clang][AST][NFC] Store template parameter position for TemplateTypeParmType in TypeBit (#102481)
`TemplateTypeParmType` currently stores the depth, index, and whether a
template type parameter is a pack in a union of `CanonicalTTPTInfo` and
`TemplateTypeParmDecl*`, and only the canonical type stores the position
information. These bits can be stored for all `TemplateTypeParmTypes` in
`TypeBits` to avoid unnecessary indirection when accessing the position
information.
2024-08-08 15:46:27 -04:00
Vladislav Belov
635d20e9e7
[RISCV] full support for riscv_rvv_vector_bits attribute (#100110)
Add support for using attribute((rvv_vector_bits(N))), when N < 8.
It allows using all fixed length vector mask types regardless VLEN
value.
2024-08-08 12:45:20 +03:00
Chuanqi Xu
847f9cb0e8
Reland [C++20] [Modules] [Itanium ABI] Generate the vtable in the mod… (#102287)
Reland https://github.com/llvm/llvm-project/pull/75912

The differences of this PR between
https://github.com/llvm/llvm-project/pull/75912 are:

- Fixed a regression in `Decl::isInAnotherModuleUnit()` in DeclBase.cpp
pointed by @mizvekov and add the corresponding test.
- Fixed the regression in windows
https://github.com/llvm/llvm-project/issues/97447. The changes are in
`CodeGenModule::getVTableLinkage` from
`clang/lib/CodeGen/CGVTables.cpp`. According to the feedbacks from MSVC
devs, the linkage of vtables won't affected by modules. So I simply
skipped the case for MSVC.

Given this is more or less fundamental to the use of modules. I hope we
can backport this to 19.x.
2024-08-08 13:14:09 +08: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
Matheus Izvekov
1299af6632
[clang] create class-type injected NTTP with correct value kind (#101395)
A template parameter object is an lvalue, which was not being respected
for injected parameters.

Fixes #101394
2024-08-03 00:36:48 -03:00
smanna12
cf79aba99d
[Clang] [NFC] Fix potential dereferencing of nullptr (#101405)
This patch replaces getAs with castAs and dyn_cast with cast to ensure
type safety and prevents potential null pointer dereferences. These
changes enforce compile-time checks for correct type casting in
ASTContext and CodeGenModule.
2024-07-31 17:36:21 -05:00
Brandon Wu
aa53f0d6fd
[ASTContext] Make the end of the switch case unreachable in encodeTypeForFunctionPointerAuth (#99763)
This prevent the warning from compiler.
2024-07-24 18:38:03 +08:00
Oliver Hunt
4dcd91aea3
[PAC] Implement authentication for C++ member function pointers (#99576)
Introduces type based signing of member function pointers. To support
this discrimination schema we no longer emit member function pointer to
virtual methods and indices into a vtable but migrate to using thunks.
This does mean member function pointers are no longer necessarily
directly comparable, however as such comparisons are UB this is
acceptable.

We derive the discriminator from the C++ mangling of the type of the
pointer being authenticated.

Co-Authored-By: Akira Hatanaka ahatanaka@apple.com
Co-Authored-By: John McCall rjmccall@apple.com
Co-authored-by: Ahmed Bougacha <ahmed@bougacha.org>
2024-07-22 18:29:06 -07:00
Akira Hatanaka
d463617d77
[PAC] Fix a crash when signing a pointer to a function with an incomplete enum parameter (#99595)
Use int as the underlying type when the enum type is incomplete.
2024-07-19 08:28:29 -07:00
Emanuele Rocca
c248d05c68
[Clang] make SVE types known to device targets too (#99446)
For the purpose of preprocessing and declarations in header files,
ensure clang accepts SVE types for both device and host targets.

Co-authored-by: Sander De Smalen <sander.desmalen@arm.com>
2024-07-19 08:25:38 +01:00
Doug Wyatt
0bb68b5571
Performance optimizations for function effects (nonblocking attribute etc.) (#96844)
- Put new FunctionProtoType trailing objects last.
- Inline FunctionEffectsRef::get()
- Manually inline FunctionEffectsRef::Profile().

---------

Co-authored-by: Doug Wyatt <dwyatt@apple.com>
2024-07-17 13:36:36 -04:00
Mital Ashok
a56e009ef8
[Clang] [C23] Fix typeof_unqual for qualified array types (#92767)
Properly remove qualifiers for both the element type and the array type

Fixes #92667

---------

Co-authored-by: cor3ntin <corentinjabot@gmail.com>
2024-07-17 16:58:21 +02:00
Mital Ashok
6451806ef7
[Clang] Require base element type of __has_unique_object_representations to be complete (#95432)
Fixes #95311

Previous behaviour was that `false` was silently returned, templated
classes were not instantiated and incomplete classes did not issue an
error.

---------

Co-authored-by: cor3ntin <corentinjabot@gmail.com>
2024-07-17 15:19:23 +02:00
Krystian Stasiowski
e6ec7c8f74
[Clang][AST] Move NamespaceDecl bits to DeclContext (#98567)
Currently, `NamespaceDecl` has a member `AnonOrFirstNamespaceAndFlags`
which stores a few pieces of data:
- a bit indicating whether the namespace was declared `inline`, and
- a bit indicating whether the namespace was declared as a
_nested-namespace-definition_, and
- a pointer a `NamespaceDecl` that either stores:
- a pointer to the first declaration of that namespace if the
declaration is no the first declaration, or
- a pointer to the unnamed namespace that inhabits the namespace
otherwise.

`Redeclarable` already stores a pointer to the first declaration of an
entity, so it's unnecessary to store this in `NamespaceDecl`.
`DeclContext` has 8 bytes in which various bitfields can be stored for a
declaration, so it's not necessary to store these in `NamespaceDecl`
either. We only need to store a pointer to the unnamed namespace that
inhabits the first declaration of a namespace. This patch moves the two
bits currently stored in `NamespaceDecl` to `DeclContext`, and only
stores a pointer to the unnamed namespace that inhabits a namespace in
the first declaration of that namespace. Since `getOriginalNamespace`
always returns the same `NamespaceDecl` as `getFirstDecl`, this function
is removed to avoid confusion.
2024-07-15 13:57:56 -04:00
Akira Hatanaka
ae18b94102
[PAC] Implement function pointer type discrimination (#96992)
Give users an option (-fptrauth-function-pointer-type-discrimination) to
sign a function pointer using a non-zero discriminator based on the
function type.

The discriminator is computed by first translating the function type to
a string and then computing the hash value of the string. Two function
types that are compatible in C must be translated to the same string
with the exception of function types that use typedefs of anonymous
structs in their return type or parameter types.

This patch doesn't have the code to resign function pointers, which is
needed when a function pointer is converted to a different function
type. That will be implemented in another patch.

Co-authored-by: John McCall <rjmccall@apple.com>

---------

Co-authored-by: John McCall <rjmccall@apple.com>
2024-07-11 09:09:20 -07:00
Chuanqi Xu
91d40ef6e3 Revert "[C++20] [Modules] [Itanium ABI] Generate the vtable in the module unit of dynamic classes (#75912)"
This reverts commit 18f3bcbb13ca83d33223b00761d8cddf463e9ffb, 15bb02650e26875c48889053d6a9697444583721 and
99873b35da7ecb905143c8a6b8deca4d4416f1a9.

See the post commit message in
https://github.com/llvm/llvm-project/pull/75912 to see the reasons.
2024-07-10 10:58:18 +08:00
Aaron Ballman
072e81db7a Revert "[Clang][Comments] Attach comments to decl even if preproc directives are in between (#88367)"
This reverts commit 9f04d75b2bd8ba83863db74ebe1a5c08cfc5815c.

There was post-commit feedback on the direction this PR took.
2024-07-02 14:45:52 -04:00
hdoc
9f04d75b2b
[Clang][Comments] Attach comments to decl even if preproc directives are in between (#88367)
### Background

It's surprisingly common for C++ code in the wild to conditionally
show/hide declarations to Doxygen through the use of preprocessor
directives. One especially common version of this pattern is
demonstrated below:

```cpp
/// @brief Test comment
#ifdef DOXYGEN_BUILD_ENABLED
template<typename T>
#else
template <typename T>
typename std::enable_if<std::is_integral<T>::value>::type
#endif
void f() {}
```

There are more examples I've collected below to demonstrate usage of
this pattern:
- Example 1:
[Magnum](8538610fa2/src/Magnum/Resource.h (L117-L127))
- Example 2:
[libcds](9985d2a87f/cds/container/michael_list_nogc.h (L36-L54))
- Example 3:
[rocPRIM](609ae19565/rocprim/include/rocprim/block/detail/block_reduce_raking_reduce.hpp (L60-L65))
 
From my research, it seems like the most common rationale for this
functionality is hiding difficult-to-parse code from Doxygen, especially
where template metaprogramming is concerned.

Currently, Clang does not support attaching comments to decls if there
are preprocessor comments between the comment and the decl. This is
enforced here:
b6ebea7972/clang/lib/AST/ASTContext.cpp (L284-L287)

Alongside preprocessor directives, any instance of `;{}#@` between a
comment and decl will cause the comment to not be attached to the decl.

#### Rationale

It would be nice for Clang-based documentation tools, such as
[hdoc](https://hdoc.io), to support code using this pattern. Users
expect to see comments attached to the relevant decl — even if there is
an `#ifdef` in the way — which Clang does not currently do.

#### History

Originally, commas were also in the list of "banned" characters, but
were removed in `b534d3a0ef69`
([link](b534d3a0ef))
because availability macros often have commas in them. From my reading
of the code, it appears that the original intent of the code was to
exclude macros and decorators between comments and decls, possibly in an
attempt to properly attribute comments to macros (discussed further in
"Complications", below). There's some more discussion here:
https://reviews.llvm.org/D125061.

### Change

This modifies Clang comment parsing so that comments are attached to
subsequent declarations even if there are preprocessor directives
between the end of the comment and the start of the decl. Furthermore,
this change:

- Adds tests to verify that comments are attached to their associated
decls even if there are preprocessor directives in between
- Adds tests to verify that current behavior has not changed (i.e. use
of the other characters between comment and decl will result in the
comment not being attached to the decl)
- Updates existing `lit` tests which would otherwise break.

#### Complications

Clang [does not yet
support](https://github.com/llvm/llvm-project/issues/38206) attaching
doc comments to macros. Consequently, the change proposed in this RFC
affects cases where a doc comment attached to a macro is followed
immediately by a normal declaration. In these cases, the macro's doc
comments will be attached to the subsequent decl. Previously they would
be ignored because any preprocessor directives between a comment and a
decl would result in the comment not being attached to the decl. An
example of this is shown below.

```cpp
/// Doc comment for a function-like macro
/// @param n
///    A macro argument
#define custom_sqrt(n) __internal_sqrt(n)

int __internal_sqrt(int n) { return __builtin_sqrt(n); }

// NB: the doc comment for the custom_sqrt macro will actually be attached to __internal_sqrt!
```

There is a real instance of this problem in the Clang codebase, namely
here:
be10070f91/clang/lib/Headers/amxcomplexintrin.h (L65-L114)

As part of this RFC, I've added a semicolon to break up the Clang
comment parsing so that the `-Wdocumentation` errors go away, but this
is a hack. The real solution is to fix Clang comment parsing so that doc
comments are properly attached to macros, however this would be a large
change that is outside of the scope of this RFC.
2024-07-01 08:47:26 -04: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
Doug Wyatt
f03cb005eb
[Clang] Introduce nonblocking/nonallocating attributes (#84983)
Introduce `nonblocking` and `nonallocating` attributes. RFC is here:
https://discourse.llvm.org/t/rfc-nolock-and-noalloc-attributes/76837

This PR introduces the attributes, with some changes in Sema to deal
with them as extensions to function (proto)types.

There are some basic type checks, most importantly, a warning when
trying to spoof the attribute (implicitly convert a function without the
attribute to one that has it).

A second, follow-on pull request will introduce new caller/callee
verification.
---------
Co-authored-by: Doug Wyatt <dwyatt@apple.com>
Co-authored-by: Shafik Yaghmour <shafik.yaghmour@intel.com>
Co-authored-by: Aaron Ballman <aaron@aaronballman.com>
Co-authored-by: Sirraide <aeternalmail@gmail.com>
2024-06-24 12:51:31 +02:00
Chuanqi Xu
2232881736 [C++20] [Modules] Avoid comparing primary module name to decide isInSameModule all the time
Previously, we decide if two module units are in the same module by
comparing name of the primary module interface. But it looks not
efficiency if we always compare the strings. It should be good to
avoid the expensive string operations if possible.

In this patch, we introduced a `llvm::StringMap` to map primary module
name to a Module* and a `llvm::DenseMap<Module*, Module*>` to map a
Module* to a representative Module *. The representative Module* is one
of the Module units belonging to a certain module. The module units have the
same representative Module* should belong to the same module.

We choose the representative Module* by the first module lookup for a
certain primary module name. So the following module units have the same
primary module name would get the same representative modules. So that
for every modules, there will be only one hash process for the primary
module name.
2024-06-24 16:55:17 +08:00
Chuanqi Xu
790f931886 [NFC] [Modules] Extract the logic to decide whether the module units belongs to the same module
This patch extracts the logci to decide how we decide the module units
belongs to the same module into a member function of ASTContext. This is
helpful to refactor the implementation in the future.
2024-06-24 15:58:46 +08:00