summaryrefslogtreecommitdiff
path: root/clang/lib/AST/Decl.cpp
AgeCommit message (Collapse)Author
2025-11-21[clang][TypePrinter] Replace AppendScope with printNestedNameSpecifier (#168534)Michael Buch
In debug-info we soon have the need to print names using the full scope of the entity (see discussion in https://github.com/llvm/llvm-project/pull/159592). Particularly, when a structure is scoped inside a function, we'd like to emit the name as `func()::foo`. `CGDebugInfo` uses the `TypePrinter` to print type names into debug-info. However, `TypePrinter` stops (and ignores) `DeclContext`s that are functions. I.e., it would just print `foo`. Ideally it would behave the same way `printNestedNameSpecifier` does. The FIXME in https://github.com/llvm/llvm-project/blob/47c1aa4cef638c97b74f3afb7bed60e92bba1f90/clang/lib/AST/TypePrinter.cpp#L1520-L1521 motivated this patch. See https://github.com/llvm/llvm-project/pull/168533 for how this will be used by `CGDebugInfo`. The plan is to introduce a new `PrintingPolicy` that prints anonymous entities using their full scope (including function/anonymous scopes) and the mangling number.
2025-11-12[Clang][NFC] Fix a typo in FunctionDecl (#167677)Younan Zhang
Found it while looking at other stuffs.
2025-10-20[ADT] Prepare for deprecation of StringSwitch cases with 4+ args. NFC. (#164173)Jakub Kuderski
Update `.Cases` and `.CasesLower` with 4+ args to use the `initializer_list` overload. The deprecation of these functions will come in a separate PR. For more context, see: https://github.com/llvm/llvm-project/pull/163405.
2025-10-15[clang] NFC: rename TagType::getOriginalDecl back to getDecl (#163271)Matheus Izvekov
This rename was made as part of https://github.com/llvm/llvm-project/pull/147835 in order to ease rebasing the PR, and give a nice window for other patches to get rebased as well. It has been a while already, so lets go ahead and rename it back.
2025-10-14[Clang] Destructors should not be immediate-escalating (#163390)Corentin Jabot
We allow destructors to become immediate functions, which makes little sense as the standard disallow consteval destructors Related CWG issue https://github.com/cplusplus/CWG/issues/780 Fixes #109096
2025-10-01[Clang][NFC] Refactor operator delete argument handling (#160554)Andy Kaylor
This change moves the getUsualDeleteParams function into the FunctionDecl class so that it can be shared between LLVM IR and CIR codegen.
2025-09-18[C++20][Modules] Fix merging of anonymous members of class templates. (#155948)Michael Park
2025-09-01[clang]: Support `analyzer_noreturn` attribute in `CFG` (#150952)Andrey Karlov
## Problem Currently, functions with `analyzer_noreturn` attribute aren't recognized as `no-return` by `CFG`: ```cpp void assertion_handler() __attribute__((analyzer_noreturn)) { log(...); } void handle_error(const std::optional<int> opt) { if (!opt) { fatal_error(); // Static analyzer doesn't know this never returns } *opt = 1; // False-positive `unchecked-optional-access` warning as analyzer thinks this is reachable } ``` ## Solution 1. Extend the `FunctionDecl` class by adding an `isAnalyzerNoReturn()` function 2. Update `CFGBuilder::VisitCallExpr` to check both `FD->isNoReturn()` and `FD->isAnalyzerNoReturn()` properties ## Comments This PR incorporates part of the work done in https://github.com/llvm/llvm-project/pull/146355
2025-08-27[clang] NFC: reintroduce clang/include/clang/AST/Type.h (#155050)Matheus Izvekov
This reintroduces `Type.h`, having earlier been renamed to `TypeBase.h`, as a redirection to `TypeBase.h`, and redirects most users to include the former instead. This is a preparatory patch for being able to provide inline definitions for `Type` methods which would otherwise cause a circular dependency with `Decl{,CXX}.h`. Doing these operations into their own NFC patch helps the git rename detection logic work, preserving the history. This patch makes clang just a little slower to build (~0.17%), just because it makes more code indirectly include `DeclCXX.h`.
2025-08-27[clang] NFC: rename clang/include/clang/AST/Type.h to TypeBase.h (#155049)Matheus Izvekov
This is a preparatory patch, to be able to provide inline definitions for `Type` functions which depend on `Decl{,CXX}.h`. As the latter also depends on `Type.h`, this would not be possible without some reorganizing. Splitting this rename into its own patch allows git to track this as a rename, and preserve all git history, and not force any code reformatting. A later NFC patch will reintroduce `Type.h` as redirection to `TypeBase.h`, rewriting most places back to directly including `Type.h` instead of `TypeBase.h`, leaving only a handful of places where this is necessary. Then yet a later patch will exploit this by making more stuff inline.
2025-08-27[clang] AST: fix getAs canonicalization of leaf types (#155028)Matheus Izvekov
2025-08-25[clang] NFC: change more places to use Type::getAsTagDecl and friends (#155313)Matheus Izvekov
This changes a bunch of places which use getAs<TagType>, including derived types, just to obtain the tag definition. This is preparation for #155028, offloading all the changes that PR used to introduce which don't depend on any new helpers.
2025-08-19[clang] fix redecl chain assumption when checking linkage consistency (#153996)Matheus Izvekov
In C++, it can be assumed the same linkage will be computed for all redeclarations of an entity, and we have assertions to check this. However, the linkage for a declaration can be requested in the middle of deserealization, and at this point the redecl chain is not well formed, as computation of the most recent declaration is deferred. This patch makes that assertion work even in such conditions. This fixes a regression introduced in https://github.com/llvm/llvm-project/pull/147835, which was never released, so there are no release notes for this. Fixes #153933
2025-08-09[clang] Improve nested name specifier AST representation (#147835)Matheus Izvekov
This is a major change on how we represent nested name qualifications in the AST. * The nested name specifier itself and how it's stored is changed. The prefixes for types are handled within the type hierarchy, which makes canonicalization for them super cheap, no memory allocation required. Also translating a type into nested name specifier form becomes a no-op. An identifier is stored as a DependentNameType. The nested name specifier gains a lightweight handle class, to be used instead of passing around pointers, which is similar to what is implemented for TemplateName. There is still one free bit available, and this handle can be used within a PointerUnion and PointerIntPair, which should keep bit-packing aficionados happy. * The ElaboratedType node is removed, all type nodes in which it could previously apply to can now store the elaborated keyword and name qualifier, tail allocating when present. * TagTypes can now point to the exact declaration found when producing these, as opposed to the previous situation of there only existing one TagType per entity. This increases the amount of type sugar retained, and can have several applications, for example in tracking module ownership, and other tools which care about source file origins, such as IWYU. These TagTypes are lazily allocated, in order to limit the increase in AST size. This patch offers a great performance benefit. It greatly improves compilation time for [stdexec](https://github.com/NVIDIA/stdexec). For one datapoint, for `test_on2.cpp` in that project, which is the slowest compiling test, this patch improves `-c` compilation time by about 7.2%, with the `-fsyntax-only` improvement being at ~12%. This has great results on compile-time-tracker as well: ![image](https://github.com/user-attachments/assets/700dce98-2cab-4aa8-97d1-b038c0bee831) This patch also further enables other optimziations in the future, and will reduce the performance impact of template specialization resugaring when that lands. It has some other miscelaneous drive-by fixes. About the review: Yes the patch is huge, sorry about that. Part of the reason is that I started by the nested name specifier part, before the ElaboratedType part, but that had a huge performance downside, as ElaboratedType is a big performance hog. I didn't have the steam to go back and change the patch after the fact. There is also a lot of internal API changes, and it made sense to remove ElaboratedType in one go, versus removing it from one type at a time, as that would present much more churn to the users. Also, the nested name specifier having a different API avoids missing changes related to how prefixes work now, which could make existing code compile but not work. How to review: The important changes are all in `clang/include/clang/AST` and `clang/lib/AST`, with also important changes in `clang/lib/Sema/TreeTransform.h`. The rest and bulk of the changes are mostly consequences of the changes in API. PS: TagType::getDecl is renamed to `getOriginalDecl` in this patch, just for easier to rebasing. I plan to rename it back after this lands. Fixes #136624 Fixes https://github.com/llvm/llvm-project/issues/43179 Fixes https://github.com/llvm/llvm-project/issues/68670 Fixes https://github.com/llvm/llvm-project/issues/92757
2025-08-04[Clang] Initial support for P2841 (Variable template and concept template ↵Corentin Jabot
parameters) (#150823) This is a first pass at implementing [P2841R7](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p2841r7.pdf). The implementation is far from complete; however, I'm aiming to do that in chunks, to make our lives easier. In particular, this does not implement - Subsumption - Mangling - Satisfaction checking is minimal as we should focus on #141776 first (note that I'm currently very stuck) FTM, release notes, status page, etc, will be updated once the feature is more mature. Given the state of the feature, it is not yet allowed in older language modes. Of note: - Mismatches between template template arguments and template template parameters are a bit wonky. This is addressed by #130603 - We use `UnresolvedLookupExpr` to model template-id. While this is pre-existing, I have been wondering if we want to introduce a different OverloadExpr subclass for that. I did not make the change in this patch.
2025-07-30[Clang][AArch64] Expect valid FunctionDecl in IsArmStreamingFunctionSander de Smalen
This follows from a conversation on #150592 where we decided to split out this change and commit it separately. The rationale is that FunctionDecl must be sufficiently parsed/created in order to tell whether it is a streaming function.
2025-07-15Check if clang::FieldDecl has constant-integer bit width before getting the ↵higher-performance
width (#148692) This avoids crashing due to template-dependent bit widths
2025-07-12[Clang][AST][NFC] (`RecordDecl` -> `CXXRecordDecl`)`::isInjectedClassName` ↵Yanzuo Liu
(#148195) Move `RecordDecl::isInjectedClassName` to `CXXRecordDecl::isInjectedClassName`. C language doesn't have the term "injected class name". Co-authored-by: Matheus Izvekov <mizvekov@gmail.com>
2025-07-07[Modules] Don't const eval VarDecls with dependent type (#147378)Henrik G. Olsson
EvaluateAsInitializer does not support evaluating values with dependent types. This was previously guarded with a check for the initializer expression, but it is possible for the VarDecl to have a dependent type without the initializer having a dependent type, when the initializer is a specialized template type and the VarDecl has the unspecialized type. This adds a guard checking for dependence in the VarDecl type as well. This fixes the issue raised by Google in https://github.com/llvm/llvm-project/pull/145447
2025-07-03[Modules] Record side effect info in EvaluatedStmt (#146468)Henrik G. Olsson
All deserialized VarDecl initializers are EvaluatedStmt, but not all EvaluatedStmt initializers are from a PCH. Calling `VarDecl::hasInitWithSideEffects` can trigger constant evaluation, but it's hard to know ahead of time whether that will trigger deserialization - even if the initializer is fully deserialized, it may contain a call to a constructor whose body is not deserialized. By caching the result of `VarDecl::hasInitWithSideEffects` and populating that cache during deserialization we can guarantee that calling it won't trigger deserialization regardless of the state of the initializer. This also reduces memory usage by removing the `InitSideEffectVars` set in `ASTReader`. rdar://154717930
2025-06-28[clang] Remove unused includes (NFC) (#146254)Kazu Hirata
These are identified by misc-include-cleaner. I've filtered out those that break builds. Also, I'm staying away from llvm-config.h, config.h, and Compiler.h, which likely cause platform- or compiler-specific build failures.
2025-06-24[HLSL][RootSignature] Add `fdx-rootsignature-version` option to specify root ↵Finn Plummer
signature version (#144813) This pr provides the ability to specify the root signature version as a compiler option and to retain this in the root signature decl. It also updates the methods to serialize the version when dumping the declaration and to output the version when generating the metadata. - Update `DXContainer.hI` to define the root signature versions - Update `Options.td` and `LangOpts.h` to define the `fdx-rootsignature-version` compiler option - Update `Options.td` to provide an alias `force-rootsig-ver` in clang-dxc - Update `Decl.[h|cpp]` and `SeamHLSL.cpp` so that `RootSignatureDecl` will retain its version type - Updates `CGHLSLRuntime.cpp` to generate the extra metadata field - Add tests to illustrate Resolves https://github.com/llvm/llvm-project/issues/126557. Note: this does not implement validation based on versioning. https://github.com/llvm/llvm-project/issues/129940 is required to retrieve the version and use it for validations.
2025-06-23Reland "[Modules] Record whether VarDecl initializers contain side effects" ↵Henrik G. Olsson
(#145447) This reverts commit 329ae86 and adds an early exit for EvaluateInPlace when the expression's type is null.
2025-06-23Revert "[Modules] Record whether VarDecl initializers contain side effects" ↵Jonas Devlieghere
(#145407) Reverts llvm/llvm-project#143739 because it triggers an assert: ``` Assertion failed: (!isNull() && "Cannot retrieve a NULL type pointer"), function getCommonPtr, file Type.h, line 952. ```
2025-06-23[NFC][Clang][AST] Drop `llvm::` in front of `ArrayRef`/`MutableArrayRef` ↵Rahul Joshi
(#145207)
2025-06-23[Modules] Record whether VarDecl initializers contain side effects (#143739)Henrik G. Olsson
Calling `DeclMustBeEmitted` should not lead to more deserialization, as it may occur before previous deserialization has finished. When passed a `VarDecl` with an initializer however, `DeclMustBeEmitted` needs to know whether that initializer contains side effects. When the `VarDecl` is deserialized but the initializer is not, this triggers deserialization of the initializer. To avoid this we add a bit to the serialization format for `VarDecl`s, indicating whether its initializer contains side effects or not, so that the `ASTReader` can query this information directly without deserializing the initializer. rdar://153085264
2025-06-23[NFC][Clang][AST] Adopt `llvm::copy` in Clang AST (#145192)Rahul Joshi
2025-06-19[NFC][Clang][AST] Adopt simplified `getTrailingObjects` in AST (#144432)Rahul Joshi
Adopt simplified `getTrailingObjects` API in several places in clag/AST that were missed by earlier changes.
2025-06-08[Clang] Support constexpr asm at global scope. (#143268)Corentin Jabot
I previously failed to realize this feature existed... Fixes #137459 Fixes #143242
2025-06-05[clang] Simplify device kernel attributes (#137882)Nick Sarnie
We have multiple different attributes in clang representing device kernels for specific targets/languages. Refactor them into one attribute with different spellings to make it more easily scalable for new languages/targets. --------- Signed-off-by: Sarnie, Nick <nick.sarnie@intel.com>
2025-05-15[NFC][Clang] Adopt simplified `getTrailingObjects` in Decl/DeclTemplate ↵Rahul Joshi
(#139977) Adopt simplied `getTrailingObjects` variants that are not templated and/or return ArrayRef in Decl/DeclTemplate .h/.cpp files.
2025-05-12[HLSL][RootSignature] Define and integrate rootsig clang attr and decl (#137690)Finn Plummer
- Defines a new declaration node `HLSLRootSignature` in `DeclNodes.td` that will consist of a `TrailingObjects` of the in-memory construction of the root signature, namely an array of `hlsl::rootsig::RootElement`s - Defines a new clang attr `RootSignature` which simply holds an identifier to a corresponding root signature declaration as above - Integrate the `HLSLRootSignatureParser` to construct the decl node in `ParseMicrosoftAttributes` and then attach the parsed attr with an identifier to the entry point function declaration. - Defines the various required declaration methods - Add testing that the declaration and reference attr are created correctly, and some syntactical error tests. It was previously proposed that we could have the root elements reference be stored directly as an additional member of the attribute and to not have a separate root signature decl. In contrast, by defining them separately as this change proposes, we will allow a unique root signature to have its own declaration in the AST tree. This allows us to only construct a single root signature for all duplicate root signature attributes. Having it located directly as a declaration might also prove advantageous when we consider root signature libraries. Resolves https://github.com/llvm/llvm-project/issues/119011
2025-05-09[clang] UEFI do not mangle main (#139179)Prabhu Rajasekaran
Entry point functions such as main, wmain etc. should not be mangled for UEFI targets.
2025-05-07[NFC][Support] Add llvm::uninitialized_copy (#138174)Rahul Joshi
Add `llvm::uninitialized_copy` that accepts a range instead of start/end iterator for the source of the copy.
2025-05-06[Clang] Implement the core language parts of P2786 - Trivial relocation ↵cor3ntin
(#127636) This adds - The parsing of `trivially_relocatable_if_eligible`, `replaceable_if_eligible` keywords - `__builtin_trivially_relocate`, implemented in terms of memmove. In the future this should - Add the appropriate start/end lifetime markers that llvm does not have (`start_lifetime_as`) - Add support for ptrauth when that's upstreamed - the `__builtin_is_cpp_trivially_relocatable` and `__builtin_is_replaceable` traits Fixes #127609
2025-04-28Reland [clang] Handle instantiated members to determine visibility (#136128) ↵Andrew Savonichev
(#136689) As reported in issue #103477, visibility of instantiated member functions used to be ignored when calculating visibility of a specialization. This patch modifies `getLVForClassMember` to look up for a source template for an instantiated member, and changes `mergeTemplateLV` to apply it. A similar issue was reported in #31462, but it seems that `extern` declaration with visibility prevents the function from being emitted as hidden. This behavior seems correct, even though GCC emits it as with default visibility instead. Both tests from #103477 and #31462 are added as LIT tests `test72` and `test73` respectively.
2025-04-22Reapply 19c708c "FunctionDecl::getFunctionTypeLoc: ignore function type ↵Owen Anderson
attributes (#118420)" (#136484) Avoid using PreservesMost in the testcase as it is not supported on all targets. Original PR #118290. Co-authored-by: Robert Dazi <14996868+v01dXYZ@users.noreply.github.com> Co-authored-by: v01dxyz <v01dxyz@v01d.xyz>
2025-04-20Revert "FunctionDecl::getFunctionTypeLoc: ignore function type attributes ↵Owen Anderson
(#118420)" This reverts commit 19c708c18963ac24822564824cb5401e71a49943 because it caused test failures on non-x86 targets.
2025-04-19FunctionDecl::getFunctionTypeLoc: ignore function type attributes (#118420)Robert Dazi
Related to #118290. --------- Co-authored-by: v01dxyz <v01dxyz@v01d.xyz> Co-authored-by: Owen Anderson <resistor@mac.com>
2025-04-18Revert "[clang] Handle instantiated members to determine visibility" (#136317)Erich Keane
Reverts llvm/llvm-project#136128 See discussion here: https://github.com/llvm/llvm-project/pull/136128#issuecomment-2815648110 and : https://github.com/llvm/llvm-project/pull/136128#issuecomment-2815652846 @asavonic can re-submit once the examples provided by @jplehr and/or @DKLoehr are fixed.
2025-04-18[clang] Handle instantiated members to determine visibility (#136128)Andrew Savonichev
As reported in issue #103477, visibility of instantiated member functions used to be ignored when calculating visibility of a specialization. This patch modifies `getLVForClassMember` to look up for a source template for an instantiated member, and changes `mergeTemplateLV` to apply it. A similar issue was reported in #31462, but it seems that `extern` declaration with visibility prevents the function from being emitted as hidden. This behavior seems correct, even though GCC emits it as with default visibility instead. Both tests from #103477 and #31462 are added as LIT tests `test72` and `test73` respectively.
2025-04-10[RFC] Initial implementation of P2719 (#113510)Oliver Hunt
This is a basic implementation of P2719: "Type-aware allocation and deallocation functions" described at http://wg21.link/P2719 The proposal includes some more details but the basic change in functionality is the addition of support for an additional implicit parameter in operators `new` and `delete` to act as a type tag. Tag is of type `std::type_identity<T>` where T is the concrete type being allocated. So for example, a custom type specific allocator for `int` say can be provided by the declaration of void *operator new(std::type_identity<int>, size_t, std::align_val_t); void operator delete(std::type_identity<int>, void*, size_t, std::align_val_t); However this becomes more powerful by specifying templated declarations, for example template <typename T> void *operator new(std::type_identity<T>, size_t, std::align_val_t); template <typename T> void operator delete(std::type_identity<T>, void*, size_t, std::align_val_t);); Where the operators being resolved will be the concrete type being operated over (NB. A completely unconstrained global definition as above is not recommended as it triggers many problems similar to a general override of the global operators). These type aware operators can be declared as either free functions or in class, and can be specified with or without the other implicit parameters, with overload resolution performed according to the existing standard parameter prioritisation, only with type parameterised operators having higher precedence than non-type aware operators. The only exception is destroying_delete which for reasons discussed in the paper we do not support type-aware variants by default.
2025-04-08[Clang][OpenCL][AMDGPU] Allow a kernel to call another kernel (#115821)Aniket Lal
This feature is currently not supported in the compiler. To facilitate this we emit a stub version of each kernel function body with different name mangling scheme, and replaces the respective kernel call-sites appropriately. Fixes https://github.com/llvm/llvm-project/issues/60313 D120566 was an earlier attempt made to upstream a solution for this issue. --------- Co-authored-by: anikelal <anikelal@amd.com>
2025-04-03[clang] NFC: introduce UnsignedOrNone as a replacement for ↵Matheus Izvekov
std::optional<unsigned> (#134142) This introduces a new class 'UnsignedOrNone', which models a lite version of `std::optional<unsigned>`, but has the same size as 'unsigned'. This replaces most uses of `std::optional<unsigned>`, and similar schemes utilizing 'int' and '-1' as sentinel. Besides the smaller size advantage, this is simpler to serialize, as its internal representation is a single unsigned int as well.
2025-04-03[clang] support pack expansions for trailing requires clauses (#133190)Matheus Izvekov
2025-03-28[clang][flang][Triple][llvm] Add isOffload function to LangOpts and isGPU ↵Nick Sarnie
function to Triple (#126956) I'm adding support for SPIR-V, so let's consolidate these checks. --------- Signed-off-by: Sarnie, Nick <nick.sarnie@intel.com>
2025-02-25[HLSL] Implement default constant buffer $Globals (2nd attempt) (#128589)Helena Kotas
All variable declarations in the global scope that are not resources, static or empty are implicitly added to implicit constant buffer `$Globals`. They are created in `hlsl_constant` address space and collected in an implicit `HLSLBufferDecl` node that is added to the AST at the end of the translation unit. Codegen is the same as for explicit constant buffers. Fixes #123801 This is a second attempt to implement this feature. The first attempt had to be reverted because of memory leaks. The problem was adding a `SmallVector` member on `HLSLBufferDecl` node to represent a list of default buffer declarations. When this vector needed to grow, it allocated memory that was never released, because all memory used by AST nodes must be allocated by `ASTContext` allocator and is released all at once. Destructors on AST nodes are never called. It this change the list of default buffer declarations is collected in a `SmallVector` instance on `SemaHLSL`. The `HLSLBufDecl` representing `$Globals` is created at the end of the translation unit when the number of declarations is known, and the list is copied into an array allocated by the `ASTContext` allocator.
2025-02-20Revert "[HLSL] Implement default constant buffer `$Globals`" (#128112)Helena Kotas
Reverts llvm/llvm-project#125807 Reverting this change because of failing tests.
2025-02-20[HLSL] Implement default constant buffer `$Globals` (#125807)Helena Kotas
All variable declarations in the global scope that are not resources, static or empty are implicitly added to implicit constant buffer `$Globals`. They are created in `hlsl_constant` address space and collected in an implicit `HLSLBufferDecl` node that is added to the AST at the end of the translation unit. Codegen is the same as for explicit constant buffers. Fixes #123801
2025-02-20[HLSL] Constant Buffers CodeGen (#124886)Helena Kotas
Translates `cbuffer` declaration blocks to `target("dx.CBuffer")` type. Creates global variables in `hlsl_constant` address space for all `cbuffer` constant and adds metadata describing which global constant belongs to which constant buffer. For explicit constant buffer layout information an explicit layout type `target("dx.Layout")` is used. This might change in the future. The constant globals are temporary and will be removed in upcoming pass that will translate `load` instructions in the `hlsl_constant` address space to constant buffer load intrinsics calls off a CBV handle (#124630, #112992). See [Constant buffer design doc](https://github.com/llvm/wg-hlsl/pull/94) for more details. Fixes #113514, #106596