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
333static void emitAtomicBinOp(IRBuilder<> &Builder, AtomicRMWInst *AI,
334 Value *Handle, ArrayRef<Value *> Coords) {
335 assert(!Coords.empty() && Coords.size() <= 3 &&
336 "Atomic operations take between one and three coordinates");
337
338 std::optional<dxil::AtomicBinOpCode> BinOpCode =
340 if (!BinOpCode) {
341 reportFatalUsageError("DXIL resource atomicrmw operation not implemented");
342 return;
343 }
344
346 Handle, Builder.getInt32(static_cast<uint32_t>(*BinOpCode))};
347 append_range(Args, Coords);
348 Args.append(3 - Coords.size(), PoisonValue::get(Builder.getInt32Ty()));
349 Args.push_back(AI->getValOperand());
350
351 // Emit the target-independent intrinsic; DXILOpLowering lowers it to the
352 // DXIL `AtomicBinOp` op and handles the target-ext-typed handle cast via
353 // its `createTmpHandleCast` bookkeeping.
354 Value *Result = Builder.CreateIntrinsic(
355 AI->getType(), Intrinsic::dx_resource_atomic_binop, Args);
356
357 AI->replaceAllUsesWith(Result);
358}
359
362 const DataLayout &DL = AI->getDataLayout();
363 IRBuilder<> Builder(AI);
364 Value *Index = II->getOperand(1);
365
366 // The offset for the rawbuffer load/store/atomic ops is always in bytes.
367 uint64_t AccessSize = 1;
368 Value *Offset =
369 traverseGEPOffsets(DL, Builder, AI->getPointerOperand(), AccessSize);
370
371 // For non-struct buffers (RawBuffer or TypedBuffer), fold the byte offset
372 // into the index and only pass a single coordinate — only StructuredBuffer
373 // atomics use both a struct index and a byte offset.
374 if (!RTI.isStruct()) {
375 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
376 if (!ConstantOffset || !ConstantOffset->isZero())
377 Index = Builder.CreateAdd(Index, Offset);
378
379 emitAtomicBinOp(Builder, AI, II->getOperand(0), {Index});
380 return;
381 }
382
383 emitAtomicBinOp(Builder, AI, II->getOperand(0), {Index, Offset});
384}
385
388 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
389 if (!ContainedType->isIntegerTy()) {
390 reportFatalUsageError("DXIL atomicrmw requires a texture resource with a "
391 "scalar integer element type");
392 return;
393 }
394
395 IRBuilder<> Builder(AI);
396
397 // The coordinates of a texture access are a scalar or a vector with one
398 // element per texture dimension, including the array slice if there is one.
399 // These map directly onto the coordinate operands of the atomic op.
400 Value *Coords = II->getOperand(1);
401 SmallVector<Value *, 3> CoordArgs;
402 if (auto *VecTy = dyn_cast<FixedVectorType>(Coords->getType())) {
403 assert(VecTy->getNumElements() <= 3 && "Too many texture coordinates");
404 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I)
405 CoordArgs.push_back(Builder.CreateExtractElement(Coords, I));
406 } else {
407 CoordArgs.push_back(Coords);
408 }
409
410 emitAtomicBinOp(Builder, AI, II->getOperand(0), CoordArgs);
411}
412
415 switch (RTI.getResourceKind()) {
419 return createBufferAtomicBinOp(II, AI, RTI);
425 return createTextureAtomicBinOp(II, AI, RTI);
433 "DXIL atomicrmw not implemented for this texture resource kind");
434 return;
439 "DXIL atomicrmw not implemented for this resource type");
440 return;
444 llvm_unreachable("Invalid resource kind for atomicrmw");
445 }
446 llvm_unreachable("Unhandled case in switch");
447}
448
451 const DataLayout &DL = LI->getDataLayout();
452 IRBuilder<> Builder(LI);
453 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
454 Type *LoadType = StructType::get(ContainedType, Builder.getInt1Ty());
455
456 Value *V =
457 Builder.CreateIntrinsic(LoadType, Intrinsic::dx_resource_load_typedbuffer,
458 {II->getOperand(0), II->getOperand(1)});
459 V = Builder.CreateExtractValue(V, {0});
460
461 Type *ScalarType = ContainedType->getScalarType();
462 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
463 Value *Offset =
464 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
465 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
466 if (!ConstantOffset || !ConstantOffset->isZero())
467 V = Builder.CreateExtractElement(V, Offset);
468
469 // If we loaded a <1 x ...> instead of a scalar (presumably to feed a
470 // shufflevector), then make sure we're maintaining the resulting type.
471 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType()))
472 if (VT->getNumElements() == 1 && !isa<FixedVectorType>(V->getType()))
473 V = Builder.CreateInsertElement(PoisonValue::get(VT), V,
474 Builder.getInt32(0));
475
476 LI->replaceAllUsesWith(V);
477}
478
481 const DataLayout &DL = LI->getDataLayout();
482 IRBuilder<> Builder(LI);
483 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
484
485 Value *Handle = II->getOperand(0);
486 Value *Coords = II->getOperand(1);
487
488 // For operator[], mip level is 0.
489 Value *MipLevel = Builder.getInt32(0);
490
491 // For operator[], offsets are zero.
492 Value *Offsets = getNullOffsetsFor(Builder, Coords);
493
494 Value *V =
495 Builder.CreateIntrinsic(ContainedType, Intrinsic::dx_resource_load_level,
496 {Handle, Coords, MipLevel, Offsets});
497
498 Type *ScalarType = ContainedType->getScalarType();
499 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
500 Value *Offset =
501 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
502 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
503 if (!ConstantOffset || !ConstantOffset->isZero())
504 V = Builder.CreateExtractElement(V, Offset);
505
506 // If we loaded a <1 x ...> instead of a scalar (presumably to feed a
507 // shufflevector), then make sure we're maintaining the resulting type.
508 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType()))
509 if (VT->getNumElements() == 1 && !isa<FixedVectorType>(V->getType()))
510 V = Builder.CreateInsertElement(PoisonValue::get(VT), V,
511 Builder.getInt32(0));
512
513 LI->replaceAllUsesWith(V);
514}
515
516static Value *emitRawLoad(IRBuilder<> &Builder, Type *Ty, Value *Buffer,
517 Value *Index, Value *Offset,
519 // For raw buffer (ie, HLSL's ByteAddressBuffer), we need to fold the access
520 // entirely into the index.
521 if (!RTI.isStruct()) {
522 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
523 if (!ConstantOffset || !ConstantOffset->isZero())
524 Index = Builder.CreateAdd(Index, Offset);
525 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
526 }
527
528 // The load intrinsic includes the bit for CheckAccessFullyMapped, so we need
529 // to add that to the return type.
530 Type *TypeWithCheck = StructType::get(Ty, Builder.getInt1Ty());
531 Value *V = Builder.CreateIntrinsic(TypeWithCheck,
532 Intrinsic::dx_resource_load_rawbuffer,
533 {Buffer, Index, Offset});
534 return Builder.CreateExtractValue(V, {0});
535}
536
539 const DataLayout &DL = LI->getDataLayout();
540 IRBuilder<> Builder(LI);
541
542 Value *Index = II->getOperand(1);
543 // The offset for the rawbuffer load and store ops is always in bytes.
544 uint64_t AccessSize = 1;
545 Value *Offset =
546 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
547
548 // TODO: We could make this handle aggregates by walking the structure and
549 // handling each field individually, but we don't ever generate code that
550 // would hit that so it seems superfluous.
551 assert(!LI->getType()->isAggregateType() &&
552 "Resource load should be scalar or vector type");
553
554 Value *V;
555 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType())) {
556 // Split into loads of at most 4 elements.
557 Type *EltTy = VT->getElementType();
558 Value *Stride = ConstantInt::get(Builder.getInt32Ty(),
559 4 * (DL.getTypeSizeInBits(EltTy) / 8));
560
562 for (unsigned int I = 0, N = VT->getNumElements(); I < N; I += 4) {
563 Type *Ty = FixedVectorType::get(EltTy, N - I < 4 ? N - I : 4);
564 if (I > 0)
565 Offset = Builder.CreateAdd(Offset, Stride);
566 Parts.push_back(
567 emitRawLoad(Builder, Ty, II->getOperand(0), Index, Offset, RTI));
568 }
569
570 V = Parts.size() > 1 ? concatenateVectors(Builder, Parts) : Parts[0];
571 } else
572 V = emitRawLoad(Builder, LI->getType(), II->getOperand(0), Index, Offset,
573 RTI);
574
575 LI->replaceAllUsesWith(V);
576}
577
578namespace {
579/// Helper for building a `load.cbufferrow` intrinsic given a simple type.
580struct CBufferRowIntrin {
581 Intrinsic::ID IID;
582 Type *RetTy;
583 unsigned int EltSize;
584 unsigned int NumElts;
585
586 CBufferRowIntrin(const DataLayout &DL, Type *Ty) {
587 assert(Ty == Ty->getScalarType() && "Expected scalar type");
588
589 switch (DL.getTypeSizeInBits(Ty)) {
590 case 16:
591 IID = Intrinsic::dx_resource_load_cbufferrow_8;
592 RetTy = StructType::get(Ty, Ty, Ty, Ty, Ty, Ty, Ty, Ty);
593 EltSize = 2;
594 NumElts = 8;
595 break;
596 case 32:
597 IID = Intrinsic::dx_resource_load_cbufferrow_4;
598 RetTy = StructType::get(Ty, Ty, Ty, Ty);
599 EltSize = 4;
600 NumElts = 4;
601 break;
602 case 64:
603 IID = Intrinsic::dx_resource_load_cbufferrow_2;
604 RetTy = StructType::get(Ty, Ty);
605 EltSize = 8;
606 NumElts = 2;
607 break;
608 default:
609 llvm_unreachable("Only 16, 32, and 64 bit types supported");
610 }
611 }
612};
613} // namespace
614
617 const DataLayout &DL = LI->getDataLayout();
618
619 Type *Ty = LI->getType();
620 assert(!isa<StructType>(Ty) && "Structs not handled yet");
621 CBufferRowIntrin Intrin(DL, Ty->getScalarType());
622
623 StringRef Name = LI->getName();
624 Value *Handle = II->getOperand(0);
625
626 IRBuilder<> Builder(LI);
627
628 ConstantInt *GlobalOffset =
629 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer
630 ? ConstantInt::get(Builder.getInt32Ty(), 0)
631 : dyn_cast<ConstantInt>(II->getOperand(1));
632 assert(GlobalOffset && "CBuffer getpointer index must be constant");
633
634 uint64_t GlobalOffsetVal = GlobalOffset->getZExtValue();
635 Value *CurrentRow = ConstantInt::get(
636 Builder.getInt32Ty(), GlobalOffsetVal / hlsl::CBufferRowSizeInBytes);
637 unsigned int CurrentIndex =
638 (GlobalOffsetVal % hlsl::CBufferRowSizeInBytes) / Intrin.EltSize;
639
640 // Every object in a cbuffer either fits in a row or is aligned to a row. This
641 // means that only the very last pointer access can point into a row.
642 auto *LastGEP = dyn_cast<GEPOperator>(LI->getPointerOperand());
643 if (!LastGEP) {
644 // If we don't have a GEP at all we're just accessing the resource through
645 // the result of getpointer directly.
646 assert(LI->getPointerOperand() == II &&
647 "Unexpected indirect access to resource without GEP");
648 } else {
649 Value *GEPOffset = traverseGEPOffsets(
650 DL, Builder, LastGEP->getPointerOperand(), hlsl::CBufferRowSizeInBytes);
651 CurrentRow = Builder.CreateAdd(GEPOffset, CurrentRow);
652
653 APInt ConstantOffset(DL.getIndexTypeSizeInBits(LastGEP->getType()), 0);
654 if (LastGEP->accumulateConstantOffset(DL, ConstantOffset)) {
655 APInt Remainder(DL.getIndexTypeSizeInBits(LastGEP->getType()),
657 APInt::udivrem(ConstantOffset, Remainder, ConstantOffset, Remainder);
658 CurrentRow = Builder.CreateAdd(
659 CurrentRow, ConstantInt::get(Builder.getInt32Ty(), ConstantOffset));
660 CurrentIndex += Remainder.udiv(Intrin.EltSize).getZExtValue();
661 } else {
662 assert(LastGEP->getNumIndices() == 1 &&
663 "Last GEP of cbuffer access is not array or struct access");
664 // We assume a non-constant access will be row-aligned. This is safe
665 // because arrays and structs are always row aligned, and accesses to
666 // vector elements will show up as a load of the vector followed by an
667 // extractelement.
668 CurrentRow = cast<ConstantInt>(CurrentRow)->isZero()
669 ? *LastGEP->idx_begin()
670 : Builder.CreateAdd(CurrentRow, *LastGEP->idx_begin());
671 CurrentIndex = 0;
672 }
673 }
674
675 auto *CBufLoad = Builder.CreateIntrinsic(
676 Intrin.RetTy, Intrin.IID, {Handle, CurrentRow}, nullptr, Name + ".load");
677 auto *Elt =
678 Builder.CreateExtractValue(CBufLoad, {CurrentIndex++}, Name + ".extract");
679
680 // At this point we've loaded the first scalar of our result, but our original
681 // type may have been a vector.
682 unsigned int Remaining =
683 ((DL.getTypeSizeInBits(Ty) / 8) / Intrin.EltSize) - 1;
684 if (Remaining == 0) {
685 // We only have a single element, so we're done.
686 Value *Result = Elt;
687
688 // However, if we loaded a <1 x T>, then we need to adjust the type.
689 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
690 assert(VT->getNumElements() == 1 && "Can't have multiple elements here");
691 Result = Builder.CreateInsertElement(PoisonValue::get(VT), Result,
692 Builder.getInt32(0), Name);
693 }
694 LI->replaceAllUsesWith(Result);
695 return;
696 }
697
698 // Walk each element and extract it, wrapping to new rows as needed.
699 SmallVector<Value *> Extracts{Elt};
700 while (Remaining--) {
701 CurrentIndex %= Intrin.NumElts;
702
703 if (CurrentIndex == 0) {
704 CurrentRow = Builder.CreateAdd(CurrentRow,
705 ConstantInt::get(Builder.getInt32Ty(), 1));
706 CBufLoad = Builder.CreateIntrinsic(Intrin.RetTy, Intrin.IID,
707 {Handle, CurrentRow}, nullptr,
708 Name + ".load");
709 }
710
711 Extracts.push_back(Builder.CreateExtractValue(CBufLoad, {CurrentIndex++},
712 Name + ".extract"));
713 }
714
715 // Finally, we build up the original loaded value.
716 Value *Result = PoisonValue::get(Ty);
717 for (int I = 0, E = Extracts.size(); I < E; ++I)
718 Result = Builder.CreateInsertElement(
719 Result, Extracts[I], Builder.getInt32(I), Name + formatv(".upto{}", I));
720 LI->replaceAllUsesWith(Result);
721}
722
756
758 if (auto *LI = dyn_cast<LoadInst>(AI))
759 return dyn_cast<Instruction>(LI->getPointerOperand());
760 if (auto *SI = dyn_cast<StoreInst>(AI))
761 return dyn_cast<Instruction>(SI->getPointerOperand());
762 if (auto *RMWI = dyn_cast<AtomicRMWInst>(AI))
763 return dyn_cast<Instruction>(RMWI->getPointerOperand());
764
765 return nullptr;
766}
767
768static const std::array<Intrinsic::ID, 2> HandleIntrins = {
769 Intrinsic::dx_resource_handlefrombinding,
770 Intrinsic::dx_resource_handlefromimplicitbinding,
771};
772
774 SmallVector<Value *> Worklist = {Ptr};
776 SmallSet<Value *, 4> VisitedPhis;
777
778 while (!Worklist.empty()) {
779 Value *X = Worklist.pop_back_val();
780
781 if (!X->getType()->isPointerTy() && !X->getType()->isTargetExtTy())
782 return {}; // Early exit on store/load into non-resource
783
784 if (auto *Phi = dyn_cast<PHINode>(X)) {
785 if (VisitedPhis.contains(X))
786 continue;
787 for (Use &V : Phi->incoming_values())
788 Worklist.push_back(V.get());
789 VisitedPhis.insert(Phi);
790 } else if (auto *Select = dyn_cast<SelectInst>(X))
791 for (Value *V : {Select->getTrueValue(), Select->getFalseValue()})
792 Worklist.push_back(V);
793 else if (auto *II = dyn_cast<IntrinsicInst>(X)) {
794 Intrinsic::ID IID = II->getIntrinsicID();
795
796 if (IID == Intrinsic::dx_resource_getpointer)
797 Worklist.push_back(II->getArgOperand(/*Handle=*/0));
798
800 Handles.push_back(II);
801 }
802 }
803
804 return Handles;
805}
806
808 DXILResourceTypeMap &DRTM) {
810 "Only expects a Handle as determined from collectUsedHandles.");
811
812 auto *HandleTy = cast<TargetExtType>(Handle->getType());
813 dxil::ResourceClass Class = DRTM[HandleTy].getResourceClass();
814 uint32_t Space = cast<ConstantInt>(Handle->getArgOperand(0))->getZExtValue();
815 uint32_t LowerBound =
816 cast<ConstantInt>(Handle->getArgOperand(1))->getZExtValue();
817 uint32_t Size = cast<ConstantInt>(Handle->getArgOperand(2))->getZExtValue();
818 uint32_t UpperBound = Size == UINT32_MAX ? UINT32_MAX : LowerBound + Size - 1;
819
820 return hlsl::Binding(Class, Space, LowerBound, UpperBound, nullptr);
821}
822
823namespace {
824/// Helper for propagating the current handle and ptr indices.
825struct AccessIndices {
826 Value *GetPtrIdx;
827 Value *HandleIdx;
828
829 bool hasGetPtrIdx() { return GetPtrIdx != nullptr; }
830 bool hasHandleIdx() { return HandleIdx != nullptr; }
831};
832} // namespace
833
834// getAccessIndices traverses up the control flow that a ptr came from and
835// propagates back the indicies used to access the resource (AccessIndices):
836//
837// - GetPtrIdx is the index of dx.resource.getpointer
838// - HandleIdx is the index of dx.resource.handlefrom.*
839static AccessIndices
842 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
843 if (llvm::is_contained(HandleIntrins, II->getIntrinsicID())) {
844 DeadInsts.insert(II);
845 return {nullptr, II->getArgOperand(/*Index=*/3)};
846 }
847
848 if (II->getIntrinsicID() == Intrinsic::dx_resource_getpointer) {
849 auto *V = dyn_cast<Instruction>(II->getArgOperand(/*Handle=*/0));
850 auto AccessIdx = getAccessIndices(V, DeadInsts, VisitedPhis);
851 assert(!AccessIdx.hasGetPtrIdx() &&
852 "Encountered multiple dx.resource.getpointers in ptr chain?");
853 AccessIdx.GetPtrIdx = II->getArgOperand(1);
854
855 DeadInsts.insert(II);
856 return AccessIdx;
857 }
858 }
859
860 if (auto *Phi = dyn_cast<PHINode>(I)) {
861 // If we're already building indices for this phi, return a ref to the phi
862 if (auto It = VisitedPhis.find(Phi); It != VisitedPhis.end())
863 return {nullptr, It->second};
864
865 unsigned NumEdges = Phi->getNumIncomingValues();
866 assert(NumEdges != 0 && "Malformed Phi Node");
867
868 IRBuilder<> Builder(Phi);
869 std::unique_ptr<PHINode> GetPtrPhi(
870 PHINode::Create(Builder.getInt32Ty(), NumEdges));
871 std::unique_ptr<PHINode> HandlePhi(
872 PHINode::Create(Builder.getInt32Ty(), NumEdges));
873
874 // Register a ref to this phi for a recursive phi. This is safe to add to
875 // the map even if we end up deleting newly created phi below since we can't
876 // possibly have a constant value if we recursed.
877 if (Phi->getType()->isTargetExtTy())
878 VisitedPhis[Phi] = HandlePhi.get();
879
880 for (unsigned Idx = 0; Idx < NumEdges; Idx++) {
881 auto *BB = Phi->getIncomingBlock(Idx);
882 auto *V = dyn_cast<Instruction>(Phi->getIncomingValue(Idx));
883 auto AccessIdx = getAccessIndices(V, DeadInsts, VisitedPhis);
884 if (AccessIdx.hasGetPtrIdx())
885 GetPtrPhi->addIncoming(AccessIdx.GetPtrIdx, BB);
886 HandlePhi->addIncoming(AccessIdx.HandleIdx, BB);
887 }
888
889 Value *GetPtrIdx;
890 if (GetPtrPhi->getNumIncomingValues() == 0)
891 GetPtrIdx = nullptr;
892 else if (Value *ConstantGetPtr = GetPtrPhi->hasConstantValue())
893 GetPtrIdx = ConstantGetPtr;
894 else {
895 GetPtrIdx = GetPtrPhi.release();
896 Builder.Insert(GetPtrIdx);
897 }
898
899 Value *HandleIdx;
900 if (Value *ConstantHandle = HandlePhi->hasConstantValue())
901 HandleIdx = ConstantHandle;
902 else {
903 HandleIdx = HandlePhi.release();
904 Builder.Insert(HandleIdx);
905 }
906
907 DeadInsts.insert(Phi);
908 return {GetPtrIdx, HandleIdx};
909 }
910
911 if (auto *Select = dyn_cast<SelectInst>(I)) {
912 auto *TrueV = dyn_cast<Instruction>(Select->getTrueValue());
913 auto TrueAccessIdx = getAccessIndices(TrueV, DeadInsts, VisitedPhis);
914
915 auto *FalseV = dyn_cast<Instruction>(Select->getFalseValue());
916 auto FalseAccessIdx = getAccessIndices(FalseV, DeadInsts, VisitedPhis);
917
918 IRBuilder<> Builder(Select);
919 Value *GetPtrSelect = nullptr;
920
921 if (TrueAccessIdx.hasGetPtrIdx() && FalseAccessIdx.hasGetPtrIdx())
922 GetPtrSelect =
923 Builder.CreateSelect(Select->getCondition(), TrueAccessIdx.GetPtrIdx,
924 FalseAccessIdx.GetPtrIdx);
925
926 auto *HandleSelect =
927 Builder.CreateSelect(Select->getCondition(), TrueAccessIdx.HandleIdx,
928 FalseAccessIdx.HandleIdx);
929 DeadInsts.insert(Select);
930 return {GetPtrSelect, HandleSelect};
931 }
932
933 llvm_unreachable("collectUsedHandles should assure this does not occur");
934}
935
936static void
940 auto AccessIdx = getAccessIndices(Ptr, DeadInsts, VisitedPhis);
941 assert(AccessIdx.hasGetPtrIdx() && AccessIdx.hasHandleIdx() &&
942 "Couldn't retrieve indices. This is guaranteed by getAccessIndices");
943
944 IRBuilder<> Builder(Ptr);
945 if (isa<PHINode>(Ptr))
946 Builder.SetInsertPoint(Ptr->getParent()->getFirstNonPHIIt());
947 IntrinsicInst *Handle = cast<IntrinsicInst>(OldHandle->clone());
948 Handle->setArgOperand(/*Index=*/3, AccessIdx.HandleIdx);
949 Builder.Insert(Handle);
950
951 auto *GetPtr =
952 Builder.CreateIntrinsic(Ptr->getType(), Intrinsic::dx_resource_getpointer,
953 {Handle, AccessIdx.GetPtrIdx});
954
955 Ptr->replaceAllUsesWith(GetPtr);
956 DeadInsts.insert(Ptr);
957}
958
959// Try to legalize dx.resource.handlefrom.*.binding and dx.resource.getpointer
960// calls with their respective index values and propagate the index values to
961// be used at resource access.
962//
963// If it can't be transformed to be legal then:
964//
965// Reports an error if a resource access is not guaranteed into a unique global
966// resource.
967//
968// Returns true if any changes are made.
972
973 for (BasicBlock &BB : make_early_inc_range(F)) {
974 for (Instruction &I : BB) {
975 if (auto *PtrOp = getStoreLoadPointerOperand(&I)) {
977 unsigned NumHandles = Handles.size();
978 if (NumHandles <= 1)
979 continue; // Legal, no-replacement required
980
981 bool SameGlobalBinding = true;
982 hlsl::Binding B = getHandleIntrinsicBinding(Handles[0], DRTM);
983 for (unsigned Idx = 1; Idx < NumHandles; Idx++)
984 SameGlobalBinding &=
985 (B == getHandleIntrinsicBinding(Handles[Idx], DRTM));
986
987 if (!SameGlobalBinding) {
989 continue;
990 }
991
992 replaceHandleWithIndices(PtrOp, Handles[0], DeadInsts, VisitedPhis);
993 }
994 }
995 }
996
997 bool MadeChanges = false;
998
999 // Set up the phis to track if they are erased below
1000 SmallVector<WeakTrackingVH> ResourcePhis;
1001 for (const auto &HandleToIndex : VisitedPhis)
1002 ResourcePhis.push_back(HandleToIndex.first);
1003
1004 for (auto *I : llvm::reverse(DeadInsts))
1005 if (I->hasNUses(0)) { // Handle can still be used outside of replaced path
1006 I->eraseFromParent();
1007 MadeChanges = true;
1008 }
1009
1010 // Any remaining phi nodes are now looped with another phi node and have no
1011 // other uses
1012 for (WeakTrackingVH &VH : ResourcePhis)
1013 if (VH) // True if not removed above or already in this loop
1014 MadeChanges |= RecursivelyDeleteDeadPHINode(cast<PHINode>(VH));
1015
1016 return MadeChanges;
1017}
1018
1020 SmallVector<User *> Worklist;
1021 for (User *U : II->users())
1022 Worklist.push_back(U);
1023
1025 while (!Worklist.empty()) {
1026 User *U = Worklist.back();
1027 Worklist.pop_back();
1028
1029 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
1030 for (User *U : GEP->users())
1031 Worklist.push_back(U);
1032 DeadInsts.push_back(GEP);
1033
1034 } else if (auto *SI = dyn_cast<StoreInst>(U)) {
1035 assert(SI->getValueOperand() != II && "Pointer escaped!");
1036 createStoreIntrinsic(II, SI, RTI);
1037 DeadInsts.push_back(SI);
1038
1039 } else if (auto *LI = dyn_cast<LoadInst>(U)) {
1040 createLoadIntrinsic(II, LI, RTI);
1041 DeadInsts.push_back(LI);
1042 } else if (auto *AI = dyn_cast<AtomicRMWInst>(U)) {
1044 DeadInsts.push_back(AI);
1045 } else
1046 llvm_unreachable("Unhandled instruction - pointer escaped?");
1047 }
1048
1049 // Traverse the now-dead instructions in RPO and remove them.
1050 for (Instruction *Dead : llvm::reverse(DeadInsts))
1051 Dead->eraseFromParent();
1052 II->eraseFromParent();
1053}
1054
1057 for (BasicBlock &BB : make_early_inc_range(F))
1058 for (Instruction &I : BB)
1059 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1060 if (II->getIntrinsicID() == Intrinsic::dx_resource_getpointer ||
1061 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer) {
1062 auto *HandleTy = cast<TargetExtType>(II->getArgOperand(0)->getType());
1063 assert(
1064 (DRTM[HandleTy].isCBuffer() ||
1065 II->getIntrinsicID() != Intrinsic::dx_resource_getbasepointer) &&
1066 "dx_resource_getbasepointer should only be used by cbuffers");
1067 Resources.emplace_back(II, DRTM[HandleTy]);
1068 }
1069
1070 for (auto &[II, RI] : Resources)
1071 replaceAccess(II, RI);
1072
1073 return !Resources.empty();
1074}
1075
1078 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1079 DXILResourceTypeMap *DRTM =
1080 MAMProxy.getCachedResult<DXILResourceTypeAnalysis>(*F.getParent());
1081 assert(DRTM && "DXILResourceTypeAnalysis must be available");
1082
1083 bool MadeHandleChanges = legalizeResourceHandles(F, *DRTM);
1084 bool MadeResourceChanges = transformResourcePointers(F, *DRTM);
1085 if (!(MadeHandleChanges || MadeResourceChanges))
1086 return PreservedAnalyses::all();
1087
1091 return PA;
1092}
1093
1094namespace {
1095class DXILResourceAccessLegacy : public FunctionPass {
1096public:
1097 bool runOnFunction(Function &F) override {
1098 DXILResourceTypeMap &DRTM =
1099 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
1100 bool MadeHandleChanges = legalizeResourceHandles(F, DRTM);
1101 bool MadeResourceChanges = transformResourcePointers(F, DRTM);
1102 return MadeHandleChanges || MadeResourceChanges;
1103 }
1104 StringRef getPassName() const override { return "DXIL Resource Access"; }
1105 DXILResourceAccessLegacy() : FunctionPass(ID) {}
1106
1107 static char ID; // Pass identification.
1108 void getAnalysisUsage(llvm::AnalysisUsage &AU) const override {
1109 AU.addRequired<DXILResourceTypeWrapperPass>();
1110 AU.addPreserved<DominatorTreeWrapperPass>();
1111 }
1112};
1113char DXILResourceAccessLegacy::ID = 0;
1114} // end anonymous namespace
1115
1116INITIALIZE_PASS_BEGIN(DXILResourceAccessLegacy, DEBUG_TYPE,
1117 "DXIL Resource Access", false, false)
1119INITIALIZE_PASS_END(DXILResourceAccessLegacy, DEBUG_TYPE,
1120 "DXIL Resource Access", false, false)
1121
1123 return new DXILResourceAccessLegacy();
1124}
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 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 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 void createRawStores(IntrinsicInst *II, StoreInst *SI, dxil::ResourceTypeInfo &RTI)
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 Instruction * getStoreLoadPointerOperand(Instruction *AI)
static void createAtomicBinOpIntrinsic(IntrinsicInst *II, AtomicRMWInst *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:1561
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 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:251
iterator end()
Definition DenseMap.h:169
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
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:2908
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
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
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
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 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:2208
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:633
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:407
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:1947
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