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