LLVM 23.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/SetVector.h"
15#include "llvm/IR/BasicBlock.h"
17#include "llvm/IR/Dominators.h"
18#include "llvm/IR/IRBuilder.h"
19#include "llvm/IR/Instruction.h"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/IntrinsicsDirectX.h"
24#include "llvm/IR/LLVMContext.h"
25#include "llvm/IR/User.h"
29
30#define DEBUG_TYPE "dxil-resource-access"
31
32using namespace llvm;
33
36 LLVMContext &Context = I->getContext();
37 std::string InstStr;
38 raw_string_ostream InstOS(InstStr);
39 I->print(InstOS);
40 Context.diagnose(
41 DiagnosticInfoGeneric("At resource access:" + Twine(InstStr), DS_Note));
42
43 for (auto *Handle : Handles) {
44 std::string HandleStr;
45 raw_string_ostream HandleOS(HandleStr);
46 Handle->print(HandleOS);
47 Context.diagnose(DiagnosticInfoGeneric(
48 "Uses resource handle:" + Twine(HandleStr), DS_Note));
49 }
50 Context.diagnose(DiagnosticInfoGeneric(
51 "Resource access is not guaranteed to map to a unique global resource"));
52}
53
55 Value *Ptr, uint64_t AccessSize) {
56 Value *Offset = nullptr;
57
58 while (Ptr) {
59 if (auto *II = dyn_cast<IntrinsicInst>(Ptr)) {
60 assert(II->getIntrinsicID() == Intrinsic::dx_resource_getpointer &&
61 "Resource access through unexpected intrinsic");
62 return Offset ? Offset : ConstantInt::get(Builder.getInt32Ty(), 0);
63 }
64
66 assert(GEP && "Resource access through unexpected instruction");
67
68 unsigned NumIndices = GEP->getNumIndices();
69 uint64_t IndexScale = DL.getTypeAllocSize(GEP->getSourceElementType());
70 APInt ConstantOffset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
71 Value *GEPOffset;
72 if (GEP->accumulateConstantOffset(DL, ConstantOffset)) {
73 // We have a constant offset (in bytes).
74 GEPOffset =
75 ConstantInt::get(DL.getIndexType(GEP->getType()), ConstantOffset);
76 IndexScale = 1;
77 } else if (NumIndices == 1) {
78 // If we have a single index we're indexing into a top level array. This
79 // generally only happens with cbuffers.
80 GEPOffset = *GEP->idx_begin();
81 } else if (NumIndices == 2) {
82 // If we have two indices, this should be an access through a pointer.
83 auto *IndexIt = GEP->idx_begin();
84 assert(cast<ConstantInt>(IndexIt)->getZExtValue() == 0 &&
85 "GEP is not indexing through pointer");
86 GEPOffset = *(++IndexIt);
87 } else
88 llvm_unreachable("Unhandled GEP structure for resource access");
89
90 uint64_t ElemSize = AccessSize;
91 if (!(IndexScale % ElemSize)) {
92 // If our scale is an exact multiple of the access size, adjust the
93 // scaling to avoid an unnecessary division.
94 IndexScale /= ElemSize;
95 ElemSize = 1;
96 }
97 if (IndexScale != 1)
98 GEPOffset = Builder.CreateMul(
99 GEPOffset, ConstantInt::get(Builder.getInt32Ty(), IndexScale));
100 if (ElemSize != 1)
101 GEPOffset = Builder.CreateUDiv(
102 GEPOffset, ConstantInt::get(Builder.getInt32Ty(), ElemSize));
103
104 Offset = Offset ? Builder.CreateAdd(Offset, GEPOffset) : GEPOffset;
105 Ptr = GEP->getPointerOperand();
106 }
107
108 llvm_unreachable("GEP of null pointer?");
109}
110
113 const DataLayout &DL = SI->getDataLayout();
114 IRBuilder<> Builder(SI);
115 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
116 Type *ScalarType = ContainedType->getScalarType();
117 Type *LoadType = StructType::get(ContainedType, Builder.getInt1Ty());
118
119 Value *V = SI->getValueOperand();
120 if (V->getType() == ContainedType) {
121 // V is already the right type.
122 assert(SI->getPointerOperand() == II &&
123 "Store of whole element has mismatched address to store to");
124 } else if (V->getType() == ScalarType) {
125 // We're storing a scalar, so we need to load the current value and only
126 // replace the relevant part.
127 auto *Load = Builder.CreateIntrinsic(
128 LoadType, Intrinsic::dx_resource_load_typedbuffer,
129 {II->getOperand(0), II->getOperand(1)});
130 auto *Struct = Builder.CreateExtractValue(Load, {0});
131
132 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
133 Value *Offset =
134 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
135 V = Builder.CreateInsertElement(Struct, V, Offset);
136 } else {
137 llvm_unreachable("Store to typed resource has invalid type");
138 }
139
140 auto *Inst = Builder.CreateIntrinsic(
141 Builder.getVoidTy(), Intrinsic::dx_resource_store_typedbuffer,
142 {II->getOperand(0), II->getOperand(1), V});
143 SI->replaceAllUsesWith(Inst);
144}
145
146static void emitRawStore(IRBuilder<> &Builder, Value *Buffer, Value *Index,
148 // For raw buffer (ie, HLSL's ByteAddressBuffer), we need to fold the access
149 // entirely into the index.
150 if (!RTI.isStruct()) {
151 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
152 if (!ConstantOffset || !ConstantOffset->isZero())
153 Index = Builder.CreateAdd(Index, Offset);
154 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
155 }
156
157 Builder.CreateIntrinsic(Builder.getVoidTy(),
158 Intrinsic::dx_resource_store_rawbuffer,
159 {Buffer, Index, Offset, V});
160}
161
164 const DataLayout &DL = SI->getDataLayout();
165 IRBuilder<> Builder(SI);
166
167 Value *V = SI->getValueOperand();
168 assert(!V->getType()->isAggregateType() &&
169 "Resource store should be scalar or vector type");
170
171 Value *Index = II->getOperand(1);
172 // The offset for the rawbuffer load and store ops is always in bytes.
173 uint64_t AccessSize = 1;
174 Value *Offset =
175 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
176
177 auto *VT = dyn_cast<FixedVectorType>(V->getType());
178 if (VT && VT->getNumElements() > 4) {
179 // Split into stores of at most 4 elements.
180 Type *EltTy = VT->getElementType();
181 Value *Stride = ConstantInt::get(Builder.getInt32Ty(),
182 4 * (DL.getTypeSizeInBits(EltTy) / 8));
183
184 SmallVector<int, 4> Indices;
185 for (unsigned int I = 0, N = VT->getNumElements(); I < N; I += 4) {
186 if (I > 0)
187 Offset = Builder.CreateAdd(Offset, Stride);
188
189 for (unsigned int J = I, E = std::min(N, J + 4); J < E; ++J)
190 Indices.push_back(J);
191 Value *Part = Builder.CreateShuffleVector(V, Indices);
192 emitRawStore(Builder, II->getOperand(0), Index, Offset, Part, RTI);
193
194 Indices.clear();
195 }
196 } else
197 emitRawStore(Builder, II->getOperand(0), Index, Offset, V, RTI);
198}
199
231
234 const DataLayout &DL = LI->getDataLayout();
235 IRBuilder<> Builder(LI);
236 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
237 Type *LoadType = StructType::get(ContainedType, Builder.getInt1Ty());
238
239 Value *V =
240 Builder.CreateIntrinsic(LoadType, Intrinsic::dx_resource_load_typedbuffer,
241 {II->getOperand(0), II->getOperand(1)});
242 V = Builder.CreateExtractValue(V, {0});
243
244 Type *ScalarType = ContainedType->getScalarType();
245 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
246 Value *Offset =
247 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
248 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
249 if (!ConstantOffset || !ConstantOffset->isZero())
250 V = Builder.CreateExtractElement(V, Offset);
251
252 // If we loaded a <1 x ...> instead of a scalar (presumably to feed a
253 // shufflevector), then make sure we're maintaining the resulting type.
254 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType()))
255 if (VT->getNumElements() == 1 && !isa<FixedVectorType>(V->getType()))
256 V = Builder.CreateInsertElement(PoisonValue::get(VT), V,
257 Builder.getInt32(0));
258
259 LI->replaceAllUsesWith(V);
260}
261
262static Value *emitRawLoad(IRBuilder<> &Builder, Type *Ty, Value *Buffer,
263 Value *Index, Value *Offset,
265 // For raw buffer (ie, HLSL's ByteAddressBuffer), we need to fold the access
266 // entirely into the index.
267 if (!RTI.isStruct()) {
268 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
269 if (!ConstantOffset || !ConstantOffset->isZero())
270 Index = Builder.CreateAdd(Index, Offset);
271 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
272 }
273
274 // The load intrinsic includes the bit for CheckAccessFullyMapped, so we need
275 // to add that to the return type.
276 Type *TypeWithCheck = StructType::get(Ty, Builder.getInt1Ty());
277 Value *V = Builder.CreateIntrinsic(TypeWithCheck,
278 Intrinsic::dx_resource_load_rawbuffer,
279 {Buffer, Index, Offset});
280 return Builder.CreateExtractValue(V, {0});
281}
282
285 const DataLayout &DL = LI->getDataLayout();
286 IRBuilder<> Builder(LI);
287
288 Value *Index = II->getOperand(1);
289 // The offset for the rawbuffer load and store ops is always in bytes.
290 uint64_t AccessSize = 1;
291 Value *Offset =
292 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
293
294 // TODO: We could make this handle aggregates by walking the structure and
295 // handling each field individually, but we don't ever generate code that
296 // would hit that so it seems superfluous.
297 assert(!LI->getType()->isAggregateType() &&
298 "Resource load should be scalar or vector type");
299
300 Value *V;
301 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType())) {
302 // Split into loads of at most 4 elements.
303 Type *EltTy = VT->getElementType();
304 Value *Stride = ConstantInt::get(Builder.getInt32Ty(),
305 4 * (DL.getTypeSizeInBits(EltTy) / 8));
306
308 for (unsigned int I = 0, N = VT->getNumElements(); I < N; I += 4) {
309 Type *Ty = FixedVectorType::get(EltTy, N - I < 4 ? N - I : 4);
310 if (I > 0)
311 Offset = Builder.CreateAdd(Offset, Stride);
312 Parts.push_back(
313 emitRawLoad(Builder, Ty, II->getOperand(0), Index, Offset, RTI));
314 }
315
316 V = Parts.size() > 1 ? concatenateVectors(Builder, Parts) : Parts[0];
317 } else
318 V = emitRawLoad(Builder, LI->getType(), II->getOperand(0), Index, Offset,
319 RTI);
320
321 LI->replaceAllUsesWith(V);
322}
323
324namespace {
325/// Helper for building a `load.cbufferrow` intrinsic given a simple type.
326struct CBufferRowIntrin {
327 Intrinsic::ID IID;
328 Type *RetTy;
329 unsigned int EltSize;
330 unsigned int NumElts;
331
332 CBufferRowIntrin(const DataLayout &DL, Type *Ty) {
333 assert(Ty == Ty->getScalarType() && "Expected scalar type");
334
335 switch (DL.getTypeSizeInBits(Ty)) {
336 case 16:
337 IID = Intrinsic::dx_resource_load_cbufferrow_8;
338 RetTy = StructType::get(Ty, Ty, Ty, Ty, Ty, Ty, Ty, Ty);
339 EltSize = 2;
340 NumElts = 8;
341 break;
342 case 32:
343 IID = Intrinsic::dx_resource_load_cbufferrow_4;
344 RetTy = StructType::get(Ty, Ty, Ty, Ty);
345 EltSize = 4;
346 NumElts = 4;
347 break;
348 case 64:
349 IID = Intrinsic::dx_resource_load_cbufferrow_2;
350 RetTy = StructType::get(Ty, Ty);
351 EltSize = 8;
352 NumElts = 2;
353 break;
354 default:
355 llvm_unreachable("Only 16, 32, and 64 bit types supported");
356 }
357 }
358};
359} // namespace
360
363 const DataLayout &DL = LI->getDataLayout();
364
365 Type *Ty = LI->getType();
366 assert(!isa<StructType>(Ty) && "Structs not handled yet");
367 CBufferRowIntrin Intrin(DL, Ty->getScalarType());
368
369 StringRef Name = LI->getName();
370 Value *Handle = II->getOperand(0);
371
372 IRBuilder<> Builder(LI);
373
374 ConstantInt *GlobalOffset = dyn_cast<ConstantInt>(II->getOperand(1));
375 assert(GlobalOffset && "CBuffer getpointer index must be constant");
376
377 uint64_t GlobalOffsetVal = GlobalOffset->getZExtValue();
378 Value *CurrentRow = ConstantInt::get(
379 Builder.getInt32Ty(), GlobalOffsetVal / hlsl::CBufferRowSizeInBytes);
380 unsigned int CurrentIndex =
381 (GlobalOffsetVal % hlsl::CBufferRowSizeInBytes) / Intrin.EltSize;
382
383 // Every object in a cbuffer either fits in a row or is aligned to a row. This
384 // means that only the very last pointer access can point into a row.
385 auto *LastGEP = dyn_cast<GEPOperator>(LI->getPointerOperand());
386 if (!LastGEP) {
387 // If we don't have a GEP at all we're just accessing the resource through
388 // the result of getpointer directly.
389 assert(LI->getPointerOperand() == II &&
390 "Unexpected indirect access to resource without GEP");
391 } else {
392 Value *GEPOffset = traverseGEPOffsets(
393 DL, Builder, LastGEP->getPointerOperand(), hlsl::CBufferRowSizeInBytes);
394 CurrentRow = Builder.CreateAdd(GEPOffset, CurrentRow);
395
396 APInt ConstantOffset(DL.getIndexTypeSizeInBits(LastGEP->getType()), 0);
397 if (LastGEP->accumulateConstantOffset(DL, ConstantOffset)) {
398 APInt Remainder(DL.getIndexTypeSizeInBits(LastGEP->getType()),
400 APInt::udivrem(ConstantOffset, Remainder, ConstantOffset, Remainder);
401 CurrentRow = Builder.CreateAdd(
402 CurrentRow, ConstantInt::get(Builder.getInt32Ty(), ConstantOffset));
403 CurrentIndex += Remainder.udiv(Intrin.EltSize).getZExtValue();
404 } else {
405 assert(LastGEP->getNumIndices() == 1 &&
406 "Last GEP of cbuffer access is not array or struct access");
407 // We assume a non-constant access will be row-aligned. This is safe
408 // because arrays and structs are always row aligned, and accesses to
409 // vector elements will show up as a load of the vector followed by an
410 // extractelement.
411 CurrentRow = cast<ConstantInt>(CurrentRow)->isZero()
412 ? *LastGEP->idx_begin()
413 : Builder.CreateAdd(CurrentRow, *LastGEP->idx_begin());
414 CurrentIndex = 0;
415 }
416 }
417
418 auto *CBufLoad = Builder.CreateIntrinsic(
419 Intrin.RetTy, Intrin.IID, {Handle, CurrentRow}, nullptr, Name + ".load");
420 auto *Elt =
421 Builder.CreateExtractValue(CBufLoad, {CurrentIndex++}, Name + ".extract");
422
423 // At this point we've loaded the first scalar of our result, but our original
424 // type may have been a vector.
425 unsigned int Remaining =
426 ((DL.getTypeSizeInBits(Ty) / 8) / Intrin.EltSize) - 1;
427 if (Remaining == 0) {
428 // We only have a single element, so we're done.
429 Value *Result = Elt;
430
431 // However, if we loaded a <1 x T>, then we need to adjust the type.
432 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
433 assert(VT->getNumElements() == 1 && "Can't have multiple elements here");
434 Result = Builder.CreateInsertElement(PoisonValue::get(VT), Result,
435 Builder.getInt32(0), Name);
436 }
437 LI->replaceAllUsesWith(Result);
438 return;
439 }
440
441 // Walk each element and extract it, wrapping to new rows as needed.
442 SmallVector<Value *> Extracts{Elt};
443 while (Remaining--) {
444 CurrentIndex %= Intrin.NumElts;
445
446 if (CurrentIndex == 0) {
447 CurrentRow = Builder.CreateAdd(CurrentRow,
448 ConstantInt::get(Builder.getInt32Ty(), 1));
449 CBufLoad = Builder.CreateIntrinsic(Intrin.RetTy, Intrin.IID,
450 {Handle, CurrentRow}, nullptr,
451 Name + ".load");
452 }
453
454 Extracts.push_back(Builder.CreateExtractValue(CBufLoad, {CurrentIndex++},
455 Name + ".extract"));
456 }
457
458 // Finally, we build up the original loaded value.
459 Value *Result = PoisonValue::get(Ty);
460 for (int I = 0, E = Extracts.size(); I < E; ++I)
461 Result = Builder.CreateInsertElement(
462 Result, Extracts[I], Builder.getInt32(I), Name + formatv(".upto{}", I));
463 LI->replaceAllUsesWith(Result);
464}
465
498
500 if (auto *LI = dyn_cast<LoadInst>(AI))
501 return dyn_cast<Instruction>(LI->getPointerOperand());
502 if (auto *SI = dyn_cast<StoreInst>(AI))
503 return dyn_cast<Instruction>(SI->getPointerOperand());
504
505 return nullptr;
506}
507
508static const std::array<Intrinsic::ID, 2> HandleIntrins = {
509 Intrinsic::dx_resource_handlefrombinding,
510 Intrinsic::dx_resource_handlefromimplicitbinding,
511};
512
514 SmallVector<Value *> Worklist = {Ptr};
516
517 while (!Worklist.empty()) {
518 Value *X = Worklist.pop_back_val();
519
520 if (!X->getType()->isPointerTy() && !X->getType()->isTargetExtTy())
521 return {}; // Early exit on store/load into non-resource
522
523 if (auto *Phi = dyn_cast<PHINode>(X))
524 for (Use &V : Phi->incoming_values())
525 Worklist.push_back(V.get());
526 else if (auto *Select = dyn_cast<SelectInst>(X))
527 for (Value *V : {Select->getTrueValue(), Select->getFalseValue()})
528 Worklist.push_back(V);
529 else if (auto *II = dyn_cast<IntrinsicInst>(X)) {
530 Intrinsic::ID IID = II->getIntrinsicID();
531
532 if (IID == Intrinsic::dx_resource_getpointer)
533 Worklist.push_back(II->getArgOperand(/*Handle=*/0));
534
536 Handles.push_back(II);
537 }
538 }
539
540 return Handles;
541}
542
544 DXILResourceTypeMap &DRTM) {
546 "Only expects a Handle as determined from collectUsedHandles.");
547
548 auto *HandleTy = cast<TargetExtType>(Handle->getType());
549 dxil::ResourceClass Class = DRTM[HandleTy].getResourceClass();
550 uint32_t Space = cast<ConstantInt>(Handle->getArgOperand(0))->getZExtValue();
551 uint32_t LowerBound =
552 cast<ConstantInt>(Handle->getArgOperand(1))->getZExtValue();
553 uint32_t Size = cast<ConstantInt>(Handle->getArgOperand(2))->getZExtValue();
554 uint32_t UpperBound = Size == UINT32_MAX ? UINT32_MAX : LowerBound + Size - 1;
555
556 return hlsl::Binding(Class, Space, LowerBound, UpperBound, nullptr);
557}
558
559namespace {
560/// Helper for propagating the current handle and ptr indices.
561struct AccessIndices {
562 Value *GetPtrIdx;
563 Value *HandleIdx;
564
565 bool hasGetPtrIdx() { return GetPtrIdx != nullptr; }
566 bool hasHandleIdx() { return HandleIdx != nullptr; }
567};
568} // namespace
569
570// getAccessIndices traverses up the control flow that a ptr came from and
571// propagates back the indicies used to access the resource (AccessIndices):
572//
573// - GetPtrIdx is the index of dx.resource.getpointer
574// - HandleIdx is the index of dx.resource.handlefrom.*
575static AccessIndices
577 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
578 if (llvm::is_contained(HandleIntrins, II->getIntrinsicID())) {
579 DeadInsts.insert(II);
580 return {nullptr, II->getArgOperand(/*Index=*/3)};
581 }
582
583 if (II->getIntrinsicID() == Intrinsic::dx_resource_getpointer) {
584 auto *V = dyn_cast<Instruction>(II->getArgOperand(/*Handle=*/0));
585 auto AccessIdx = getAccessIndices(V, DeadInsts);
586 assert(!AccessIdx.hasGetPtrIdx() &&
587 "Encountered multiple dx.resource.getpointers in ptr chain?");
588 AccessIdx.GetPtrIdx = II->getArgOperand(1);
589
590 DeadInsts.insert(II);
591 return AccessIdx;
592 }
593 }
594
595 if (auto *Phi = dyn_cast<PHINode>(I)) {
596 unsigned NumEdges = Phi->getNumIncomingValues();
597 assert(NumEdges != 0 && "Malformed Phi Node");
598
599 IRBuilder<> Builder(Phi);
600 PHINode *GetPtrPhi = PHINode::Create(Builder.getInt32Ty(), NumEdges);
601 PHINode *HandlePhi = PHINode::Create(Builder.getInt32Ty(), NumEdges);
602
603 bool HasGetPtr = true;
604 for (unsigned Idx = 0; Idx < NumEdges; Idx++) {
605 auto *BB = Phi->getIncomingBlock(Idx);
606 auto *V = dyn_cast<Instruction>(Phi->getIncomingValue(Idx));
607 auto AccessIdx = getAccessIndices(V, DeadInsts);
608 HasGetPtr &= AccessIdx.hasGetPtrIdx();
609 if (HasGetPtr)
610 GetPtrPhi->addIncoming(AccessIdx.GetPtrIdx, BB);
611 HandlePhi->addIncoming(AccessIdx.HandleIdx, BB);
612 }
613
614 if (HasGetPtr)
615 Builder.Insert(GetPtrPhi);
616 else
617 GetPtrPhi = nullptr;
618
619 Builder.Insert(HandlePhi);
620
621 DeadInsts.insert(Phi);
622 return {GetPtrPhi, HandlePhi};
623 }
624
625 if (auto *Select = dyn_cast<SelectInst>(I)) {
626 auto *TrueV = dyn_cast<Instruction>(Select->getTrueValue());
627 auto TrueAccessIdx = getAccessIndices(TrueV, DeadInsts);
628
629 auto *FalseV = dyn_cast<Instruction>(Select->getFalseValue());
630 auto FalseAccessIdx = getAccessIndices(FalseV, DeadInsts);
631
632 IRBuilder<> Builder(Select);
633 Value *GetPtrSelect = nullptr;
634
635 if (TrueAccessIdx.hasGetPtrIdx() && FalseAccessIdx.hasGetPtrIdx())
636 GetPtrSelect =
637 Builder.CreateSelect(Select->getCondition(), TrueAccessIdx.GetPtrIdx,
638 FalseAccessIdx.GetPtrIdx);
639
640 auto *HandleSelect =
641 Builder.CreateSelect(Select->getCondition(), TrueAccessIdx.HandleIdx,
642 FalseAccessIdx.HandleIdx);
643 DeadInsts.insert(Select);
644 return {GetPtrSelect, HandleSelect};
645 }
646
647 llvm_unreachable("collectUsedHandles should assure this does not occur");
648}
649
650static void
653 auto AccessIdx = getAccessIndices(Ptr, DeadInsts);
654 assert(AccessIdx.hasGetPtrIdx() && AccessIdx.hasHandleIdx() &&
655 "Couldn't retrieve indices. This is guaranteed by getAccessIndices");
656
657 IRBuilder<> Builder(Ptr);
658 IntrinsicInst *Handle = cast<IntrinsicInst>(OldHandle->clone());
659 Handle->setArgOperand(/*Index=*/3, AccessIdx.HandleIdx);
660 Builder.Insert(Handle);
661
662 auto *GetPtr =
663 Builder.CreateIntrinsic(Ptr->getType(), Intrinsic::dx_resource_getpointer,
664 {Handle, AccessIdx.GetPtrIdx});
665
666 Ptr->replaceAllUsesWith(GetPtr);
667 DeadInsts.insert(Ptr);
668}
669
670// Try to legalize dx.resource.handlefrom.*.binding and dx.resource.getpointer
671// calls with their respective index values and propagate the index values to
672// be used at resource access.
673//
674// If it can't be transformed to be legal then:
675//
676// Reports an error if a resource access is not guaranteed into a unique global
677// resource.
678//
679// Returns true if any changes are made.
682 for (BasicBlock &BB : make_early_inc_range(F)) {
683 for (Instruction &I : BB) {
684 if (auto *PtrOp = getStoreLoadPointerOperand(&I)) {
686 unsigned NumHandles = Handles.size();
687 if (NumHandles <= 1)
688 continue; // Legal, no-replacement required
689
690 bool SameGlobalBinding = true;
691 hlsl::Binding B = getHandleIntrinsicBinding(Handles[0], DRTM);
692 for (unsigned Idx = 1; Idx < NumHandles; Idx++)
693 SameGlobalBinding &=
694 (B == getHandleIntrinsicBinding(Handles[Idx], DRTM));
695
696 if (!SameGlobalBinding) {
698 continue;
699 }
700
701 replaceHandleWithIndices(PtrOp, Handles[0], DeadInsts);
702 }
703 }
704 }
705
706 bool MadeChanges = false;
707
708 for (auto *I : llvm::reverse(DeadInsts))
709 if (I->hasNUses(0)) { // Handle can still be used outside of replaced path
710 I->eraseFromParent();
711 MadeChanges = true;
712 }
713
714 return MadeChanges;
715}
716
718 SmallVector<User *> Worklist;
719 for (User *U : II->users())
720 Worklist.push_back(U);
721
723 while (!Worklist.empty()) {
724 User *U = Worklist.back();
725 Worklist.pop_back();
726
727 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
728 for (User *U : GEP->users())
729 Worklist.push_back(U);
730 DeadInsts.push_back(GEP);
731
732 } else if (auto *SI = dyn_cast<StoreInst>(U)) {
733 assert(SI->getValueOperand() != II && "Pointer escaped!");
735 DeadInsts.push_back(SI);
736
737 } else if (auto *LI = dyn_cast<LoadInst>(U)) {
738 createLoadIntrinsic(II, LI, RTI);
739 DeadInsts.push_back(LI);
740 } else
741 llvm_unreachable("Unhandled instruction - pointer escaped?");
742 }
743
744 // Traverse the now-dead instructions in RPO and remove them.
745 for (Instruction *Dead : llvm::reverse(DeadInsts))
746 Dead->eraseFromParent();
747 II->eraseFromParent();
748}
749
753 for (Instruction &I : BB)
754 if (auto *II = dyn_cast<IntrinsicInst>(&I))
755 if (II->getIntrinsicID() == Intrinsic::dx_resource_getpointer) {
756 auto *HandleTy = cast<TargetExtType>(II->getArgOperand(0)->getType());
757 Resources.emplace_back(II, DRTM[HandleTy]);
758 }
759
760 for (auto &[II, RI] : Resources)
761 replaceAccess(II, RI);
762
763 return !Resources.empty();
764}
765
768 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
769 DXILResourceTypeMap *DRTM =
770 MAMProxy.getCachedResult<DXILResourceTypeAnalysis>(*F.getParent());
771 assert(DRTM && "DXILResourceTypeAnalysis must be available");
772
773 bool MadeHandleChanges = legalizeResourceHandles(F, *DRTM);
774 bool MadeResourceChanges = transformResourcePointers(F, *DRTM);
775 if (!(MadeHandleChanges || MadeResourceChanges))
776 return PreservedAnalyses::all();
777
781 return PA;
782}
783
784namespace {
785class DXILResourceAccessLegacy : public FunctionPass {
786public:
787 bool runOnFunction(Function &F) override {
788 DXILResourceTypeMap &DRTM =
789 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
790 bool MadeHandleChanges = legalizeResourceHandles(F, DRTM);
791 bool MadeResourceChanges = transformResourcePointers(F, DRTM);
792 return MadeHandleChanges || MadeResourceChanges;
793 }
794 StringRef getPassName() const override { return "DXIL Resource Access"; }
795 DXILResourceAccessLegacy() : FunctionPass(ID) {}
796
797 static char ID; // Pass identification.
798 void getAnalysisUsage(llvm::AnalysisUsage &AU) const override {
799 AU.addRequired<DXILResourceTypeWrapperPass>();
800 AU.addPreserved<DominatorTreeWrapperPass>();
801 }
802};
803char DXILResourceAccessLegacy::ID = 0;
804} // end anonymous namespace
805
806INITIALIZE_PASS_BEGIN(DXILResourceAccessLegacy, DEBUG_TYPE,
807 "DXIL Resource Access", false, false)
809INITIALIZE_PASS_END(DXILResourceAccessLegacy, DEBUG_TYPE,
810 "DXIL Resource Access", false, false)
811
813 return new DXILResourceAccessLegacy();
814}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:849
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static void diagnoseNonUniqueResourceAccess(Instruction *I, ArrayRef< IntrinsicInst * > Handles)
static void createLoadIntrinsic(IntrinsicInst *II, LoadInst *LI, 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 AccessIndices getAccessIndices(Instruction *I, SmallSetVector< Instruction *, 16 > &DeadInsts)
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 replaceHandleWithIndices(Instruction *Ptr, IntrinsicInst *OldHandle, SmallSetVector< Instruction *, 16 > &DeadInsts)
static void emitRawStore(IRBuilder<> &Builder, Value *Buffer, Value *Index, Value *Offset, Value *V, dxil::ResourceTypeInfo &RTI)
static Value * traverseGEPOffsets(const DataLayout &DL, IRBuilder<> &Builder, Value *Ptr, uint64_t AccessSize)
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 createRawLoads(IntrinsicInst *II, LoadInst *LI, dxil::ResourceTypeInfo &RTI)
static Instruction * getStoreLoadPointerOperand(Instruction *AI)
static void replaceAccess(IntrinsicInst *II, dxil::ResourceTypeInfo &RTI)
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Hexagon Common GEP
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file implements a set that has insertion order iteration characteristics.
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1584
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1769
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1555
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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
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
Analysis pass which computes a DominatorTree.
Definition Dominators.h:283
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:802
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:2788
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()
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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:151
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
reference emplace_back(ArgTypes &&... Args)
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
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:413
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:45
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:304
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
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:256
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:322
TargetExtType * getHandleTy() const
LLVM_ABI bool isStruct() const
dxil::ResourceKind getResourceKind() const
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
const unsigned CBufferRowSizeInBytes
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
@ 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
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
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:634
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
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.
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