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/MapVector.h"
13#include "llvm/ADT/SetVector.h"
18#include "llvm/IR/BasicBlock.h"
19#include "llvm/IR/Dominators.h"
20#include "llvm/IR/IRBuilder.h"
21#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/IntrinsicsDirectX.h"
26#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/User.h"
29#include "llvm/IR/ValueHandle.h"
38#include <optional>
39
40#define DEBUG_TYPE "dxil-resource-access"
41
42using namespace llvm;
43
44[[noreturn]] static void
47 LLVMContext &Context = I->getContext();
48 std::string InstStr;
49 raw_string_ostream InstOS(InstStr);
50 I->print(InstOS);
51 Context.diagnose(
52 DiagnosticInfoGeneric("At resource access:" + Twine(InstStr), DS_Note));
53
54 for (auto *Handle : Handles) {
55 std::string HandleStr;
56 raw_string_ostream HandleOS(HandleStr);
57 Handle->print(HandleOS);
58 Context.diagnose(DiagnosticInfoGeneric(
59 "Uses resource handle:" + Twine(HandleStr), DS_Note));
60 }
62 "Resource access is not guaranteed to map to a unique global resource",
63 /*gen_crash_diag=*/false);
64}
65
67 Value *Ptr, uint64_t AccessSize) {
68 Value *Offset = nullptr;
69
70 while (Ptr) {
71 if ([[maybe_unused]] auto *II = dyn_cast<IntrinsicInst>(Ptr)) {
72 assert((II->getIntrinsicID() == Intrinsic::dx_resource_getpointer ||
73 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer) &&
74 "Resource access through unexpected intrinsic");
75 return Offset ? Offset : ConstantInt::get(Builder.getInt32Ty(), 0);
76 }
77
79 assert(GEP && "Resource access through unexpected instruction");
80
81 unsigned NumIndices = GEP->getNumIndices();
82 uint64_t IndexScale = DL.getTypeAllocSize(GEP->getSourceElementType());
83 APInt ConstantOffset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
84 Value *GEPOffset;
85 if (GEP->accumulateConstantOffset(DL, ConstantOffset)) {
86 // We have a constant offset (in bytes).
87 GEPOffset =
88 ConstantInt::get(DL.getIndexType(GEP->getType()), ConstantOffset);
89 IndexScale = 1;
90 } else if (NumIndices == 1) {
91 // If we have a single index we're indexing into a top level array. This
92 // generally only happens with cbuffers.
93 GEPOffset = *GEP->idx_begin();
94 } else if (NumIndices == 2) {
95 // If we have two indices, this should be an access through a pointer.
96 auto *IndexIt = GEP->idx_begin();
97 assert(cast<ConstantInt>(IndexIt)->getZExtValue() == 0 &&
98 "GEP is not indexing through pointer");
99 GEPOffset = *(++IndexIt);
100 } else
101 llvm_unreachable("Unhandled GEP structure for resource access");
102
103 uint64_t ElemSize = AccessSize;
104 if (!(IndexScale % ElemSize)) {
105 // If our scale is an exact multiple of the access size, adjust the
106 // scaling to avoid an unnecessary division.
107 IndexScale /= ElemSize;
108 ElemSize = 1;
109 }
110 if (IndexScale != 1)
111 GEPOffset = Builder.CreateMul(
112 GEPOffset, ConstantInt::get(Builder.getInt32Ty(), IndexScale));
113 if (ElemSize != 1)
114 GEPOffset = Builder.CreateUDiv(
115 GEPOffset, ConstantInt::get(Builder.getInt32Ty(), ElemSize));
116
117 Offset = Offset ? Builder.CreateAdd(Offset, GEPOffset) : GEPOffset;
118 Ptr = GEP->getPointerOperand();
119 }
120
121 llvm_unreachable("GEP of null pointer?");
122}
123
126 const DataLayout &DL = SI->getDataLayout();
127 IRBuilder<> Builder(SI);
128 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
129 Type *ScalarType = ContainedType->getScalarType();
130 Type *LoadType = StructType::get(ContainedType, Builder.getInt1Ty());
131
132 Value *V = SI->getValueOperand();
133 if (V->getType() == ContainedType) {
134 // V is already the right type.
135 assert(SI->getPointerOperand() == II &&
136 "Store of whole element has mismatched address to store to");
137 } else if (V->getType() == ScalarType) {
138 // We're storing a scalar, so we need to load the current value and only
139 // replace the relevant part.
140 auto *Load = Builder.CreateIntrinsic(
141 LoadType, Intrinsic::dx_resource_load_typedbuffer,
142 {II->getOperand(0), II->getOperand(1)});
143 auto *Struct = Builder.CreateExtractValue(Load, {0});
144
145 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
146 Value *Offset =
147 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
148 V = Builder.CreateInsertElement(Struct, V, Offset);
149 } else {
150 llvm_unreachable("Store to typed resource has invalid type");
151 }
152
153 auto *Inst = Builder.CreateIntrinsic(
154 Builder.getVoidTy(), Intrinsic::dx_resource_store_typedbuffer,
155 {II->getOperand(0), II->getOperand(1), V});
156 SI->replaceAllUsesWith(Inst);
157}
158
159/// Build a zero-initialized offset operand matching the shape of the given
160/// coordinate operand. Accesses through `operator[]` never have offsets.
161static Value *getNullOffsetsFor(IRBuilder<> &Builder, Value *Coords) {
162 Type *CoordTy = Coords->getType();
163 Type *OffsetTy;
164 if (auto *VecTy = dyn_cast<FixedVectorType>(CoordTy))
165 OffsetTy =
166 FixedVectorType::get(Builder.getInt32Ty(), VecTy->getNumElements());
167 else
168 OffsetTy = Builder.getInt32Ty();
169 return Constant::getNullValue(OffsetTy);
170}
171
174 const DataLayout &DL = SI->getDataLayout();
175 IRBuilder<> Builder(SI);
176 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
177 Type *ScalarType = ContainedType->getScalarType();
178
179 Value *Handle = II->getOperand(0);
180 Value *Coords = II->getOperand(1);
181
182 Value *V = SI->getValueOperand();
183 if (V->getType() == ContainedType) {
184 // V is already the right type.
185 assert(SI->getPointerOperand() == II &&
186 "Store of whole element has mismatched address to store to");
187 } else if (V->getType() == ScalarType) {
188 // We're storing a scalar, so we need to load the current value and only
189 // replace the relevant part. For operator[] the mip level and the offsets
190 // are always zero; DXILOpLowering drops the mip level for UAVs.
191 Value *MipLevel = Builder.getInt32(0);
192 Value *Offsets = getNullOffsetsFor(Builder, Coords);
193 auto *Load = Builder.CreateIntrinsic(ContainedType,
194 Intrinsic::dx_resource_load_level,
195 {Handle, Coords, MipLevel, Offsets});
196
197 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
198 Value *Offset =
199 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
200 V = Builder.CreateInsertElement(Load, V, Offset);
201 } else {
202 llvm_unreachable("Store to texture resource has invalid type");
203 }
204
205 auto *Inst = Builder.CreateIntrinsic(Builder.getVoidTy(),
206 Intrinsic::dx_resource_store_texture,
207 {Handle, Coords, V});
208 SI->replaceAllUsesWith(Inst);
209}
210
211static void emitRawStore(IRBuilder<> &Builder, Value *Buffer, Value *Index,
213 // For raw buffer (ie, HLSL's ByteAddressBuffer), we need to fold the access
214 // entirely into the index.
215 if (!RTI.isStruct()) {
216 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
217 if (!ConstantOffset || !ConstantOffset->isZero())
218 Index = Builder.CreateAdd(Index, Offset);
219 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
220 }
221
222 Builder.CreateIntrinsic(Builder.getVoidTy(),
223 Intrinsic::dx_resource_store_rawbuffer,
224 {Buffer, Index, Offset, V});
225}
226
229 const DataLayout &DL = SI->getDataLayout();
230 IRBuilder<> Builder(SI);
231
232 Value *V = SI->getValueOperand();
233 assert(!V->getType()->isAggregateType() &&
234 "Resource store should be scalar or vector type");
235
236 Value *Index = II->getOperand(1);
237 // The offset for the rawbuffer load and store ops is always in bytes.
238 uint64_t AccessSize = 1;
239 Value *Offset =
240 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
241
242 auto *VT = dyn_cast<FixedVectorType>(V->getType());
243 if (VT && VT->getNumElements() > 4) {
244 // Split into stores of at most 4 elements.
245 Type *EltTy = VT->getElementType();
246 Value *Stride = ConstantInt::get(Builder.getInt32Ty(),
247 4 * (DL.getTypeSizeInBits(EltTy) / 8));
248
249 SmallVector<int, 4> Indices;
250 for (unsigned int I = 0, N = VT->getNumElements(); I < N; I += 4) {
251 if (I > 0)
252 Offset = Builder.CreateAdd(Offset, Stride);
253
254 for (unsigned int J = I, E = std::min(N, J + 4); J < E; ++J)
255 Indices.push_back(J);
256 Value *Part = Builder.CreateShuffleVector(V, Indices);
257 emitRawStore(Builder, II->getOperand(0), Index, Offset, Part, RTI);
258
259 Indices.clear();
260 }
261 } else
262 emitRawStore(Builder, II->getOperand(0), Index, Offset, V, RTI);
263}
264
298
299static std::optional<dxil::AtomicBinOpCode>
339
340// Compute the (coord0, coord1) pair for a buffer resource atomic operation.
341// Non-struct buffers (RawBuffer or TypedBuffer) fold the byte offset into the
342// index and leave coord1 poison. Only StructuredBuffer atomics use both a
343// struct index and a byte offset.
344static std::pair<Value *, Value *>
346 dxil::ResourceTypeInfo &RTI, IRBuilder<> &Builder,
347 const DataLayout &DL) {
348 Value *Index = II->getOperand(1);
349
350 // The offset for the rawbuffer load/store/atomic ops is always in bytes.
351 uint64_t AccessSize = 1;
352 Value *Offset = traverseGEPOffsets(DL, Builder, PointerOperand, AccessSize);
353
354 if (!RTI.isStruct()) {
355 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
356 if (!ConstantOffset || !ConstantOffset->isZero())
357 Index = Builder.CreateAdd(Index, Offset);
358 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
359 }
360
361 return {Index, Offset};
362}
363
364// The coordinates of a texture access are a scalar or a vector with one element
365// per texture dimension, including the array slice if there is one. These map
366// directly onto the coordinate operands of the atomic ops.
368 IRBuilder<> &Builder) {
369 Value *Coords = II->getOperand(1);
370 SmallVector<Value *, 3> CoordArgs;
371 if (auto *VecTy = dyn_cast<FixedVectorType>(Coords->getType())) {
372 assert(VecTy->getNumElements() <= 3 && "Too many texture coordinates");
373 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I)
374 CoordArgs.push_back(Builder.CreateExtractElement(Coords, I));
375 } else {
376 CoordArgs.push_back(Coords);
377 }
378 return CoordArgs;
379}
380
381static void emitAtomicBinOp(IRBuilder<> &Builder, AtomicRMWInst *AI,
382 Value *Handle, ArrayRef<Value *> Coords) {
383 assert(!Coords.empty() && Coords.size() <= 3 &&
384 "Atomic operations take between one and three coordinates");
385
386 std::optional<dxil::AtomicBinOpCode> BinOpCode =
388 if (!BinOpCode) {
389 reportFatalUsageError("DXIL resource atomicrmw operation not implemented");
390 return;
391 }
392
393 // DXIL has no floating-point atomic op. A float exchange only moves the bit
394 // pattern, so cast the value to an integer of the same width, exchange, and
395 // cast the result back. This matches what DXC emits.
396 Value *Val = AI->getValOperand();
397 Type *ValTy = Val->getType();
398 Type *OpTy = ValTy;
399 if (ValTy->isFloatingPointTy()) {
400 OpTy = Builder.getIntNTy(ValTy->getPrimitiveSizeInBits());
401 Val = Builder.CreateBitCast(Val, OpTy);
402 }
403
405 Handle, Builder.getInt32(static_cast<uint32_t>(*BinOpCode))};
406 append_range(Args, Coords);
407 Args.append(3 - Coords.size(), PoisonValue::get(Builder.getInt32Ty()));
408 Args.push_back(Val);
409
410 // Emit the target-independent intrinsic; DXILOpLowering lowers it to the
411 // DXIL `AtomicBinOp` op and handles the target-ext-typed handle cast via
412 // its `createTmpHandleCast` bookkeeping.
413 Value *Result =
414 Builder.CreateIntrinsic(OpTy, Intrinsic::dx_resource_atomic_binop, Args);
415
416 if (OpTy != ValTy)
417 Result = Builder.CreateBitCast(Result, ValTy);
418
419 AI->replaceAllUsesWith(Result);
420}
421
424 const DataLayout &DL = AI->getDataLayout();
425 IRBuilder<> Builder(AI);
426 auto [Index, Offset] =
427 getAtomicResourceCoords(II, AI->getPointerOperand(), RTI, Builder, DL);
428
429 emitAtomicBinOp(Builder, AI, II->getOperand(0), {Index, Offset});
430}
431
434 // A texture atomic operates on a whole texel, so a multi-component texel has
435 // no single addressable component. A scalar float texel is allowed, because
436 // emitAtomicBinOp exchanges its bit pattern as an integer.
437 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
438 if (!ContainedType->isIntegerTy() && !ContainedType->isFloatingPointTy()) {
439 reportFatalUsageError("DXIL atomicrmw requires a texture resource with a "
440 "scalar element type");
441 return;
442 }
443
444 IRBuilder<> Builder(AI);
445
446 emitAtomicBinOp(Builder, AI, II->getOperand(0),
447 getTextureAtomicCoords(II, Builder));
448}
449
451 AtomicCmpXchgInst *AI, Value *Handle,
452 ArrayRef<Value *> Coords) {
453 assert(!Coords.empty() && Coords.size() <= 3 &&
454 "Atomic operations take between one and three coordinates");
455
456 Value *Compare = AI->getCompareOperand();
457 Value *NewValue = AI->getNewValOperand();
458
459 SmallVector<Value *, 6> Args{Handle};
460 append_range(Args, Coords);
461 Args.append(3 - Coords.size(), PoisonValue::get(Builder.getInt32Ty()));
462 Args.push_back(Compare);
463 Args.push_back(NewValue);
464
465 Value *Original = Builder.CreateIntrinsic(
466 NewValue->getType(), Intrinsic::dx_resource_atomic_compare_exchange,
467 Args);
468
469 // `cmpxchg` yields a { original, success } pair, but the DXIL op returns
470 // only the original value. DXIL has no way to express the success flag, and
471 // no HLSL builtin reads it, so replace the users of the pair directly
472 // instead of building it again. No pass after this one removes dead code.
474 for (User *U : AI->users()) {
475 auto *EV = dyn_cast<ExtractValueInst>(U);
476 if (!EV || EV->getIndices()[0] != 0)
477 reportFatalUsageError("DXIL cmpxchg provides only the original value");
478 Extracts.push_back(EV);
479 }
480
481 for (ExtractValueInst *EV : Extracts) {
482 EV->replaceAllUsesWith(Original);
483 EV->eraseFromParent();
484 }
485}
486
490 const DataLayout &DL = AI->getDataLayout();
491 IRBuilder<> Builder(AI);
492 auto [Index, Offset] =
493 getAtomicResourceCoords(II, AI->getPointerOperand(), RTI, Builder, DL);
494
495 emitAtomicCompareExchange(Builder, AI, II->getOperand(0), {Index, Offset});
496}
497
498// `cmpxchg` operands are always integers, so unlike atomicrmw there is no
499// float element type to convert here. The element type must be scalar.
503 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
504 if (!ContainedType->isIntegerTy() && !ContainedType->isFloatingPointTy()) {
505 reportFatalUsageError("DXIL cmpxchg requires a texture resource with a "
506 "scalar element type");
507 return;
508 }
509
510 IRBuilder<> Builder(AI);
511
512 emitAtomicCompareExchange(Builder, AI, II->getOperand(0),
513 getTextureAtomicCoords(II, Builder));
514}
515
518 switch (RTI.getResourceKind()) {
522 return createBufferAtomicBinOp(II, AI, RTI);
528 return createTextureAtomicBinOp(II, AI, RTI);
536 "DXIL atomicrmw not implemented for this texture resource kind");
537 return;
542 "DXIL atomicrmw not implemented for this resource type");
543 return;
547 llvm_unreachable("Invalid resource kind for atomicrmw");
548 }
549 llvm_unreachable("Unhandled case in switch");
550}
551
588
591 const DataLayout &DL = LI->getDataLayout();
592 IRBuilder<> Builder(LI);
593 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
594 Type *LoadType = StructType::get(ContainedType, Builder.getInt1Ty());
595
596 Value *V =
597 Builder.CreateIntrinsic(LoadType, Intrinsic::dx_resource_load_typedbuffer,
598 {II->getOperand(0), II->getOperand(1)});
599 V = Builder.CreateExtractValue(V, {0});
600
601 Type *ScalarType = ContainedType->getScalarType();
602 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
603 Value *Offset =
604 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
605 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
606 if (!ConstantOffset || !ConstantOffset->isZero())
607 V = Builder.CreateExtractElement(V, Offset);
608
609 // If we loaded a <1 x ...> instead of a scalar (presumably to feed a
610 // shufflevector), then make sure we're maintaining the resulting type.
611 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType()))
612 if (VT->getNumElements() == 1 && !isa<FixedVectorType>(V->getType()))
613 V = Builder.CreateInsertElement(PoisonValue::get(VT), V,
614 Builder.getInt32(0));
615
616 LI->replaceAllUsesWith(V);
617}
618
621 const DataLayout &DL = LI->getDataLayout();
622 IRBuilder<> Builder(LI);
623 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
624
625 Value *Handle = II->getOperand(0);
626 Value *Coords = II->getOperand(1);
627
628 // For operator[], mip level is 0.
629 Value *MipLevel = Builder.getInt32(0);
630
631 // For operator[], offsets are zero.
632 Value *Offsets = getNullOffsetsFor(Builder, Coords);
633
634 Value *V =
635 Builder.CreateIntrinsic(ContainedType, Intrinsic::dx_resource_load_level,
636 {Handle, Coords, MipLevel, Offsets});
637
638 Type *ScalarType = ContainedType->getScalarType();
639 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
640 Value *Offset =
641 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
642 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
643 if (!ConstantOffset || !ConstantOffset->isZero())
644 V = Builder.CreateExtractElement(V, Offset);
645
646 // If we loaded a <1 x ...> instead of a scalar (presumably to feed a
647 // shufflevector), then make sure we're maintaining the resulting type.
648 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType()))
649 if (VT->getNumElements() == 1 && !isa<FixedVectorType>(V->getType()))
650 V = Builder.CreateInsertElement(PoisonValue::get(VT), V,
651 Builder.getInt32(0));
652
653 LI->replaceAllUsesWith(V);
654}
655
656static Value *emitRawLoad(IRBuilder<> &Builder, Type *Ty, Value *Buffer,
657 Value *Index, Value *Offset,
659 // For raw buffer (ie, HLSL's ByteAddressBuffer), we need to fold the access
660 // entirely into the index.
661 if (!RTI.isStruct()) {
662 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
663 if (!ConstantOffset || !ConstantOffset->isZero())
664 Index = Builder.CreateAdd(Index, Offset);
665 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
666 }
667
668 // The load intrinsic includes the bit for CheckAccessFullyMapped, so we need
669 // to add that to the return type.
670 Type *TypeWithCheck = StructType::get(Ty, Builder.getInt1Ty());
671 Value *V = Builder.CreateIntrinsic(TypeWithCheck,
672 Intrinsic::dx_resource_load_rawbuffer,
673 {Buffer, Index, Offset});
674 return Builder.CreateExtractValue(V, {0});
675}
676
679 const DataLayout &DL = LI->getDataLayout();
680 IRBuilder<> Builder(LI);
681
682 Value *Index = II->getOperand(1);
683 // The offset for the rawbuffer load and store ops is always in bytes.
684 uint64_t AccessSize = 1;
685 Value *Offset =
686 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
687
688 // TODO: We could make this handle aggregates by walking the structure and
689 // handling each field individually, but we don't ever generate code that
690 // would hit that so it seems superfluous.
691 assert(!LI->getType()->isAggregateType() &&
692 "Resource load should be scalar or vector type");
693
694 Value *V;
695 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType())) {
696 // Split into loads of at most 4 elements.
697 Type *EltTy = VT->getElementType();
698 Value *Stride = ConstantInt::get(Builder.getInt32Ty(),
699 4 * (DL.getTypeSizeInBits(EltTy) / 8));
700
702 for (unsigned int I = 0, N = VT->getNumElements(); I < N; I += 4) {
703 Type *Ty = FixedVectorType::get(EltTy, N - I < 4 ? N - I : 4);
704 if (I > 0)
705 Offset = Builder.CreateAdd(Offset, Stride);
706 Parts.push_back(
707 emitRawLoad(Builder, Ty, II->getOperand(0), Index, Offset, RTI));
708 }
709
710 V = Parts.size() > 1 ? concatenateVectors(Builder, Parts) : Parts[0];
711 } else
712 V = emitRawLoad(Builder, LI->getType(), II->getOperand(0), Index, Offset,
713 RTI);
714
715 LI->replaceAllUsesWith(V);
716}
717
718namespace {
719/// Helper for building a `load.cbufferrow` intrinsic given a simple type.
720struct CBufferRowIntrin {
721 Intrinsic::ID IID;
722 Type *RetTy;
723 unsigned int EltSize;
724 unsigned int NumElts;
725
726 CBufferRowIntrin(const DataLayout &DL, Type *Ty) {
727 assert(Ty == Ty->getScalarType() && "Expected scalar type");
728
729 switch (DL.getTypeSizeInBits(Ty)) {
730 case 16:
731 IID = Intrinsic::dx_resource_load_cbufferrow_8;
732 RetTy = StructType::get(Ty, Ty, Ty, Ty, Ty, Ty, Ty, Ty);
733 EltSize = 2;
734 NumElts = 8;
735 break;
736 case 32:
737 IID = Intrinsic::dx_resource_load_cbufferrow_4;
738 RetTy = StructType::get(Ty, Ty, Ty, Ty);
739 EltSize = 4;
740 NumElts = 4;
741 break;
742 case 64:
743 IID = Intrinsic::dx_resource_load_cbufferrow_2;
744 RetTy = StructType::get(Ty, Ty);
745 EltSize = 8;
746 NumElts = 2;
747 break;
748 default:
749 llvm_unreachable("Only 16, 32, and 64 bit types supported");
750 }
751 }
752};
753} // namespace
754
756 const CBufferRowIntrin &Intrin,
757 Value *Handle, Value *FirstRow,
758 Value *Window, unsigned RowNumber,
759 StringRef Name) {
760 Value *RowIndex =
761 RowNumber == 0 ? FirstRow
762 : Builder.CreateAdd(FirstRow, Builder.getInt32(RowNumber));
763 Value *RowLoad = Builder.CreateIntrinsic(
764 Intrin.RetTy, Intrin.IID, {Handle, RowIndex}, nullptr, Name + ".load");
765 for (unsigned J = 0; J != Intrin.NumElts; ++J) {
766 Value *Element = Builder.CreateExtractValue(RowLoad, {J});
767 Window = Builder.CreateInsertElement(
768 Window, Element, Builder.getInt32(RowNumber * Intrin.NumElts + J));
769 }
770 return Window;
771}
772
774 const CBufferRowIntrin &Intrin,
775 Value *BaseRow, Value *ByteOffset,
776 const KnownBits &WithinRow) {
777 IRBuilder<> Builder(LI);
778 Type *Ty = LI->getType();
779 auto *VT = dyn_cast<FixedVectorType>(Ty);
780 unsigned NumElements = VT ? VT->getNumElements() : 1;
781 StringRef Name = LI->getName();
782 Value *Handle = II->getOperand(0);
783 Value *RowSize = Builder.getInt32(hlsl::CBufferRowSizeInBytes);
784 Value *FirstRow =
785 Builder.CreateAdd(BaseRow, Builder.CreateUDiv(ByteOffset, RowSize));
786 Value *Component = Builder.CreateUDiv(Builder.CreateURem(ByteOffset, RowSize),
787 Builder.getInt32(Intrin.EltSize));
788 unsigned MinComponent =
789 WithinRow.getMinValue().getZExtValue() / Intrin.EltSize;
790 unsigned MaxComponent =
791 WithinRow.getMaxValue().getZExtValue() / Intrin.EltSize;
792 unsigned MinRows = 1 + (MinComponent + NumElements - 1) / Intrin.NumElts;
793 unsigned MaxRows = 1 + (MaxComponent + NumElements - 1) / Intrin.NumElts;
794 auto *WindowTy =
795 FixedVectorType::get(Ty->getScalarType(), MaxRows * Intrin.NumElts);
796 Value *Window = PoisonValue::get(WindowTy);
797 for (unsigned I = 0; I != MinRows; ++I)
798 Window = loadCBufferRowIntoWindow(Builder, Intrin, Handle, FirstRow, Window,
799 I, Name);
800
801 // The unknown starting component can require at most one extra row.
802 // Load it only when needed, rather than accessing beyond the load.
803 if (MaxRows != MinRows) {
804 BasicBlock *Head = LI->getParent();
805 Value *LastComponent =
806 Builder.CreateAdd(Component, Builder.getInt32(NumElements - 1));
807 Value *CrossesRow = Builder.CreateICmpUGE(
808 LastComponent, Builder.getInt32(MinRows * Intrin.NumElts));
809 Instruction *ThenTerm = SplitBlockAndInsertIfThen(CrossesRow, LI, false);
811 DEBUG_TYPE);
812 Builder.SetInsertPoint(ThenTerm);
813 Value *NextWindow = loadCBufferRowIntoWindow(
814 Builder, Intrin, Handle, FirstRow, Window, MinRows, Name);
815 Builder.SetInsertPoint(LI);
816 auto *Rows = Builder.CreatePHI(WindowTy, 2, Name + ".rows");
817 Rows->addIncoming(Window, Head);
818 Rows->addIncoming(NextWindow, ThenTerm->getParent());
819 Window = Rows;
820 }
821
822 Value *Result = PoisonValue::get(Ty);
823 for (unsigned I = 0; I != NumElements; ++I) {
824 Value *Index =
825 I == 0 ? Component : Builder.CreateAdd(Component, Builder.getInt32(I));
826 Value *Element =
827 Builder.CreateExtractElement(Window, Index, Name + ".extract");
828 Result =
829 VT ? Builder.CreateInsertElement(Result, Element, Builder.getInt32(I))
830 : Element;
831 }
832 return Result;
833}
834
836 const DataLayout &DL,
837 const Instruction *CxtI) {
838 KnownBits Known = computeKnownBits(Offset, DL, nullptr, CxtI);
839 auto *Phi = dyn_cast<PHINode>(Offset);
840 if (!Phi || Phi->getNumIncomingValues() == 0)
841 return Known;
842
843 // PHI queries limit recursion into each input, which can hide row alignment.
844 KnownBits IncomingKnown(Known.getBitWidth());
845 IncomingKnown.setAllConflict();
846 for (unsigned I = 0; I != Phi->getNumIncomingValues(); ++I)
847 IncomingKnown = IncomingKnown.intersectWith(
848 computeKnownBits(Phi->getIncomingValue(I), DL, nullptr,
849 Phi->getIncomingBlock(I)->getTerminator()));
850 return Known.unionWith(IncomingKnown);
851}
852
855 const DataLayout &DL = LI->getDataLayout();
856
857 Type *Ty = LI->getType();
858 assert(!isa<StructType>(Ty) && "Structs not handled yet");
859 CBufferRowIntrin Intrin(DL, Ty->getScalarType());
860
861 StringRef Name = LI->getName();
862 Value *Handle = II->getOperand(0);
863
864 IRBuilder<> Builder(LI);
865
866 ConstantInt *GlobalOffset =
867 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer
868 ? ConstantInt::get(Builder.getInt32Ty(), 0)
869 : dyn_cast<ConstantInt>(II->getOperand(1));
870 assert(GlobalOffset && "CBuffer getpointer index must be constant");
871
872 uint64_t GlobalOffsetVal = GlobalOffset->getZExtValue();
873 Value *CurrentRow = ConstantInt::get(
874 Builder.getInt32Ty(), GlobalOffsetVal / hlsl::CBufferRowSizeInBytes);
875 unsigned int CurrentIndex =
876 (GlobalOffsetVal % hlsl::CBufferRowSizeInBytes) / Intrin.EltSize;
877
878 // Every object in a cbuffer either fits in a row or is aligned to a row. This
879 // means that only the very last pointer access can point into a row.
880 auto *LastGEP = dyn_cast<GEPOperator>(LI->getPointerOperand());
881 if (!LastGEP) {
882 // If we don't have a GEP at all we're just accessing the resource through
883 // the result of getpointer directly.
884 assert(LI->getPointerOperand() == II &&
885 "Unexpected indirect access to resource without GEP");
886 } else {
887 Value *GEPOffset = traverseGEPOffsets(
888 DL, Builder, LastGEP->getPointerOperand(), hlsl::CBufferRowSizeInBytes);
889 CurrentRow = Builder.CreateAdd(GEPOffset, CurrentRow);
890
891 APInt ConstantOffset(DL.getIndexTypeSizeInBits(LastGEP->getType()), 0);
892 if (LastGEP->accumulateConstantOffset(DL, ConstantOffset)) {
893 APInt Remainder(DL.getIndexTypeSizeInBits(LastGEP->getType()),
895 APInt::udivrem(ConstantOffset, Remainder, ConstantOffset, Remainder);
896 CurrentRow = Builder.CreateAdd(
897 CurrentRow, ConstantInt::get(Builder.getInt32Ty(), ConstantOffset));
898 CurrentIndex += Remainder.udiv(Intrin.EltSize).getZExtValue();
899 } else {
900 assert(LastGEP->getNumIndices() == 1 &&
901 "Last GEP of cbuffer access is not array or struct access");
902 // Aggregate strides are row-aligned, but merged byte offsets can select
903 // different components within a row.
904 Value *RowIndex = Builder.CreateSExtOrTrunc(*LastGEP->idx_begin(),
905 Builder.getInt32Ty());
906 uint64_t IndexScale =
907 DL.getTypeAllocSize(LastGEP->getSourceElementType());
908 if (IndexScale < hlsl::CBufferRowSizeInBytes) {
909 assert(hlsl::CBufferRowSizeInBytes % IndexScale == 0 &&
910 "CBuffer GEP index is not row aligned");
911 Value *ByteOffset =
912 IndexScale == 1
913 ? RowIndex
914 : Builder.CreateMul(RowIndex, Builder.getInt32(IndexScale));
915 uint64_t BaseWithinRow = GlobalOffsetVal % hlsl::CBufferRowSizeInBytes;
916 if (BaseWithinRow != 0)
917 ByteOffset =
918 Builder.CreateAdd(ByteOffset, Builder.getInt32(BaseWithinRow));
919 Value *RowSize = Builder.getInt32(hlsl::CBufferRowSizeInBytes);
920 KnownBits WithinRow =
921 computeCBufferOffsetKnownBits(ByteOffset, DL, LI) &
923 if (!WithinRow.isConstant()) {
925 II, LI, Intrin, CurrentRow, ByteOffset, WithinRow));
926 return;
927 }
928 RowIndex = Builder.CreateUDiv(ByteOffset, RowSize, "",
929 WithinRow.getConstant().isZero());
930 CurrentIndex = WithinRow.getConstant().getZExtValue() / Intrin.EltSize;
931 } else if (IndexScale > hlsl::CBufferRowSizeInBytes) {
932 assert(IndexScale % hlsl::CBufferRowSizeInBytes == 0 &&
933 "CBuffer GEP index is not row aligned");
934 RowIndex = Builder.CreateMul(
935 RowIndex,
936 ConstantInt::get(Builder.getInt32Ty(),
937 IndexScale / hlsl::CBufferRowSizeInBytes));
938 }
939 if (auto *BaseRow = dyn_cast<ConstantInt>(CurrentRow);
940 BaseRow && BaseRow->isZero())
941 CurrentRow = RowIndex;
942 else
943 CurrentRow = Builder.CreateAdd(CurrentRow, RowIndex);
944 }
945 }
946
947 auto *CBufLoad = Builder.CreateIntrinsic(
948 Intrin.RetTy, Intrin.IID, {Handle, CurrentRow}, nullptr, Name + ".load");
949 auto *Elt =
950 Builder.CreateExtractValue(CBufLoad, {CurrentIndex++}, Name + ".extract");
951
952 // At this point we've loaded the first scalar of our result, but our original
953 // type may have been a vector.
954 unsigned int Remaining =
955 ((DL.getTypeSizeInBits(Ty) / 8) / Intrin.EltSize) - 1;
956 if (Remaining == 0) {
957 // We only have a single element, so we're done.
958 Value *Result = Elt;
959
960 // However, if we loaded a <1 x T>, then we need to adjust the type.
961 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
962 assert(VT->getNumElements() == 1 && "Can't have multiple elements here");
963 Result = Builder.CreateInsertElement(PoisonValue::get(VT), Result,
964 Builder.getInt32(0), Name);
965 }
966 LI->replaceAllUsesWith(Result);
967 return;
968 }
969
970 // Walk each element and extract it, wrapping to new rows as needed.
971 SmallVector<Value *> Extracts{Elt};
972 while (Remaining--) {
973 CurrentIndex %= Intrin.NumElts;
974
975 if (CurrentIndex == 0) {
976 CurrentRow = Builder.CreateAdd(CurrentRow,
977 ConstantInt::get(Builder.getInt32Ty(), 1));
978 CBufLoad = Builder.CreateIntrinsic(Intrin.RetTy, Intrin.IID,
979 {Handle, CurrentRow}, nullptr,
980 Name + ".load");
981 }
982
983 Extracts.push_back(Builder.CreateExtractValue(CBufLoad, {CurrentIndex++},
984 Name + ".extract"));
985 }
986
987 // Finally, we build up the original loaded value.
988 Value *Result = PoisonValue::get(Ty);
989 for (int I = 0, E = Extracts.size(); I < E; ++I)
990 Result = Builder.CreateInsertElement(
991 Result, Extracts[I], Builder.getInt32(I), Name + formatv(".upto{}", I));
992 LI->replaceAllUsesWith(Result);
993}
994
1028
1030 if (auto *LI = dyn_cast<LoadInst>(AI))
1031 return dyn_cast<Instruction>(LI->getPointerOperand());
1032 if (auto *SI = dyn_cast<StoreInst>(AI))
1033 return dyn_cast<Instruction>(SI->getPointerOperand());
1034 if (auto *RMWI = dyn_cast<AtomicRMWInst>(AI))
1035 return dyn_cast<Instruction>(RMWI->getPointerOperand());
1036 if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(AI))
1037 return dyn_cast<Instruction>(CXI->getPointerOperand());
1038 if (auto *II = dyn_cast<IntrinsicInst>(AI))
1039 if (II->getIntrinsicID() == Intrinsic::dx_resource_updatecounter)
1040 return dyn_cast<Instruction>(II->getArgOperand(0));
1041
1042 return nullptr;
1043}
1044
1046 while (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
1047 auto *PointerI = dyn_cast<Instruction>(GEP->getPointerOperand());
1048 if (!PointerI)
1049 break;
1050 I = PointerI;
1051 }
1052 return I;
1053}
1054
1055static const std::array<Intrinsic::ID, 2> HandleIntrins = {
1056 Intrinsic::dx_resource_handlefrombinding,
1057 Intrinsic::dx_resource_handlefromimplicitbinding,
1058};
1059
1061 SmallVector<Value *> Worklist = {Ptr};
1063 SmallPtrSet<Value *, 4> VisitedPhis;
1064
1065 while (!Worklist.empty()) {
1066 Value *X = Worklist.pop_back_val();
1067
1068 if (!X->getType()->isPointerTy() && !X->getType()->isTargetExtTy())
1069 return {}; // Early exit on store/load into non-resource
1070
1071 if (auto *Phi = dyn_cast<PHINode>(X)) {
1072 if (VisitedPhis.contains(X))
1073 continue;
1074 for (Use &V : Phi->incoming_values())
1075 Worklist.push_back(V.get());
1076 VisitedPhis.insert(Phi);
1077 } else if (auto *Select = dyn_cast<SelectInst>(X)) {
1078 Worklist.push_back(Select->getTrueValue());
1079 Worklist.push_back(Select->getFalseValue());
1080 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(X)) {
1081 Worklist.push_back(GEP->getPointerOperand());
1082 } else if (auto *II = dyn_cast<IntrinsicInst>(X)) {
1083 Intrinsic::ID IID = II->getIntrinsicID();
1084
1085 if (IID == Intrinsic::dx_resource_getpointer ||
1086 IID == Intrinsic::dx_resource_getbasepointer)
1087 Worklist.push_back(II->getArgOperand(/*Handle=*/0));
1088
1090 Handles.push_back(II);
1091 }
1092 }
1093
1094 return Handles;
1095}
1096
1098 DXILResourceTypeMap &DRTM) {
1100 "Only expects a Handle as determined from collectUsedHandles.");
1101
1102 auto *HandleTy = cast<TargetExtType>(Handle->getType());
1103 dxil::ResourceClass Class = DRTM[HandleTy].getResourceClass();
1104 uint32_t Space = cast<ConstantInt>(Handle->getArgOperand(0))->getZExtValue();
1105 uint32_t LowerBound =
1106 cast<ConstantInt>(Handle->getArgOperand(1))->getZExtValue();
1107 uint32_t Size = cast<ConstantInt>(Handle->getArgOperand(2))->getZExtValue();
1108 uint32_t UpperBound = Size == UINT32_MAX ? UINT32_MAX : LowerBound + Size - 1;
1109
1110 return hlsl::Binding(Class, Space, LowerBound, UpperBound, nullptr);
1111}
1112
1113namespace {
1114/// Helper for propagating the current handle and ptr indices.
1115struct AccessIndices {
1116 Value *GetPtrIdx;
1117 Value *HandleIdx;
1118 Value *OffsetIdx;
1119
1120 bool hasGetPtrIdx() { return GetPtrIdx != nullptr; }
1121 bool hasHandleIdx() { return HandleIdx != nullptr; }
1122 bool hasOffsetIdx() { return OffsetIdx != nullptr; }
1123};
1124
1125/// AccessIndices cached per phi. The values may be placeholder phis that are
1126/// later folded away (via replaceAllUsesWith) and freed, so track them with
1127/// value handles rather than raw pointers.
1128struct TrackedAccessIndices {
1129 WeakTrackingVH GetPtrIdx;
1130 WeakTrackingVH HandleIdx;
1131 WeakTrackingVH OffsetIdx;
1132
1133 TrackedAccessIndices() = default;
1134 TrackedAccessIndices(const AccessIndices &AI)
1135 : GetPtrIdx(AI.GetPtrIdx), HandleIdx(AI.HandleIdx),
1136 OffsetIdx(AI.OffsetIdx) {}
1137 operator AccessIndices() const { return {GetPtrIdx, HandleIdx, OffsetIdx}; }
1138};
1139
1140using PhiAccessIndicesMap = SmallDenseMap<PHINode *, TrackedAccessIndices>;
1141} // namespace
1142
1143// Compute the total byte offset described by a GEP as a single i32 value,
1144// handling both constant and variable indices.
1146 IRBuilder<> &Builder) {
1147 const DataLayout &DL = GEP->getDataLayout();
1148 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
1149 SmallMapVector<Value *, APInt, 4> VariableOffsets;
1150 APInt ConstantOffset(BitWidth, 0);
1151 bool Success =
1152 GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset);
1153 assert(Success && "Unhandled GEP structure for resource access");
1154 (void)Success;
1155
1156 Type *I32 = Builder.getInt32Ty();
1157 Value *Offset = ConstantInt::get(I32, ConstantOffset.getSExtValue());
1158 for (auto &[V, Scale] : VariableOffsets) {
1159 Value *Index = Builder.CreateSExtOrTrunc(V, I32);
1160 if (!Scale.isOne())
1161 Index =
1162 Builder.CreateMul(Index, ConstantInt::get(I32, Scale.getSExtValue()));
1163 Offset = Builder.CreateAdd(Offset, Index);
1164 }
1165 return Offset;
1166}
1167
1168// getAccessIndices traverses up the control flow that a ptr came from and
1169// propagates back the indicies used to access the resource (AccessIndices):
1170//
1171// - GetPtrIdx is the index of dx.resource.getpointer
1172// - HandleIdx is the index of dx.resource.handlefrom.*
1173// - OffsetIdx is the accumulated byte offset of any GEPs in the ptr chain
1174static AccessIndices
1176 PhiAccessIndicesMap &VisitedPhis) {
1177 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1178 if (llvm::is_contained(HandleIntrins, II->getIntrinsicID())) {
1179 DeadInsts.insert(II);
1180 return {nullptr, II->getArgOperand(/*Index=*/3), nullptr};
1181 }
1182
1183 Intrinsic::ID IID = II->getIntrinsicID();
1184 if (IID == Intrinsic::dx_resource_getpointer ||
1185 IID == Intrinsic::dx_resource_getbasepointer) {
1186 auto *V = dyn_cast<Instruction>(II->getArgOperand(/*Handle=*/0));
1187 auto AccessIdx = getAccessIndices(V, DeadInsts, VisitedPhis);
1188 assert(!AccessIdx.hasGetPtrIdx() &&
1189 "Encountered multiple dx.resource.getpointers in ptr chain?");
1190 IRBuilder<> Builder(II);
1191 AccessIdx.GetPtrIdx = ConstantInt::get(Builder.getInt32Ty(), 0);
1192 if (IID == Intrinsic::dx_resource_getpointer)
1193 AccessIdx.GetPtrIdx = II->getArgOperand(1);
1194
1195 DeadInsts.insert(II);
1196 return AccessIdx;
1197 }
1198 }
1199
1200 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
1201 auto *V = dyn_cast<Instruction>(GEP->getPointerOperand());
1202 auto AccessIdx = getAccessIndices(V, DeadInsts, VisitedPhis);
1203
1204 IRBuilder<> Builder(GEP);
1205 Value *GEPOffset = accumulateGEPOffset(GEP, Builder);
1206 AccessIdx.OffsetIdx =
1207 AccessIdx.hasOffsetIdx()
1208 ? Builder.CreateAdd(AccessIdx.OffsetIdx, GEPOffset)
1209 : GEPOffset;
1210
1211 DeadInsts.insert(GEP);
1212 return AccessIdx;
1213 }
1214
1215 if (auto *Phi = dyn_cast<PHINode>(I)) {
1216 // If we're already building indices for this phi, return a ref to the phi
1217 if (auto It = VisitedPhis.find(Phi); It != VisitedPhis.end())
1218 return It->second;
1219
1220 unsigned NumEdges = Phi->getNumIncomingValues();
1221 assert(NumEdges != 0 && "Malformed Phi Node");
1222
1223 IRBuilder<> Builder(Phi);
1224 std::unique_ptr<PHINode> GetPtrPhi(
1225 PHINode::Create(Builder.getInt32Ty(), NumEdges));
1226 std::unique_ptr<PHINode> HandlePhi(
1227 PHINode::Create(Builder.getInt32Ty(), NumEdges));
1228 std::unique_ptr<PHINode> OffsetPhi(
1229 PHINode::Create(Builder.getInt32Ty(), NumEdges));
1230 bool HasOffset = false;
1231
1232 // Register a ref to this phi for a recursive phi. If a placeholder phi
1233 // below folds to a single value, replaceAllUsesWith updates any cached
1234 // entries that captured it.
1235 if (Phi->getType()->isTargetExtTy())
1236 VisitedPhis[Phi] = AccessIndices{/*GetPtrIdx=*/nullptr, HandlePhi.get(),
1237 /*OffsetIdx=*/nullptr};
1238 else if (Phi->getType()->isPointerTy())
1239 VisitedPhis[Phi] =
1240 AccessIndices{GetPtrPhi.get(), HandlePhi.get(), OffsetPhi.get()};
1241
1242 for (unsigned Idx = 0; Idx < NumEdges; Idx++) {
1243 auto *BB = Phi->getIncomingBlock(Idx);
1244 auto *V = dyn_cast<Instruction>(Phi->getIncomingValue(Idx));
1245 auto AccessIdx = getAccessIndices(V, DeadInsts, VisitedPhis);
1246 if (AccessIdx.hasGetPtrIdx())
1247 GetPtrPhi->addIncoming(AccessIdx.GetPtrIdx, BB);
1248 HandlePhi->addIncoming(AccessIdx.HandleIdx, BB);
1249 if (AccessIdx.hasOffsetIdx()) {
1250 OffsetPhi->addIncoming(AccessIdx.OffsetIdx, BB);
1251 HasOffset = true;
1252 } else {
1253 OffsetPhi->addIncoming(ConstantInt::get(Builder.getInt32Ty(), 0), BB);
1254 }
1255 }
1256
1257 Value *GetPtrIdx;
1258 if (GetPtrPhi->getNumIncomingValues() == 0) {
1259 GetPtrIdx = nullptr;
1260 } else if (Value *ConstantGetPtr = GetPtrPhi->hasConstantValue()) {
1261 GetPtrIdx = ConstantGetPtr;
1262 GetPtrPhi->replaceAllUsesWith(GetPtrIdx);
1263 } else {
1264 GetPtrIdx = GetPtrPhi.release();
1265 Builder.Insert(GetPtrIdx);
1266 }
1267
1268 Value *HandleIdx;
1269 if (Value *ConstantHandle = HandlePhi->hasConstantValue()) {
1270 HandleIdx = ConstantHandle;
1271 HandlePhi->replaceAllUsesWith(HandleIdx);
1272 } else {
1273 HandleIdx = HandlePhi.release();
1274 Builder.Insert(HandleIdx);
1275 }
1276
1277 Value *OffsetIdx = nullptr;
1278 if (HasOffset) {
1279 if (Value *ConstantIdx = OffsetPhi->hasConstantValue()) {
1280 OffsetIdx = ConstantIdx;
1281 OffsetPhi->replaceAllUsesWith(OffsetIdx);
1282 } else {
1283 OffsetIdx = OffsetPhi.release();
1284 Builder.Insert(OffsetIdx);
1285 }
1286 }
1287
1288 // Replace the placeholder entry with the final indices.
1289 AccessIndices Result = {GetPtrIdx, HandleIdx, OffsetIdx};
1290 VisitedPhis[Phi] = Result;
1291 DeadInsts.insert(Phi);
1292 return Result;
1293 }
1294
1295 if (auto *Select = dyn_cast<SelectInst>(I)) {
1296 auto *TrueV = dyn_cast<Instruction>(Select->getTrueValue());
1297 auto TrueAccessIdx = getAccessIndices(TrueV, DeadInsts, VisitedPhis);
1298
1299 auto *FalseV = dyn_cast<Instruction>(Select->getFalseValue());
1300 auto FalseAccessIdx = getAccessIndices(FalseV, DeadInsts, VisitedPhis);
1301
1302 IRBuilder<> Builder(Select);
1303 Value *GetPtrSelect = nullptr;
1304 Value *OffsetSelect = nullptr;
1305
1306 if (TrueAccessIdx.hasGetPtrIdx() && FalseAccessIdx.hasGetPtrIdx())
1307 GetPtrSelect =
1308 Builder.CreateSelect(Select->getCondition(), TrueAccessIdx.GetPtrIdx,
1309 FalseAccessIdx.GetPtrIdx, "", Select);
1310
1311 auto *HandleSelect =
1312 Builder.CreateSelect(Select->getCondition(), TrueAccessIdx.HandleIdx,
1313 FalseAccessIdx.HandleIdx, "", Select);
1314
1315 if (TrueAccessIdx.hasOffsetIdx() || FalseAccessIdx.hasOffsetIdx()) {
1316 Value *Zero = ConstantInt::get(Builder.getInt32Ty(), 0);
1317 Value *TrueOffset =
1318 TrueAccessIdx.hasOffsetIdx() ? TrueAccessIdx.OffsetIdx : Zero;
1319 Value *FalseOffset =
1320 FalseAccessIdx.hasOffsetIdx() ? FalseAccessIdx.OffsetIdx : Zero;
1321 OffsetSelect = Builder.CreateSelect(Select->getCondition(), TrueOffset,
1322 FalseOffset, "", Select);
1323 }
1324
1325 DeadInsts.insert(Select);
1326 return {GetPtrSelect, HandleSelect, OffsetSelect};
1327 }
1328
1329 llvm_unreachable("collectUsedHandles should assure this does not occur");
1330}
1331
1332static void
1335 PhiAccessIndicesMap &VisitedPhis) {
1336 auto AccessIdx = getAccessIndices(Ptr, DeadInsts, VisitedPhis);
1337 assert(AccessIdx.hasHandleIdx() &&
1338 "Couldn't retrieve handle index. This is guaranteed by "
1339 "getAccessIndices");
1340
1341 IRBuilder<> Builder(Ptr);
1342 if (isa<PHINode>(Ptr))
1343 Builder.SetInsertPoint(Ptr->getParent()->getFirstNonPHIIt());
1344 IntrinsicInst *Handle = cast<IntrinsicInst>(OldHandle->clone());
1345 Handle->setArgOperand(/*Index=*/3, AccessIdx.HandleIdx);
1346 Builder.Insert(Handle);
1347
1348 if (Ptr->getType()->isPointerTy()) {
1349 assert(AccessIdx.hasGetPtrIdx() &&
1350 "Couldn't retrieve getpointer index. This is guaranteed by "
1351 "getAccessIndices");
1352 auto *GetPtr = Builder.CreateIntrinsic(Ptr->getType(),
1353 Intrinsic::dx_resource_getpointer,
1354 {Handle, AccessIdx.GetPtrIdx});
1355
1356 // Reapply any byte offset that came from GEPs in the original ptr chain so
1357 // that later access lowering still sees it.
1358 Value *Result = GetPtr;
1359 if (AccessIdx.hasOffsetIdx())
1360 Result = Builder.CreatePtrAdd(GetPtr, AccessIdx.OffsetIdx);
1361 Ptr->replaceAllUsesWith(Result);
1362 } else {
1363 assert(Ptr->getType()->isTargetExtTy() && !AccessIdx.hasGetPtrIdx() &&
1364 "Unexpected resource access operand type");
1365 Ptr->replaceAllUsesWith(Handle);
1366 }
1367
1368 DeadInsts.insert(Ptr);
1369}
1370
1371// Try to legalize dx.resource.handlefrom.*.binding and dx.resource.getpointer
1372// calls with their respective index values and propagate the index values to
1373// be used at resource access.
1374//
1375// If it can't be transformed to be legal then:
1376//
1377// Reports an error if a resource access is not guaranteed into a unique global
1378// resource.
1379//
1380// Returns true if any changes are made.
1383 PhiAccessIndicesMap VisitedPhis;
1384
1385 for (BasicBlock &BB : make_early_inc_range(F)) {
1386 for (Instruction &I : BB) {
1387 if (auto *HandleOp = getHandleOperand(&I)) {
1389 unsigned NumHandles = Handles.size();
1390 if (NumHandles <= 1)
1391 continue; // Legal, no-replacement required
1392
1393 bool SameGlobalBinding = true;
1394 hlsl::Binding B = getHandleIntrinsicBinding(Handles[0], DRTM);
1395 for (unsigned Idx = 1; Idx < NumHandles; Idx++)
1396 SameGlobalBinding &=
1397 (B == getHandleIntrinsicBinding(Handles[Idx], DRTM));
1398
1399 if (!SameGlobalBinding)
1401
1402 replaceHandleWithIndices(getHandleRoot(HandleOp), Handles[0], DeadInsts,
1403 VisitedPhis);
1404 }
1405 }
1406 }
1407
1408 bool MadeChanges = false;
1409
1410 // Set up the phis to track if they are erased below
1411 SmallVector<WeakTrackingVH> ResourcePhis;
1412 for (const auto &HandleToIndex : VisitedPhis)
1413 ResourcePhis.push_back(HandleToIndex.first);
1414
1415 for (auto *I : llvm::reverse(DeadInsts))
1416 if (I->hasNUses(0)) { // Handle can still be used outside of replaced path
1417 I->eraseFromParent();
1418 MadeChanges = true;
1419 }
1420
1421 // Any remaining phi nodes are now looped with another phi node and have no
1422 // other uses
1423 for (WeakTrackingVH &VH : ResourcePhis)
1424 if (VH) // True if not removed above or already in this loop
1425 MadeChanges |= RecursivelyDeleteDeadPHINode(cast<PHINode>(VH));
1426
1427 return MadeChanges;
1428}
1429
1431 SmallVector<User *> Worklist;
1432 for (User *U : II->users())
1433 Worklist.push_back(U);
1434
1436 while (!Worklist.empty()) {
1437 User *U = Worklist.back();
1438 Worklist.pop_back();
1439
1440 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
1441 for (User *U : GEP->users())
1442 Worklist.push_back(U);
1443 DeadInsts.push_back(GEP);
1444
1445 } else if (auto *SI = dyn_cast<StoreInst>(U)) {
1446 assert(SI->getValueOperand() != II && "Pointer escaped!");
1447 createStoreIntrinsic(II, SI, RTI);
1448 DeadInsts.push_back(SI);
1449
1450 } else if (auto *LI = dyn_cast<LoadInst>(U)) {
1451 createLoadIntrinsic(II, LI, RTI);
1452 DeadInsts.push_back(LI);
1453 } else if (auto *AI = dyn_cast<AtomicRMWInst>(U)) {
1455 DeadInsts.push_back(AI);
1456 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(U)) {
1458 DeadInsts.push_back(CXI);
1459 } else
1460 llvm_unreachable("Unhandled instruction - pointer escaped?");
1461 }
1462
1463 // Traverse the now-dead instructions in RPO and remove them.
1464 for (Instruction *Dead : llvm::reverse(DeadInsts))
1465 Dead->eraseFromParent();
1466 II->eraseFromParent();
1467}
1468
1471 for (BasicBlock &BB : make_early_inc_range(F))
1472 for (Instruction &I : BB)
1473 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1474 if (II->getIntrinsicID() == Intrinsic::dx_resource_getpointer ||
1475 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer) {
1476 auto *HandleTy = cast<TargetExtType>(II->getArgOperand(0)->getType());
1477 assert(
1478 (DRTM[HandleTy].isCBuffer() ||
1479 II->getIntrinsicID() != Intrinsic::dx_resource_getbasepointer) &&
1480 "dx_resource_getbasepointer should only be used by cbuffers");
1481 Resources.emplace_back(II, DRTM[HandleTy]);
1482 }
1483
1484 for (auto &[II, RI] : Resources)
1485 replaceAccess(II, RI);
1486
1487 return !Resources.empty();
1488}
1489
1492 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1493 DXILResourceTypeMap *DRTM =
1494 MAMProxy.getCachedResult<DXILResourceTypeAnalysis>(*F.getParent());
1495 assert(DRTM && "DXILResourceTypeAnalysis must be available");
1496
1497 bool MadeHandleChanges = legalizeResourceHandles(F, *DRTM);
1498 bool MadeResourceChanges = transformResourcePointers(F, *DRTM);
1499 if (!(MadeHandleChanges || MadeResourceChanges))
1500 return PreservedAnalyses::all();
1501
1504 return PA;
1505}
1506
1507namespace {
1508class DXILResourceAccessLegacy : public FunctionPass {
1509public:
1510 bool runOnFunction(Function &F) override {
1511 DXILResourceTypeMap &DRTM =
1512 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
1513 bool MadeHandleChanges = legalizeResourceHandles(F, DRTM);
1514 bool MadeResourceChanges = transformResourcePointers(F, DRTM);
1515 return MadeHandleChanges || MadeResourceChanges;
1516 }
1517 StringRef getPassName() const override { return "DXIL Resource Access"; }
1518 DXILResourceAccessLegacy() : FunctionPass(ID) {}
1519
1520 static char ID; // Pass identification.
1521 void getAnalysisUsage(llvm::AnalysisUsage &AU) const override {
1522 AU.addRequired<DXILResourceTypeWrapperPass>();
1523 }
1524};
1525char DXILResourceAccessLegacy::ID = 0;
1526} // end anonymous namespace
1527
1528INITIALIZE_PASS_BEGIN(DXILResourceAccessLegacy, DEBUG_TYPE,
1529 "DXIL Resource Access", false, false)
1531INITIALIZE_PASS_END(DXILResourceAccessLegacy, DEBUG_TYPE,
1532 "DXIL Resource Access", false, false)
1533
1535 return new DXILResourceAccessLegacy();
1536}
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t 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 std::optional< dxil::AtomicBinOpCode > getAtomicBinOpCode(AtomicRMWInst::BinOp BinOp)
static void replaceHandleWithIndices(Instruction *Ptr, IntrinsicInst *OldHandle, SmallSetVector< Instruction *, 16 > &DeadInsts, PhiAccessIndicesMap &VisitedPhis)
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 Value * createDynamicCBufferLoad(IntrinsicInst *II, LoadInst *LI, const CBufferRowIntrin &Intrin, Value *BaseRow, Value *ByteOffset, const KnownBits &WithinRow)
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 Instruction * getHandleRoot(Instruction *I)
static void createBufferAtomicCompareExchange(IntrinsicInst *II, AtomicCmpXchgInst *AI, dxil::ResourceTypeInfo &RTI)
static Value * traverseGEPOffsets(const DataLayout &DL, IRBuilder<> &Builder, Value *Ptr, uint64_t AccessSize)
static Value * loadCBufferRowIntoWindow(IRBuilder<> &Builder, const CBufferRowIntrin &Intrin, Value *Handle, Value *FirstRow, Value *Window, unsigned RowNumber, StringRef Name)
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 KnownBits computeCBufferOffsetKnownBits(Value *Offset, const DataLayout &DL, const Instruction *CxtI)
static Value * accumulateGEPOffset(GetElementPtrInst *GEP, IRBuilder<> &Builder)
static void emitAtomicBinOp(IRBuilder<> &Builder, AtomicRMWInst *AI, Value *Handle, ArrayRef< Value * > Coords)
static AccessIndices getAccessIndices(Instruction *I, SmallSetVector< Instruction *, 16 > &DeadInsts, PhiAccessIndicesMap &VisitedPhis)
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
This file implements a map that provides insertion order iteration.
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 contains the declarations for profiling metadata utility functions.
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
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
AnalysisUsage & addRequired()
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
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
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
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:312
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
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:76
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:549
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
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
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
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 void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
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: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
constexpr unsigned BitWidth
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
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
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
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
void setAllConflict()
Make all bits known to be both zero and one.
Definition KnownBits.h:97
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition KnownBits.h:58
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342