LLVM 24.0.0git
DXILResourceAccess.cpp
Go to the documentation of this file.
1//===- DXILResourceAccess.cpp - Resource access via load/store ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "DirectX.h"
11#include "llvm/ADT/DenseMap.h"
12#include "llvm/ADT/SetVector.h"
16#include "llvm/IR/BasicBlock.h"
17#include "llvm/IR/Dominators.h"
18#include "llvm/IR/IRBuilder.h"
19#include "llvm/IR/Instruction.h"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/IntrinsicsDirectX.h"
24#include "llvm/IR/LLVMContext.h"
25#include "llvm/IR/User.h"
26#include "llvm/IR/ValueHandle.h"
33#include <optional>
34
35#define DEBUG_TYPE "dxil-resource-access"
36
37using namespace llvm;
38
39[[noreturn]] static void
42 LLVMContext &Context = I->getContext();
43 std::string InstStr;
44 raw_string_ostream InstOS(InstStr);
45 I->print(InstOS);
46 Context.diagnose(
47 DiagnosticInfoGeneric("At resource access:" + Twine(InstStr), DS_Note));
48
49 for (auto *Handle : Handles) {
50 std::string HandleStr;
51 raw_string_ostream HandleOS(HandleStr);
52 Handle->print(HandleOS);
53 Context.diagnose(DiagnosticInfoGeneric(
54 "Uses resource handle:" + Twine(HandleStr), DS_Note));
55 }
57 "Resource access is not guaranteed to map to a unique global resource",
58 /*gen_crash_diag=*/false);
59}
60
62 Value *Ptr, uint64_t AccessSize) {
63 Value *Offset = nullptr;
64
65 while (Ptr) {
66 if ([[maybe_unused]] auto *II = dyn_cast<IntrinsicInst>(Ptr)) {
67 assert((II->getIntrinsicID() == Intrinsic::dx_resource_getpointer ||
68 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer) &&
69 "Resource access through unexpected intrinsic");
70 return Offset ? Offset : ConstantInt::get(Builder.getInt32Ty(), 0);
71 }
72
74 assert(GEP && "Resource access through unexpected instruction");
75
76 unsigned NumIndices = GEP->getNumIndices();
77 uint64_t IndexScale = DL.getTypeAllocSize(GEP->getSourceElementType());
78 APInt ConstantOffset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
79 Value *GEPOffset;
80 if (GEP->accumulateConstantOffset(DL, ConstantOffset)) {
81 // We have a constant offset (in bytes).
82 GEPOffset =
83 ConstantInt::get(DL.getIndexType(GEP->getType()), ConstantOffset);
84 IndexScale = 1;
85 } else if (NumIndices == 1) {
86 // If we have a single index we're indexing into a top level array. This
87 // generally only happens with cbuffers.
88 GEPOffset = *GEP->idx_begin();
89 } else if (NumIndices == 2) {
90 // If we have two indices, this should be an access through a pointer.
91 auto *IndexIt = GEP->idx_begin();
92 assert(cast<ConstantInt>(IndexIt)->getZExtValue() == 0 &&
93 "GEP is not indexing through pointer");
94 GEPOffset = *(++IndexIt);
95 } else
96 llvm_unreachable("Unhandled GEP structure for resource access");
97
98 uint64_t ElemSize = AccessSize;
99 if (!(IndexScale % ElemSize)) {
100 // If our scale is an exact multiple of the access size, adjust the
101 // scaling to avoid an unnecessary division.
102 IndexScale /= ElemSize;
103 ElemSize = 1;
104 }
105 if (IndexScale != 1)
106 GEPOffset = Builder.CreateMul(
107 GEPOffset, ConstantInt::get(Builder.getInt32Ty(), IndexScale));
108 if (ElemSize != 1)
109 GEPOffset = Builder.CreateUDiv(
110 GEPOffset, ConstantInt::get(Builder.getInt32Ty(), ElemSize));
111
112 Offset = Offset ? Builder.CreateAdd(Offset, GEPOffset) : GEPOffset;
113 Ptr = GEP->getPointerOperand();
114 }
115
116 llvm_unreachable("GEP of null pointer?");
117}
118
121 const DataLayout &DL = SI->getDataLayout();
122 IRBuilder<> Builder(SI);
123 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
124 Type *ScalarType = ContainedType->getScalarType();
125 Type *LoadType = StructType::get(ContainedType, Builder.getInt1Ty());
126
127 Value *V = SI->getValueOperand();
128 if (V->getType() == ContainedType) {
129 // V is already the right type.
130 assert(SI->getPointerOperand() == II &&
131 "Store of whole element has mismatched address to store to");
132 } else if (V->getType() == ScalarType) {
133 // We're storing a scalar, so we need to load the current value and only
134 // replace the relevant part.
135 auto *Load = Builder.CreateIntrinsic(
136 LoadType, Intrinsic::dx_resource_load_typedbuffer,
137 {II->getOperand(0), II->getOperand(1)});
138 auto *Struct = Builder.CreateExtractValue(Load, {0});
139
140 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
141 Value *Offset =
142 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
143 V = Builder.CreateInsertElement(Struct, V, Offset);
144 } else {
145 llvm_unreachable("Store to typed resource has invalid type");
146 }
147
148 auto *Inst = Builder.CreateIntrinsic(
149 Builder.getVoidTy(), Intrinsic::dx_resource_store_typedbuffer,
150 {II->getOperand(0), II->getOperand(1), V});
151 SI->replaceAllUsesWith(Inst);
152}
153
154/// Build a zero-initialized offset operand matching the shape of the given
155/// coordinate operand. Accesses through `operator[]` never have offsets.
156static Value *getNullOffsetsFor(IRBuilder<> &Builder, Value *Coords) {
157 Type *CoordTy = Coords->getType();
158 Type *OffsetTy;
159 if (auto *VecTy = dyn_cast<FixedVectorType>(CoordTy))
160 OffsetTy =
161 FixedVectorType::get(Builder.getInt32Ty(), VecTy->getNumElements());
162 else
163 OffsetTy = Builder.getInt32Ty();
164 return Constant::getNullValue(OffsetTy);
165}
166
169 const DataLayout &DL = SI->getDataLayout();
170 IRBuilder<> Builder(SI);
171 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
172 Type *ScalarType = ContainedType->getScalarType();
173
174 Value *Handle = II->getOperand(0);
175 Value *Coords = II->getOperand(1);
176
177 Value *V = SI->getValueOperand();
178 if (V->getType() == ContainedType) {
179 // V is already the right type.
180 assert(SI->getPointerOperand() == II &&
181 "Store of whole element has mismatched address to store to");
182 } else if (V->getType() == ScalarType) {
183 // We're storing a scalar, so we need to load the current value and only
184 // replace the relevant part. For operator[] the mip level and the offsets
185 // are always zero; DXILOpLowering drops the mip level for UAVs.
186 Value *MipLevel = Builder.getInt32(0);
187 Value *Offsets = getNullOffsetsFor(Builder, Coords);
188 auto *Load = Builder.CreateIntrinsic(ContainedType,
189 Intrinsic::dx_resource_load_level,
190 {Handle, Coords, MipLevel, Offsets});
191
192 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
193 Value *Offset =
194 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
195 V = Builder.CreateInsertElement(Load, V, Offset);
196 } else {
197 llvm_unreachable("Store to texture resource has invalid type");
198 }
199
200 auto *Inst = Builder.CreateIntrinsic(Builder.getVoidTy(),
201 Intrinsic::dx_resource_store_texture,
202 {Handle, Coords, V});
203 SI->replaceAllUsesWith(Inst);
204}
205
206static void emitRawStore(IRBuilder<> &Builder, Value *Buffer, Value *Index,
208 // For raw buffer (ie, HLSL's ByteAddressBuffer), we need to fold the access
209 // entirely into the index.
210 if (!RTI.isStruct()) {
211 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
212 if (!ConstantOffset || !ConstantOffset->isZero())
213 Index = Builder.CreateAdd(Index, Offset);
214 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
215 }
216
217 Builder.CreateIntrinsic(Builder.getVoidTy(),
218 Intrinsic::dx_resource_store_rawbuffer,
219 {Buffer, Index, Offset, V});
220}
221
224 const DataLayout &DL = SI->getDataLayout();
225 IRBuilder<> Builder(SI);
226
227 Value *V = SI->getValueOperand();
228 assert(!V->getType()->isAggregateType() &&
229 "Resource store should be scalar or vector type");
230
231 Value *Index = II->getOperand(1);
232 // The offset for the rawbuffer load and store ops is always in bytes.
233 uint64_t AccessSize = 1;
234 Value *Offset =
235 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
236
237 auto *VT = dyn_cast<FixedVectorType>(V->getType());
238 if (VT && VT->getNumElements() > 4) {
239 // Split into stores of at most 4 elements.
240 Type *EltTy = VT->getElementType();
241 Value *Stride = ConstantInt::get(Builder.getInt32Ty(),
242 4 * (DL.getTypeSizeInBits(EltTy) / 8));
243
244 SmallVector<int, 4> Indices;
245 for (unsigned int I = 0, N = VT->getNumElements(); I < N; I += 4) {
246 if (I > 0)
247 Offset = Builder.CreateAdd(Offset, Stride);
248
249 for (unsigned int J = I, E = std::min(N, J + 4); J < E; ++J)
250 Indices.push_back(J);
251 Value *Part = Builder.CreateShuffleVector(V, Indices);
252 emitRawStore(Builder, II->getOperand(0), Index, Offset, Part, RTI);
253
254 Indices.clear();
255 }
256 } else
257 emitRawStore(Builder, II->getOperand(0), Index, Offset, V, RTI);
258}
259
293
294static std::optional<dxil::AtomicBinOpCode>
334
335// Compute the (coord0, coord1) pair for a buffer resource atomic operation.
336// Non-struct buffers (RawBuffer or TypedBuffer) fold the byte offset into the
337// index and leave coord1 poison. Only StructuredBuffer atomics use both a
338// struct index and a byte offset.
339static std::pair<Value *, Value *>
341 dxil::ResourceTypeInfo &RTI, IRBuilder<> &Builder,
342 const DataLayout &DL) {
343 Value *Index = II->getOperand(1);
344
345 // The offset for the rawbuffer load/store/atomic ops is always in bytes.
346 uint64_t AccessSize = 1;
347 Value *Offset = traverseGEPOffsets(DL, Builder, PointerOperand, AccessSize);
348
349 if (!RTI.isStruct()) {
350 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
351 if (!ConstantOffset || !ConstantOffset->isZero())
352 Index = Builder.CreateAdd(Index, Offset);
353 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
354 }
355
356 return {Index, Offset};
357}
358
359// The coordinates of a texture access are a scalar or a vector with one element
360// per texture dimension, including the array slice if there is one. These map
361// directly onto the coordinate operands of the atomic ops.
363 IRBuilder<> &Builder) {
364 Value *Coords = II->getOperand(1);
365 SmallVector<Value *, 3> CoordArgs;
366 if (auto *VecTy = dyn_cast<FixedVectorType>(Coords->getType())) {
367 assert(VecTy->getNumElements() <= 3 && "Too many texture coordinates");
368 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I)
369 CoordArgs.push_back(Builder.CreateExtractElement(Coords, I));
370 } else {
371 CoordArgs.push_back(Coords);
372 }
373 return CoordArgs;
374}
375
376static void emitAtomicBinOp(IRBuilder<> &Builder, AtomicRMWInst *AI,
377 Value *Handle, ArrayRef<Value *> Coords) {
378 assert(!Coords.empty() && Coords.size() <= 3 &&
379 "Atomic operations take between one and three coordinates");
380
381 std::optional<dxil::AtomicBinOpCode> BinOpCode =
383 if (!BinOpCode) {
384 reportFatalUsageError("DXIL resource atomicrmw operation not implemented");
385 return;
386 }
387
388 // DXIL has no floating-point atomic op. A float exchange only moves the bit
389 // pattern, so cast the value to an integer of the same width, exchange, and
390 // cast the result back. This matches what DXC emits.
391 Value *Val = AI->getValOperand();
392 Type *ValTy = Val->getType();
393 Type *OpTy = ValTy;
394 if (ValTy->isFloatingPointTy()) {
395 OpTy = Builder.getIntNTy(ValTy->getPrimitiveSizeInBits());
396 Val = Builder.CreateBitCast(Val, OpTy);
397 }
398
400 Handle, Builder.getInt32(static_cast<uint32_t>(*BinOpCode))};
401 append_range(Args, Coords);
402 Args.append(3 - Coords.size(), PoisonValue::get(Builder.getInt32Ty()));
403 Args.push_back(Val);
404
405 // Emit the target-independent intrinsic; DXILOpLowering lowers it to the
406 // DXIL `AtomicBinOp` op and handles the target-ext-typed handle cast via
407 // its `createTmpHandleCast` bookkeeping.
408 Value *Result =
409 Builder.CreateIntrinsic(OpTy, Intrinsic::dx_resource_atomic_binop, Args);
410
411 if (OpTy != ValTy)
412 Result = Builder.CreateBitCast(Result, ValTy);
413
414 AI->replaceAllUsesWith(Result);
415}
416
419 const DataLayout &DL = AI->getDataLayout();
420 IRBuilder<> Builder(AI);
421 auto [Index, Offset] =
422 getAtomicResourceCoords(II, AI->getPointerOperand(), RTI, Builder, DL);
423
424 emitAtomicBinOp(Builder, AI, II->getOperand(0), {Index, Offset});
425}
426
429 // A texture atomic operates on a whole texel, so a multi-component texel has
430 // no single addressable component. A scalar float texel is allowed, because
431 // emitAtomicBinOp exchanges its bit pattern as an integer.
432 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
433 if (!ContainedType->isIntegerTy() && !ContainedType->isFloatingPointTy()) {
434 reportFatalUsageError("DXIL atomicrmw requires a texture resource with a "
435 "scalar element type");
436 return;
437 }
438
439 IRBuilder<> Builder(AI);
440
441 emitAtomicBinOp(Builder, AI, II->getOperand(0),
442 getTextureAtomicCoords(II, Builder));
443}
444
446 AtomicCmpXchgInst *AI, Value *Handle,
447 ArrayRef<Value *> Coords) {
448 assert(!Coords.empty() && Coords.size() <= 3 &&
449 "Atomic operations take between one and three coordinates");
450
451 Value *Compare = AI->getCompareOperand();
452 Value *NewValue = AI->getNewValOperand();
453
454 SmallVector<Value *, 6> Args{Handle};
455 append_range(Args, Coords);
456 Args.append(3 - Coords.size(), PoisonValue::get(Builder.getInt32Ty()));
457 Args.push_back(Compare);
458 Args.push_back(NewValue);
459
460 Value *Original = Builder.CreateIntrinsic(
461 NewValue->getType(), Intrinsic::dx_resource_atomic_compare_exchange,
462 Args);
463
464 // `cmpxchg` yields a { original, success } pair, but the DXIL op returns
465 // only the original value. DXIL has no way to express the success flag, and
466 // no HLSL builtin reads it, so replace the users of the pair directly
467 // instead of building it again. No pass after this one removes dead code.
469 for (User *U : AI->users()) {
470 auto *EV = dyn_cast<ExtractValueInst>(U);
471 if (!EV || EV->getIndices()[0] != 0)
472 reportFatalUsageError("DXIL cmpxchg provides only the original value");
473 Extracts.push_back(EV);
474 }
475
476 for (ExtractValueInst *EV : Extracts) {
477 EV->replaceAllUsesWith(Original);
478 EV->eraseFromParent();
479 }
480}
481
485 const DataLayout &DL = AI->getDataLayout();
486 IRBuilder<> Builder(AI);
487 auto [Index, Offset] =
488 getAtomicResourceCoords(II, AI->getPointerOperand(), RTI, Builder, DL);
489
490 emitAtomicCompareExchange(Builder, AI, II->getOperand(0), {Index, Offset});
491}
492
493// `cmpxchg` operands are always integers, so unlike atomicrmw there is no
494// float element type to convert here. The element type must be scalar.
498 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
499 if (!ContainedType->isIntegerTy() && !ContainedType->isFloatingPointTy()) {
500 reportFatalUsageError("DXIL cmpxchg requires a texture resource with a "
501 "scalar element type");
502 return;
503 }
504
505 IRBuilder<> Builder(AI);
506
507 emitAtomicCompareExchange(Builder, AI, II->getOperand(0),
508 getTextureAtomicCoords(II, Builder));
509}
510
513 switch (RTI.getResourceKind()) {
517 return createBufferAtomicBinOp(II, AI, RTI);
523 return createTextureAtomicBinOp(II, AI, RTI);
531 "DXIL atomicrmw not implemented for this texture resource kind");
532 return;
537 "DXIL atomicrmw not implemented for this resource type");
538 return;
542 llvm_unreachable("Invalid resource kind for atomicrmw");
543 }
544 llvm_unreachable("Unhandled case in switch");
545}
546
583
586 const DataLayout &DL = LI->getDataLayout();
587 IRBuilder<> Builder(LI);
588 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
589 Type *LoadType = StructType::get(ContainedType, Builder.getInt1Ty());
590
591 Value *V =
592 Builder.CreateIntrinsic(LoadType, Intrinsic::dx_resource_load_typedbuffer,
593 {II->getOperand(0), II->getOperand(1)});
594 V = Builder.CreateExtractValue(V, {0});
595
596 Type *ScalarType = ContainedType->getScalarType();
597 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
598 Value *Offset =
599 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
600 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
601 if (!ConstantOffset || !ConstantOffset->isZero())
602 V = Builder.CreateExtractElement(V, Offset);
603
604 // If we loaded a <1 x ...> instead of a scalar (presumably to feed a
605 // shufflevector), then make sure we're maintaining the resulting type.
606 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType()))
607 if (VT->getNumElements() == 1 && !isa<FixedVectorType>(V->getType()))
608 V = Builder.CreateInsertElement(PoisonValue::get(VT), V,
609 Builder.getInt32(0));
610
611 LI->replaceAllUsesWith(V);
612}
613
616 const DataLayout &DL = LI->getDataLayout();
617 IRBuilder<> Builder(LI);
618 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
619
620 Value *Handle = II->getOperand(0);
621 Value *Coords = II->getOperand(1);
622
623 // For operator[], mip level is 0.
624 Value *MipLevel = Builder.getInt32(0);
625
626 // For operator[], offsets are zero.
627 Value *Offsets = getNullOffsetsFor(Builder, Coords);
628
629 Value *V =
630 Builder.CreateIntrinsic(ContainedType, Intrinsic::dx_resource_load_level,
631 {Handle, Coords, MipLevel, Offsets});
632
633 Type *ScalarType = ContainedType->getScalarType();
634 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
635 Value *Offset =
636 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
637 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
638 if (!ConstantOffset || !ConstantOffset->isZero())
639 V = Builder.CreateExtractElement(V, Offset);
640
641 // If we loaded a <1 x ...> instead of a scalar (presumably to feed a
642 // shufflevector), then make sure we're maintaining the resulting type.
643 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType()))
644 if (VT->getNumElements() == 1 && !isa<FixedVectorType>(V->getType()))
645 V = Builder.CreateInsertElement(PoisonValue::get(VT), V,
646 Builder.getInt32(0));
647
648 LI->replaceAllUsesWith(V);
649}
650
651static Value *emitRawLoad(IRBuilder<> &Builder, Type *Ty, Value *Buffer,
652 Value *Index, Value *Offset,
654 // For raw buffer (ie, HLSL's ByteAddressBuffer), we need to fold the access
655 // entirely into the index.
656 if (!RTI.isStruct()) {
657 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
658 if (!ConstantOffset || !ConstantOffset->isZero())
659 Index = Builder.CreateAdd(Index, Offset);
660 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
661 }
662
663 // The load intrinsic includes the bit for CheckAccessFullyMapped, so we need
664 // to add that to the return type.
665 Type *TypeWithCheck = StructType::get(Ty, Builder.getInt1Ty());
666 Value *V = Builder.CreateIntrinsic(TypeWithCheck,
667 Intrinsic::dx_resource_load_rawbuffer,
668 {Buffer, Index, Offset});
669 return Builder.CreateExtractValue(V, {0});
670}
671
674 const DataLayout &DL = LI->getDataLayout();
675 IRBuilder<> Builder(LI);
676
677 Value *Index = II->getOperand(1);
678 // The offset for the rawbuffer load and store ops is always in bytes.
679 uint64_t AccessSize = 1;
680 Value *Offset =
681 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
682
683 // TODO: We could make this handle aggregates by walking the structure and
684 // handling each field individually, but we don't ever generate code that
685 // would hit that so it seems superfluous.
686 assert(!LI->getType()->isAggregateType() &&
687 "Resource load should be scalar or vector type");
688
689 Value *V;
690 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType())) {
691 // Split into loads of at most 4 elements.
692 Type *EltTy = VT->getElementType();
693 Value *Stride = ConstantInt::get(Builder.getInt32Ty(),
694 4 * (DL.getTypeSizeInBits(EltTy) / 8));
695
697 for (unsigned int I = 0, N = VT->getNumElements(); I < N; I += 4) {
698 Type *Ty = FixedVectorType::get(EltTy, N - I < 4 ? N - I : 4);
699 if (I > 0)
700 Offset = Builder.CreateAdd(Offset, Stride);
701 Parts.push_back(
702 emitRawLoad(Builder, Ty, II->getOperand(0), Index, Offset, RTI));
703 }
704
705 V = Parts.size() > 1 ? concatenateVectors(Builder, Parts) : Parts[0];
706 } else
707 V = emitRawLoad(Builder, LI->getType(), II->getOperand(0), Index, Offset,
708 RTI);
709
710 LI->replaceAllUsesWith(V);
711}
712
713namespace {
714/// Helper for building a `load.cbufferrow` intrinsic given a simple type.
715struct CBufferRowIntrin {
716 Intrinsic::ID IID;
717 Type *RetTy;
718 unsigned int EltSize;
719 unsigned int NumElts;
720
721 CBufferRowIntrin(const DataLayout &DL, Type *Ty) {
722 assert(Ty == Ty->getScalarType() && "Expected scalar type");
723
724 switch (DL.getTypeSizeInBits(Ty)) {
725 case 16:
726 IID = Intrinsic::dx_resource_load_cbufferrow_8;
727 RetTy = StructType::get(Ty, Ty, Ty, Ty, Ty, Ty, Ty, Ty);
728 EltSize = 2;
729 NumElts = 8;
730 break;
731 case 32:
732 IID = Intrinsic::dx_resource_load_cbufferrow_4;
733 RetTy = StructType::get(Ty, Ty, Ty, Ty);
734 EltSize = 4;
735 NumElts = 4;
736 break;
737 case 64:
738 IID = Intrinsic::dx_resource_load_cbufferrow_2;
739 RetTy = StructType::get(Ty, Ty);
740 EltSize = 8;
741 NumElts = 2;
742 break;
743 default:
744 llvm_unreachable("Only 16, 32, and 64 bit types supported");
745 }
746 }
747};
748} // namespace
749
752 const DataLayout &DL = LI->getDataLayout();
753
754 Type *Ty = LI->getType();
755 assert(!isa<StructType>(Ty) && "Structs not handled yet");
756 CBufferRowIntrin Intrin(DL, Ty->getScalarType());
757
758 StringRef Name = LI->getName();
759 Value *Handle = II->getOperand(0);
760
761 IRBuilder<> Builder(LI);
762
763 ConstantInt *GlobalOffset =
764 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer
765 ? ConstantInt::get(Builder.getInt32Ty(), 0)
766 : dyn_cast<ConstantInt>(II->getOperand(1));
767 assert(GlobalOffset && "CBuffer getpointer index must be constant");
768
769 uint64_t GlobalOffsetVal = GlobalOffset->getZExtValue();
770 Value *CurrentRow = ConstantInt::get(
771 Builder.getInt32Ty(), GlobalOffsetVal / hlsl::CBufferRowSizeInBytes);
772 unsigned int CurrentIndex =
773 (GlobalOffsetVal % hlsl::CBufferRowSizeInBytes) / Intrin.EltSize;
774
775 // Every object in a cbuffer either fits in a row or is aligned to a row. This
776 // means that only the very last pointer access can point into a row.
777 auto *LastGEP = dyn_cast<GEPOperator>(LI->getPointerOperand());
778 if (!LastGEP) {
779 // If we don't have a GEP at all we're just accessing the resource through
780 // the result of getpointer directly.
781 assert(LI->getPointerOperand() == II &&
782 "Unexpected indirect access to resource without GEP");
783 } else {
784 Value *GEPOffset = traverseGEPOffsets(
785 DL, Builder, LastGEP->getPointerOperand(), hlsl::CBufferRowSizeInBytes);
786 CurrentRow = Builder.CreateAdd(GEPOffset, CurrentRow);
787
788 APInt ConstantOffset(DL.getIndexTypeSizeInBits(LastGEP->getType()), 0);
789 if (LastGEP->accumulateConstantOffset(DL, ConstantOffset)) {
790 APInt Remainder(DL.getIndexTypeSizeInBits(LastGEP->getType()),
792 APInt::udivrem(ConstantOffset, Remainder, ConstantOffset, Remainder);
793 CurrentRow = Builder.CreateAdd(
794 CurrentRow, ConstantInt::get(Builder.getInt32Ty(), ConstantOffset));
795 CurrentIndex += Remainder.udiv(Intrin.EltSize).getZExtValue();
796 } else {
797 assert(LastGEP->getNumIndices() == 1 &&
798 "Last GEP of cbuffer access is not array or struct access");
799 // We assume a non-constant access will be row-aligned. This is safe
800 // because arrays and structs are always row aligned, and accesses to
801 // vector elements will show up as a load of the vector followed by an
802 // extractelement.
803 CurrentRow = cast<ConstantInt>(CurrentRow)->isZero()
804 ? *LastGEP->idx_begin()
805 : Builder.CreateAdd(CurrentRow, *LastGEP->idx_begin());
806 CurrentIndex = 0;
807 }
808 }
809
810 auto *CBufLoad = Builder.CreateIntrinsic(
811 Intrin.RetTy, Intrin.IID, {Handle, CurrentRow}, nullptr, Name + ".load");
812 auto *Elt =
813 Builder.CreateExtractValue(CBufLoad, {CurrentIndex++}, Name + ".extract");
814
815 // At this point we've loaded the first scalar of our result, but our original
816 // type may have been a vector.
817 unsigned int Remaining =
818 ((DL.getTypeSizeInBits(Ty) / 8) / Intrin.EltSize) - 1;
819 if (Remaining == 0) {
820 // We only have a single element, so we're done.
821 Value *Result = Elt;
822
823 // However, if we loaded a <1 x T>, then we need to adjust the type.
824 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
825 assert(VT->getNumElements() == 1 && "Can't have multiple elements here");
826 Result = Builder.CreateInsertElement(PoisonValue::get(VT), Result,
827 Builder.getInt32(0), Name);
828 }
829 LI->replaceAllUsesWith(Result);
830 return;
831 }
832
833 // Walk each element and extract it, wrapping to new rows as needed.
834 SmallVector<Value *> Extracts{Elt};
835 while (Remaining--) {
836 CurrentIndex %= Intrin.NumElts;
837
838 if (CurrentIndex == 0) {
839 CurrentRow = Builder.CreateAdd(CurrentRow,
840 ConstantInt::get(Builder.getInt32Ty(), 1));
841 CBufLoad = Builder.CreateIntrinsic(Intrin.RetTy, Intrin.IID,
842 {Handle, CurrentRow}, nullptr,
843 Name + ".load");
844 }
845
846 Extracts.push_back(Builder.CreateExtractValue(CBufLoad, {CurrentIndex++},
847 Name + ".extract"));
848 }
849
850 // Finally, we build up the original loaded value.
851 Value *Result = PoisonValue::get(Ty);
852 for (int I = 0, E = Extracts.size(); I < E; ++I)
853 Result = Builder.CreateInsertElement(
854 Result, Extracts[I], Builder.getInt32(I), Name + formatv(".upto{}", I));
855 LI->replaceAllUsesWith(Result);
856}
857
891
893 if (auto *LI = dyn_cast<LoadInst>(AI))
894 return dyn_cast<Instruction>(LI->getPointerOperand());
895 if (auto *SI = dyn_cast<StoreInst>(AI))
896 return dyn_cast<Instruction>(SI->getPointerOperand());
897 if (auto *RMWI = dyn_cast<AtomicRMWInst>(AI))
898 return dyn_cast<Instruction>(RMWI->getPointerOperand());
899 if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(AI))
900 return dyn_cast<Instruction>(CXI->getPointerOperand());
901 if (auto *II = dyn_cast<IntrinsicInst>(AI))
902 if (II->getIntrinsicID() == Intrinsic::dx_resource_updatecounter)
903 return dyn_cast<Instruction>(II->getArgOperand(0));
904
905 return nullptr;
906}
907
908static const std::array<Intrinsic::ID, 2> HandleIntrins = {
909 Intrinsic::dx_resource_handlefrombinding,
910 Intrinsic::dx_resource_handlefromimplicitbinding,
911};
912
914 SmallVector<Value *> Worklist = {Ptr};
916 SmallPtrSet<Value *, 4> VisitedPhis;
917
918 while (!Worklist.empty()) {
919 Value *X = Worklist.pop_back_val();
920
921 if (!X->getType()->isPointerTy() && !X->getType()->isTargetExtTy())
922 return {}; // Early exit on store/load into non-resource
923
924 if (auto *Phi = dyn_cast<PHINode>(X)) {
925 if (VisitedPhis.contains(X))
926 continue;
927 for (Use &V : Phi->incoming_values())
928 Worklist.push_back(V.get());
929 VisitedPhis.insert(Phi);
930 } else if (auto *Select = dyn_cast<SelectInst>(X))
931 for (Value *V : {Select->getTrueValue(), Select->getFalseValue()})
932 Worklist.push_back(V);
933 else if (auto *II = dyn_cast<IntrinsicInst>(X)) {
934 Intrinsic::ID IID = II->getIntrinsicID();
935
936 if (IID == Intrinsic::dx_resource_getpointer)
937 Worklist.push_back(II->getArgOperand(/*Handle=*/0));
938
940 Handles.push_back(II);
941 }
942 }
943
944 return Handles;
945}
946
948 DXILResourceTypeMap &DRTM) {
950 "Only expects a Handle as determined from collectUsedHandles.");
951
952 auto *HandleTy = cast<TargetExtType>(Handle->getType());
953 dxil::ResourceClass Class = DRTM[HandleTy].getResourceClass();
954 uint32_t Space = cast<ConstantInt>(Handle->getArgOperand(0))->getZExtValue();
955 uint32_t LowerBound =
956 cast<ConstantInt>(Handle->getArgOperand(1))->getZExtValue();
957 uint32_t Size = cast<ConstantInt>(Handle->getArgOperand(2))->getZExtValue();
958 uint32_t UpperBound = Size == UINT32_MAX ? UINT32_MAX : LowerBound + Size - 1;
959
960 return hlsl::Binding(Class, Space, LowerBound, UpperBound, nullptr);
961}
962
963namespace {
964/// Helper for propagating the current handle and ptr indices.
965struct AccessIndices {
966 Value *GetPtrIdx;
967 Value *HandleIdx;
968
969 bool hasGetPtrIdx() { return GetPtrIdx != nullptr; }
970 bool hasHandleIdx() { return HandleIdx != nullptr; }
971};
972} // namespace
973
974// getAccessIndices traverses up the control flow that a ptr came from and
975// propagates back the indicies used to access the resource (AccessIndices):
976//
977// - GetPtrIdx is the index of dx.resource.getpointer
978// - HandleIdx is the index of dx.resource.handlefrom.*
979static AccessIndices
982 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
983 if (llvm::is_contained(HandleIntrins, II->getIntrinsicID())) {
984 DeadInsts.insert(II);
985 return {nullptr, II->getArgOperand(/*Index=*/3)};
986 }
987
988 if (II->getIntrinsicID() == Intrinsic::dx_resource_getpointer) {
989 auto *V = dyn_cast<Instruction>(II->getArgOperand(/*Handle=*/0));
990 auto AccessIdx = getAccessIndices(V, DeadInsts, VisitedPhis);
991 assert(!AccessIdx.hasGetPtrIdx() &&
992 "Encountered multiple dx.resource.getpointers in ptr chain?");
993 AccessIdx.GetPtrIdx = II->getArgOperand(1);
994
995 DeadInsts.insert(II);
996 return AccessIdx;
997 }
998 }
999
1000 if (auto *Phi = dyn_cast<PHINode>(I)) {
1001 // If we're already building indices for this phi, return a ref to the phi
1002 if (auto It = VisitedPhis.find(Phi); It != VisitedPhis.end())
1003 return {nullptr, It->second};
1004
1005 unsigned NumEdges = Phi->getNumIncomingValues();
1006 assert(NumEdges != 0 && "Malformed Phi Node");
1007
1008 IRBuilder<> Builder(Phi);
1009 std::unique_ptr<PHINode> GetPtrPhi(
1010 PHINode::Create(Builder.getInt32Ty(), NumEdges));
1011 std::unique_ptr<PHINode> HandlePhi(
1012 PHINode::Create(Builder.getInt32Ty(), NumEdges));
1013
1014 // Register a ref to this phi for a recursive phi. This is safe to add to
1015 // the map even if we end up deleting newly created phi below since we can't
1016 // possibly have a constant value if we recursed.
1017 if (Phi->getType()->isTargetExtTy())
1018 VisitedPhis[Phi] = HandlePhi.get();
1019
1020 for (unsigned Idx = 0; Idx < NumEdges; Idx++) {
1021 auto *BB = Phi->getIncomingBlock(Idx);
1022 auto *V = dyn_cast<Instruction>(Phi->getIncomingValue(Idx));
1023 auto AccessIdx = getAccessIndices(V, DeadInsts, VisitedPhis);
1024 if (AccessIdx.hasGetPtrIdx())
1025 GetPtrPhi->addIncoming(AccessIdx.GetPtrIdx, BB);
1026 HandlePhi->addIncoming(AccessIdx.HandleIdx, BB);
1027 }
1028
1029 Value *GetPtrIdx;
1030 if (GetPtrPhi->getNumIncomingValues() == 0)
1031 GetPtrIdx = nullptr;
1032 else if (Value *ConstantGetPtr = GetPtrPhi->hasConstantValue())
1033 GetPtrIdx = ConstantGetPtr;
1034 else {
1035 GetPtrIdx = GetPtrPhi.release();
1036 Builder.Insert(GetPtrIdx);
1037 }
1038
1039 Value *HandleIdx;
1040 if (Value *ConstantHandle = HandlePhi->hasConstantValue())
1041 HandleIdx = ConstantHandle;
1042 else {
1043 HandleIdx = HandlePhi.release();
1044 Builder.Insert(HandleIdx);
1045 }
1046
1047 DeadInsts.insert(Phi);
1048 return {GetPtrIdx, HandleIdx};
1049 }
1050
1051 if (auto *Select = dyn_cast<SelectInst>(I)) {
1052 auto *TrueV = dyn_cast<Instruction>(Select->getTrueValue());
1053 auto TrueAccessIdx = getAccessIndices(TrueV, DeadInsts, VisitedPhis);
1054
1055 auto *FalseV = dyn_cast<Instruction>(Select->getFalseValue());
1056 auto FalseAccessIdx = getAccessIndices(FalseV, DeadInsts, VisitedPhis);
1057
1058 IRBuilder<> Builder(Select);
1059 Value *GetPtrSelect = nullptr;
1060
1061 if (TrueAccessIdx.hasGetPtrIdx() && FalseAccessIdx.hasGetPtrIdx())
1062 GetPtrSelect =
1063 Builder.CreateSelect(Select->getCondition(), TrueAccessIdx.GetPtrIdx,
1064 FalseAccessIdx.GetPtrIdx);
1065
1066 auto *HandleSelect =
1067 Builder.CreateSelect(Select->getCondition(), TrueAccessIdx.HandleIdx,
1068 FalseAccessIdx.HandleIdx);
1069 DeadInsts.insert(Select);
1070 return {GetPtrSelect, HandleSelect};
1071 }
1072
1073 llvm_unreachable("collectUsedHandles should assure this does not occur");
1074}
1075
1076static void
1080 auto AccessIdx = getAccessIndices(Ptr, DeadInsts, VisitedPhis);
1081 assert(AccessIdx.hasHandleIdx() &&
1082 "Couldn't retrieve handle index. This is guaranteed by "
1083 "getAccessIndices");
1084
1085 IRBuilder<> Builder(Ptr);
1086 if (isa<PHINode>(Ptr))
1087 Builder.SetInsertPoint(Ptr->getParent()->getFirstNonPHIIt());
1088 IntrinsicInst *Handle = cast<IntrinsicInst>(OldHandle->clone());
1089 Handle->setArgOperand(/*Index=*/3, AccessIdx.HandleIdx);
1090 Builder.Insert(Handle);
1091
1092 if (Ptr->getType()->isPointerTy()) {
1093 assert(AccessIdx.hasGetPtrIdx() &&
1094 "Couldn't retrieve getpointer index. This is guaranteed by "
1095 "getAccessIndices");
1096 auto *GetPtr = Builder.CreateIntrinsic(Ptr->getType(),
1097 Intrinsic::dx_resource_getpointer,
1098 {Handle, AccessIdx.GetPtrIdx});
1099 Ptr->replaceAllUsesWith(GetPtr);
1100 } else {
1101 assert(Ptr->getType()->isTargetExtTy() && !AccessIdx.hasGetPtrIdx() &&
1102 "Unexpected resource access operand type");
1103 Ptr->replaceAllUsesWith(Handle);
1104 }
1105
1106 DeadInsts.insert(Ptr);
1107}
1108
1109// Try to legalize dx.resource.handlefrom.*.binding and dx.resource.getpointer
1110// calls with their respective index values and propagate the index values to
1111// be used at resource access.
1112//
1113// If it can't be transformed to be legal then:
1114//
1115// Reports an error if a resource access is not guaranteed into a unique global
1116// resource.
1117//
1118// Returns true if any changes are made.
1122
1123 for (BasicBlock &BB : make_early_inc_range(F)) {
1124 for (Instruction &I : BB) {
1125 if (auto *HandleOp = getHandleOperand(&I)) {
1127 unsigned NumHandles = Handles.size();
1128 if (NumHandles <= 1)
1129 continue; // Legal, no-replacement required
1130
1131 bool SameGlobalBinding = true;
1132 hlsl::Binding B = getHandleIntrinsicBinding(Handles[0], DRTM);
1133 for (unsigned Idx = 1; Idx < NumHandles; Idx++)
1134 SameGlobalBinding &=
1135 (B == getHandleIntrinsicBinding(Handles[Idx], DRTM));
1136
1137 if (!SameGlobalBinding)
1139
1140 replaceHandleWithIndices(HandleOp, Handles[0], DeadInsts, VisitedPhis);
1141 }
1142 }
1143 }
1144
1145 bool MadeChanges = false;
1146
1147 // Set up the phis to track if they are erased below
1148 SmallVector<WeakTrackingVH> ResourcePhis;
1149 for (const auto &HandleToIndex : VisitedPhis)
1150 ResourcePhis.push_back(HandleToIndex.first);
1151
1152 for (auto *I : llvm::reverse(DeadInsts))
1153 if (I->hasNUses(0)) { // Handle can still be used outside of replaced path
1154 I->eraseFromParent();
1155 MadeChanges = true;
1156 }
1157
1158 // Any remaining phi nodes are now looped with another phi node and have no
1159 // other uses
1160 for (WeakTrackingVH &VH : ResourcePhis)
1161 if (VH) // True if not removed above or already in this loop
1162 MadeChanges |= RecursivelyDeleteDeadPHINode(cast<PHINode>(VH));
1163
1164 return MadeChanges;
1165}
1166
1168 SmallVector<User *> Worklist;
1169 for (User *U : II->users())
1170 Worklist.push_back(U);
1171
1173 while (!Worklist.empty()) {
1174 User *U = Worklist.back();
1175 Worklist.pop_back();
1176
1177 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
1178 for (User *U : GEP->users())
1179 Worklist.push_back(U);
1180 DeadInsts.push_back(GEP);
1181
1182 } else if (auto *SI = dyn_cast<StoreInst>(U)) {
1183 assert(SI->getValueOperand() != II && "Pointer escaped!");
1184 createStoreIntrinsic(II, SI, RTI);
1185 DeadInsts.push_back(SI);
1186
1187 } else if (auto *LI = dyn_cast<LoadInst>(U)) {
1188 createLoadIntrinsic(II, LI, RTI);
1189 DeadInsts.push_back(LI);
1190 } else if (auto *AI = dyn_cast<AtomicRMWInst>(U)) {
1192 DeadInsts.push_back(AI);
1193 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(U)) {
1195 DeadInsts.push_back(CXI);
1196 } else
1197 llvm_unreachable("Unhandled instruction - pointer escaped?");
1198 }
1199
1200 // Traverse the now-dead instructions in RPO and remove them.
1201 for (Instruction *Dead : llvm::reverse(DeadInsts))
1202 Dead->eraseFromParent();
1203 II->eraseFromParent();
1204}
1205
1208 for (BasicBlock &BB : make_early_inc_range(F))
1209 for (Instruction &I : BB)
1210 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1211 if (II->getIntrinsicID() == Intrinsic::dx_resource_getpointer ||
1212 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer) {
1213 auto *HandleTy = cast<TargetExtType>(II->getArgOperand(0)->getType());
1214 assert(
1215 (DRTM[HandleTy].isCBuffer() ||
1216 II->getIntrinsicID() != Intrinsic::dx_resource_getbasepointer) &&
1217 "dx_resource_getbasepointer should only be used by cbuffers");
1218 Resources.emplace_back(II, DRTM[HandleTy]);
1219 }
1220
1221 for (auto &[II, RI] : Resources)
1222 replaceAccess(II, RI);
1223
1224 return !Resources.empty();
1225}
1226
1229 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1230 DXILResourceTypeMap *DRTM =
1231 MAMProxy.getCachedResult<DXILResourceTypeAnalysis>(*F.getParent());
1232 assert(DRTM && "DXILResourceTypeAnalysis must be available");
1233
1234 bool MadeHandleChanges = legalizeResourceHandles(F, *DRTM);
1235 bool MadeResourceChanges = transformResourcePointers(F, *DRTM);
1236 if (!(MadeHandleChanges || MadeResourceChanges))
1237 return PreservedAnalyses::all();
1238
1242 return PA;
1243}
1244
1245namespace {
1246class DXILResourceAccessLegacy : public FunctionPass {
1247public:
1248 bool runOnFunction(Function &F) override {
1249 DXILResourceTypeMap &DRTM =
1250 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
1251 bool MadeHandleChanges = legalizeResourceHandles(F, DRTM);
1252 bool MadeResourceChanges = transformResourcePointers(F, DRTM);
1253 return MadeHandleChanges || MadeResourceChanges;
1254 }
1255 StringRef getPassName() const override { return "DXIL Resource Access"; }
1256 DXILResourceAccessLegacy() : FunctionPass(ID) {}
1257
1258 static char ID; // Pass identification.
1259 void getAnalysisUsage(llvm::AnalysisUsage &AU) const override {
1260 AU.addRequired<DXILResourceTypeWrapperPass>();
1261 AU.addPreserved<DominatorTreeWrapperPass>();
1262 }
1263};
1264char DXILResourceAccessLegacy::ID = 0;
1265} // end anonymous namespace
1266
1267INITIALIZE_PASS_BEGIN(DXILResourceAccessLegacy, DEBUG_TYPE,
1268 "DXIL Resource Access", false, false)
1270INITIALIZE_PASS_END(DXILResourceAccessLegacy, DEBUG_TYPE,
1271 "DXIL Resource Access", false, false)
1272
1274 return new DXILResourceAccessLegacy();
1275}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
DXIL Remove Unused Resources
static void diagnoseNonUniqueResourceAccess(Instruction *I, ArrayRef< IntrinsicInst * > Handles)
static AccessIndices getAccessIndices(Instruction *I, SmallSetVector< Instruction *, 16 > &DeadInsts, SmallDenseMap< PHINode *, PHINode * > &VisitedPhis)
static std::optional< dxil::AtomicBinOpCode > getAtomicBinOpCode(AtomicRMWInst::BinOp BinOp)
static void createLoadIntrinsic(IntrinsicInst *II, LoadInst *LI, dxil::ResourceTypeInfo &RTI)
static void createTextureStore(IntrinsicInst *II, StoreInst *SI, dxil::ResourceTypeInfo &RTI)
static Value * emitRawLoad(IRBuilder<> &Builder, Type *Ty, Value *Buffer, Value *Index, Value *Offset, dxil::ResourceTypeInfo &RTI)
static void emitAtomicCompareExchange(IRBuilder<> &Builder, AtomicCmpXchgInst *AI, Value *Handle, ArrayRef< Value * > Coords)
static bool legalizeResourceHandles(Function &F, DXILResourceTypeMap &DRTM)
static void createTypedBufferLoad(IntrinsicInst *II, LoadInst *LI, dxil::ResourceTypeInfo &RTI)
static void createTypedBufferStore(IntrinsicInst *II, StoreInst *SI, dxil::ResourceTypeInfo &RTI)
static SmallVector< IntrinsicInst * > collectUsedHandles(Value *Ptr)
static const std::array< Intrinsic::ID, 2 > HandleIntrins
static bool transformResourcePointers(Function &F, DXILResourceTypeMap &DRTM)
static void createTextureLoad(IntrinsicInst *II, LoadInst *LI, dxil::ResourceTypeInfo &RTI)
static void emitRawStore(IRBuilder<> &Builder, Value *Buffer, Value *Index, Value *Offset, Value *V, dxil::ResourceTypeInfo &RTI)
static Value * getNullOffsetsFor(IRBuilder<> &Builder, Value *Coords)
Build a zero-initialized offset operand matching the shape of the given coordinate operand.
static void createBufferAtomicCompareExchange(IntrinsicInst *II, AtomicCmpXchgInst *AI, dxil::ResourceTypeInfo &RTI)
static void replaceHandleWithIndices(Instruction *Ptr, IntrinsicInst *OldHandle, SmallSetVector< Instruction *, 16 > &DeadInsts, SmallDenseMap< PHINode *, PHINode * > &VisitedPhis)
static Value * traverseGEPOffsets(const DataLayout &DL, IRBuilder<> &Builder, Value *Ptr, uint64_t AccessSize)
static void createBufferAtomicBinOp(IntrinsicInst *II, AtomicRMWInst *AI, dxil::ResourceTypeInfo &RTI)
static hlsl::Binding getHandleIntrinsicBinding(IntrinsicInst *Handle, DXILResourceTypeMap &DRTM)
static void createStoreIntrinsic(IntrinsicInst *II, StoreInst *SI, dxil::ResourceTypeInfo &RTI)
static void createCBufferLoad(IntrinsicInst *II, LoadInst *LI, dxil::ResourceTypeInfo &RTI)
static std::pair< Value *, Value * > getAtomicResourceCoords(IntrinsicInst *II, Value *PointerOperand, dxil::ResourceTypeInfo &RTI, IRBuilder<> &Builder, const DataLayout &DL)
static void createRawStores(IntrinsicInst *II, StoreInst *SI, dxil::ResourceTypeInfo &RTI)
static SmallVector< Value *, 3 > getTextureAtomicCoords(IntrinsicInst *II, IRBuilder<> &Builder)
static void createTextureAtomicBinOp(IntrinsicInst *II, AtomicRMWInst *AI, dxil::ResourceTypeInfo &RTI)
static void emitAtomicBinOp(IRBuilder<> &Builder, AtomicRMWInst *AI, Value *Handle, ArrayRef< Value * > Coords)
static void createRawLoads(IntrinsicInst *II, LoadInst *LI, dxil::ResourceTypeInfo &RTI)
static void createAtomicCompareExchangeIntrinsic(IntrinsicInst *II, AtomicCmpXchgInst *AI, dxil::ResourceTypeInfo &RTI)
static void createAtomicBinOpIntrinsic(IntrinsicInst *II, AtomicRMWInst *AI, dxil::ResourceTypeInfo &RTI)
static Instruction * getHandleOperand(Instruction *AI)
static void createTextureAtomicCompareExchange(IntrinsicInst *II, AtomicCmpXchgInst *AI, dxil::ResourceTypeInfo &RTI)
static void replaceAccess(IntrinsicInst *II, dxil::ResourceTypeInfo &RTI)
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Hexagon Common GEP
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file implements a set that has insertion order iteration characteristics.
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
Value * getPointerOperand()
BinOp getOperation() const
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
iterator end()
Definition DenseMap.h:687
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
This instruction extracts a struct member or array element value from an aggregate value.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2918
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
iterator_range< user_iterator > users()
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Value * getPointerOperand()
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:467
Type * getTypeParameter(unsigned i) const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isTargetExtTy() const
Return true if this is a target extension type.
Definition Type.h:205
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:314
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
Value handle that is nullable, but tries to track the Value.
TargetExtType * getHandleTy() const
LLVM_ABI bool isStruct() const
dxil::ResourceKind getResourceKind() const
const ParentTy * getParent() const
Definition ilist_node.h:34
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const unsigned CBufferRowSizeInBytes
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
@ Dead
Unused definition.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
FunctionPass * createDXILResourceAccessLegacyPass()
Pass to update resource accesses to use load/store directly.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition Local.cpp:626
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N