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"
13#include "llvm/ADT/SmallSet.h"
17#include "llvm/IR/BasicBlock.h"
18#include "llvm/IR/Dominators.h"
19#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/Instruction.h"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/IntrinsicsDirectX.h"
25#include "llvm/IR/LLVMContext.h"
26#include "llvm/IR/User.h"
27#include "llvm/IR/ValueHandle.h"
33#include <optional>
34
35#define DEBUG_TYPE "dxil-resource-access"
36
37using namespace llvm;
38
41 LLVMContext &Context = I->getContext();
42 std::string InstStr;
43 raw_string_ostream InstOS(InstStr);
44 I->print(InstOS);
45 Context.diagnose(
46 DiagnosticInfoGeneric("At resource access:" + Twine(InstStr), DS_Note));
47
48 for (auto *Handle : Handles) {
49 std::string HandleStr;
50 raw_string_ostream HandleOS(HandleStr);
51 Handle->print(HandleOS);
52 Context.diagnose(DiagnosticInfoGeneric(
53 "Uses resource handle:" + Twine(HandleStr), DS_Note));
54 }
55 Context.diagnose(DiagnosticInfoGeneric(
56 "Resource access is not guaranteed to map to a unique global resource"));
57}
58
60 Value *Ptr, uint64_t AccessSize) {
61 Value *Offset = nullptr;
62
63 while (Ptr) {
64 if ([[maybe_unused]] auto *II = dyn_cast<IntrinsicInst>(Ptr)) {
65 assert((II->getIntrinsicID() == Intrinsic::dx_resource_getpointer ||
66 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer) &&
67 "Resource access through unexpected intrinsic");
68 return Offset ? Offset : ConstantInt::get(Builder.getInt32Ty(), 0);
69 }
70
72 assert(GEP && "Resource access through unexpected instruction");
73
74 unsigned NumIndices = GEP->getNumIndices();
75 uint64_t IndexScale = DL.getTypeAllocSize(GEP->getSourceElementType());
76 APInt ConstantOffset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
77 Value *GEPOffset;
78 if (GEP->accumulateConstantOffset(DL, ConstantOffset)) {
79 // We have a constant offset (in bytes).
80 GEPOffset =
81 ConstantInt::get(DL.getIndexType(GEP->getType()), ConstantOffset);
82 IndexScale = 1;
83 } else if (NumIndices == 1) {
84 // If we have a single index we're indexing into a top level array. This
85 // generally only happens with cbuffers.
86 GEPOffset = *GEP->idx_begin();
87 } else if (NumIndices == 2) {
88 // If we have two indices, this should be an access through a pointer.
89 auto *IndexIt = GEP->idx_begin();
90 assert(cast<ConstantInt>(IndexIt)->getZExtValue() == 0 &&
91 "GEP is not indexing through pointer");
92 GEPOffset = *(++IndexIt);
93 } else
94 llvm_unreachable("Unhandled GEP structure for resource access");
95
96 uint64_t ElemSize = AccessSize;
97 if (!(IndexScale % ElemSize)) {
98 // If our scale is an exact multiple of the access size, adjust the
99 // scaling to avoid an unnecessary division.
100 IndexScale /= ElemSize;
101 ElemSize = 1;
102 }
103 if (IndexScale != 1)
104 GEPOffset = Builder.CreateMul(
105 GEPOffset, ConstantInt::get(Builder.getInt32Ty(), IndexScale));
106 if (ElemSize != 1)
107 GEPOffset = Builder.CreateUDiv(
108 GEPOffset, ConstantInt::get(Builder.getInt32Ty(), ElemSize));
109
110 Offset = Offset ? Builder.CreateAdd(Offset, GEPOffset) : GEPOffset;
111 Ptr = GEP->getPointerOperand();
112 }
113
114 llvm_unreachable("GEP of null pointer?");
115}
116
119 const DataLayout &DL = SI->getDataLayout();
120 IRBuilder<> Builder(SI);
121 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
122 Type *ScalarType = ContainedType->getScalarType();
123 Type *LoadType = StructType::get(ContainedType, Builder.getInt1Ty());
124
125 Value *V = SI->getValueOperand();
126 if (V->getType() == ContainedType) {
127 // V is already the right type.
128 assert(SI->getPointerOperand() == II &&
129 "Store of whole element has mismatched address to store to");
130 } else if (V->getType() == ScalarType) {
131 // We're storing a scalar, so we need to load the current value and only
132 // replace the relevant part.
133 auto *Load = Builder.CreateIntrinsic(
134 LoadType, Intrinsic::dx_resource_load_typedbuffer,
135 {II->getOperand(0), II->getOperand(1)});
136 auto *Struct = Builder.CreateExtractValue(Load, {0});
137
138 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
139 Value *Offset =
140 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
141 V = Builder.CreateInsertElement(Struct, V, Offset);
142 } else {
143 llvm_unreachable("Store to typed resource has invalid type");
144 }
145
146 auto *Inst = Builder.CreateIntrinsic(
147 Builder.getVoidTy(), Intrinsic::dx_resource_store_typedbuffer,
148 {II->getOperand(0), II->getOperand(1), V});
149 SI->replaceAllUsesWith(Inst);
150}
151
152/// Build a zero-initialized offset operand matching the shape of the given
153/// coordinate operand. Accesses through `operator[]` never have offsets.
154static Value *getNullOffsetsFor(IRBuilder<> &Builder, Value *Coords) {
155 Type *CoordTy = Coords->getType();
156 Type *OffsetTy;
157 if (auto *VecTy = dyn_cast<FixedVectorType>(CoordTy))
158 OffsetTy =
159 FixedVectorType::get(Builder.getInt32Ty(), VecTy->getNumElements());
160 else
161 OffsetTy = Builder.getInt32Ty();
162 return Constant::getNullValue(OffsetTy);
163}
164
167 const DataLayout &DL = SI->getDataLayout();
168 IRBuilder<> Builder(SI);
169 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
170 Type *ScalarType = ContainedType->getScalarType();
171
172 Value *Handle = II->getOperand(0);
173 Value *Coords = II->getOperand(1);
174
175 Value *V = SI->getValueOperand();
176 if (V->getType() == ContainedType) {
177 // V is already the right type.
178 assert(SI->getPointerOperand() == II &&
179 "Store of whole element has mismatched address to store to");
180 } else if (V->getType() == ScalarType) {
181 // We're storing a scalar, so we need to load the current value and only
182 // replace the relevant part. For operator[] the mip level and the offsets
183 // are always zero; DXILOpLowering drops the mip level for UAVs.
184 Value *MipLevel = Builder.getInt32(0);
185 Value *Offsets = getNullOffsetsFor(Builder, Coords);
186 auto *Load = Builder.CreateIntrinsic(ContainedType,
187 Intrinsic::dx_resource_load_level,
188 {Handle, Coords, MipLevel, Offsets});
189
190 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
191 Value *Offset =
192 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
193 V = Builder.CreateInsertElement(Load, V, Offset);
194 } else {
195 llvm_unreachable("Store to texture resource has invalid type");
196 }
197
198 auto *Inst = Builder.CreateIntrinsic(Builder.getVoidTy(),
199 Intrinsic::dx_resource_store_texture,
200 {Handle, Coords, V});
201 SI->replaceAllUsesWith(Inst);
202}
203
204static void emitRawStore(IRBuilder<> &Builder, Value *Buffer, Value *Index,
206 // For raw buffer (ie, HLSL's ByteAddressBuffer), we need to fold the access
207 // entirely into the index.
208 if (!RTI.isStruct()) {
209 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
210 if (!ConstantOffset || !ConstantOffset->isZero())
211 Index = Builder.CreateAdd(Index, Offset);
212 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
213 }
214
215 Builder.CreateIntrinsic(Builder.getVoidTy(),
216 Intrinsic::dx_resource_store_rawbuffer,
217 {Buffer, Index, Offset, V});
218}
219
222 const DataLayout &DL = SI->getDataLayout();
223 IRBuilder<> Builder(SI);
224
225 Value *V = SI->getValueOperand();
226 assert(!V->getType()->isAggregateType() &&
227 "Resource store should be scalar or vector type");
228
229 Value *Index = II->getOperand(1);
230 // The offset for the rawbuffer load and store ops is always in bytes.
231 uint64_t AccessSize = 1;
232 Value *Offset =
233 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
234
235 auto *VT = dyn_cast<FixedVectorType>(V->getType());
236 if (VT && VT->getNumElements() > 4) {
237 // Split into stores of at most 4 elements.
238 Type *EltTy = VT->getElementType();
239 Value *Stride = ConstantInt::get(Builder.getInt32Ty(),
240 4 * (DL.getTypeSizeInBits(EltTy) / 8));
241
242 SmallVector<int, 4> Indices;
243 for (unsigned int I = 0, N = VT->getNumElements(); I < N; I += 4) {
244 if (I > 0)
245 Offset = Builder.CreateAdd(Offset, Stride);
246
247 for (unsigned int J = I, E = std::min(N, J + 4); J < E; ++J)
248 Indices.push_back(J);
249 Value *Part = Builder.CreateShuffleVector(V, Indices);
250 emitRawStore(Builder, II->getOperand(0), Index, Offset, Part, RTI);
251
252 Indices.clear();
253 }
254 } else
255 emitRawStore(Builder, II->getOperand(0), Index, Offset, V, RTI);
256}
257
291
292static std::optional<dxil::AtomicBinOpCode>
332
333// Compute the (coord0, coord1) pair for a buffer resource atomic operation.
334// Non-struct buffers (RawBuffer or TypedBuffer) fold the byte offset into the
335// index and leave coord1 poison. Only StructuredBuffer atomics use both a
336// struct index and a byte offset.
337static std::pair<Value *, Value *>
339 dxil::ResourceTypeInfo &RTI, IRBuilder<> &Builder,
340 const DataLayout &DL) {
341 Value *Index = II->getOperand(1);
342
343 // The offset for the rawbuffer load/store/atomic ops is always in bytes.
344 uint64_t AccessSize = 1;
345 Value *Offset = traverseGEPOffsets(DL, Builder, PointerOperand, AccessSize);
346
347 if (!RTI.isStruct()) {
348 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
349 if (!ConstantOffset || !ConstantOffset->isZero())
350 Index = Builder.CreateAdd(Index, Offset);
351 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
352 }
353
354 return {Index, Offset};
355}
356
357// The coordinates of a texture access are a scalar or a vector with one element
358// per texture dimension, including the array slice if there is one. These map
359// directly onto the coordinate operands of the atomic ops.
361 IRBuilder<> &Builder) {
362 Value *Coords = II->getOperand(1);
363 SmallVector<Value *, 3> CoordArgs;
364 if (auto *VecTy = dyn_cast<FixedVectorType>(Coords->getType())) {
365 assert(VecTy->getNumElements() <= 3 && "Too many texture coordinates");
366 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I)
367 CoordArgs.push_back(Builder.CreateExtractElement(Coords, I));
368 } else {
369 CoordArgs.push_back(Coords);
370 }
371 return CoordArgs;
372}
373
374static void emitAtomicBinOp(IRBuilder<> &Builder, AtomicRMWInst *AI,
375 Value *Handle, ArrayRef<Value *> Coords) {
376 assert(!Coords.empty() && Coords.size() <= 3 &&
377 "Atomic operations take between one and three coordinates");
378
379 std::optional<dxil::AtomicBinOpCode> BinOpCode =
381 if (!BinOpCode) {
382 reportFatalUsageError("DXIL resource atomicrmw operation not implemented");
383 return;
384 }
385
386 // DXIL has no floating-point atomic op. A float exchange only moves the bit
387 // pattern, so cast the value to an integer of the same width, exchange, and
388 // cast the result back. This matches what DXC emits.
389 Value *Val = AI->getValOperand();
390 Type *ValTy = Val->getType();
391 Type *OpTy = ValTy;
392 if (ValTy->isFloatingPointTy()) {
393 OpTy = Builder.getIntNTy(ValTy->getPrimitiveSizeInBits());
394 Val = Builder.CreateBitCast(Val, OpTy);
395 }
396
398 Handle, Builder.getInt32(static_cast<uint32_t>(*BinOpCode))};
399 append_range(Args, Coords);
400 Args.append(3 - Coords.size(), PoisonValue::get(Builder.getInt32Ty()));
401 Args.push_back(Val);
402
403 // Emit the target-independent intrinsic; DXILOpLowering lowers it to the
404 // DXIL `AtomicBinOp` op and handles the target-ext-typed handle cast via
405 // its `createTmpHandleCast` bookkeeping.
406 Value *Result =
407 Builder.CreateIntrinsic(OpTy, Intrinsic::dx_resource_atomic_binop, Args);
408
409 if (OpTy != ValTy)
410 Result = Builder.CreateBitCast(Result, ValTy);
411
412 AI->replaceAllUsesWith(Result);
413}
414
417 const DataLayout &DL = AI->getDataLayout();
418 IRBuilder<> Builder(AI);
419 auto [Index, Offset] =
420 getAtomicResourceCoords(II, AI->getPointerOperand(), RTI, Builder, DL);
421
422 emitAtomicBinOp(Builder, AI, II->getOperand(0), {Index, Offset});
423}
424
427 // A texture atomic operates on a whole texel, so a multi-component texel has
428 // no single addressable component. A scalar float texel is allowed, because
429 // emitAtomicBinOp exchanges its bit pattern as an integer.
430 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
431 if (!ContainedType->isIntegerTy() && !ContainedType->isFloatingPointTy()) {
432 reportFatalUsageError("DXIL atomicrmw requires a texture resource with a "
433 "scalar element type");
434 return;
435 }
436
437 IRBuilder<> Builder(AI);
438
439 emitAtomicBinOp(Builder, AI, II->getOperand(0),
440 getTextureAtomicCoords(II, Builder));
441}
442
444 AtomicCmpXchgInst *AI, Value *Handle,
445 ArrayRef<Value *> Coords) {
446 assert(!Coords.empty() && Coords.size() <= 3 &&
447 "Atomic operations take between one and three coordinates");
448
449 Value *Compare = AI->getCompareOperand();
450 Value *NewValue = AI->getNewValOperand();
451
452 SmallVector<Value *, 6> Args{Handle};
453 append_range(Args, Coords);
454 Args.append(3 - Coords.size(), PoisonValue::get(Builder.getInt32Ty()));
455 Args.push_back(Compare);
456 Args.push_back(NewValue);
457
458 Value *Original = Builder.CreateIntrinsic(
459 NewValue->getType(), Intrinsic::dx_resource_atomic_compare_exchange,
460 Args);
461
462 // `cmpxchg` yields a { original, success } pair, but the DXIL op returns
463 // only the original value. DXIL has no way to express the success flag, and
464 // no HLSL builtin reads it, so replace the users of the pair directly
465 // instead of building it again. No pass after this one removes dead code.
467 for (User *U : AI->users()) {
468 auto *EV = dyn_cast<ExtractValueInst>(U);
469 if (!EV || EV->getIndices()[0] != 0)
470 reportFatalUsageError("DXIL cmpxchg provides only the original value");
471 Extracts.push_back(EV);
472 }
473
474 for (ExtractValueInst *EV : Extracts) {
475 EV->replaceAllUsesWith(Original);
476 EV->eraseFromParent();
477 }
478}
479
483 const DataLayout &DL = AI->getDataLayout();
484 IRBuilder<> Builder(AI);
485 auto [Index, Offset] =
486 getAtomicResourceCoords(II, AI->getPointerOperand(), RTI, Builder, DL);
487
488 emitAtomicCompareExchange(Builder, AI, II->getOperand(0), {Index, Offset});
489}
490
491// `cmpxchg` operands are always integers, so unlike atomicrmw there is no
492// float element type to convert here. The element type must be scalar.
496 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
497 if (!ContainedType->isIntegerTy() && !ContainedType->isFloatingPointTy()) {
498 reportFatalUsageError("DXIL cmpxchg requires a texture resource with a "
499 "scalar element type");
500 return;
501 }
502
503 IRBuilder<> Builder(AI);
504
505 emitAtomicCompareExchange(Builder, AI, II->getOperand(0),
506 getTextureAtomicCoords(II, Builder));
507}
508
511 switch (RTI.getResourceKind()) {
515 return createBufferAtomicBinOp(II, AI, RTI);
521 return createTextureAtomicBinOp(II, AI, RTI);
529 "DXIL atomicrmw not implemented for this texture resource kind");
530 return;
535 "DXIL atomicrmw not implemented for this resource type");
536 return;
540 llvm_unreachable("Invalid resource kind for atomicrmw");
541 }
542 llvm_unreachable("Unhandled case in switch");
543}
544
581
584 const DataLayout &DL = LI->getDataLayout();
585 IRBuilder<> Builder(LI);
586 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
587 Type *LoadType = StructType::get(ContainedType, Builder.getInt1Ty());
588
589 Value *V =
590 Builder.CreateIntrinsic(LoadType, Intrinsic::dx_resource_load_typedbuffer,
591 {II->getOperand(0), II->getOperand(1)});
592 V = Builder.CreateExtractValue(V, {0});
593
594 Type *ScalarType = ContainedType->getScalarType();
595 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
596 Value *Offset =
597 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
598 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
599 if (!ConstantOffset || !ConstantOffset->isZero())
600 V = Builder.CreateExtractElement(V, Offset);
601
602 // If we loaded a <1 x ...> instead of a scalar (presumably to feed a
603 // shufflevector), then make sure we're maintaining the resulting type.
604 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType()))
605 if (VT->getNumElements() == 1 && !isa<FixedVectorType>(V->getType()))
606 V = Builder.CreateInsertElement(PoisonValue::get(VT), V,
607 Builder.getInt32(0));
608
609 LI->replaceAllUsesWith(V);
610}
611
614 const DataLayout &DL = LI->getDataLayout();
615 IRBuilder<> Builder(LI);
616 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
617
618 Value *Handle = II->getOperand(0);
619 Value *Coords = II->getOperand(1);
620
621 // For operator[], mip level is 0.
622 Value *MipLevel = Builder.getInt32(0);
623
624 // For operator[], offsets are zero.
625 Value *Offsets = getNullOffsetsFor(Builder, Coords);
626
627 Value *V =
628 Builder.CreateIntrinsic(ContainedType, Intrinsic::dx_resource_load_level,
629 {Handle, Coords, MipLevel, Offsets});
630
631 Type *ScalarType = ContainedType->getScalarType();
632 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
633 Value *Offset =
634 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
635 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
636 if (!ConstantOffset || !ConstantOffset->isZero())
637 V = Builder.CreateExtractElement(V, Offset);
638
639 // If we loaded a <1 x ...> instead of a scalar (presumably to feed a
640 // shufflevector), then make sure we're maintaining the resulting type.
641 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType()))
642 if (VT->getNumElements() == 1 && !isa<FixedVectorType>(V->getType()))
643 V = Builder.CreateInsertElement(PoisonValue::get(VT), V,
644 Builder.getInt32(0));
645
646 LI->replaceAllUsesWith(V);
647}
648
649static Value *emitRawLoad(IRBuilder<> &Builder, Type *Ty, Value *Buffer,
650 Value *Index, Value *Offset,
652 // For raw buffer (ie, HLSL's ByteAddressBuffer), we need to fold the access
653 // entirely into the index.
654 if (!RTI.isStruct()) {
655 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
656 if (!ConstantOffset || !ConstantOffset->isZero())
657 Index = Builder.CreateAdd(Index, Offset);
658 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
659 }
660
661 // The load intrinsic includes the bit for CheckAccessFullyMapped, so we need
662 // to add that to the return type.
663 Type *TypeWithCheck = StructType::get(Ty, Builder.getInt1Ty());
664 Value *V = Builder.CreateIntrinsic(TypeWithCheck,
665 Intrinsic::dx_resource_load_rawbuffer,
666 {Buffer, Index, Offset});
667 return Builder.CreateExtractValue(V, {0});
668}
669
672 const DataLayout &DL = LI->getDataLayout();
673 IRBuilder<> Builder(LI);
674
675 Value *Index = II->getOperand(1);
676 // The offset for the rawbuffer load and store ops is always in bytes.
677 uint64_t AccessSize = 1;
678 Value *Offset =
679 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
680
681 // TODO: We could make this handle aggregates by walking the structure and
682 // handling each field individually, but we don't ever generate code that
683 // would hit that so it seems superfluous.
684 assert(!LI->getType()->isAggregateType() &&
685 "Resource load should be scalar or vector type");
686
687 Value *V;
688 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType())) {
689 // Split into loads of at most 4 elements.
690 Type *EltTy = VT->getElementType();
691 Value *Stride = ConstantInt::get(Builder.getInt32Ty(),
692 4 * (DL.getTypeSizeInBits(EltTy) / 8));
693
695 for (unsigned int I = 0, N = VT->getNumElements(); I < N; I += 4) {
696 Type *Ty = FixedVectorType::get(EltTy, N - I < 4 ? N - I : 4);
697 if (I > 0)
698 Offset = Builder.CreateAdd(Offset, Stride);
699 Parts.push_back(
700 emitRawLoad(Builder, Ty, II->getOperand(0), Index, Offset, RTI));
701 }
702
703 V = Parts.size() > 1 ? concatenateVectors(Builder, Parts) : Parts[0];
704 } else
705 V = emitRawLoad(Builder, LI->getType(), II->getOperand(0), Index, Offset,
706 RTI);
707
708 LI->replaceAllUsesWith(V);
709}
710
711namespace {
712/// Helper for building a `load.cbufferrow` intrinsic given a simple type.
713struct CBufferRowIntrin {
714 Intrinsic::ID IID;
715 Type *RetTy;
716 unsigned int EltSize;
717 unsigned int NumElts;
718
719 CBufferRowIntrin(const DataLayout &DL, Type *Ty) {
720 assert(Ty == Ty->getScalarType() && "Expected scalar type");
721
722 switch (DL.getTypeSizeInBits(Ty)) {
723 case 16:
724 IID = Intrinsic::dx_resource_load_cbufferrow_8;
725 RetTy = StructType::get(Ty, Ty, Ty, Ty, Ty, Ty, Ty, Ty);
726 EltSize = 2;
727 NumElts = 8;
728 break;
729 case 32:
730 IID = Intrinsic::dx_resource_load_cbufferrow_4;
731 RetTy = StructType::get(Ty, Ty, Ty, Ty);
732 EltSize = 4;
733 NumElts = 4;
734 break;
735 case 64:
736 IID = Intrinsic::dx_resource_load_cbufferrow_2;
737 RetTy = StructType::get(Ty, Ty);
738 EltSize = 8;
739 NumElts = 2;
740 break;
741 default:
742 llvm_unreachable("Only 16, 32, and 64 bit types supported");
743 }
744 }
745};
746} // namespace
747
750 const DataLayout &DL = LI->getDataLayout();
751
752 Type *Ty = LI->getType();
753 assert(!isa<StructType>(Ty) && "Structs not handled yet");
754 CBufferRowIntrin Intrin(DL, Ty->getScalarType());
755
756 StringRef Name = LI->getName();
757 Value *Handle = II->getOperand(0);
758
759 IRBuilder<> Builder(LI);
760
761 ConstantInt *GlobalOffset =
762 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer
763 ? ConstantInt::get(Builder.getInt32Ty(), 0)
764 : dyn_cast<ConstantInt>(II->getOperand(1));
765 assert(GlobalOffset && "CBuffer getpointer index must be constant");
766
767 uint64_t GlobalOffsetVal = GlobalOffset->getZExtValue();
768 Value *CurrentRow = ConstantInt::get(
769 Builder.getInt32Ty(), GlobalOffsetVal / hlsl::CBufferRowSizeInBytes);
770 unsigned int CurrentIndex =
771 (GlobalOffsetVal % hlsl::CBufferRowSizeInBytes) / Intrin.EltSize;
772
773 // Every object in a cbuffer either fits in a row or is aligned to a row. This
774 // means that only the very last pointer access can point into a row.
775 auto *LastGEP = dyn_cast<GEPOperator>(LI->getPointerOperand());
776 if (!LastGEP) {
777 // If we don't have a GEP at all we're just accessing the resource through
778 // the result of getpointer directly.
779 assert(LI->getPointerOperand() == II &&
780 "Unexpected indirect access to resource without GEP");
781 } else {
782 Value *GEPOffset = traverseGEPOffsets(
783 DL, Builder, LastGEP->getPointerOperand(), hlsl::CBufferRowSizeInBytes);
784 CurrentRow = Builder.CreateAdd(GEPOffset, CurrentRow);
785
786 APInt ConstantOffset(DL.getIndexTypeSizeInBits(LastGEP->getType()), 0);
787 if (LastGEP->accumulateConstantOffset(DL, ConstantOffset)) {
788 APInt Remainder(DL.getIndexTypeSizeInBits(LastGEP->getType()),
790 APInt::udivrem(ConstantOffset, Remainder, ConstantOffset, Remainder);
791 CurrentRow = Builder.CreateAdd(
792 CurrentRow, ConstantInt::get(Builder.getInt32Ty(), ConstantOffset));
793 CurrentIndex += Remainder.udiv(Intrin.EltSize).getZExtValue();
794 } else {
795 assert(LastGEP->getNumIndices() == 1 &&
796 "Last GEP of cbuffer access is not array or struct access");
797 // We assume a non-constant access will be row-aligned. This is safe
798 // because arrays and structs are always row aligned, and accesses to
799 // vector elements will show up as a load of the vector followed by an
800 // extractelement.
801 CurrentRow = cast<ConstantInt>(CurrentRow)->isZero()
802 ? *LastGEP->idx_begin()
803 : Builder.CreateAdd(CurrentRow, *LastGEP->idx_begin());
804 CurrentIndex = 0;
805 }
806 }
807
808 auto *CBufLoad = Builder.CreateIntrinsic(
809 Intrin.RetTy, Intrin.IID, {Handle, CurrentRow}, nullptr, Name + ".load");
810 auto *Elt =
811 Builder.CreateExtractValue(CBufLoad, {CurrentIndex++}, Name + ".extract");
812
813 // At this point we've loaded the first scalar of our result, but our original
814 // type may have been a vector.
815 unsigned int Remaining =
816 ((DL.getTypeSizeInBits(Ty) / 8) / Intrin.EltSize) - 1;
817 if (Remaining == 0) {
818 // We only have a single element, so we're done.
819 Value *Result = Elt;
820
821 // However, if we loaded a <1 x T>, then we need to adjust the type.
822 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
823 assert(VT->getNumElements() == 1 && "Can't have multiple elements here");
824 Result = Builder.CreateInsertElement(PoisonValue::get(VT), Result,
825 Builder.getInt32(0), Name);
826 }
827 LI->replaceAllUsesWith(Result);
828 return;
829 }
830
831 // Walk each element and extract it, wrapping to new rows as needed.
832 SmallVector<Value *> Extracts{Elt};
833 while (Remaining--) {
834 CurrentIndex %= Intrin.NumElts;
835
836 if (CurrentIndex == 0) {
837 CurrentRow = Builder.CreateAdd(CurrentRow,
838 ConstantInt::get(Builder.getInt32Ty(), 1));
839 CBufLoad = Builder.CreateIntrinsic(Intrin.RetTy, Intrin.IID,
840 {Handle, CurrentRow}, nullptr,
841 Name + ".load");
842 }
843
844 Extracts.push_back(Builder.CreateExtractValue(CBufLoad, {CurrentIndex++},
845 Name + ".extract"));
846 }
847
848 // Finally, we build up the original loaded value.
849 Value *Result = PoisonValue::get(Ty);
850 for (int I = 0, E = Extracts.size(); I < E; ++I)
851 Result = Builder.CreateInsertElement(
852 Result, Extracts[I], Builder.getInt32(I), Name + formatv(".upto{}", I));
853 LI->replaceAllUsesWith(Result);
854}
855
889
891 if (auto *LI = dyn_cast<LoadInst>(AI))
892 return dyn_cast<Instruction>(LI->getPointerOperand());
893 if (auto *SI = dyn_cast<StoreInst>(AI))
894 return dyn_cast<Instruction>(SI->getPointerOperand());
895 if (auto *RMWI = dyn_cast<AtomicRMWInst>(AI))
896 return dyn_cast<Instruction>(RMWI->getPointerOperand());
897 if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(AI))
898 return dyn_cast<Instruction>(CXI->getPointerOperand());
899 if (auto *II = dyn_cast<IntrinsicInst>(AI))
900 if (II->getIntrinsicID() == Intrinsic::dx_resource_updatecounter)
901 return dyn_cast<Instruction>(II->getArgOperand(0));
902
903 return nullptr;
904}
905
906static const std::array<Intrinsic::ID, 2> HandleIntrins = {
907 Intrinsic::dx_resource_handlefrombinding,
908 Intrinsic::dx_resource_handlefromimplicitbinding,
909};
910
912 SmallVector<Value *> Worklist = {Ptr};
914 SmallSet<Value *, 4> VisitedPhis;
915
916 while (!Worklist.empty()) {
917 Value *X = Worklist.pop_back_val();
918
919 if (!X->getType()->isPointerTy() && !X->getType()->isTargetExtTy())
920 return {}; // Early exit on store/load into non-resource
921
922 if (auto *Phi = dyn_cast<PHINode>(X)) {
923 if (VisitedPhis.contains(X))
924 continue;
925 for (Use &V : Phi->incoming_values())
926 Worklist.push_back(V.get());
927 VisitedPhis.insert(Phi);
928 } else if (auto *Select = dyn_cast<SelectInst>(X))
929 for (Value *V : {Select->getTrueValue(), Select->getFalseValue()})
930 Worklist.push_back(V);
931 else if (auto *II = dyn_cast<IntrinsicInst>(X)) {
932 Intrinsic::ID IID = II->getIntrinsicID();
933
934 if (IID == Intrinsic::dx_resource_getpointer)
935 Worklist.push_back(II->getArgOperand(/*Handle=*/0));
936
938 Handles.push_back(II);
939 }
940 }
941
942 return Handles;
943}
944
946 DXILResourceTypeMap &DRTM) {
948 "Only expects a Handle as determined from collectUsedHandles.");
949
950 auto *HandleTy = cast<TargetExtType>(Handle->getType());
951 dxil::ResourceClass Class = DRTM[HandleTy].getResourceClass();
952 uint32_t Space = cast<ConstantInt>(Handle->getArgOperand(0))->getZExtValue();
953 uint32_t LowerBound =
954 cast<ConstantInt>(Handle->getArgOperand(1))->getZExtValue();
955 uint32_t Size = cast<ConstantInt>(Handle->getArgOperand(2))->getZExtValue();
956 uint32_t UpperBound = Size == UINT32_MAX ? UINT32_MAX : LowerBound + Size - 1;
957
958 return hlsl::Binding(Class, Space, LowerBound, UpperBound, nullptr);
959}
960
961namespace {
962/// Helper for propagating the current handle and ptr indices.
963struct AccessIndices {
964 Value *GetPtrIdx;
965 Value *HandleIdx;
966
967 bool hasGetPtrIdx() { return GetPtrIdx != nullptr; }
968 bool hasHandleIdx() { return HandleIdx != nullptr; }
969};
970} // namespace
971
972// getAccessIndices traverses up the control flow that a ptr came from and
973// propagates back the indicies used to access the resource (AccessIndices):
974//
975// - GetPtrIdx is the index of dx.resource.getpointer
976// - HandleIdx is the index of dx.resource.handlefrom.*
977static AccessIndices
980 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
981 if (llvm::is_contained(HandleIntrins, II->getIntrinsicID())) {
982 DeadInsts.insert(II);
983 return {nullptr, II->getArgOperand(/*Index=*/3)};
984 }
985
986 if (II->getIntrinsicID() == Intrinsic::dx_resource_getpointer) {
987 auto *V = dyn_cast<Instruction>(II->getArgOperand(/*Handle=*/0));
988 auto AccessIdx = getAccessIndices(V, DeadInsts, VisitedPhis);
989 assert(!AccessIdx.hasGetPtrIdx() &&
990 "Encountered multiple dx.resource.getpointers in ptr chain?");
991 AccessIdx.GetPtrIdx = II->getArgOperand(1);
992
993 DeadInsts.insert(II);
994 return AccessIdx;
995 }
996 }
997
998 if (auto *Phi = dyn_cast<PHINode>(I)) {
999 // If we're already building indices for this phi, return a ref to the phi
1000 if (auto It = VisitedPhis.find(Phi); It != VisitedPhis.end())
1001 return {nullptr, It->second};
1002
1003 unsigned NumEdges = Phi->getNumIncomingValues();
1004 assert(NumEdges != 0 && "Malformed Phi Node");
1005
1006 IRBuilder<> Builder(Phi);
1007 std::unique_ptr<PHINode> GetPtrPhi(
1008 PHINode::Create(Builder.getInt32Ty(), NumEdges));
1009 std::unique_ptr<PHINode> HandlePhi(
1010 PHINode::Create(Builder.getInt32Ty(), NumEdges));
1011
1012 // Register a ref to this phi for a recursive phi. This is safe to add to
1013 // the map even if we end up deleting newly created phi below since we can't
1014 // possibly have a constant value if we recursed.
1015 if (Phi->getType()->isTargetExtTy())
1016 VisitedPhis[Phi] = HandlePhi.get();
1017
1018 for (unsigned Idx = 0; Idx < NumEdges; Idx++) {
1019 auto *BB = Phi->getIncomingBlock(Idx);
1020 auto *V = dyn_cast<Instruction>(Phi->getIncomingValue(Idx));
1021 auto AccessIdx = getAccessIndices(V, DeadInsts, VisitedPhis);
1022 if (AccessIdx.hasGetPtrIdx())
1023 GetPtrPhi->addIncoming(AccessIdx.GetPtrIdx, BB);
1024 HandlePhi->addIncoming(AccessIdx.HandleIdx, BB);
1025 }
1026
1027 Value *GetPtrIdx;
1028 if (GetPtrPhi->getNumIncomingValues() == 0)
1029 GetPtrIdx = nullptr;
1030 else if (Value *ConstantGetPtr = GetPtrPhi->hasConstantValue())
1031 GetPtrIdx = ConstantGetPtr;
1032 else {
1033 GetPtrIdx = GetPtrPhi.release();
1034 Builder.Insert(GetPtrIdx);
1035 }
1036
1037 Value *HandleIdx;
1038 if (Value *ConstantHandle = HandlePhi->hasConstantValue())
1039 HandleIdx = ConstantHandle;
1040 else {
1041 HandleIdx = HandlePhi.release();
1042 Builder.Insert(HandleIdx);
1043 }
1044
1045 DeadInsts.insert(Phi);
1046 return {GetPtrIdx, HandleIdx};
1047 }
1048
1049 if (auto *Select = dyn_cast<SelectInst>(I)) {
1050 auto *TrueV = dyn_cast<Instruction>(Select->getTrueValue());
1051 auto TrueAccessIdx = getAccessIndices(TrueV, DeadInsts, VisitedPhis);
1052
1053 auto *FalseV = dyn_cast<Instruction>(Select->getFalseValue());
1054 auto FalseAccessIdx = getAccessIndices(FalseV, DeadInsts, VisitedPhis);
1055
1056 IRBuilder<> Builder(Select);
1057 Value *GetPtrSelect = nullptr;
1058
1059 if (TrueAccessIdx.hasGetPtrIdx() && FalseAccessIdx.hasGetPtrIdx())
1060 GetPtrSelect =
1061 Builder.CreateSelect(Select->getCondition(), TrueAccessIdx.GetPtrIdx,
1062 FalseAccessIdx.GetPtrIdx);
1063
1064 auto *HandleSelect =
1065 Builder.CreateSelect(Select->getCondition(), TrueAccessIdx.HandleIdx,
1066 FalseAccessIdx.HandleIdx);
1067 DeadInsts.insert(Select);
1068 return {GetPtrSelect, HandleSelect};
1069 }
1070
1071 llvm_unreachable("collectUsedHandles should assure this does not occur");
1072}
1073
1074static void
1078 auto AccessIdx = getAccessIndices(Ptr, DeadInsts, VisitedPhis);
1079 assert(AccessIdx.hasHandleIdx() &&
1080 "Couldn't retrieve handle index. This is guaranteed by "
1081 "getAccessIndices");
1082
1083 IRBuilder<> Builder(Ptr);
1084 if (isa<PHINode>(Ptr))
1085 Builder.SetInsertPoint(Ptr->getParent()->getFirstNonPHIIt());
1086 IntrinsicInst *Handle = cast<IntrinsicInst>(OldHandle->clone());
1087 Handle->setArgOperand(/*Index=*/3, AccessIdx.HandleIdx);
1088 Builder.Insert(Handle);
1089
1090 if (Ptr->getType()->isPointerTy()) {
1091 assert(AccessIdx.hasGetPtrIdx() &&
1092 "Couldn't retrieve getpointer index. This is guaranteed by "
1093 "getAccessIndices");
1094 auto *GetPtr = Builder.CreateIntrinsic(Ptr->getType(),
1095 Intrinsic::dx_resource_getpointer,
1096 {Handle, AccessIdx.GetPtrIdx});
1097 Ptr->replaceAllUsesWith(GetPtr);
1098 } else {
1099 assert(Ptr->getType()->isTargetExtTy() && !AccessIdx.hasGetPtrIdx() &&
1100 "Unexpected resource access operand type");
1101 Ptr->replaceAllUsesWith(Handle);
1102 }
1103
1104 DeadInsts.insert(Ptr);
1105}
1106
1107// Try to legalize dx.resource.handlefrom.*.binding and dx.resource.getpointer
1108// calls with their respective index values and propagate the index values to
1109// be used at resource access.
1110//
1111// If it can't be transformed to be legal then:
1112//
1113// Reports an error if a resource access is not guaranteed into a unique global
1114// resource.
1115//
1116// Returns true if any changes are made.
1120
1121 for (BasicBlock &BB : make_early_inc_range(F)) {
1122 for (Instruction &I : BB) {
1123 if (auto *HandleOp = getHandleOperand(&I)) {
1125 unsigned NumHandles = Handles.size();
1126 if (NumHandles <= 1)
1127 continue; // Legal, no-replacement required
1128
1129 bool SameGlobalBinding = true;
1130 hlsl::Binding B = getHandleIntrinsicBinding(Handles[0], DRTM);
1131 for (unsigned Idx = 1; Idx < NumHandles; Idx++)
1132 SameGlobalBinding &=
1133 (B == getHandleIntrinsicBinding(Handles[Idx], DRTM));
1134
1135 if (!SameGlobalBinding) {
1137 continue;
1138 }
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.
This file defines the SmallSet class.
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:258
iterator end()
Definition DenseMap.h:176
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:2903
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
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
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 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:622
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