summaryrefslogtreecommitdiff
path: root/clang/lib/CodeGen/CGHLSLRuntime.cpp
AgeCommit message (Collapse)Author
2025-06-26Clarify some code based on static analysis complaints; NFC (#145679)Aaron Ballman
In one case, we have a null pointer check that's unnecessary because the only caller of the function already asserts the value is non-null. In the other case, we've got an anti-pattern of `is` followed by `get`. The logic was easier to repair by changing `get` to `cast`. Neither case is a functional change. Fixes #145525
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-20[HLSL] Emit a version in the dx.rootsignatures metadata (#145113)Justin Bogner
In #144957 the backend was updated to expect a version in the metadata, but since the frontend wasn't updated this breaks compilation. This is a somewhat temporary fix to that until #144813 lands.
2025-06-18[HLSL][SPIR-V] Fix LinkageAttribute emission for BuiltIn (#144701)Nathan Gauër
BuiltIn variables were missing the visibility attribute, which caused the Linkage capability to be emitted by the backend.
2025-06-16[HLSL] Use hidden visibility for external linkage. (#140292)Steven Perron
Implements https://github.com/llvm/wg-hlsl/blob/main/proposals/0026-symbol-visibility.md. The change is to stop using the `hlsl.export` attribute. Instead, symbols with "program linkage" in HLSL will have export linkage with default visibility, and symbols with "external linkage" in HLSL will have export linkage with hidden visibility.
2025-06-15[clang] Remove unused includes (NFC) (#144285)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-13[HLSL][SPIRV] Use resource names (#143412)Steven Perron
The SPIR-V backend does not have access to the original name of a resource in the source, so it tries to create a name. This leads to some problems with reflection. That is why start to pass the name of the resource from Clang to the SPIR-V backend. Fixes #138533
2025-06-11[HLSL][SPIR-V] Handle SV_Position builtin in PS (#141759)Nathan Gauër
This commit is using the same mechanism as vk::ext_builtin_input to implement the SV_Position semantic input. The HLSL signature is not yet ready for DXIL, hence this commit only implements the SPIR-V side. This is incomplete as it doesn't allow the semantic on hull/domain and other shaders, but it's a first step to validate the overall input/output semantic logic. Fixes https://github.com/llvm/llvm-project/issues/136969
2025-06-04[HLSL][SPIR-V] Implement vk::ext_builtin_input attribute (#138530)Nathan Gauër
This variable attribute is used in HLSL to add Vulkan specific builtins in a shader. The attribute is documented here: https://github.com/microsoft/hlsl-specs/blob/17727e88fd1cb09013cb3a144110826af05f4dd5/proposals/0011-inline-spirv.md Those variable, even if marked as `static` are externally initialized by the pipeline/driver/GPU. This is handled by moving them to a specific address space `hlsl_input`, also added by this commit. The design for input variables in Clang can be found here: https://github.com/llvm/wg-hlsl/blob/355771361ef69259fef39a65caef8bff9cb4046d/proposals/0019-spirv-input-builtin.md Co-authored-by: Justin Bogner <mail@justinbogner.com>
2025-06-03[NFC][RootSignature] Move RootSignature util functions (#142491)Finn Plummer
`HLSLRootSignature.h` was originally created to hold the struct definitions of an `llvm::hlsl::rootsig::RootElement` and some helper functions for it. However, there many users of the structs that don't require any of the helper methods. This requires us to link the `FrontendHLSL` library, where we otherwise wouldn't need to. For instance: - This [revert](https://github.com/llvm/llvm-project/pull/142005) was required as it requires linking to the unrequired `FrontendHLSL` library - As part of the change required here: https://github.com/llvm/llvm-project/issues/126557. We will want to add an `HLSLRootSignatureVersion` enum. Ideally this could live with the root signature struct defs, but we don't want to link the helper objects into `clang/Basic/TargetOptions.h` This change allows the struct definitions to be kept in a single header file and to then have the `FrontendHLSL` library only be linked when required.
2025-05-27[DirectX] Add resource name argument to llvm.dx.handlefrom[implicit]binding ↵Helena Kotas
intrinsics (#139991) Adds resource name argument to `llvm.dx.handlefrombinding` and `llvm.dx.handlefromimplicitbinding` intrinsics. SPIR-V currently does not seem to need the resource names so this change only affects DirectX binding intrinsics. Part 2/4 of https://github.com/llvm/llvm-project/issues/105059
2025-05-15[HLSL] Implicit resource binding for cbuffers (#139022)Helena Kotas
Constant buffers defined with the `cbuffer` keyword do not have a constructor. Instead, the call to initialize the resource handle based on its binding is generated in codegen. This change adds initialization of `cbuffer` handles that have implicit binding. Closes #139617
2025-05-15[HLSL][RootSignature] Add metadata generation for descriptor tables (#139633)Finn Plummer
- prereq: Modify `RootSignatureAttr` to hold a reference to the owned declaration - Define and implement `MetadataBuilder` in `HLSLRootSignature` - Integrate and invoke the builder in `CGHLSLRuntime.cpp` to generate the Root Signature for any associated entry functions - Add tests to demonstrate functionality in `RootSignature.hlsl` Resolves https://github.com/llvm/llvm-project/issues/126584 Note: this is essentially just https://github.com/llvm/llvm-project/pull/125131 rebased onto the new approach of constructing a root signature decl, instead of holding the elements in `AdditionalMembers`.
2025-05-08[HLSL][NFC] Rename isImplicit() to hasRegisterStot() on ↵Helena Kotas
HLSLResourceBindingAttr (#138964) Renaming because the name `isImplicit` is ambiguous. It can mean implicit attribute or implicit binding.
2025-05-04[clang] Remove unused local variables (NFC) (#138453)Kazu Hirata
2025-04-30[HLSL] Allow resource annotations to specify only register space (#135287)Helena Kotas
Specifying only `space` in a `register` annotation means the compiler should implicitly assign a register slot to the resource from the provided virtual register space. Closes #133346
2025-04-29[HLSL] Resource initialization by constructors (#135120)Helena Kotas
- Adds resource constructor that takes explicit binding for all resource classes. - Updates implementation of default resource constructor to initialize resource handle to `poison`. - Removes initialization of resource classes from Codegen. - Initialization of `cbuffer` still needs to happen in `CGHLSLRuntime` because it does not have a corresponding resource class type. - Adds `ImplicitCastExpr` for builtin function calls. Sema adds these automatically when a method of a template class is instantiated, but some resource classes like `ByteAddressBuffer` are not templates so they need to have this added explicitly. Design proposal: llvm/wg-hlsl#197 Closes #134154
2025-04-10[DirectX] Implement Shader Flags Analysis for ResMayNotAlias (#131070)Deric C.
Fixes #112270 Completed ACs: - `-res-may-alias` clang-dxc command-line option added - It inserts and sets a module metadata flag `dx.resmayalias` to 1 - Shader flag set appropriately: - The flag IS NOT set if DXIL Version <= 1.6 OR the command-line option `-res-may-alias` is specified - Otherwise the flag IS set when: - DXIL Version > 1.7 AND function uses UAVs, OR - DXIL Version <= 1.7 AND UAVs present globally - Add tests - Tests for Shader Models 6.6, 6.7, and 6.8 corresponding to DXIL Versions 1.6, 1.7, and 1.8 - Tests (`res-may-alias-0.ll`/`res-may-alias-1.ll`) for when the module metadata flag `dx.resmayalias` is set to 0 or 1 respectively - A frontend test (`res-may-alias.hlsl`) for testing that that the command-line option `-res-may-alias` inserts `dx.resmayalias` module metadata correctly
2025-04-09[DirectX] Implement UseNativeLowPrecision shader flag analysis (#134288)Deric C.
Fixes #112267 Implement the shader flag analysis to set the UseNativeLowPrecision DXIL module flag. The flag is only able to be set when the command-line flag `-enable-16bit-types` is passed to clang-dxc, or equivalently `-fnative-half-type` is passed to clang. When the command-line flag is passed, a module metadata flag called "dx.nativelowprec" is set to 1. The DXILShaderFlags shader flags analysis checks that the module metadata flag "dx.nativelowprec" is set to 1 and the DXIL Version is 1.2 or greater before setting the UseNativeLowPrecision DXIL module flag.
2025-03-31[IRBuilder] Add new overload for CreateIntrinsic (#131942)Rahul Joshi
Add a new `CreateIntrinsic` overload with no `Types`, useful for creating calls to non-overloaded intrinsics that don't need additional mangling.
2025-03-21[HLSL] Add support for SV_GroupIndex in SPIR-V (#130672)Cassandra Beckley
Lower the `SV_GroupIndex` semantic as the `llvm.spv.flattened.thread.id.in.group` intrinsic. Depends on #130670. --------- Co-authored-by: Steven Perron <stevenperron@google.com>
2025-03-20[HLSL] Buffer handle globals should not be constants (#130231)Justin Bogner
If these are constants their initializers will be removed by InstCombine. Change them to not be constants and initialize them with poison.
2025-03-14[HLSL] Remove old resource annotations (#130338)Helena Kotas
Fixes #114126
2025-03-12[HLSL] Implement explicit layout for default constant buffer ($Globals) ↵Helena Kotas
(#128991) Processes `HLSLResourceBindingAttr` attributes that represent `register(c#)` annotations on default constant buffer declarations and applies its value to the buffer layout. Any default buffer declarations without an explicit `register(c#)` annotation are placed after the elements with explicit layout. This PR also adds a test case for a `cbuffer` that does not have `packoffset` on all declarations. Same layout rules apply here as well. Fixes #126791
2025-03-05[HLSL] Fix resource wrapper declaration (#129100)Steven Perron
The resource wrapper should have internal linkage because it contains a handle to the global resource, and it not the actual global. Makeing this changed exposed that we were zeroinitializing the resouce, which is a problem. The handle cannot be zeroinitialized. This is changed to use poison instead. Fixes https://github.com/llvm/llvm-project/issues/122767. --------- Co-authored-by: Helena Kotas <hekotas@microsoft.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
2025-02-15[HLSL] Implement HLSL intialization list support (#123141)Chris B
This PR implements HLSL's initialization list behvaior as specified in the draft language specifcation under [*Decl.Init.Agg*](https://microsoft.github.io/hlsl-specs/specs/hlsl.html#Decl.Init.Agg). This behavior is a bit unusual for C/C++ because intermediate braces in initializer lists are ignored and a whole array of additional conversions occur unintuitively to how initializaiton works in C. The implementaiton in this PR generates a valid C/C++ initialization list AST for the HLSL initializer so that there are no changes required to Clang's CodeGen to support this. This design will also allow us to use Clang's rewrite to convert HLSL initializers to valid C/C++ initializers that are equivalent. It does have the downside that it will generate often redundant accesses during codegen. The IR optimizer is extremely good at eliminating those so this will have no impact on the final executable performance. There is some opportunity for optimizing the initializer list generation that we could consider in subsequent commits. One notable opportunity would be to identify aggregate objects that occur in the same place in both initializers and do not require converison, those aggregates could be initialized as aggregates rather than fully scalarized. Closes #56067 --------- Co-authored-by: Finn Plummer <50529406+inbelic@users.noreply.github.com> Co-authored-by: Helena Kotas <hekotas@microsoft.com> Co-authored-by: Justin Bogner <mail@justinbogner.com>
2025-02-12[DirectX] Set Shader Flag DisableOptimizations (#126813)S. Bharadwaj Yadavalli
- Set the shader flag `DisableOptimizations` based on `optnone` attribute of shader entry functions. - Add DXIL Metadata Analysis pass as pre-requisite for Shader Flags pass to obtain entry function information collected therein. - Named module metadata `dx.disable_optimizations` is intended to indicate disabling optimizations (`-O0`) via commandline flag. However, its intent is fulfilled by `optnone` attribute of shader entry functions as implemented in a recent change, and thus not needed. Delete generation of named metadata and corresponding test file `disable_opt.ll`. - Add tests to verify correctness of setting shader flag. Closes #112263
2025-02-11[HLSL] Appropriately set function attribute optnone (#125937)S. Bharadwaj Yadavalli
When optimization is disabled, set `optnone` attribute all module entry functions. Updated test in accordance with the change. Closes #124796
2025-01-24[HLSL] Introduce address space `hlsl_constant(2)` for constant buffer ↵Helena Kotas
declarations (#123411) Introduces a new address space `hlsl_constant(2)` for constant buffer declarations. This address space is applied to declarations inside `cbuffer` block. Later on, it will also be applied to `ConstantBuffer<T>` syntax and the default `$Globals` constant buffer. Clang codegen translates constant buffer declarations to global variables and loads from `hlsl_constant(2)` address space. More work coming soon will include addition of metadata that will map these globals to individual constant buffers and enable their transformation to appropriate constant buffer load intrinsics later on in an LLVM pass. Fixes #123406
2025-01-22[HLSL] Fix global resource initialization (#123394)Helena Kotas
Create separate resource initialization function for each resource and add them to CodeGenModule's `CXXGlobalInits` list. Fixes #120636 and addresses this [comment ](https://github.com/llvm/llvm-project/pull/119755/files#r1894093603).
2025-01-04[HLSL][SPIR-V] implement SV_GroupID semantic lowering (#121521)Zhengxing li
The HLSL SV_GroupID semantic attribute is lowered into @llvm.spv.group.id intrinsic in LLVM IR for SPIR-V target. In the SPIR-V backend, this is now translated to a `WorkgroupId` builtin variable. Fixes #118700 which's a follow-up work to #70120
2024-12-17[HLSL] Fix call convention mismatch for ctor/dtor (#118651)Nathan Gauër
Before this patch, there was a calling-convention mismatch between the constructors and the actual call emitted for the entrypoint wrapper. Such mismatch causes the InstCombine pass to replace this call with an `unreachable`, breaking the whole function. Signed-off-by: Nathan Gauër <brioche@google.com>
2024-12-10[HLSL] Implement SV_GroupThreadId semantic (#117781)Zhengxing li
Support HLSL SV_GroupThreadId attribute. For `directx` target, translate it into `dx.thread.id.in.group` in clang codeGen and lower `dx.thread.id.in.group` to `dx.op.threadIdInGroup` in LLVM DirectX backend. For `spir-v` target, translate it into `spv.thread.id.in.group` in clang codeGen and lower `spv.thread.id.in.group` to a `LocalInvocationId` builtin variable in LLVM SPIR-V backend. Fixes: #70122
2024-11-26[HLSL] Implement SV_GroupID semantic (#115911)Zhengxing li
Support SV_GroupID attribute. Translate it into dx.group.id in clang codeGen. Fixes: #70120
2024-10-30[HLSL] Remove old resource annotations for UAVs and SRVs (#114139)Helena Kotas
UAVs and SRVs have already been converted to use LLVM target types and we can disable generating of the !hlsl.uavs and !hlsl.srvs! annotations. This will enable adding tests for structured buffers with user defined types that this old resource annotations code does not handle (it crashes). Part 1 of #114126
2024-10-28[HLSL][SPIRV] Add convergence tokens to entry point wrapper (#112757)Steven Perron
Inlining currently assumes that either all function use controled convergence or none of them do. This is why we need to have the entry point wrapper use controled convergence. https://github.com/llvm/llvm-project/blob/c85611e8583e6392d56075ebdfa60893b6284813/llvm/lib/Transforms/Utils/InlineFunction.cpp#L2431-L2439
2024-10-17[HLSL] Add handle initialization for simple resource declarations (#111207)Helena Kotas
Adds `@_init_resource_bindings()` function to module initialization that includes `handle.fromBinding` intrinsic calls for simple resource declarations. Arrays of resources or resources inside user defined types are not supported yet. While this unblocks our progress on [Compile a runnable shader from clang](https://github.com/llvm/wg-hlsl/issues/7) milestone, this is probably not the way we would like to handle resource binding initialization going forward. Ideally, it should be done via the resource class constructors in order to support dynamic resource binding or unbounded arrays if resources. Depends on PRs #110327 and #111203. Part 1 of #105076
2024-10-01[HLSL][SPIRV] Fix calling convention for call in entry function. (#110542)Steven Perron
Fix the calling convention used for the call in the entry point wrapper. No calling convention is currently set. It can easily use the calling convention of the function that is being called. Without this, there is a mismatch in the calling convention between the call site and the callee. This is undefined behaviour.
2024-09-17[HLSL] generate hlsl.wavesize attribute (#107176)Xiang Li
Generate function attribute hlsl.wavesize from [WaveSize]. For #70118
2024-09-17Reapply "[HLSL] set alwaysinline on HLSL functions (#106588)"Thurston Dang
This reverts commit 4a63f4d301c0e044073e1b1f8f110015ec1778a1. It was reverted because of a buildbot breakage, but the fix-forward has landed (https://github.com/llvm/llvm-project/pull/109023).
2024-09-17Revert "[HLSL] set alwaysinline on HLSL functions (#106588)"Thurston Dang
This reverts commit a729e706de3fc6ebee49ede3c50afb47f2e29191. Reason:bBuildbot failure (https://lab.llvm.org/buildbot/#/builders/25/builds/2541): 'Clang :: CodeGenHLSL/builtins/StructuredBuffer-subscript.hlsl' failed
2024-09-17[HLSL] set alwaysinline on HLSL functions (#106588)Greg Roth
HLSL inlines all its functions by default. This uses the alwaysinline attribute to make the alwaysinliner pass inline any function not explicitly marked noinline by the user or autogeneration. The alwayslinline marking takes place in `SetLLVMFunctionAttributesForDefinitions` where all other inlining interactions are determined. The outermost entry function is marked noinline because there's no reason to inline it. Any user calls to an entry function will instead call the internal mangled version of the entry function. Adds tests for function and constructor inlining and augments some existing tests to verify correct inlining of implicitly created functions as well. Incidentally restore RUN line that I believe was mistakenly removed as part of #88918 Fixes #89282
2024-09-05[HLSL] Apply resource attributes to the resource type rather than the handle ↵Helena Kotas
member (#107160) Converts existing resource attributes `[[hlsl::resource_class(..)]]` and `[[is_rov]]` from declaration attributes to type attributes. During type attribute processing all HLSL resource type attributes are validated and collected by `SemaHLSL` (`SemaHLSL::handleResourceTypeAttr`). At the end of the declaration they are be combined into a single `HLSLAttributedResourceType` instance (`SemaHLSL::ProcessResourceTypeAttributes`) that wraps the original type and stores all of the necessary information about the resource. `SemaHLSL` will also need to short-term-store the `TypeLoc` information for the newly created type that will be grabbed by `TypeSpecLocFiller` soon after it is created. Updates all places that expected resource attributes on declarations like resource binding diagnostic, builtin types in HLSLExternalSemaSource, or codegen. Also includes implementation of `TreeTransform<Derived>::TransformHLSLAttributedResourceType` that enables the use of attributed resource types inside templates. Fixes #104861 Part 2/2
2024-08-14[HLSL] Split out the ROV attribute from the resource attribute, make it a ↵Joshua Batista
new spellable attribute. (#102414) Much like #98193, this PR takes some more data out of the resource attribute, specifically the ROV data. This PR introduces a new attribute called HLSLROVAttr, which contains data on whether or not the decl the attribute applies to is an ROV. Tests were added to ensure the attribute is found on the AST. This attribute may take any boolean condition as an argument. If the condition is true, then the object the attribute applies to "is" an ROV. Fixes #https://github.com/llvm/llvm-project/issues/102392
2024-08-13[HLSL] Mark exported functions with "hlsl.export" attribute (#102275)Helena Kotas
Marks exported functions with `"hlsl.export"` attribute. This information will be later used by DXILFinalizeLinkage pass (coming soon) to determine which functions should have internal linkage in the final DXIL code. Related to #llvm/llvm-project#92071
2024-08-05[HLSL] Implement intangible AST type (#97362)Helena Kotas
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>