<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/144573>144573</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[DirectX] Accessing a cbuffer array with a dynamic index hits an assertion error or generates incorrect code
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
Icohedron
</td>
</tr>
</table>
<pre>
Compiling the following shader results in an assertion error (if compiled with assertions enabled) or incorrect code generated (if no assertions are enabled) when compiled under clang: https://godbolt.org/z/5Yszfrx1K
`clang-dxc -E CSMain -T cs_6_2 -enable-16bit-types`
```hlsl
RWStructuredBuffer<uint32_t> output;
cbuffer Constants {
uint32_t v[2];
}
[numthreads(1, 1, 1)]
void CSMain(uint3 Tid : SV_DispatchThreadID) {
output[Tid.x] = v[Tid.x];
}
```
```
clang-dxc: /workspace/llvm-project/llvm/lib/Target/DirectX/DXILCBufferAccess.cpp:69: size_t getOffsetForCBufferGEP(GEPOperator *, GlobalVariable *, const DataLayout &): Assertion `Success && "Offsets into cbuffer globals must be constant"' failed.
```
https://github.com/llvm/llvm-project/blob/9e0186d925f0c375a627866c59394f25c22eb3ff/llvm/lib/Target/DirectX/DXILCBufferAccess.cpp#L69
The generated DXIL has the following incorrect cbuffer load instruction which always loads from index 0 instead of the thread id.
```
%3 = call i32 @dx.op.threadId.i32(i32 93, i32 0) #2
%4 = call %dx.types.CBufRet.i32 @dx.op.cbufferLoadLegacy.i32(i32 59, %dx.types.Handle %2, i32 0) #1, !dbg !101
```
The same shader will successfully compile and validate under dxc.
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJycVU1v4zYT_jX0ZWBBGpmydfDBH_G-wZtiFxtjuz0FFElZbGnSIKnYzq8vqI_E8fbSAoI0IueLM88zZN6rg5FySeia0O2EtaGxbvnIbSOFs2ZSWXFdbuzxpLQyBwiNhNpqbc_xzzd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