LLVM 24.0.0git
DXILOpLowering.cpp
Go to the documentation of this file.
1//===- DXILOpLowering.cpp - Lowering to DXIL operations -------------------===//
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
9#include "DXILOpLowering.h"
10#include "DXILConstants.h"
11#include "DXILOpBuilder.h"
12#include "DXILRootSignature.h"
13#include "DXILShaderFlags.h"
14#include "DirectX.h"
18#include "llvm/CodeGen/Passes.h"
19#include "llvm/IR/Constant.h"
21#include "llvm/IR/IRBuilder.h"
22#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/IntrinsicsDirectX.h"
26#include "llvm/IR/Module.h"
27#include "llvm/IR/PassManager.h"
28#include "llvm/IR/Use.h"
30#include "llvm/Pass.h"
33
34#define DEBUG_TYPE "dxil-op-lower"
35
36using namespace llvm;
37using namespace llvm::dxil;
38
39/// Write mask covering all four components of a UAV element. Typed UAV stores
40/// (textures and typed buffers) must always use this mask - the DXIL validator
41/// rejects anything narrower. Only raw and / structured buffer stores may use a
42/// partial mask.
43static constexpr uint8_t TypedUAVStoreWriteMask = 0xF;
44
45namespace {
46class OpLowerer {
47 Module &M;
48 DXILOpBuilder OpBuilder;
49 DXILResourceMap &DRM;
51 const ModuleMetadataInfo &MMDI;
52 SmallVector<CallInst *> CleanupCasts;
53 Function *CleanupNURI = nullptr;
54
55public:
56 OpLowerer(Module &M, DXILResourceMap &DRM, DXILResourceTypeMap &DRTM,
57 const ModuleMetadataInfo &MMDI)
58 : M(M), OpBuilder(M), DRM(DRM), DRTM(DRTM), MMDI(MMDI) {}
59
60 /// Replace every call to \c F using \c ReplaceCall, and then erase \c F. If
61 /// there is an error replacing a call, we emit a diagnostic and return true.
62 [[nodiscard]] bool
63 replaceFunction(Function &F,
64 llvm::function_ref<Error(CallInst *CI)> ReplaceCall) {
65 for (User *U : make_early_inc_range(F.users())) {
67 if (!CI)
68 continue;
69
70 if (Error E = ReplaceCall(CI)) {
71 std::string Message(toString(std::move(E)));
72 M.getContext().diagnose(DiagnosticInfoUnsupported(
73 *CI->getFunction(), Message, CI->getDebugLoc()));
74
75 return true;
76 }
77 }
78 if (F.user_empty())
79 F.eraseFromParent();
80 return false;
81 }
82
83 struct IntrinArgSelect {
84 enum class Type {
85#define DXIL_OP_INTRINSIC_ARG_SELECT_TYPE(name) name,
86#include "DXILOperation.inc"
87 };
88 Type Type;
89 int Value;
90 };
91
92 /// Replaces uses of a struct with uses of an equivalent named struct.
93 ///
94 /// DXIL operations that return structs give them well known names, so we need
95 /// to update uses when we switch from an LLVM intrinsic to an op.
96 Error replaceNamedStructUses(CallInst *Intrin, CallInst *DXILOp) {
97 auto *IntrinTy = cast<StructType>(Intrin->getType());
98 auto *DXILOpTy = cast<StructType>(DXILOp->getType());
99 if (!IntrinTy->isLayoutIdentical(DXILOpTy))
101 "Type mismatch between intrinsic and DXIL op",
103
104 for (Use &U : make_early_inc_range(Intrin->uses()))
105 if (auto *EVI = dyn_cast<ExtractValueInst>(U.getUser()))
106 EVI->setOperand(0, DXILOp);
107 else if (auto *IVI = dyn_cast<InsertValueInst>(U.getUser()))
108 IVI->setOperand(0, DXILOp);
109 else
110 return make_error<StringError>("DXIL ops that return structs may only "
111 "be used by insert- and extractvalue",
113 return Error::success();
114 }
115
116 bool isFast(FastMathFlags Flags) {
117 // HLSL Fast Math doesn't enable AllowContract flag; This can be
118 // removed when we enable it in the future.
119 return Flags.allowReassoc() && Flags.noNaNs() && Flags.noInfs() &&
120 Flags.noSignedZeros() && Flags.allowReciprocal() &&
121 Flags.approxFunc();
122 }
123
124 void setDxPrecise(CallInst *CI) {
125 const StringRef Key = "dx.precise";
126 Module *M = CI->getModule();
127
128 LLVMContext &Ctx = M->getContext();
129 MDNode *One =
130 llvm::MDNode::get(Ctx, ConstantAsMetadata::get(ConstantInt::get(
131 llvm::Type::getInt32Ty(Ctx), 1)));
132
133 CI->setMetadata(Key, One);
134 }
135
136 [[nodiscard]] bool
137 replaceFunctionWithOp(Function &F, dxil::OpCode DXILOp,
138 ArrayRef<IntrinArgSelect> ArgSelects) {
139 return replaceFunction(F, [&](CallInst *CI) -> Error {
140 OpBuilder.getIRB().SetInsertPoint(CI);
142 if (ArgSelects.size()) {
143 for (const IntrinArgSelect &A : ArgSelects) {
144 switch (A.Type) {
145 case IntrinArgSelect::Type::Index:
146 Args.push_back(CI->getArgOperand(A.Value));
147 break;
148 case IntrinArgSelect::Type::I8:
149 Args.push_back(OpBuilder.getIRB().getInt8((uint8_t)A.Value));
150 break;
151 case IntrinArgSelect::Type::I32:
152 Args.push_back(OpBuilder.getIRB().getInt32(A.Value));
153 break;
154 }
155 }
156 } else {
157 Args.append(CI->arg_begin(), CI->arg_end());
158 }
159
160 Expected<CallInst *> OpCall =
161 OpBuilder.tryCreateOp(DXILOp, Args, CI->getName(), F.getReturnType());
162 if (Error E = OpCall.takeError())
163 return E;
164
165 if (isa<FPMathOperator>(CI) &&
167 setDxPrecise(*OpCall);
168
169 if (isa<StructType>(CI->getType())) {
170 if (Error E = replaceNamedStructUses(CI, *OpCall))
171 return E;
172 } else
173 CI->replaceAllUsesWith(*OpCall);
174
175 CI->eraseFromParent();
176 return Error::success();
177 });
178 }
179
180 /// Create a cast between a `target("dx")` type and `dx.types.Handle`, which
181 /// is intended to be removed by the end of lowering. This is used to allow
182 /// lowering of ops which need to change their return or argument types in a
183 /// piecemeal way - we can add the casts in to avoid updating all of the uses
184 /// or defs, and by the end all of the casts will be redundant.
185 Value *createTmpHandleCast(Value *V, Type *Ty) {
186 CallInst *Cast = OpBuilder.getIRB().CreateIntrinsicWithoutFolding(
187 Intrinsic::dx_resource_casthandle, {Ty, V->getType()}, {V});
188 CleanupCasts.push_back(Cast);
189 return Cast;
190 }
191
192 void cleanupHandleCasts() {
195
196 for (CallInst *Cast : CleanupCasts) {
197 // These casts were only put in to ease the move from `target("dx")` types
198 // to `dx.types.Handle in a piecemeal way. At this point, all of the
199 // non-cast uses should now be `dx.types.Handle`, and remaining casts
200 // should all form pairs to and from the now unused `target("dx")` type.
201 CastFns.push_back(Cast->getCalledFunction());
202
203 // If the cast is not to `dx.types.Handle`, it should be the first part of
204 // the pair. Keep track so we can remove it once it has no more uses.
205 if (Cast->getType() != OpBuilder.getHandleType()) {
206 ToRemove.push_back(Cast);
207 continue;
208 }
209 // Otherwise, we're the second handle in a pair. Forward the arguments and
210 // remove the (second) cast.
211 CallInst *Def = cast<CallInst>(Cast->getOperand(0));
212 assert(Def->getIntrinsicID() == Intrinsic::dx_resource_casthandle &&
213 "Unbalanced pair of temporary handle casts");
214 Cast->replaceAllUsesWith(Def->getOperand(0));
215 Cast->eraseFromParent();
216 }
217 for (CallInst *Cast : ToRemove) {
218 assert(Cast->user_empty() && "Temporary handle cast still has users");
219 Cast->eraseFromParent();
220 }
221
222 // Deduplicate the cast functions so that we only erase each one once.
223 llvm::sort(CastFns);
224 CastFns.erase(llvm::unique(CastFns), CastFns.end());
225 for (Function *F : CastFns)
226 F->eraseFromParent();
227
228 CleanupCasts.clear();
229 }
230
231 void cleanupNonUniformResourceIndexCalls() {
232 // Replace all NonUniformResourceIndex calls with their argument.
233 if (!CleanupNURI)
234 return;
235 for (User *U : make_early_inc_range(CleanupNURI->users())) {
236 CallInst *CI = dyn_cast<CallInst>(U);
237 if (!CI)
238 continue;
240 CI->eraseFromParent();
241 }
242 CleanupNURI->eraseFromParent();
243 CleanupNURI = nullptr;
244 }
245
246 // Remove the resource global associated with the handleFromBinding call
247 // instruction and their uses as they aren't needed anymore.
248 // TODO: We should verify that all the globals get removed.
249 // It's expected we'll need a custom pass in the future that will eliminate
250 // the need for this here.
251 void removeResourceGlobals(CallInst *CI) {
252 for (User *User : make_early_inc_range(CI->users())) {
253 if (StoreInst *Store = dyn_cast<StoreInst>(User)) {
254 Value *V = Store->getOperand(1);
255 Store->eraseFromParent();
256 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
257 if (GV->use_empty()) {
258 GV->removeDeadConstantUsers();
259 GV->eraseFromParent();
260 }
261 }
262 }
263 }
264
265 void replaceHandleFromBindingCall(CallInst *CI, Value *Replacement) {
267 Intrinsic::dx_resource_handlefrombinding);
268
269 removeResourceGlobals(CI);
270
271 auto *NameGlobal = dyn_cast<llvm::GlobalVariable>(CI->getArgOperand(4));
272
273 CI->replaceAllUsesWith(Replacement);
274 CI->eraseFromParent();
275
276 if (NameGlobal && NameGlobal->use_empty())
277 NameGlobal->removeFromParent();
278 }
279
280 bool hasNonUniformIndex(Value *IndexOp) {
281 if (isa<llvm::Constant>(IndexOp))
282 return false;
283
284 SmallVector<Value *, 16> Worklist;
285 SmallPtrSet<Value *, 16> Visited;
286 Worklist.push_back(IndexOp);
287
288 while (!Worklist.empty()) {
289 Value *V = Worklist.pop_back_val();
290
291 if (isa<llvm::Constant>(V))
292 continue;
293
294 if (!Visited.insert(V).second)
295 continue;
296
297 if (auto *CI = dyn_cast<CallInst>(V))
298 if (CI->getIntrinsicID() == Intrinsic::dx_resource_nonuniformindex)
299 return true;
300
301 // If it's a PHI node, check ALL incoming values —
302 // taint from ANY predecessor counts
303 if (auto *Phi = dyn_cast<PHINode>(V)) {
304 for (Value *Incoming : Phi->incoming_values())
305 Worklist.push_back(Incoming);
306 continue;
307 }
308
309 if (auto *Inst = dyn_cast<Instruction>(V))
310 if (Inst->getNumOperands() > 0 && !Inst->isTerminator())
311 for (Value *Op : Inst->operands())
312 Worklist.push_back(Op);
313 }
314 return false;
315 }
316
317 Error validateRawBufferElementIndex(Value *Resource, Value *ElementIndex) {
318 bool IsStructured =
319 cast<RawBufferExtType>(Resource->getType())->isStructured();
320 bool IsPoison = isa<PoisonValue>(ElementIndex);
321
322 if (IsStructured && IsPoison)
324 "Element index of structured buffer may not be poison",
326
327 if (!IsStructured && !IsPoison)
329 "Element index of raw buffer must be poison",
331
332 return Error::success();
333 }
334
335 [[nodiscard]] bool lowerToCreateHandle(Function &F) {
336 IRBuilder<> &IRB = OpBuilder.getIRB();
337 Type *Int8Ty = IRB.getInt8Ty();
338 Type *Int32Ty = IRB.getInt32Ty();
339 Type *Int1Ty = IRB.getInt1Ty();
340
341 return replaceFunction(F, [&](CallInst *CI) -> Error {
342 IRB.SetInsertPoint(CI);
343
344 auto *It = DRM.find(CI);
345 assert(It != DRM.end() && "Resource not in map?");
346 dxil::ResourceInfo &RI = *It;
347
348 const auto &Binding = RI.getBinding();
349 dxil::ResourceClass RC = DRTM[RI.getHandleTy()].getResourceClass();
350
351 Value *IndexOp = CI->getArgOperand(3);
352 if (Binding.LowerBound != 0)
353 IndexOp = IRB.CreateAdd(IndexOp,
354 ConstantInt::get(Int32Ty, Binding.LowerBound));
355
356 bool HasNonUniformIndex =
357 (Binding.Size == 1) ? false : hasNonUniformIndex(IndexOp);
358 std::array<Value *, 4> Args{
359 ConstantInt::get(Int8Ty, llvm::to_underlying(RC)),
360 ConstantInt::get(Int32Ty, Binding.RecordID), IndexOp,
361 ConstantInt::get(Int1Ty, HasNonUniformIndex)};
362 Expected<CallInst *> OpCall =
363 OpBuilder.tryCreateOp(OpCode::CreateHandle, Args, CI->getName());
364 if (Error E = OpCall.takeError())
365 return E;
366
367 Value *Cast = createTmpHandleCast(*OpCall, CI->getType());
368 replaceHandleFromBindingCall(CI, Cast);
369 return Error::success();
370 });
371 }
372
373 [[nodiscard]] bool lowerToBindAndAnnotateHandle(Function &F) {
374 IRBuilder<> &IRB = OpBuilder.getIRB();
375 Type *Int32Ty = IRB.getInt32Ty();
376 Type *Int1Ty = IRB.getInt1Ty();
377
378 return replaceFunction(F, [&](CallInst *CI) -> Error {
379 IRB.SetInsertPoint(CI);
380
381 auto *It = DRM.find(CI);
382 assert(It != DRM.end() && "Resource not in map?");
383 dxil::ResourceInfo &RI = *It;
384
385 const auto &Binding = RI.getBinding();
386 dxil::ResourceTypeInfo &RTI = DRTM[RI.getHandleTy()];
388
389 Value *IndexOp = CI->getArgOperand(3);
390 if (Binding.LowerBound != 0)
391 IndexOp = IRB.CreateAdd(IndexOp,
392 ConstantInt::get(Int32Ty, Binding.LowerBound));
393
394 std::pair<uint32_t, uint32_t> Props =
395 RI.getAnnotateProps(*F.getParent(), RTI);
396
397 // For `CreateHandleFromBinding` we need the upper bound rather than the
398 // size, so we need to be careful about the difference for "unbounded".
399 uint32_t UpperBound = Binding.Size == 0
400 ? std::numeric_limits<uint32_t>::max()
401 : Binding.LowerBound + Binding.Size - 1;
402 Constant *ResBind = OpBuilder.getResBind(Binding.LowerBound, UpperBound,
403 Binding.Space, RC);
404 bool NonUniformIndex =
405 (Binding.Size == 1) ? false : hasNonUniformIndex(IndexOp);
406 Constant *NonUniformOp = ConstantInt::get(Int1Ty, NonUniformIndex);
407 std::array<Value *, 3> BindArgs{ResBind, IndexOp, NonUniformOp};
408 Expected<CallInst *> OpBind = OpBuilder.tryCreateOp(
409 OpCode::CreateHandleFromBinding, BindArgs, CI->getName());
410 if (Error E = OpBind.takeError())
411 return E;
412
413 std::array<Value *, 2> AnnotateArgs{
414 *OpBind, OpBuilder.getResProps(Props.first, Props.second)};
415 Expected<CallInst *> OpAnnotate = OpBuilder.tryCreateOp(
416 OpCode::AnnotateHandle, AnnotateArgs,
417 CI->hasName() ? CI->getName() + "_annot" : Twine());
418 if (Error E = OpAnnotate.takeError())
419 return E;
420
421 Value *Cast = createTmpHandleCast(*OpAnnotate, CI->getType());
422 replaceHandleFromBindingCall(CI, Cast);
423 return Error::success();
424 });
425 }
426
427 /// Lower `dx.resource.handlefrombinding` intrinsics depending on the shader
428 /// model and taking into account binding information from
429 /// DXILResourceAnalysis.
430 bool lowerHandleFromBinding(Function &F) {
431 if (MMDI.DXILVersion < VersionTuple(1, 6))
432 return lowerToCreateHandle(F);
433 return lowerToBindAndAnnotateHandle(F);
434 }
435
436 /// Replace uses of \c Intrin with the values in the `dx.ResRet` of \c Op.
437 /// Since we expect to be post-scalarization, make an effort to avoid vectors.
438 Error replaceResRetUses(CallInst *Intrin, CallInst *Op, bool HasCheckBit) {
439 IRBuilder<> &IRB = OpBuilder.getIRB();
440
441 Instruction *OldResult = Intrin;
442 Type *OldTy = Intrin->getType();
443
444 if (HasCheckBit) {
445 auto *ST = cast<StructType>(OldTy);
446
447 Value *CheckOp = nullptr;
448 Type *Int32Ty = IRB.getInt32Ty();
449 for (Use &U : make_early_inc_range(OldResult->uses())) {
450 if (auto *EVI = dyn_cast<ExtractValueInst>(U.getUser())) {
451 ArrayRef<unsigned> Indices = EVI->getIndices();
452 assert(Indices.size() == 1);
453 // We're only interested in uses of the check bit for now.
454 if (Indices[0] != 1)
455 continue;
456 if (!CheckOp) {
457 Value *NewEVI = IRB.CreateExtractValue(Op, 4);
458 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
459 OpCode::CheckAccessFullyMapped, {NewEVI},
460 OldResult->hasName() ? OldResult->getName() + "_check"
461 : Twine(),
462 Int32Ty);
463 if (Error E = OpCall.takeError())
464 return E;
465 CheckOp = *OpCall;
466 }
467 EVI->replaceAllUsesWith(CheckOp);
468 EVI->eraseFromParent();
469 }
470 }
471
472 if (OldResult->use_empty()) {
473 // Only the check bit was used, so we're done here.
474 OldResult->eraseFromParent();
475 return Error::success();
476 }
477
478 assert(OldResult->hasOneUse() &&
479 isa<ExtractValueInst>(*OldResult->user_begin()) &&
480 "Expected only use to be extract of first element");
481 OldResult = cast<Instruction>(*OldResult->user_begin());
482 OldTy = ST->getElementType(0);
483 }
484
485 // For scalars, we just extract the first element.
486 if (!isa<FixedVectorType>(OldTy)) {
487 Value *EVI = IRB.CreateExtractValue(Op, 0);
488 OldResult->replaceAllUsesWith(EVI);
489 OldResult->eraseFromParent();
490 if (OldResult != Intrin) {
491 assert(Intrin->use_empty() && "Intrinsic still has uses?");
492 Intrin->eraseFromParent();
493 }
494 return Error::success();
495 }
496
497 std::array<Value *, 4> Extracts = {};
498 SmallVector<ExtractElementInst *> DynamicAccesses;
499
500 // The users of the operation should all be scalarized, so we attempt to
501 // replace the extractelements with extractvalues directly.
502 for (Use &U : make_early_inc_range(OldResult->uses())) {
503 if (auto *EEI = dyn_cast<ExtractElementInst>(U.getUser())) {
504 if (auto *IndexOp = dyn_cast<ConstantInt>(EEI->getIndexOperand())) {
505 size_t IndexVal = IndexOp->getZExtValue();
506 assert(IndexVal < 4 && "Index into buffer load out of range");
507 if (!Extracts[IndexVal])
508 Extracts[IndexVal] = IRB.CreateExtractValue(Op, IndexVal);
509 EEI->replaceAllUsesWith(Extracts[IndexVal]);
510 EEI->eraseFromParent();
511 } else {
512 DynamicAccesses.push_back(EEI);
513 }
514 }
515 }
516
517 const auto *VecTy = cast<FixedVectorType>(OldTy);
518 const unsigned N = VecTy->getNumElements();
519
520 // If there's a dynamic access we need to round trip through stack memory so
521 // that we don't leave vectors around.
522 if (!DynamicAccesses.empty()) {
523 Type *Int32Ty = IRB.getInt32Ty();
524 Constant *Zero = ConstantInt::get(Int32Ty, 0);
525
526 Type *ElTy = VecTy->getElementType();
527 Type *ArrayTy = ArrayType::get(ElTy, N);
528 Value *Alloca = IRB.CreateAlloca(ArrayTy);
529
530 for (int I = 0, E = N; I != E; ++I) {
531 if (!Extracts[I])
532 Extracts[I] = IRB.CreateExtractValue(Op, I);
534 ArrayTy, Alloca, {Zero, ConstantInt::get(Int32Ty, I)});
535 IRB.CreateStore(Extracts[I], GEP);
536 }
537
538 for (ExtractElementInst *EEI : DynamicAccesses) {
539 Value *GEP = IRB.CreateInBoundsGEP(ArrayTy, Alloca,
540 {Zero, EEI->getIndexOperand()});
541 Value *Load = IRB.CreateLoad(ElTy, GEP);
543 EEI->eraseFromParent();
544 }
545 }
546
547 // If we still have uses, then we're not fully scalarized and need to
548 // recreate the vector. This should only happen for things like exported
549 // functions from libraries.
550 if (!OldResult->use_empty()) {
551 for (int I = 0, E = N; I != E; ++I)
552 if (!Extracts[I])
553 Extracts[I] = IRB.CreateExtractValue(Op, I);
554
555 Value *Vec = PoisonValue::get(OldTy);
556 for (int I = 0, E = N; I != E; ++I)
557 Vec = IRB.CreateInsertElement(Vec, Extracts[I], I);
558 OldResult->replaceAllUsesWith(Vec);
559 }
560
561 OldResult->eraseFromParent();
562 if (OldResult != Intrin) {
563 assert(Intrin->use_empty() && "Intrinsic still has uses?");
564 Intrin->eraseFromParent();
565 }
566
567 return Error::success();
568 }
569
570 [[nodiscard]] bool lowerTypedBufferLoad(Function &F, bool HasCheckBit) {
571 IRBuilder<> &IRB = OpBuilder.getIRB();
572 Type *Int32Ty = IRB.getInt32Ty();
573
574 return replaceFunction(F, [&](CallInst *CI) -> Error {
575 IRB.SetInsertPoint(CI);
576
577 Value *Handle =
578 createTmpHandleCast(CI->getArgOperand(0), OpBuilder.getHandleType());
579 Value *Index0 = CI->getArgOperand(1);
580 Value *Index1 = UndefValue::get(Int32Ty);
581
582 Type *OldTy = CI->getType();
583 if (HasCheckBit)
584 OldTy = cast<StructType>(OldTy)->getElementType(0);
585 Type *NewRetTy = OpBuilder.getResRetType(OldTy->getScalarType());
586
587 std::array<Value *, 3> Args{Handle, Index0, Index1};
588 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
589 OpCode::BufferLoad, Args, CI->getName(), NewRetTy);
590 if (Error E = OpCall.takeError())
591 return E;
592 if (Error E = replaceResRetUses(CI, *OpCall, HasCheckBit))
593 return E;
594
595 return Error::success();
596 });
597 }
598
599 // Copies `Src` into `Args` starting at `ArgIdx`. If `Src` is a vector, its
600 // elements are extracted and stored in consecutive slots; otherwise `Src`
601 // is stored directly. At most `MaxElements` elements are expected.
602 static void extractElementsIntoArgs(IRBuilder<> &IRB,
604 unsigned ArgIdx, Value *Src,
605 unsigned MaxElements) {
606 Type *Ty = Src->getType();
607 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
608 unsigned Count = VecTy->getNumElements();
609 assert(Count <= MaxElements && "Expected at most 3 elements in vector");
610 for (unsigned I = 0; I < Count; ++I)
611 Args[ArgIdx + I] = IRB.CreateExtractElement(Src, uint64_t(I));
612 } else {
613 Args[ArgIdx] = Src;
614 }
615 }
616
617 /// Copy offsets into the argument list at the given index, unless
618 /// the offsets are known to be zero (i.e., a null constant).
619 static void extractNonZeroOffsets(IRBuilder<> &IRB,
621 unsigned ArgIdx, Value *Offsets,
622 unsigned MaxElements) {
623 auto *COff = dyn_cast<Constant>(Offsets);
624 bool OffsetsAreZero = COff && COff->isNullValue();
625 if (!OffsetsAreZero)
626 extractElementsIntoArgs(IRB, Args, ArgIdx, Offsets, MaxElements);
627 }
628
629 [[nodiscard]] bool lowerTextureLoad(Function &F) {
630 IRBuilder<> &IRB = OpBuilder.getIRB();
631 Type *Int32Ty = IRB.getInt32Ty();
632
633 return replaceFunction(F, [&](CallInst *CI) -> Error {
634 IRB.SetInsertPoint(CI);
635
636 Value *Handle =
637 createTmpHandleCast(CI->getArgOperand(0), OpBuilder.getHandleType());
638 Value *Coords = CI->getArgOperand(1);
639 Value *MipLevel = CI->getArgOperand(2);
640 Value *Offsets = CI->getArgOperand(3);
641
642 // A UAV descriptor binds a single mip slice, so there is no mip to select
643 // in the case of a UAV. Multisampled UAVs are the exception: the slot
644 // carries a sample index and stays live.
645 auto *HandleTy = cast<TargetExtType>(CI->getArgOperand(0)->getType());
646 dxil::ResourceTypeInfo &RTI = DRTM[HandleTy];
648 if (RTI.isUAV() && Kind != dxil::ResourceKind::Texture2DMS &&
649 Kind != dxil::ResourceKind::Texture2DMSArray)
650 MipLevel = UndefValue::get(Int32Ty);
651
652 Type *OldTy = CI->getType();
653 Type *NewRetTy = OpBuilder.getResRetType(OldTy->getScalarType());
654
655 Value *Undef = UndefValue::get(Int32Ty);
656 std::array<Value *, 8> Args{Handle, MipLevel, Undef, Undef,
658
659 // Copy coordinates and offsets into Args.
660 extractElementsIntoArgs(IRB, Args, 2, Coords, 3);
661 extractNonZeroOffsets(IRB, Args, 5, Offsets, 3);
662
663 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
664 OpCode::TextureLoad, Args, CI->getName(), NewRetTy);
665 if (Error E = OpCall.takeError())
666 return E;
667 if (Error E = replaceResRetUses(CI, *OpCall, /*HasCheckBit=*/false))
668 return E;
669
670 return Error::success();
671 });
672 }
673
674 /// Common helper for lowering sample operations (SampleBias, SampleGrad,
675 /// etc.) that share the same pattern: extract handle/sampler, unpack
676 /// coordinates and offsets, build the DXIL arg list, and replace uses.
677 [[nodiscard]] bool lowerSampleOp(
678 Function &F, OpCode Op, unsigned CoordsIdx, unsigned OffsetsIdx,
679 llvm::function_ref<void(IRBuilder<> &, CallInst *,
680 SmallVectorImpl<Value *> &)> EmitExtraArgs) {
681 IRBuilder<> &IRB = OpBuilder.getIRB();
682 return replaceFunction(F, [&](CallInst *CI) -> Error {
683 IRB.SetInsertPoint(CI);
684
685 Value *Handle =
686 createTmpHandleCast(CI->getArgOperand(0), OpBuilder.getHandleType());
687 Value *Sampler =
688 createTmpHandleCast(CI->getArgOperand(1), OpBuilder.getHandleType());
689 Value *Coords = CI->getArgOperand(CoordsIdx);
690 Value *Offsets = CI->getArgOperand(OffsetsIdx);
691
692 Type *OldTy = CI->getType();
693 Type *NewRetTy = OpBuilder.getResRetType(OldTy->getScalarType());
694
695 Value *UndefF = UndefValue::get(IRB.getFloatTy());
696 Value *UndefI = UndefValue::get(IRB.getInt32Ty());
697 // Common prefix: Handle, Sampler, Coord0..3, Offset0..2
698 SmallVector<Value *, 17> Args{Handle, Sampler, UndefF, UndefF, UndefF,
699 UndefF, UndefI, UndefI, UndefI};
700
701 // Copy coordinates and offsets into Args.
702 extractElementsIntoArgs(IRB, Args, 2, Coords, 4);
703 extractNonZeroOffsets(IRB, Args, 6, Offsets, 3);
704
705 // Emit op-specific trailing arguments (e.g. Bias+Clamp, DDX+DDY+Clamp).
706 EmitExtraArgs(IRB, CI, Args);
707
708 Expected<CallInst *> OpCall =
709 OpBuilder.tryCreateOp(Op, Args, CI->getName(), NewRetTy);
710 if (Error E = OpCall.takeError())
711 return E;
712 if (Error E = replaceResRetUses(CI, *OpCall, /*HasCheckBit=*/false))
713 return E;
714
715 return Error::success();
716 });
717 }
718
719 [[nodiscard]] bool lowerSample(Function &F, bool HasClamp) {
720 return lowerSampleOp(F, OpCode::Sample, /*CoordsIdx=*/2, /*OffsetsIdx=*/3,
721 [HasClamp](IRBuilder<> &IRB, CallInst *CI,
722 SmallVectorImpl<Value *> &Args) {
723 // Clamp
724 Args.push_back(
725 HasClamp ? CI->getArgOperand(4)
726 : UndefValue::get(IRB.getFloatTy()));
727 });
728 }
729
730 [[nodiscard]] bool lowerSampleBias(Function &F, bool HasClamp) {
731 return lowerSampleOp(
732 F, OpCode::SampleBias, /*CoordsIdx=*/2, /*OffsetsIdx=*/4,
733 [HasClamp](IRBuilder<> &IRB, CallInst *CI,
734 SmallVectorImpl<Value *> &Args) {
735 // Bias is operand 3.
736 Args.push_back(CI->getArgOperand(3));
737 // Clamp
738 Args.push_back(HasClamp ? CI->getArgOperand(5)
739 : UndefValue::get(IRB.getFloatTy()));
740 });
741 }
742
743 [[nodiscard]] bool lowerSampleLevel(Function &F) {
744 return lowerSampleOp(
745 F, OpCode::SampleLevel, /*CoordsIdx=*/2, /*OffsetsIdx=*/4,
746 [](IRBuilder<> &, CallInst *CI, SmallVectorImpl<Value *> &Args) {
747 // LOD is operand 3.
748 Args.push_back(CI->getArgOperand(3));
749 });
750 }
751
752 [[nodiscard]] bool lowerSampleGrad(Function &F, bool HasClamp) {
753 return lowerSampleOp(
754 F, OpCode::SampleGrad, /*CoordsIdx=*/2, /*OffsetsIdx=*/5,
755 [HasClamp](IRBuilder<> &IRB, CallInst *CI,
756 SmallVectorImpl<Value *> &Args) {
757 Value *DDX = CI->getArgOperand(3);
758 Value *DDY = CI->getArgOperand(4);
759 Value *UndefF = UndefValue::get(IRB.getFloatTy());
760 // DDX0..2
761 size_t DDXStart = Args.size();
762 Args.append(3, UndefF);
763 extractElementsIntoArgs(IRB, Args, DDXStart, DDX, 3);
764 // DDY0..2
765 size_t DDYStart = Args.size();
766 Args.append(3, UndefF);
767 extractElementsIntoArgs(IRB, Args, DDYStart, DDY, 3);
768 // Clamp
769 Args.push_back(HasClamp ? CI->getArgOperand(6) : UndefF);
770 });
771 }
772
773 [[nodiscard]] bool lowerRawBufferLoad(Function &F) {
774 const DataLayout &DL = F.getDataLayout();
775 IRBuilder<> &IRB = OpBuilder.getIRB();
776 Type *Int8Ty = IRB.getInt8Ty();
777 Type *Int32Ty = IRB.getInt32Ty();
778
779 return replaceFunction(F, [&](CallInst *CI) -> Error {
780 IRB.SetInsertPoint(CI);
781
782 Type *OldTy = cast<StructType>(CI->getType())->getElementType(0);
783 Type *ScalarTy = OldTy->getScalarType();
784 Type *NewRetTy = OpBuilder.getResRetType(ScalarTy);
785
786 Value *Handle =
787 createTmpHandleCast(CI->getArgOperand(0), OpBuilder.getHandleType());
788 Value *Index0 = CI->getArgOperand(1);
789 Value *Index1 = CI->getArgOperand(2);
790 uint64_t NumElements =
791 DL.getTypeSizeInBits(OldTy) / DL.getTypeSizeInBits(ScalarTy);
792 Value *Mask = ConstantInt::get(Int8Ty, ~(~0U << NumElements));
793 Value *Align =
794 ConstantInt::get(Int32Ty, DL.getPrefTypeAlign(ScalarTy).value());
795
796 if (Error E = validateRawBufferElementIndex(CI->getOperand(0), Index1))
797 return E;
798 if (isa<PoisonValue>(Index1))
799 Index1 = UndefValue::get(Index1->getType());
800
801 Expected<CallInst *> OpCall =
802 MMDI.DXILVersion >= VersionTuple(1, 2)
803 ? OpBuilder.tryCreateOp(OpCode::RawBufferLoad,
804 {Handle, Index0, Index1, Mask, Align},
805 CI->getName(), NewRetTy)
806 : OpBuilder.tryCreateOp(OpCode::BufferLoad,
807 {Handle, Index0, Index1}, CI->getName(),
808 NewRetTy);
809 if (Error E = OpCall.takeError())
810 return E;
811 if (Error E = replaceResRetUses(CI, *OpCall, /*HasCheckBit=*/true))
812 return E;
813
814 return Error::success();
815 });
816 }
817
818 [[nodiscard]] bool lowerCBufferLoad(Function &F) {
819 IRBuilder<> &IRB = OpBuilder.getIRB();
820
821 return replaceFunction(F, [&](CallInst *CI) -> Error {
822 IRB.SetInsertPoint(CI);
823
824 Type *OldTy = cast<StructType>(CI->getType())->getElementType(0);
825 Type *ScalarTy = OldTy->getScalarType();
826 Type *NewRetTy = OpBuilder.getCBufRetType(ScalarTy);
827
828 Value *Handle =
829 createTmpHandleCast(CI->getArgOperand(0), OpBuilder.getHandleType());
830 Value *Index = CI->getArgOperand(1);
831
832 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
833 OpCode::CBufferLoadLegacy, {Handle, Index}, CI->getName(), NewRetTy);
834 if (Error E = OpCall.takeError())
835 return E;
836 if (Error E = replaceNamedStructUses(CI, *OpCall))
837 return E;
838
839 CI->eraseFromParent();
840 return Error::success();
841 });
842 }
843
844 [[nodiscard]] bool lowerUpdateCounter(Function &F) {
845 IRBuilder<> &IRB = OpBuilder.getIRB();
846 Type *Int32Ty = IRB.getInt32Ty();
847
848 return replaceFunction(F, [&](CallInst *CI) -> Error {
849 IRB.SetInsertPoint(CI);
850 Value *Handle =
851 createTmpHandleCast(CI->getArgOperand(0), OpBuilder.getHandleType());
852 Value *Op1 = CI->getArgOperand(1);
853
854 std::array<Value *, 2> Args{Handle, Op1};
855
856 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
857 OpCode::UpdateCounter, Args, CI->getName(), Int32Ty);
858
859 if (Error E = OpCall.takeError())
860 return E;
861
862 CI->replaceAllUsesWith(*OpCall);
863 CI->eraseFromParent();
864 return Error::success();
865 });
866 }
867
868 [[nodiscard]] bool lowerGetDimensionsX(Function &F) {
869 IRBuilder<> &IRB = OpBuilder.getIRB();
870 Type *Int32Ty = IRB.getInt32Ty();
871
872 return replaceFunction(F, [&](CallInst *CI) -> Error {
873 IRB.SetInsertPoint(CI);
874 Value *Handle =
875 createTmpHandleCast(CI->getArgOperand(0), OpBuilder.getHandleType());
876 Value *Undef = UndefValue::get(Int32Ty);
877
878 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
879 OpCode::GetDimensions, {Handle, Undef}, CI->getName(), Int32Ty);
880 if (Error E = OpCall.takeError())
881 return E;
882 Value *Dim = IRB.CreateExtractValue(*OpCall, 0);
883
884 CI->replaceAllUsesWith(Dim);
885 CI->eraseFromParent();
886 return Error::success();
887 });
888 }
889
890 [[nodiscard]] bool lowerGetPointer(Function &F) {
891 // These should have already been handled in DXILResourceAccess, so we can
892 // just clean up the dead prototype.
893 assert(F.user_empty() && "getpointer operations should have been removed");
894 F.eraseFromParent();
895 return false;
896 }
897
898 /// Splits the value operand of a resource store into its (at most four)
899 /// scalar components. Slots beyond the length of `Data` are filled with
900 /// `undef` when `FillWithUndef` is set (raw and structured buffers), or with
901 /// the first component otherwise (typed UAVs, which must write all four
902 /// components - repeating the first one matches DXC).
903 static std::array<Value *, 4> splitStoreData(IRBuilder<> &IRB, Value *Data,
904 uint64_t NumElements,
905 bool FillWithUndef) {
906 Type *DataTy = Data->getType();
907 Type *ScalarTy = DataTy->getScalarType();
908
909 std::array<Value *, 4> DataElements{nullptr, nullptr, nullptr, nullptr};
910 if (DataTy == ScalarTy)
911 DataElements[0] = Data;
912 else {
913 // Since we're post-scalarizer, if we see a vector here it's likely
914 // constructed solely for the argument of the store. Just use the scalar
915 // values from before they're inserted into the temporary.
917 while (IEI) {
918 auto *IndexOp = dyn_cast<ConstantInt>(IEI->getOperand(2));
919 if (!IndexOp)
920 break;
921 size_t IndexVal = IndexOp->getZExtValue();
922 assert(IndexVal < 4 && "Too many elements for resource store");
923 DataElements[IndexVal] = IEI->getOperand(1);
924 IEI = dyn_cast<InsertElementInst>(IEI->getOperand(0));
925 }
926 }
927
928 // If for some reason we weren't able to forward the arguments from the
929 // scalarizer artifact, then we may need to actually extract elements from
930 // the vector.
931 for (uint64_t I = 0, E = NumElements; I < E; ++I)
932 if (DataElements[I] == nullptr)
933 DataElements[I] = IRB.CreateExtractElement(
934 Data, ConstantInt::get(IRB.getInt32Ty(), I));
935
936 // For any elements beyond the length of the vector, we should fill it up
937 // with undef - however, for typed UAVs we repeat the first element to
938 // match DXC.
939 for (uint64_t I = NumElements, E = 4; I < E; ++I)
940 if (DataElements[I] == nullptr)
941 DataElements[I] =
942 FillWithUndef ? UndefValue::get(ScalarTy) : DataElements[0];
943
944 return DataElements;
945 }
946
947 /// Erase the chain of `insertelement`s that only existed to build up the
948 /// value operand of a store we've just replaced.
949 static void eraseDeadInsertElementChain(Value *Data) {
951 while (IEI && IEI->use_empty()) {
952 InsertElementInst *Tmp = IEI;
953 IEI = dyn_cast<InsertElementInst>(IEI->getOperand(0));
954 Tmp->eraseFromParent();
955 }
956 }
957
958 [[nodiscard]] bool lowerBufferStore(Function &F, bool IsRaw) {
959 const DataLayout &DL = F.getDataLayout();
960 IRBuilder<> &IRB = OpBuilder.getIRB();
961 Type *Int8Ty = IRB.getInt8Ty();
962 Type *Int32Ty = IRB.getInt32Ty();
963
964 return replaceFunction(F, [&](CallInst *CI) -> Error {
965 IRB.SetInsertPoint(CI);
966
967 Value *Handle =
968 createTmpHandleCast(CI->getArgOperand(0), OpBuilder.getHandleType());
969 Value *Index0 = CI->getArgOperand(1);
970 Value *Index1 = IsRaw ? CI->getArgOperand(2) : UndefValue::get(Int32Ty);
971
972 if (IsRaw) {
973 if (Error E = validateRawBufferElementIndex(CI->getOperand(0), Index1))
974 return E;
975 if (isa<PoisonValue>(Index1))
976 Index1 = UndefValue::get(Index1->getType());
977 }
978
979 Value *Data = CI->getArgOperand(IsRaw ? 3 : 2);
980 Type *DataTy = Data->getType();
981 Type *ScalarTy = DataTy->getScalarType();
982
983 uint64_t NumElements =
984 DL.getTypeSizeInBits(DataTy) / DL.getTypeSizeInBits(ScalarTy);
985 Value *Mask = ConstantInt::get(Int8Ty, IsRaw ? ~(~0U << NumElements)
987
988 // TODO: check that we only have vector or scalar...
989 if (NumElements > 4)
991 "Buffer store data must have at most 4 elements",
993
994 std::array<Value *, 4> DataElements =
995 splitStoreData(IRB, Data, NumElements, /*FillWithUndef=*/IsRaw);
996
997 dxil::OpCode Op = OpCode::BufferStore;
999 Handle, Index0, Index1, DataElements[0],
1000 DataElements[1], DataElements[2], DataElements[3], Mask};
1001 if (IsRaw && MMDI.DXILVersion >= VersionTuple(1, 2)) {
1002 Op = OpCode::RawBufferStore;
1003 // RawBufferStore requires the alignment
1004 Args.push_back(
1005 ConstantInt::get(Int32Ty, DL.getPrefTypeAlign(ScalarTy).value()));
1006 }
1007 Expected<CallInst *> OpCall =
1008 OpBuilder.tryCreateOp(Op, Args, CI->getName());
1009 if (Error E = OpCall.takeError())
1010 return E;
1011
1012 CI->eraseFromParent();
1013 eraseDeadInsertElementChain(Data);
1014
1015 return Error::success();
1016 });
1017 }
1018
1019 [[nodiscard]] bool lowerTextureStore(Function &F) {
1020 const DataLayout &DL = F.getDataLayout();
1021 IRBuilder<> &IRB = OpBuilder.getIRB();
1022 Type *Int8Ty = IRB.getInt8Ty();
1023 Type *Int32Ty = IRB.getInt32Ty();
1024
1025 return replaceFunction(F, [&](CallInst *CI) -> Error {
1026 IRB.SetInsertPoint(CI);
1027
1028 Value *Handle =
1029 createTmpHandleCast(CI->getArgOperand(0), OpBuilder.getHandleType());
1030 Value *Coords = CI->getArgOperand(1);
1031 Value *Data = CI->getArgOperand(2);
1032
1033 Type *DataTy = Data->getType();
1034 Type *ScalarTy = DataTy->getScalarType();
1035 uint64_t NumElements =
1036 DL.getTypeSizeInBits(DataTy) / DL.getTypeSizeInBits(ScalarTy);
1037 if (NumElements > 4)
1039 "Texture store data must have at most 4 elements",
1041
1042 Value *Mask = ConstantInt::get(Int8Ty, TypedUAVStoreWriteMask);
1043 std::array<Value *, 4> DataElements =
1044 splitStoreData(IRB, Data, NumElements, /*FillWithUndef=*/false);
1045
1046 Value *Undef = UndefValue::get(Int32Ty);
1047 std::array<Value *, 9> Args{
1048 Handle, Undef, Undef,
1049 Undef, DataElements[0], DataElements[1],
1050 DataElements[2], DataElements[3], Mask};
1051
1052 // Copy the coordinates into Args.
1053 extractElementsIntoArgs(IRB, Args, 1, Coords, 3);
1054
1055 Expected<CallInst *> OpCall =
1056 OpBuilder.tryCreateOp(OpCode::TextureStore, Args, CI->getName());
1057 if (Error E = OpCall.takeError())
1058 return E;
1059
1060 CI->eraseFromParent();
1061 eraseDeadInsertElementChain(Data);
1062
1063 return Error::success();
1064 });
1065 }
1066
1067 [[nodiscard]] bool lowerResourceAtomicBinOp(Function &F) {
1068 IRBuilder<> &IRB = OpBuilder.getIRB();
1069
1070 return replaceFunction(F, [&](CallInst *CI) -> Error {
1071 IRB.SetInsertPoint(CI);
1072
1073 // Cast the target-extension typed handle to `%dx.types.Handle`, tracked
1074 // via CleanupCasts so the pair is reconciled by `cleanupHandleCasts`.
1075 Value *Handle =
1076 createTmpHandleCast(CI->getArgOperand(0), OpBuilder.getHandleType());
1077 Value *BinOp = CI->getArgOperand(1);
1078 Value *Coord0 = CI->getArgOperand(2);
1079 Value *Coord1 = CI->getArgOperand(3);
1080 Value *NewValue = CI->getArgOperand(4);
1081
1082 std::array<Value *, 6> Args{
1083 Handle, BinOp, Coord0, Coord1, ConstantInt::get(IRB.getInt32Ty(), 0),
1084 NewValue};
1085 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
1086 dxil::OpCode::AtomicBinOp, Args, CI->getName(), CI->getType());
1087 if (Error E = OpCall.takeError()) {
1088 // Preserve the DXIL op error text but attach it as a
1089 // DiagnosticInfoUnsupported so we don't crash with a dangling call.
1090 std::string Message(toString(std::move(E)));
1091 CI->getContext().diagnose(DiagnosticInfoUnsupported(
1092 *CI->getFunction(), Message, CI->getDebugLoc()));
1094 CI->eraseFromParent();
1095 return Error::success();
1096 }
1097
1098 CI->replaceAllUsesWith(*OpCall);
1099 CI->eraseFromParent();
1100 return Error::success();
1101 });
1102 }
1103
1104 [[nodiscard]] bool lowerCtpopToCountBits(Function &F) {
1105 IRBuilder<> &IRB = OpBuilder.getIRB();
1106 Type *Int32Ty = IRB.getInt32Ty();
1107
1108 return replaceFunction(F, [&](CallInst *CI) -> Error {
1109 IRB.SetInsertPoint(CI);
1111 Args.append(CI->arg_begin(), CI->arg_end());
1112
1113 Type *RetTy = Int32Ty;
1114 Type *FRT = F.getReturnType();
1115 if (const auto *VT = dyn_cast<VectorType>(FRT))
1116 RetTy = VectorType::get(RetTy, VT);
1117
1118 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
1119 dxil::OpCode::CountBits, Args, CI->getName(), RetTy);
1120 if (Error E = OpCall.takeError())
1121 return E;
1122
1123 // If the result type is 32 bits we can do a direct replacement.
1124 if (FRT->isIntOrIntVectorTy(32)) {
1125 CI->replaceAllUsesWith(*OpCall);
1126 CI->eraseFromParent();
1127 return Error::success();
1128 }
1129
1130 unsigned CastOp;
1131 unsigned CastOp2;
1132 if (FRT->isIntOrIntVectorTy(16)) {
1133 CastOp = Instruction::ZExt;
1134 CastOp2 = Instruction::SExt;
1135 } else { // must be 64 bits
1136 assert(FRT->isIntOrIntVectorTy(64) &&
1137 "Currently only lowering 16, 32, or 64 bit ctpop to CountBits \
1138 is supported.");
1139 CastOp = Instruction::Trunc;
1140 CastOp2 = Instruction::Trunc;
1141 }
1142
1143 // It is correct to replace the ctpop with the dxil op and
1144 // remove all casts to i32
1145 bool NeedsCast = false;
1146 for (User *User : make_early_inc_range(CI->users())) {
1148 if (I && (I->getOpcode() == CastOp || I->getOpcode() == CastOp2) &&
1149 I->getType() == RetTy) {
1150 I->replaceAllUsesWith(*OpCall);
1151 I->eraseFromParent();
1152 } else
1153 NeedsCast = true;
1154 }
1155
1156 // It is correct to replace a ctpop with the dxil op and
1157 // a cast from i32 to the return type of the ctpop
1158 // the cast is emitted here if there is a non-cast to i32
1159 // instr which uses the ctpop
1160 if (NeedsCast) {
1161 Value *Cast =
1162 IRB.CreateZExtOrTrunc(*OpCall, F.getReturnType(), "ctpop.cast");
1163 CI->replaceAllUsesWith(Cast);
1164 }
1165
1166 CI->eraseFromParent();
1167 return Error::success();
1168 });
1169 }
1170
1171 [[nodiscard]] bool lowerLifetimeIntrinsic(Function &F) {
1172 IRBuilder<> &IRB = OpBuilder.getIRB();
1173 return replaceFunction(F, [&](CallInst *CI) -> Error {
1174 IRB.SetInsertPoint(CI);
1175 Value *Ptr = CI->getArgOperand(0);
1176 assert(Ptr->getType()->isPointerTy() &&
1177 "Expected operand of lifetime intrinsic to be a pointer");
1178
1179 auto ZeroOrUndef = [&](Type *Ty) {
1180 return MMDI.ValidatorVersion < VersionTuple(1, 6)
1182 : UndefValue::get(Ty);
1183 };
1184
1185 Value *Val = nullptr;
1186 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1187 if (GV->hasInitializer() || GV->isExternallyInitialized())
1188 return Error::success();
1189 Val = ZeroOrUndef(GV->getValueType());
1190 } else if (auto *AI = dyn_cast<AllocaInst>(Ptr))
1191 Val = ZeroOrUndef(AI->getAllocatedType());
1192
1193 assert(Val && "Expected operand of lifetime intrinsic to be a global "
1194 "variable or alloca instruction");
1195 IRB.CreateStore(Val, Ptr, false);
1196
1197 CI->eraseFromParent();
1198 return Error::success();
1199 });
1200 }
1201
1202 [[nodiscard]] bool lowerIsFPClass(Function &F) {
1203 IRBuilder<> &IRB = OpBuilder.getIRB();
1204 Type *RetTy = IRB.getInt1Ty();
1205
1206 return replaceFunction(F, [&](CallInst *CI) -> Error {
1207 IRB.SetInsertPoint(CI);
1209 Value *Fl = CI->getArgOperand(0);
1210 Args.push_back(Fl);
1211
1213 Value *T = CI->getArgOperand(1);
1214 auto *TCI = dyn_cast<ConstantInt>(T);
1215 switch (TCI->getZExtValue()) {
1216 case FPClassTest::fcInf:
1217 OpCode = dxil::OpCode::IsInf;
1218 break;
1219 case FPClassTest::fcNan:
1220 OpCode = dxil::OpCode::IsNaN;
1221 break;
1222 case FPClassTest::fcNormal:
1223 OpCode = dxil::OpCode::IsNormal;
1224 break;
1225 case FPClassTest::fcFinite:
1226 OpCode = dxil::OpCode::IsFinite;
1227 break;
1228 default:
1229 SmallString<128> Msg =
1230 formatv("Unsupported FPClassTest {0} for DXIL Op Lowering",
1231 TCI->getZExtValue());
1233 }
1234
1235 Expected<CallInst *> OpCall =
1236 OpBuilder.tryCreateOp(OpCode, Args, CI->getName(), RetTy);
1237 if (Error E = OpCall.takeError())
1238 return E;
1239
1240 CI->replaceAllUsesWith(*OpCall);
1241 CI->eraseFromParent();
1242 return Error::success();
1243 });
1244 }
1245
1246 bool lowerIntrinsics() {
1247 bool Updated = false;
1248 bool HasErrors = false;
1249
1250 for (Function &F : make_early_inc_range(M.functions())) {
1251 if (!F.isDeclaration())
1252 continue;
1253 Intrinsic::ID ID = F.getIntrinsicID();
1254 switch (ID) {
1255 // NOTE: Skip dx_resource_casthandle here. They are
1256 // resolved after this loop in cleanupHandleCasts.
1257 case Intrinsic::dx_resource_casthandle:
1258 // NOTE: llvm.dbg.value is supported as is in DXIL.
1259 case Intrinsic::dbg_value:
1261 if (F.use_empty())
1262 F.eraseFromParent();
1263 continue;
1264 default:
1265 if (F.use_empty())
1266 F.eraseFromParent();
1267 else {
1268 SmallString<128> Msg = formatv(
1269 "Unsupported intrinsic {0} for DXIL lowering", F.getName());
1270 M.getContext().emitError(Msg);
1271 HasErrors |= true;
1272 }
1273 break;
1274
1275#define DXIL_OP_INTRINSIC(OpCode, Intrin, ...) \
1276 case Intrin: \
1277 HasErrors |= replaceFunctionWithOp( \
1278 F, OpCode, ArrayRef<IntrinArgSelect>{__VA_ARGS__}); \
1279 break;
1280#include "DXILOperation.inc"
1281 case Intrinsic::dx_resource_handlefrombinding:
1282 HasErrors |= lowerHandleFromBinding(F);
1283 break;
1284 case Intrinsic::dx_resource_getbasepointer:
1285 case Intrinsic::dx_resource_getpointer:
1286 HasErrors |= lowerGetPointer(F);
1287 break;
1288 case Intrinsic::dx_resource_nonuniformindex:
1289 assert(!CleanupNURI &&
1290 "overloaded llvm.dx.resource.nonuniformindex intrinsics?");
1291 CleanupNURI = &F;
1292 break;
1293 case Intrinsic::dx_resource_load_typedbuffer:
1294 HasErrors |= lowerTypedBufferLoad(F, /*HasCheckBit=*/true);
1295 break;
1296 case Intrinsic::dx_resource_load_level:
1297 HasErrors |= lowerTextureLoad(F);
1298 break;
1299 case Intrinsic::dx_resource_sample:
1300 HasErrors |= lowerSample(F, /*HasClamp=*/false);
1301 break;
1302 case Intrinsic::dx_resource_sample_clamp:
1303 HasErrors |= lowerSample(F, /*HasClamp=*/true);
1304 break;
1305 case Intrinsic::dx_resource_samplebias:
1306 HasErrors |= lowerSampleBias(F, /*HasClamp=*/false);
1307 break;
1308 case Intrinsic::dx_resource_samplebias_clamp:
1309 HasErrors |= lowerSampleBias(F, /*HasClamp=*/true);
1310 break;
1311 case Intrinsic::dx_resource_samplelevel:
1312 HasErrors |= lowerSampleLevel(F);
1313 break;
1314 case Intrinsic::dx_resource_samplegrad:
1315 HasErrors |= lowerSampleGrad(F, /*HasClamp=*/false);
1316 break;
1317 case Intrinsic::dx_resource_samplegrad_clamp:
1318 HasErrors |= lowerSampleGrad(F, /*HasClamp=*/true);
1319 break;
1320 case Intrinsic::dx_resource_store_typedbuffer:
1321 HasErrors |= lowerBufferStore(F, /*IsRaw=*/false);
1322 break;
1323 case Intrinsic::dx_resource_store_texture:
1324 HasErrors |= lowerTextureStore(F);
1325 break;
1326 case Intrinsic::dx_resource_load_rawbuffer:
1327 HasErrors |= lowerRawBufferLoad(F);
1328 break;
1329 case Intrinsic::dx_resource_store_rawbuffer:
1330 HasErrors |= lowerBufferStore(F, /*IsRaw=*/true);
1331 break;
1332 case Intrinsic::dx_resource_load_cbufferrow_2:
1333 case Intrinsic::dx_resource_load_cbufferrow_4:
1334 case Intrinsic::dx_resource_load_cbufferrow_8:
1335 HasErrors |= lowerCBufferLoad(F);
1336 break;
1337 case Intrinsic::dx_resource_updatecounter:
1338 HasErrors |= lowerUpdateCounter(F);
1339 break;
1340 case Intrinsic::dx_resource_atomic_binop:
1341 HasErrors |= lowerResourceAtomicBinOp(F);
1342 break;
1343 case Intrinsic::dx_resource_getdimensions_x:
1344 HasErrors |= lowerGetDimensionsX(F);
1345 break;
1346 case Intrinsic::ctpop:
1347 HasErrors |= lowerCtpopToCountBits(F);
1348 break;
1349 case Intrinsic::lifetime_start:
1350 case Intrinsic::lifetime_end:
1351 if (F.use_empty())
1352 F.eraseFromParent();
1353 else {
1354 if (MMDI.DXILVersion < VersionTuple(1, 6))
1355 HasErrors |= lowerLifetimeIntrinsic(F);
1356 else
1357 continue;
1358 }
1359 break;
1360 case Intrinsic::is_fpclass:
1361 HasErrors |= lowerIsFPClass(F);
1362 break;
1363 }
1364 Updated = true;
1365 }
1366 if (Updated && !HasErrors) {
1367 cleanupHandleCasts();
1368 cleanupNonUniformResourceIndexCalls();
1369 }
1370
1371 return Updated;
1372 }
1373};
1374} // namespace
1375
1377 DXILResourceMap &DRM = MAM.getResult<DXILResourceAnalysis>(M);
1378 DXILResourceTypeMap &DRTM = MAM.getResult<DXILResourceTypeAnalysis>(M);
1379 const ModuleMetadataInfo MMDI = MAM.getResult<DXILMetadataAnalysis>(M);
1380
1381 const bool MadeChanges = OpLowerer(M, DRM, DRTM, MMDI).lowerIntrinsics();
1382 if (!MadeChanges)
1383 return PreservedAnalyses::all();
1389 return PA;
1390}
1391
1392namespace {
1393class DXILOpLoweringLegacy : public ModulePass {
1394public:
1395 bool runOnModule(Module &M) override {
1396 DXILResourceMap &DRM =
1397 getAnalysis<DXILResourceWrapperPass>().getResourceMap();
1398 DXILResourceTypeMap &DRTM =
1399 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
1400 const ModuleMetadataInfo MMDI =
1401 getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata();
1402
1403 return OpLowerer(M, DRM, DRTM, MMDI).lowerIntrinsics();
1404 }
1405 StringRef getPassName() const override { return "DXIL Op Lowering"; }
1406 DXILOpLoweringLegacy() : ModulePass(ID) {}
1407
1408 static char ID; // Pass identification.
1409 void getAnalysisUsage(llvm::AnalysisUsage &AU) const override {
1410 AU.addRequired<DXILResourceTypeWrapperPass>();
1411 AU.addRequired<DXILResourceWrapperPass>();
1412 AU.addRequired<DXILMetadataAnalysisWrapperPass>();
1413 AU.addPreserved<DXILResourceWrapperPass>();
1414 AU.addPreserved<DXILMetadataAnalysisWrapperPass>();
1415 AU.addPreserved<ShaderFlagsAnalysisWrapper>();
1416 AU.addPreserved<RootSignatureAnalysisWrapper>();
1417 }
1418};
1419char DXILOpLoweringLegacy::ID = 0;
1420} // end anonymous namespace
1421
1422INITIALIZE_PASS_BEGIN(DXILOpLoweringLegacy, DEBUG_TYPE, "DXIL Op Lowering",
1423 false, false)
1426INITIALIZE_PASS_END(DXILOpLoweringLegacy, DEBUG_TYPE, "DXIL Op Lowering", false,
1427 false)
1428
1430 return new DXILOpLoweringLegacy();
1431}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static constexpr uint8_t TypedUAVStoreWriteMask
Write mask covering all four components of a UAV element.
DXIL Resource Implicit Binding
#define DEBUG_TYPE
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
#define T
ModuleAnalysisManager MAM
if(PassOpts->AAPipeline)
#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
const char * Msg
static unsigned getFastMathFlags(const MachineInstr &I, const SPIRVSubtarget &ST)
This file defines the SmallVector class.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
This class represents a function call, abstracting a target machine's calling convention.
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
Diagnostic information for unsupported feature in backend.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:246
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2662
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition IRBuilder.h:1879
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:519
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2650
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2139
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2709
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:534
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition IRBuilder.h:2019
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1906
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1925
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1422
Type * getFloatTy()
Fetch the type representing a 32-bit floating point value.
Definition IRBuilder.h:562
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:524
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:327
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
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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:309
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * getOperand(unsigned i) const
Definition User.h:207
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
user_iterator user_begin()
Definition Value.h:402
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
bool use_empty() const
Definition Value.h:346
iterator_range< use_iterator > uses()
Definition Value.h:380
bool hasName() const
Definition Value.h:261
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
bool user_empty() const
Definition Value.h:389
TargetExtType * getHandleTy() const
LLVM_ABI std::pair< uint32_t, uint32_t > getAnnotateProps(Module &M, dxil::ResourceTypeInfo &RTI) const
const ResourceBinding & getBinding() const
dxil::ResourceClass getResourceClass() const
LLVM_ABI bool isUAV() const
dxil::ResourceKind getResourceKind() const
An efficient, type-erasing, non-owning reference to a callable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Offsets
Offsets in bytes from the start of the input buffer.
ResourceKind
The kind of resource for an SRV or UAV resource.
Definition DXILABI.h:44
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Undef
Value of the register doesn't matter.
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).
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
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
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2134
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
ModulePass * createDXILOpLoweringLegacyPass()
Pass to lowering LLVM intrinsic call to DXIL op function call.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
#define N