Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constant buffers (cbuffer) #94

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions proposals/NNNN-constant-buffers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@

# Constant buffers

* Proposal: [NNNN](NNNN-constant-buffers.md)
* Author(s): [Helena Kotas](https://github.com/hekota)
* Status: **Design In Progress**

## Introduction

Shader inputs usually include a number of constants which are stored in one or more buffer resources in memory with specific packing rules. These resources can be organized into two types of buffers: constant buffers and texture buffers.

From the compiler point of view constant buffers and texture buffers are very similar. The major difference is that constant buffers load from a constant buffer view (CBV) and bind to register `b` while texture buffers load from a typed buffer (SRV) and bind to the `t` register.

Declaring a constant buffer or a texture buffer looks very much like a structure declaration in C, with the addition of the register and packoffset keywords for manually assigning registers or packing data. For example:

```c++
cbuffer MyConstant register(b1) {
float4 F;
}
```

Constant buffer variables can be accessed anywhere from a shader using the variable name `F` without referencing the constant buffer name .

Another way of declaring buffers with constants is via `ConstantBuffer` or `TextureBuffer` resource classes:

```c++
struct MyConstants {
float4 F;
};

ConstantBuffer<MyConstants> CB;
```

In this case the buffer variables are reference as if they were members of the `ConstantBuffer` class: `CB.F`.

## Motivation

We need to support constant buffers in Clang as they are a fundamental part of the HLSL language.

## Proposed solution

### Parsing cbuffer/tbuffer declaration

In Clang frontend the `cbuffer` and `tbuffer` declarations will be parsed into a new AST Node called `HLSLConstantBufferDecl`. This class will be based on from `NameDecl` and `DeclContext`.

Variable declarations inside the `cbuffer` or `tbuffer` context will be children of this new AST node. If a variable declaration specifies a `packoffset`, this information will be parsed into an attribute `HLSLPackOffsetAttr` and applied to the variable declaration. See [packoffset attribute](0003-packoffset.md).

In order to make the variables declared in constant buffer exposed into global scope we can take advantage of `DeclContext::isTransparentContext` and make sure it is true for `HLSLConstantBufferDecl`.

Because the syntax similarities the`tbuffer` declaration will also be using `HLSLConstantBufferDecl` AST node. The method `isCBuffer()` can be used to determine which kind of constant buffer the declaration represents.

*Note: This is already implemented in Clang as `HLSLBufferDecl`. Since constant buffers are not the only buffers in HLSL we should rename it to `HLSLConstantBufferDecl`.*

*Q: Does resource handle with typed attributes come into play here at all?*

### Parsing ConstantBuffer/TextureBuffer declaration

`ConstantBuffer`/`TextureBuffer` will be added to the `HLSLExternalSemaSource` the same way other resource buffers are added. At the same time Clang needs to recognize these classes represents constant buffers.

One way to do that is to create `HLSLConstantBufferDecl` instance in addition to the `ConstantBuffer`, basically treating `ConstantBuffer<MyConstants> CB;` as `cbuffer CB { MyConstants CB; }`. The constant buffer declaration would need to keep track that is it based on `ConstantBuffer` declaration.

### Lowering cbuffer to LLVM IR

Constant buffers will be lowered to global variables with LLVM target type `target("dx.CBuffer", ..)`. In addition to the type name (`"dx.CBuffer"`) LLVM target types can also include a list of types and a list of integer constants. Any information needed for lowering to DXIL or SPIRV needs to be encoded using these parameters. To encode the shape of the constant buffers we can set the type parameter of the LLVM target type to be a struct with all of the buffer variable declarations.

For example:

```c++
cbuffer MyConstants {
float2 a;
float b[2];
int c;
}
```

Would be lowered to LLVM target type:

```
@MyConstants.cb = global target("dx.CBuffer", %struct.MyConstants = type { <2 x float>, [2 x float], int })
```

### Lowering ConstantBuffer to LLVM IR

The result of codegen for `cbuffer` and `ConstantBuffer` should be identical, or at least very close.

### Lowering `tbuffer` and `TextureBuffer` to LLVM IR

These should be lowered to `target("dx.TypedBuffer", ..)`.Detailed design TBD.

### Lowering constant buffer variable access
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm trying to understand how the layout rules for SPIR-V will work. The only real problem is cbuffers. There is a problem because cbuffers have a different layout than other buffer types, and I don't know how that will be represented in llvm-ir.

Here is the example I am thinking about: https://godbolt.org/z/f45r7vEoG.

In llvm-ir, will the load from the cbuffer be a single load of an object of type S with the cbuffer layout? Will the store to the structured buffer store an object of type S with the structured buffer layout? If the answer is yes to both, does there need to be a conversion from one to the other in between the load and store?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have just updated the document. We would like to include the cbuffer layout on the LLVM target type so the backend does not need to know the specific cbuffer layout rules. Alternatively, it could be a type annotation, but we would like to investigate the including in on the target type first. It probably does not answer your question though.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that the conversion from one to the other will look like an address space cast, or something like that. We'll need to make sure we aren't mixing raw memory operations between cbuffer memory and other resource memories, but as long as we have each type of thing in its own address space the boundaries themselves should be clear at least.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hekota Thanks. That answers part of my question and was in line with what I was thinking. The layout rules are a language feature. This is consistent with what I see in C/C++. The basic types are encoded in the data layout, and then the layout for the structs are set by being explicit with the padding in the struct.

@bogner I'll wait to see what you do. I don't see how the address space cast will work because that works on pointer, but we need to cast after the load. We also want to make sure that whatever we do, it can be easily optimized. In SPIRV there is an OpCopyLogical instruction to do the cast, when it cannot be optimized away.


The layout of constant buffers will be calculated during codegen in `CGHLSLRuntime`, which will also take into account `packoffset` attributes.

Access to `cbuffer` variables will be lowered to LLVM IR the same way as other resource types lower read-only access via subscript operator, except it will use the calculated layout offset. The constant value access would be translated into a memory access in a specific "resource address space" using the `cbuffer` global variable and offset.

### DXIL Lowering

Later, during lowering to DXIL, an LLVM pass would translate these specific "resource address space" memory accesses into `cbufferLoadLegacy` DXIL ops. This pass would take into account specific constant buffer layout rules (loading data one row at a time and extracing specific elements).

### Handle initialization

Constant buffers will be initialized the same way as other resources using the `createHandleFromBinding` intrinsics. Module initialization will need to be updated to initialize all the constant buffers declared in a shader in addition to initialization of resources declared in global variables.

### Constant buffers metadata

TBD

## Detailed design

*TBD*

## Alternatives considered (Optional)

Should we handle the constant buffer layout and `packoffset` later? Should we encode it int into the CBuffer LLVM target type?

## Links

[Shader Constants](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-constants)<br/>
[Packing Rules for Constant Variables](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-packing-rules)<br/>
[HLSL Constant Buffer Layout Visualizer](https://maraneshi.github.io/HLSL-ConstantBufferLayoutVisualizer)<br/>
[`packoffset` Attribute](0003-packoffset.md)

## Acknowledgments (Optional)