LLVM 23.0.0git
DXILIntrinsicExpansion.cpp
Go to the documentation of this file.
1//===- DXILIntrinsicExpansion.cpp - Prepare LLVM Module for DXIL encoding--===//
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/// \file This file contains DXIL intrinsic expansions for those that don't have
10// opcodes in DirectX Intermediate Language (DXIL).
11//===----------------------------------------------------------------------===//
12
14#include "DirectX.h"
15#include "llvm/ADT/STLExtras.h"
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/InstrTypes.h"
21#include "llvm/IR/Instruction.h"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/IntrinsicsDirectX.h"
26#include "llvm/IR/Module.h"
27#include "llvm/IR/PassManager.h"
28#include "llvm/IR/Type.h"
29#include "llvm/Pass.h"
33
34#define DEBUG_TYPE "dxil-intrinsic-expansion"
35
36using namespace llvm;
37
39
40public:
41 bool runOnModule(Module &M) override;
43
44 static char ID; // Pass identification.
45};
46
47static bool resourceAccessNeeds64BitExpansion(Module *M, Type *OverloadTy,
48 bool IsRaw) {
49 if (IsRaw && M->getTargetTriple().getDXILVersion() > VersionTuple(1, 2))
50 return false;
51
52 Type *ScalarTy = OverloadTy->getScalarType();
53 return ScalarTy->isDoubleTy() || ScalarTy->isIntegerTy(64);
54}
55
57 Module *M = Orig->getModule();
58 if (M->getTargetTriple().getDXILVersion() >= VersionTuple(1, 9))
59 return nullptr;
60
61 Value *Val = Orig->getOperand(0);
62 Type *ValTy = Val->getType();
63 if (!ValTy->getScalarType()->isHalfTy())
64 return nullptr;
65
66 IRBuilder<> Builder(Orig);
67 Type *IType = Type::getInt16Ty(M->getContext());
68 Constant *PosInf =
69 ValTy->isVectorTy()
73 ConstantInt::get(IType, 0x7c00))
74 : ConstantInt::get(IType, 0x7c00);
75
76 Constant *NegInf =
77 ValTy->isVectorTy()
81 ConstantInt::get(IType, 0xfc00))
82 : ConstantInt::get(IType, 0xfc00);
83
84 Value *IVal = Builder.CreateBitCast(Val, PosInf->getType());
85 Value *B1 = Builder.CreateICmpEQ(IVal, PosInf);
86 Value *B2 = Builder.CreateICmpEQ(IVal, NegInf);
87 Value *B3 = Builder.CreateOr(B1, B2);
88 return B3;
89}
90
92 Module *M = Orig->getModule();
93 if (M->getTargetTriple().getDXILVersion() >= VersionTuple(1, 9))
94 return nullptr;
95
96 Value *Val = Orig->getOperand(0);
97 Type *ValTy = Val->getType();
98 if (!ValTy->getScalarType()->isHalfTy())
99 return nullptr;
100
101 IRBuilder<> Builder(Orig);
102 Type *IType = Type::getInt16Ty(M->getContext());
103
104 Constant *ExpBitMask =
105 ValTy->isVectorTy()
109 ConstantInt::get(IType, 0x7c00))
110 : ConstantInt::get(IType, 0x7c00);
111 Constant *SigBitMask =
112 ValTy->isVectorTy()
116 ConstantInt::get(IType, 0x3ff))
117 : ConstantInt::get(IType, 0x3ff);
118
119 Constant *Zero =
120 ValTy->isVectorTy()
124 ConstantInt::get(IType, 0))
125 : ConstantInt::get(IType, 0);
126
127 Value *IVal = Builder.CreateBitCast(Val, ExpBitMask->getType());
128 Value *Exp = Builder.CreateAnd(IVal, ExpBitMask);
129 Value *B1 = Builder.CreateICmpEQ(Exp, ExpBitMask);
130
131 Value *Sig = Builder.CreateAnd(IVal, SigBitMask);
132 Value *B2 = Builder.CreateICmpNE(Sig, Zero);
133 Value *B3 = Builder.CreateAnd(B1, B2);
134 return B3;
135}
136
138 Module *M = Orig->getModule();
139 if (M->getTargetTriple().getDXILVersion() >= VersionTuple(1, 9))
140 return nullptr;
141
142 Value *Val = Orig->getOperand(0);
143 Type *ValTy = Val->getType();
144 if (!ValTy->getScalarType()->isHalfTy())
145 return nullptr;
146
147 IRBuilder<> Builder(Orig);
148 Type *IType = Type::getInt16Ty(M->getContext());
149
150 Constant *ExpBitMask =
151 ValTy->isVectorTy()
155 ConstantInt::get(IType, 0x7c00))
156 : ConstantInt::get(IType, 0x7c00);
157
158 Value *IVal = Builder.CreateBitCast(Val, ExpBitMask->getType());
159 Value *Exp = Builder.CreateAnd(IVal, ExpBitMask);
160 Value *B1 = Builder.CreateICmpNE(Exp, ExpBitMask);
161 return B1;
162}
163
165 Module *M = Orig->getModule();
166 if (M->getTargetTriple().getDXILVersion() >= VersionTuple(1, 9))
167 return nullptr;
168
169 Value *Val = Orig->getOperand(0);
170 Type *ValTy = Val->getType();
171 if (!ValTy->getScalarType()->isHalfTy())
172 return nullptr;
173
174 IRBuilder<> Builder(Orig);
175 Type *IType = Type::getInt16Ty(M->getContext());
176
177 Constant *ExpBitMask =
178 ValTy->isVectorTy()
182 ConstantInt::get(IType, 0x7c00))
183 : ConstantInt::get(IType, 0x7c00);
184 Constant *Zero =
185 ValTy->isVectorTy()
189 ConstantInt::get(IType, 0))
190 : ConstantInt::get(IType, 0);
191
192 Value *IVal = Builder.CreateBitCast(Val, ExpBitMask->getType());
193 Value *Exp = Builder.CreateAnd(IVal, ExpBitMask);
194 Value *NotAllZeroes = Builder.CreateICmpNE(Exp, Zero);
195 Value *NotAllOnes = Builder.CreateICmpNE(Exp, ExpBitMask);
196 Value *B1 = Builder.CreateAnd(NotAllZeroes, NotAllOnes);
197 return B1;
198}
199
201 switch (F.getIntrinsicID()) {
202 case Intrinsic::assume:
203 case Intrinsic::abs:
204 case Intrinsic::atan2:
205 case Intrinsic::fshl:
206 case Intrinsic::fshr:
207 case Intrinsic::exp:
208 case Intrinsic::is_fpclass:
209 case Intrinsic::log:
210 case Intrinsic::log10:
211 case Intrinsic::pow:
212 case Intrinsic::powi:
213 case Intrinsic::dx_all:
214 case Intrinsic::dx_any:
215 case Intrinsic::dx_cross:
216 case Intrinsic::dx_uclamp:
217 case Intrinsic::dx_sclamp:
218 case Intrinsic::dx_nclamp:
219 case Intrinsic::dx_degrees:
220 case Intrinsic::dx_isinf:
221 case Intrinsic::dx_isnan:
222 case Intrinsic::dx_lerp:
223 case Intrinsic::dx_normalize:
224 case Intrinsic::dx_fdot:
225 case Intrinsic::dx_sdot:
226 case Intrinsic::dx_udot:
227 case Intrinsic::dx_sign:
228 case Intrinsic::dx_step:
229 case Intrinsic::dx_radians:
230 case Intrinsic::usub_sat:
231 case Intrinsic::vector_reduce_add:
232 case Intrinsic::vector_reduce_fadd:
233 case Intrinsic::matrix_multiply:
234 return true;
235 case Intrinsic::dx_resource_load_rawbuffer:
237 F.getParent(), F.getReturnType()->getStructElementType(0),
238 /*IsRaw*/ true);
239 case Intrinsic::dx_resource_load_typedbuffer:
241 F.getParent(), F.getReturnType()->getStructElementType(0),
242 /*IsRaw*/ false);
243 case Intrinsic::dx_resource_store_rawbuffer:
245 F.getParent(), F.getFunctionType()->getParamType(3), /*IsRaw*/ true);
246 case Intrinsic::dx_resource_store_typedbuffer:
248 F.getParent(), F.getFunctionType()->getParamType(2), /*IsRaw*/ false);
249 }
250 return false;
251}
252
254 Value *A = Orig->getArgOperand(0);
255 Value *B = Orig->getArgOperand(1);
256 Type *Ty = A->getType();
257
258 IRBuilder<> Builder(Orig);
259
260 Value *Cmp = Builder.CreateICmpULT(A, B, "usub.cmp");
261 Value *Sub = Builder.CreateSub(A, B, "usub.sub");
262 Value *Zero = ConstantInt::get(Ty, 0);
263 return Builder.CreateSelect(Cmp, Zero, Sub, "usub.sat");
264}
265
266static Value *expandVecReduceAdd(CallInst *Orig, Intrinsic::ID IntrinsicId) {
267 assert(IntrinsicId == Intrinsic::vector_reduce_add ||
268 IntrinsicId == Intrinsic::vector_reduce_fadd);
269
270 IRBuilder<> Builder(Orig);
271 bool IsFAdd = (IntrinsicId == Intrinsic::vector_reduce_fadd);
272
273 Value *X = Orig->getOperand(IsFAdd ? 1 : 0);
274 Type *Ty = X->getType();
275 auto *XVec = dyn_cast<FixedVectorType>(Ty);
276 unsigned XVecSize = XVec->getNumElements();
277 Value *Sum = Builder.CreateExtractElement(X, static_cast<uint64_t>(0));
278
279 // Handle the initial start value for floating-point addition.
280 if (IsFAdd) {
281 Constant *StartValue = dyn_cast<Constant>(Orig->getOperand(0));
282 if (StartValue && !StartValue->isNullValue())
283 Sum = Builder.CreateFAdd(Sum, StartValue);
284 }
285
286 // Accumulate the remaining vector elements.
287 for (unsigned I = 1; I < XVecSize; I++) {
288 Value *Elt = Builder.CreateExtractElement(X, I);
289 if (IsFAdd)
290 Sum = Builder.CreateFAdd(Sum, Elt);
291 else
292 Sum = Builder.CreateAdd(Sum, Elt);
293 }
294
295 return Sum;
296}
297
298static Value *expandAbs(CallInst *Orig) {
299 Value *X = Orig->getOperand(0);
300 IRBuilder<> Builder(Orig);
301 Type *Ty = X->getType();
302 Type *EltTy = Ty->getScalarType();
303 Constant *Zero = Ty->isVectorTy()
307 ConstantInt::get(EltTy, 0))
308 : ConstantInt::get(EltTy, 0);
309 auto *V = Builder.CreateSub(Zero, X);
310 return Builder.CreateIntrinsic(Ty, Intrinsic::smax, {X, V}, nullptr,
311 "dx.max");
312}
313
315
316 VectorType *VT = cast<VectorType>(Orig->getType());
318 reportFatalUsageError("return vector must have exactly 3 elements");
319
320 Value *op0 = Orig->getOperand(0);
321 Value *op1 = Orig->getOperand(1);
322 IRBuilder<> Builder(Orig);
323
324 Value *op0_x = Builder.CreateExtractElement(op0, (uint64_t)0, "x0");
325 Value *op0_y = Builder.CreateExtractElement(op0, 1, "x1");
326 Value *op0_z = Builder.CreateExtractElement(op0, 2, "x2");
327
328 Value *op1_x = Builder.CreateExtractElement(op1, (uint64_t)0, "y0");
329 Value *op1_y = Builder.CreateExtractElement(op1, 1, "y1");
330 Value *op1_z = Builder.CreateExtractElement(op1, 2, "y2");
331
332 auto MulSub = [&](Value *x0, Value *y0, Value *x1, Value *y1) -> Value * {
333 Value *xy = Builder.CreateFMul(x0, y1);
334 Value *yx = Builder.CreateFMul(y0, x1);
335 return Builder.CreateFSub(xy, yx, Orig->getName());
336 };
337
338 Value *yz_zy = MulSub(op0_y, op0_z, op1_y, op1_z);
339 Value *zx_xz = MulSub(op0_z, op0_x, op1_z, op1_x);
340 Value *xy_yx = MulSub(op0_x, op0_y, op1_x, op1_y);
341
342 Value *cross = PoisonValue::get(VT);
343 cross = Builder.CreateInsertElement(cross, yz_zy, (uint64_t)0);
344 cross = Builder.CreateInsertElement(cross, zx_xz, 1);
345 cross = Builder.CreateInsertElement(cross, xy_yx, 2);
346 return cross;
347}
348
349// Create appropriate DXIL float dot intrinsic for the given A and B operands
350// The appropriate opcode will be determined by the size of the operands
351// The dot product is placed in the position indicated by Orig
353 Type *ATy = A->getType();
354 [[maybe_unused]] Type *BTy = B->getType();
355 assert(ATy->isVectorTy() && BTy->isVectorTy());
356
357 IRBuilder<> Builder(Orig);
358
359 auto *AVec = dyn_cast<FixedVectorType>(ATy);
360
362
363 Intrinsic::ID DotIntrinsic = Intrinsic::dx_dot4;
364 int NumElts = AVec->getNumElements();
365 switch (NumElts) {
366 case 2:
367 DotIntrinsic = Intrinsic::dx_dot2;
368 break;
369 case 3:
370 DotIntrinsic = Intrinsic::dx_dot3;
371 break;
372 case 4:
373 DotIntrinsic = Intrinsic::dx_dot4;
374 break;
375 default:
377 "Invalid dot product input vector: length is outside 2-4");
378 return nullptr;
379 }
380
382 for (int I = 0; I < NumElts; ++I)
383 Args.push_back(Builder.CreateExtractElement(A, Builder.getInt32(I)));
384 for (int I = 0; I < NumElts; ++I)
385 Args.push_back(Builder.CreateExtractElement(B, Builder.getInt32(I)));
386 return Builder.CreateIntrinsic(ATy->getScalarType(), DotIntrinsic, Args,
387 nullptr, "dot");
388}
389
390// Create the appropriate DXIL float dot intrinsic for the operands of Orig
391// The appropriate opcode will be determined by the size of the operands
392// The dot product is placed in the position indicated by Orig
394 return expandFloatDotIntrinsic(Orig, Orig->getOperand(0),
395 Orig->getOperand(1));
396}
397
398// Expand integer dot product to multiply and add ops
400 Intrinsic::ID DotIntrinsic) {
401 assert(DotIntrinsic == Intrinsic::dx_sdot ||
402 DotIntrinsic == Intrinsic::dx_udot);
403 Value *A = Orig->getOperand(0);
404 Value *B = Orig->getOperand(1);
405 Type *ATy = A->getType();
406 [[maybe_unused]] Type *BTy = B->getType();
407 assert(ATy->isVectorTy() && BTy->isVectorTy());
408
409 IRBuilder<> Builder(Orig);
410
411 auto *AVec = dyn_cast<FixedVectorType>(ATy);
412
414
415 Value *Result;
416 Intrinsic::ID MadIntrinsic = DotIntrinsic == Intrinsic::dx_sdot
417 ? Intrinsic::dx_imad
418 : Intrinsic::dx_umad;
419 Value *Elt0 = Builder.CreateExtractElement(A, (uint64_t)0);
420 Value *Elt1 = Builder.CreateExtractElement(B, (uint64_t)0);
421 Result = Builder.CreateMul(Elt0, Elt1);
422 for (unsigned I = 1; I < AVec->getNumElements(); I++) {
423 Elt0 = Builder.CreateExtractElement(A, I);
424 Elt1 = Builder.CreateExtractElement(B, I);
425 Result = Builder.CreateIntrinsic(Result->getType(), MadIntrinsic,
426 ArrayRef<Value *>{Elt0, Elt1, Result},
427 nullptr, "dx.mad");
428 }
429 return Result;
430}
431
433 Value *X = Orig->getOperand(0);
434 IRBuilder<> Builder(Orig);
435 Type *Ty = X->getType();
436 Type *EltTy = Ty->getScalarType();
437 Constant *Log2eConst =
438 Ty->isVectorTy() ? ConstantVector::getSplat(
441 ConstantFP::get(EltTy, numbers::log2ef))
442 : ConstantFP::get(EltTy, numbers::log2ef);
443 Value *NewX = Builder.CreateFMul(Log2eConst, X);
444 auto *Exp2Call =
445 Builder.CreateIntrinsic(Ty, Intrinsic::exp2, {NewX}, nullptr, "dx.exp2");
446 Exp2Call->setTailCall(Orig->isTailCall());
447 Exp2Call->setAttributes(Orig->getAttributes());
448 return Exp2Call;
449}
450
452 Value *T = Orig->getArgOperand(1);
453 auto *TCI = dyn_cast<ConstantInt>(T);
454
455 // These FPClassTest cases have DXIL opcodes, so they will be handled in
456 // DXIL Op Lowering instead for all non f16 cases.
457 switch (TCI->getZExtValue()) {
459 return expand16BitIsInf(Orig);
461 return expand16BitIsNaN(Orig);
463 return expand16BitIsNormal(Orig);
465 return expand16BitIsFinite(Orig);
466 }
467
468 IRBuilder<> Builder(Orig);
469
470 Value *F = Orig->getArgOperand(0);
471 Type *FTy = F->getType();
472 unsigned FNumElem = 0; // 0 => F is not a vector
473
474 unsigned BitWidth; // Bit width of F or the ElemTy of F
475 Type *BitCastTy; // An IntNTy of the same bitwidth as F or ElemTy of F
476
477 if (auto *FVecTy = dyn_cast<FixedVectorType>(FTy)) {
478 Type *ElemTy = FVecTy->getElementType();
479 FNumElem = FVecTy->getNumElements();
480 BitWidth = ElemTy->getPrimitiveSizeInBits();
481 BitCastTy = FixedVectorType::get(Builder.getIntNTy(BitWidth), FNumElem);
482 } else {
484 BitCastTy = Builder.getIntNTy(BitWidth);
485 }
486
487 Value *FBitCast = Builder.CreateBitCast(F, BitCastTy);
488 switch (TCI->getZExtValue()) {
490 Value *NegZero =
491 ConstantInt::get(Builder.getIntNTy(BitWidth), 1 << (BitWidth - 1),
492 /*IsSigned=*/true);
493 Value *RetVal;
494 if (FNumElem) {
495 Value *NegZeroSplat = Builder.CreateVectorSplat(FNumElem, NegZero);
496 RetVal =
497 Builder.CreateICmpEQ(FBitCast, NegZeroSplat, "is.fpclass.negzero");
498 } else
499 RetVal = Builder.CreateICmpEQ(FBitCast, NegZero, "is.fpclass.negzero");
500 return RetVal;
501 }
502 default:
503 reportFatalUsageError("Unsupported FPClassTest");
504 }
505}
506
508 Intrinsic::ID IntrinsicId) {
509 Value *X = Orig->getOperand(0);
510 IRBuilder<> Builder(Orig);
511 Type *Ty = X->getType();
512 Type *EltTy = Ty->getScalarType();
513
514 auto ApplyOp = [&Builder](Intrinsic::ID IntrinsicId, Value *Result,
515 Value *Elt) {
516 if (IntrinsicId == Intrinsic::dx_any)
517 return Builder.CreateOr(Result, Elt);
518 assert(IntrinsicId == Intrinsic::dx_all);
519 return Builder.CreateAnd(Result, Elt);
520 };
521
522 Value *Result = nullptr;
523 if (!Ty->isVectorTy()) {
524 Result = EltTy->isFloatingPointTy()
525 ? Builder.CreateFCmpUNE(X, ConstantFP::get(EltTy, 0))
526 : Builder.CreateICmpNE(X, ConstantInt::get(EltTy, 0));
527 } else {
528 auto *XVec = dyn_cast<FixedVectorType>(Ty);
529 Value *Cond =
530 EltTy->isFloatingPointTy()
531 ? Builder.CreateFCmpUNE(
533 ElementCount::getFixed(XVec->getNumElements()),
534 ConstantFP::get(EltTy, 0)))
535 : Builder.CreateICmpNE(
537 ElementCount::getFixed(XVec->getNumElements()),
538 ConstantInt::get(EltTy, 0)));
539 Result = Builder.CreateExtractElement(Cond, (uint64_t)0);
540 for (unsigned I = 1; I < XVec->getNumElements(); I++) {
541 Value *Elt = Builder.CreateExtractElement(Cond, I);
542 Result = ApplyOp(IntrinsicId, Result, Elt);
543 }
544 }
545 return Result;
546}
547
549 Value *X = Orig->getOperand(0);
550 Value *Y = Orig->getOperand(1);
551 Value *S = Orig->getOperand(2);
552 IRBuilder<> Builder(Orig);
553 auto *V = Builder.CreateFSub(Y, X);
554 V = Builder.CreateFMul(S, V);
555 return Builder.CreateFAdd(X, V, "dx.lerp");
556}
557
559 float LogConstVal = numbers::ln2f) {
560 Value *X = Orig->getOperand(0);
561 IRBuilder<> Builder(Orig);
562 Type *Ty = X->getType();
563 Type *EltTy = Ty->getScalarType();
564 Constant *Ln2Const =
565 Ty->isVectorTy() ? ConstantVector::getSplat(
568 ConstantFP::get(EltTy, LogConstVal))
569 : ConstantFP::get(EltTy, LogConstVal);
570 auto *Log2Call =
571 Builder.CreateIntrinsic(Ty, Intrinsic::log2, {X}, nullptr, "elt.log2");
572 Log2Call->setTailCall(Orig->isTailCall());
573 Log2Call->setAttributes(Orig->getAttributes());
574 return Builder.CreateFMul(Ln2Const, Log2Call);
575}
579
580// Use dot product of vector operand with itself to calculate the length.
581// Divide the vector by that length to normalize it.
583 Value *X = Orig->getOperand(0);
584 Type *Ty = Orig->getType();
585 Type *EltTy = Ty->getScalarType();
586 IRBuilder<> Builder(Orig);
587
588 auto *XVec = dyn_cast<FixedVectorType>(Ty);
589 if (!XVec) {
590 if (auto *constantFP = dyn_cast<ConstantFP>(X)) {
591 const APFloat &fpVal = constantFP->getValueAPF();
592 if (fpVal.isZero())
593 reportFatalUsageError("Invalid input scalar: length is zero");
594 }
595 return Builder.CreateFDiv(X, X);
596 }
597
598 Value *DotProduct = expandFloatDotIntrinsic(Orig, X, X);
599
600 // verify that the length is non-zero
601 // (if the dot product is non-zero, then the length is non-zero)
602 if (auto *constantFP = dyn_cast<ConstantFP>(DotProduct)) {
603 const APFloat &fpVal = constantFP->getValueAPF();
604 if (fpVal.isZero())
605 reportFatalUsageError("Invalid input vector: length is zero");
606 }
607
608 Value *Multiplicand = Builder.CreateIntrinsic(EltTy, Intrinsic::dx_rsqrt,
609 ArrayRef<Value *>{DotProduct},
610 nullptr, "dx.rsqrt");
611
612 Value *MultiplicandVec =
613 Builder.CreateVectorSplat(XVec->getNumElements(), Multiplicand);
614 return Builder.CreateFMul(X, MultiplicandVec);
615}
616
618 Value *Y = Orig->getOperand(0);
619 Value *X = Orig->getOperand(1);
620 Type *Ty = X->getType();
621 IRBuilder<> Builder(Orig);
622 Builder.setFastMathFlags(Orig->getFastMathFlags());
623
624 Value *Tan = Builder.CreateFDiv(Y, X);
625
626 CallInst *Atan =
627 Builder.CreateIntrinsic(Ty, Intrinsic::atan, {Tan}, nullptr, "Elt.Atan");
628 Atan->setTailCall(Orig->isTailCall());
629 Atan->setAttributes(Orig->getAttributes());
630
631 // Modify atan result based on https://en.wikipedia.org/wiki/Atan2.
632 Constant *Pi = ConstantFP::get(Ty, llvm::numbers::pi);
633 Constant *HalfPi = ConstantFP::get(Ty, llvm::numbers::pi / 2);
634 Constant *NegHalfPi = ConstantFP::get(Ty, -llvm::numbers::pi / 2);
635 Constant *Zero = ConstantFP::get(Ty, 0);
636 Value *AtanAddPi = Builder.CreateFAdd(Atan, Pi);
637 Value *AtanSubPi = Builder.CreateFSub(Atan, Pi);
638
639 // x > 0 -> atan.
640 Value *Result = Atan;
641 Value *XLt0 = Builder.CreateFCmpOLT(X, Zero);
642 Value *XEq0 = Builder.CreateFCmpOEQ(X, Zero);
643 Value *YGe0 = Builder.CreateFCmpOGE(Y, Zero);
644 Value *YLt0 = Builder.CreateFCmpOLT(Y, Zero);
645
646 // x < 0, y >= 0 -> atan + pi.
647 Value *XLt0AndYGe0 = Builder.CreateAnd(XLt0, YGe0);
648 Result = Builder.CreateSelect(XLt0AndYGe0, AtanAddPi, Result);
649
650 // x < 0, y < 0 -> atan - pi.
651 Value *XLt0AndYLt0 = Builder.CreateAnd(XLt0, YLt0);
652 Result = Builder.CreateSelect(XLt0AndYLt0, AtanSubPi, Result);
653
654 // x == 0, y < 0 -> -pi/2
655 Value *XEq0AndYLt0 = Builder.CreateAnd(XEq0, YLt0);
656 Result = Builder.CreateSelect(XEq0AndYLt0, NegHalfPi, Result);
657
658 // x == 0, y > 0 -> pi/2
659 Value *XEq0AndYGe0 = Builder.CreateAnd(XEq0, YGe0);
660 Result = Builder.CreateSelect(XEq0AndYGe0, HalfPi, Result);
661
662 return Result;
663}
664
665template <bool LeftFunnel>
667 Type *Ty = Orig->getType();
668 Value *A = Orig->getOperand(0);
669 Value *B = Orig->getOperand(1);
670 Value *Shift = Orig->getOperand(2);
671
672 IRBuilder<> Builder(Orig);
673
674 unsigned BitWidth = Ty->getScalarSizeInBits();
676 "Can't use Mask to compute modulo and inverse");
677
678 // Note: if (Shift % BitWidth) == 0 then (BitWidth - Shift) == BitWidth,
679 // shifting by the bitwidth for shl/lshr returns a poisoned result. As such,
680 // we implement the same formula as LegalizerHelper::lowerFunnelShiftAsShifts.
681 //
682 // The funnel shift is expanded like so:
683 // fshl
684 // -> msb_extract((concat(A, B) << (Shift % BitWidth)), BitWidth)
685 // -> A << (Shift % BitWidth) | B >> 1 >> (BitWidth - 1 - (Shift % BitWidth))
686 // fshr
687 // -> lsb_extract((concat(A, B) >> (Shift % BitWidth), BitWidth))
688 // -> A << 1 << (BitWidth - 1 - (Shift % BitWidth)) | B >> (Shift % BitWidth)
689
690 // (BitWidth - 1) -> Mask
691 Constant *Mask = ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1);
692
693 // Shift % BitWidth
694 // -> Shift & (BitWidth - 1)
695 // -> Shift & Mask
696 Value *MaskedShift = Builder.CreateAnd(Shift, Mask);
697
698 // (BitWidth - 1) - (Shift % BitWidth)
699 // -> ~Shift & (BitWidth - 1)
700 // -> ~Shift & Mask
701 Value *NotShift = Builder.CreateNot(Shift);
702 Value *InverseShift = Builder.CreateAnd(NotShift, Mask);
703
704 Constant *One = ConstantInt::get(Ty, 1);
705 Value *ShiftedA;
706 Value *ShiftedB;
707
708 if (LeftFunnel) {
709 ShiftedA = Builder.CreateShl(A, MaskedShift);
710 Value *ShiftB1 = Builder.CreateLShr(B, One);
711 ShiftedB = Builder.CreateLShr(ShiftB1, InverseShift);
712 } else {
713 Value *ShiftA1 = Builder.CreateShl(A, One);
714 ShiftedA = Builder.CreateShl(ShiftA1, InverseShift);
715 ShiftedB = Builder.CreateLShr(B, MaskedShift);
716 }
717
718 Value *Result = Builder.CreateOr(ShiftedA, ShiftedB);
719 return Result;
720}
721
722static Value *expandPowIntrinsic(CallInst *Orig, Intrinsic::ID IntrinsicId) {
723
724 Value *X = Orig->getOperand(0);
725 Value *Y = Orig->getOperand(1);
726 Type *Ty = X->getType();
727 IRBuilder<> Builder(Orig);
728
729 if (IntrinsicId == Intrinsic::powi)
730 Y = Builder.CreateSIToFP(Y, Ty);
731
732 auto *Log2Call =
733 Builder.CreateIntrinsic(Ty, Intrinsic::log2, {X}, nullptr, "elt.log2");
734 auto *Mul = Builder.CreateFMul(Log2Call, Y);
735 auto *Exp2Call =
736 Builder.CreateIntrinsic(Ty, Intrinsic::exp2, {Mul}, nullptr, "elt.exp2");
737 Exp2Call->setTailCall(Orig->isTailCall());
738 Exp2Call->setAttributes(Orig->getAttributes());
739 return Exp2Call;
740}
741
743
744 Value *X = Orig->getOperand(0);
745 Value *Y = Orig->getOperand(1);
746 Type *Ty = X->getType();
747 IRBuilder<> Builder(Orig);
748
749 Constant *One = ConstantFP::get(Ty->getScalarType(), 1.0);
750 Constant *Zero = ConstantFP::get(Ty->getScalarType(), 0.0);
751 Value *Cond = Builder.CreateFCmpOLT(Y, X);
752
753 if (Ty != Ty->getScalarType()) {
754 auto *XVec = dyn_cast<FixedVectorType>(Ty);
756 ElementCount::getFixed(XVec->getNumElements()), One);
758 ElementCount::getFixed(XVec->getNumElements()), Zero);
759 }
760
761 return Builder.CreateSelect(Cond, Zero, One);
762}
763
765 Value *X = Orig->getOperand(0);
766 Type *Ty = X->getType();
767 IRBuilder<> Builder(Orig);
768 Value *PiOver180 = ConstantFP::get(Ty, llvm::numbers::pi / 180.0);
769 return Builder.CreateFMul(X, PiOver180);
770}
771
772static bool expandBufferLoadIntrinsic(CallInst *Orig, bool IsRaw) {
773 IRBuilder<> Builder(Orig);
774
775 Type *BufferTy = Orig->getType()->getStructElementType(0);
776 Type *ScalarTy = BufferTy->getScalarType();
777 bool IsDouble = ScalarTy->isDoubleTy();
778 assert(IsDouble || ScalarTy->isIntegerTy(64) &&
779 "Only expand double or int64 scalars or vectors");
780 bool IsVector = false;
781 unsigned ExtractNum = 2;
782 if (auto *VT = dyn_cast<FixedVectorType>(BufferTy)) {
783 ExtractNum = 2 * VT->getNumElements();
784 IsVector = true;
785 assert(IsRaw || ExtractNum == 4 && "TypedBufferLoad vector must be size 2");
786 }
787
789 Value *Result = PoisonValue::get(BufferTy);
790 unsigned Base = 0;
791 // If we need to extract more than 4 i32; we need to break it up into
792 // more than one load. LoadNum tells us how many i32s we are loading in
793 // each load
794 while (ExtractNum > 0) {
795 unsigned LoadNum = std::min(ExtractNum, 4u);
796 Type *Ty = VectorType::get(Builder.getInt32Ty(), LoadNum, false);
797
798 Type *LoadType = StructType::get(Ty, Builder.getInt1Ty());
799 Intrinsic::ID LoadIntrinsic = Intrinsic::dx_resource_load_typedbuffer;
800 SmallVector<Value *, 3> Args = {Orig->getOperand(0), Orig->getOperand(1)};
801 if (IsRaw) {
802 LoadIntrinsic = Intrinsic::dx_resource_load_rawbuffer;
803 Value *Tmp = Builder.getInt32(4 * Base * 2);
804 Args.push_back(Builder.CreateAdd(Orig->getOperand(2), Tmp));
805 }
806
807 CallInst *Load = Builder.CreateIntrinsic(LoadType, LoadIntrinsic, Args);
808 Loads.push_back(Load);
809
810 // extract the buffer load's result
811 Value *Extract = Builder.CreateExtractValue(Load, {0});
812
813 SmallVector<Value *> ExtractElements;
814 for (unsigned I = 0; I < LoadNum; ++I)
815 ExtractElements.push_back(
816 Builder.CreateExtractElement(Extract, Builder.getInt32(I)));
817
818 // combine into double(s) or int64(s)
819 for (unsigned I = 0; I < LoadNum; I += 2) {
820 Value *Combined = nullptr;
821 if (IsDouble)
822 // For doubles, use dx_asdouble intrinsic
823 Combined = Builder.CreateIntrinsic(
824 Builder.getDoubleTy(), Intrinsic::dx_asdouble,
825 {ExtractElements[I], ExtractElements[I + 1]});
826 else {
827 // For int64, manually combine two int32s
828 // First, zero-extend both values to i64
829 Value *Lo =
830 Builder.CreateZExt(ExtractElements[I], Builder.getInt64Ty());
831 Value *Hi =
832 Builder.CreateZExt(ExtractElements[I + 1], Builder.getInt64Ty());
833 // Shift the high bits left by 32 bits
834 Value *ShiftedHi = Builder.CreateShl(Hi, Builder.getInt64(32));
835 // OR the high and low bits together
836 Combined = Builder.CreateOr(Lo, ShiftedHi);
837 }
838
839 if (IsVector)
840 Result = Builder.CreateInsertElement(Result, Combined,
841 Builder.getInt32((I / 2) + Base));
842 else
843 Result = Combined;
844 }
845
846 ExtractNum -= LoadNum;
847 Base += LoadNum / 2;
848 }
849
850 Value *CheckBit = nullptr;
851 for (User *U : make_early_inc_range(Orig->users())) {
852 // If it's not a ExtractValueInst, we don't know how to
853 // handle it
854 auto *EVI = dyn_cast<ExtractValueInst>(U);
855 if (!EVI)
856 llvm_unreachable("Unexpected user of typedbufferload");
857
858 ArrayRef<unsigned> Indices = EVI->getIndices();
859 assert(Indices.size() == 1);
860
861 if (Indices[0] == 0) {
862 // Use of the value(s)
863 EVI->replaceAllUsesWith(Result);
864 } else {
865 // Use of the check bit
866 assert(Indices[0] == 1 && "Unexpected type for typedbufferload");
867 // Note: This does not always match the historical behaviour of DXC.
868 // See https://github.com/microsoft/DirectXShaderCompiler/issues/7622
869 if (!CheckBit) {
870 SmallVector<Value *, 2> CheckBits;
871 for (Value *L : Loads)
872 CheckBits.push_back(Builder.CreateExtractValue(L, {1}));
873 CheckBit = Builder.CreateAnd(CheckBits);
874 }
875 EVI->replaceAllUsesWith(CheckBit);
876 }
877 EVI->eraseFromParent();
878 }
879 Orig->eraseFromParent();
880 return true;
881}
882
883static bool expandBufferStoreIntrinsic(CallInst *Orig, bool IsRaw) {
884 IRBuilder<> Builder(Orig);
885
886 unsigned ValIndex = IsRaw ? 3 : 2;
887 Type *BufferTy = Orig->getFunctionType()->getParamType(ValIndex);
888 Type *ScalarTy = BufferTy->getScalarType();
889 bool IsDouble = ScalarTy->isDoubleTy();
890 assert((IsDouble || ScalarTy->isIntegerTy(64)) &&
891 "Only expand double or int64 scalars or vectors");
892
893 // Determine if we're dealing with a vector or scalar
894 bool IsVector = false;
895 unsigned ExtractNum = 2;
896 unsigned VecLen = 0;
897 if (auto *VT = dyn_cast<FixedVectorType>(BufferTy)) {
898 VecLen = VT->getNumElements();
899 assert(IsRaw || VecLen == 2 && "TypedBufferStore vector must be size 2");
900 ExtractNum = VecLen * 2;
901 IsVector = true;
902 }
903
904 // Create the appropriate vector type for the result
905 Type *Int32Ty = Builder.getInt32Ty();
906 Type *ResultTy = VectorType::get(Int32Ty, ExtractNum, false);
907 Value *Val = PoisonValue::get(ResultTy);
908
909 Type *SplitElementTy = Int32Ty;
910 if (IsVector)
911 SplitElementTy = VectorType::get(SplitElementTy, VecLen, false);
912
913 Value *LowBits = nullptr;
914 Value *HighBits = nullptr;
915 // Split the 64-bit values into 32-bit components
916 if (IsDouble) {
917 auto *SplitTy = llvm::StructType::get(SplitElementTy, SplitElementTy);
918 Value *Split = Builder.CreateIntrinsic(SplitTy, Intrinsic::dx_splitdouble,
919 {Orig->getOperand(ValIndex)});
920 LowBits = Builder.CreateExtractValue(Split, 0);
921 HighBits = Builder.CreateExtractValue(Split, 1);
922 } else {
923 // Handle int64 type(s)
924 Value *InputVal = Orig->getOperand(ValIndex);
925 Constant *ShiftAmt = Builder.getInt64(32);
926 if (IsVector)
927 ShiftAmt =
929
930 // Split into low and high 32-bit parts
931 LowBits = Builder.CreateTrunc(InputVal, SplitElementTy);
932 Value *ShiftedVal = Builder.CreateLShr(InputVal, ShiftAmt);
933 HighBits = Builder.CreateTrunc(ShiftedVal, SplitElementTy);
934 }
935
936 if (IsVector) {
938 for (unsigned I = 0; I < VecLen; ++I) {
939 Mask.push_back(I);
940 Mask.push_back(I + VecLen);
941 }
942 Val = Builder.CreateShuffleVector(LowBits, HighBits, Mask);
943 } else {
944 Val = Builder.CreateInsertElement(Val, LowBits, Builder.getInt32(0));
945 Val = Builder.CreateInsertElement(Val, HighBits, Builder.getInt32(1));
946 }
947
948 // If we need to extract more than 4 i32; we need to break it up into
949 // more than one store. StoreNum tells us how many i32s we are storing in
950 // each store
951 unsigned Base = 0;
952 while (ExtractNum > 0) {
953 unsigned StoreNum = std::min(ExtractNum, 4u);
954
955 Intrinsic::ID StoreIntrinsic = Intrinsic::dx_resource_store_typedbuffer;
956 SmallVector<Value *, 4> Args = {Orig->getOperand(0), Orig->getOperand(1)};
957 if (IsRaw) {
958 StoreIntrinsic = Intrinsic::dx_resource_store_rawbuffer;
959 Value *Tmp = Builder.getInt32(4 * Base);
960 Args.push_back(Builder.CreateAdd(Orig->getOperand(2), Tmp));
961 }
962
964 for (unsigned I = 0; I < StoreNum; ++I) {
965 Mask.push_back(Base + I);
966 }
967
968 Value *SubVal = Val;
969 if (VecLen > 2)
970 SubVal = Builder.CreateShuffleVector(Val, Mask);
971
972 Args.push_back(SubVal);
973 // Create the final intrinsic call
974 Builder.CreateIntrinsic(Builder.getVoidTy(), StoreIntrinsic, Args);
975
976 ExtractNum -= StoreNum;
977 Base += StoreNum;
978 }
979 Orig->eraseFromParent();
980 return true;
981}
982
984 if (ClampIntrinsic == Intrinsic::dx_uclamp)
985 return Intrinsic::umax;
986 if (ClampIntrinsic == Intrinsic::dx_sclamp)
987 return Intrinsic::smax;
988 assert(ClampIntrinsic == Intrinsic::dx_nclamp);
989 return Intrinsic::maxnum;
990}
991
993 if (ClampIntrinsic == Intrinsic::dx_uclamp)
994 return Intrinsic::umin;
995 if (ClampIntrinsic == Intrinsic::dx_sclamp)
996 return Intrinsic::smin;
997 assert(ClampIntrinsic == Intrinsic::dx_nclamp);
998 return Intrinsic::minnum;
999}
1000
1002 Intrinsic::ID ClampIntrinsic) {
1003 Value *X = Orig->getOperand(0);
1004 Value *Min = Orig->getOperand(1);
1005 Value *Max = Orig->getOperand(2);
1006 Type *Ty = X->getType();
1007 IRBuilder<> Builder(Orig);
1008 auto *MaxCall = Builder.CreateIntrinsic(Ty, getMaxForClamp(ClampIntrinsic),
1009 {X, Min}, nullptr, "dx.max");
1010 return Builder.CreateIntrinsic(Ty, getMinForClamp(ClampIntrinsic),
1011 {MaxCall, Max}, nullptr, "dx.min");
1012}
1013
1015 Value *X = Orig->getOperand(0);
1016 Type *Ty = X->getType();
1017 IRBuilder<> Builder(Orig);
1018 Value *DegreesRatio = ConstantFP::get(Ty, 180.0 * llvm::numbers::inv_pi);
1019 return Builder.CreateFMul(X, DegreesRatio);
1020}
1021
1023 Value *X = Orig->getOperand(0);
1024 Type *Ty = X->getType();
1025 Type *ScalarTy = Ty->getScalarType();
1026 Type *RetTy = Orig->getType();
1027 Constant *Zero = Constant::getNullValue(Ty);
1028
1029 IRBuilder<> Builder(Orig);
1030
1031 Value *GT;
1032 Value *LT;
1033 if (ScalarTy->isFloatingPointTy()) {
1034 GT = Builder.CreateFCmpOLT(Zero, X);
1035 LT = Builder.CreateFCmpOLT(X, Zero);
1036 } else {
1037 assert(ScalarTy->isIntegerTy());
1038 GT = Builder.CreateICmpSLT(Zero, X);
1039 LT = Builder.CreateICmpSLT(X, Zero);
1040 }
1041
1042 Value *ZextGT = Builder.CreateZExt(GT, RetTy);
1043 Value *ZextLT = Builder.CreateZExt(LT, RetTy);
1044
1045 return Builder.CreateSub(ZextGT, ZextLT);
1046}
1047
1048// Expand llvm.matrix.multiply by extracting row/column vectors and computing
1049// dot products.
1050// Result[r,c] = dot(row_r(LHS), col_c(RHS))
1051// Element (r,c) is at index c*NumRows + r (column-major).
1053 Value *LHS = Orig->getArgOperand(0);
1054 Value *RHS = Orig->getArgOperand(1);
1055 unsigned LHSRows = cast<ConstantInt>(Orig->getArgOperand(2))->getZExtValue();
1056 unsigned LHSCols = cast<ConstantInt>(Orig->getArgOperand(3))->getZExtValue();
1057 unsigned RHSCols = cast<ConstantInt>(Orig->getArgOperand(4))->getZExtValue();
1058
1059 auto *RetTy = cast<FixedVectorType>(Orig->getType());
1060 Type *EltTy = RetTy->getElementType();
1061 bool IsFP = EltTy->isFloatingPointTy();
1062
1063 IRBuilder<> Builder(Orig);
1064
1065 // Column-major indexing:
1066 // LHS row R, element K: index = K * LHSRows + R
1067 // RHS col C, element K: index = C * LHSCols + K
1068 Value *Result = PoisonValue::get(RetTy);
1069
1070 // Extract all scalar elements from LHS and RHS once, then reuse them.
1071 unsigned LHSSize = LHSRows * LHSCols;
1072 unsigned RHSSize = LHSCols * RHSCols;
1073 SmallVector<Value *, 16> LHSElts(LHSSize);
1074 SmallVector<Value *, 16> RHSElts(RHSSize);
1075 for (unsigned I = 0; I < LHSSize; ++I)
1076 LHSElts[I] = Builder.CreateExtractElement(LHS, I);
1077 for (unsigned I = 0; I < RHSSize; ++I)
1078 RHSElts[I] = Builder.CreateExtractElement(RHS, I);
1079
1080 // Choose the appropriate scalar-arg dot intrinsic for floats.
1081 // K=1 and double types use scalar expansion instead.
1083 bool UseScalarFP = IsFP && (EltTy->isDoubleTy() || LHSCols == 1);
1084 if (IsFP && !UseScalarFP) {
1085 switch (LHSCols) {
1086 case 2:
1087 FloatDotID = Intrinsic::dx_dot2;
1088 break;
1089 case 3:
1090 FloatDotID = Intrinsic::dx_dot3;
1091 break;
1092 case 4:
1093 FloatDotID = Intrinsic::dx_dot4;
1094 break;
1095 default:
1097 "Invalid matrix inner dimension for dot product: must be 2-4");
1098 return nullptr;
1099 }
1100 }
1101
1102 for (unsigned C = 0; C < RHSCols; ++C) {
1103 for (unsigned R = 0; R < LHSRows; ++R) {
1104 // Gather row R from LHS and column C from RHS.
1105 SmallVector<Value *, 4> RowElts, ColElts;
1106 for (unsigned K = 0; K < LHSCols; ++K) {
1107 RowElts.push_back(LHSElts[K * LHSRows + R]);
1108 ColElts.push_back(RHSElts[C * LHSCols + K]);
1109 }
1110
1111 Value *Dot;
1112 if (UseScalarFP) {
1113 // Scalar fmul+fmuladd expansion for double types and K=1.
1114 Dot = Builder.CreateFMul(RowElts[0], ColElts[0]);
1115 for (unsigned K = 1; K < LHSCols; ++K)
1116 Dot = Builder.CreateIntrinsic(EltTy, Intrinsic::fmuladd,
1117 {RowElts[K], ColElts[K], Dot});
1118 } else if (IsFP) {
1119 // Emit scalar-arg DXIL dot directly (dx.dot2/dx.dot3/dx.dot4).
1121 Args.append(RowElts.begin(), RowElts.end());
1122 Args.append(ColElts.begin(), ColElts.end());
1123 Dot = Builder.CreateIntrinsic(EltTy, FloatDotID, Args);
1124 } else {
1125 // Integer: emit multiply + imad chain.
1126 Dot = Builder.CreateMul(RowElts[0], ColElts[0]);
1127 for (unsigned K = 1; K < LHSCols; ++K)
1128 Dot = Builder.CreateIntrinsic(EltTy, Intrinsic::dx_imad,
1129 {RowElts[K], ColElts[K], Dot});
1130 }
1131 unsigned ResIdx = C * LHSRows + R;
1132 Result = Builder.CreateInsertElement(Result, Dot, ResIdx);
1133 }
1134 }
1135 return Result;
1136}
1137
1138static bool expandIntrinsic(Function &F, CallInst *Orig) {
1139 Value *Result = nullptr;
1140 Intrinsic::ID IntrinsicId = F.getIntrinsicID();
1141 switch (IntrinsicId) {
1142 case Intrinsic::abs:
1143 Result = expandAbs(Orig);
1144 break;
1145 case Intrinsic::assume:
1146 Orig->eraseFromParent();
1147 return true;
1148 case Intrinsic::atan2:
1149 Result = expandAtan2Intrinsic(Orig);
1150 break;
1151 case Intrinsic::fshl:
1152 Result = expandFunnelShiftIntrinsic<true>(Orig);
1153 break;
1154 case Intrinsic::fshr:
1155 Result = expandFunnelShiftIntrinsic<false>(Orig);
1156 break;
1157 case Intrinsic::exp:
1158 Result = expandExpIntrinsic(Orig);
1159 break;
1160 case Intrinsic::is_fpclass:
1161 Result = expandIsFPClass(Orig);
1162 break;
1163 case Intrinsic::log:
1164 Result = expandLogIntrinsic(Orig);
1165 break;
1166 case Intrinsic::log10:
1167 Result = expandLog10Intrinsic(Orig);
1168 break;
1169 case Intrinsic::pow:
1170 case Intrinsic::powi:
1171 Result = expandPowIntrinsic(Orig, IntrinsicId);
1172 break;
1173 case Intrinsic::dx_all:
1174 case Intrinsic::dx_any:
1175 Result = expandAnyOrAllIntrinsic(Orig, IntrinsicId);
1176 break;
1177 case Intrinsic::dx_cross:
1178 Result = expandCrossIntrinsic(Orig);
1179 break;
1180 case Intrinsic::dx_uclamp:
1181 case Intrinsic::dx_sclamp:
1182 case Intrinsic::dx_nclamp:
1183 Result = expandClampIntrinsic(Orig, IntrinsicId);
1184 break;
1185 case Intrinsic::dx_degrees:
1186 Result = expandDegreesIntrinsic(Orig);
1187 break;
1188 case Intrinsic::dx_isinf:
1189 Result = expand16BitIsInf(Orig);
1190 break;
1191 case Intrinsic::dx_isnan:
1192 Result = expand16BitIsNaN(Orig);
1193 break;
1194 case Intrinsic::dx_lerp:
1195 Result = expandLerpIntrinsic(Orig);
1196 break;
1197 case Intrinsic::dx_normalize:
1198 Result = expandNormalizeIntrinsic(Orig);
1199 break;
1200 case Intrinsic::dx_fdot:
1201 Result = expandFloatDotIntrinsic(Orig);
1202 break;
1203 case Intrinsic::dx_sdot:
1204 case Intrinsic::dx_udot:
1205 Result = expandIntegerDotIntrinsic(Orig, IntrinsicId);
1206 break;
1207 case Intrinsic::dx_sign:
1208 Result = expandSignIntrinsic(Orig);
1209 break;
1210 case Intrinsic::dx_step:
1211 Result = expandStepIntrinsic(Orig);
1212 break;
1213 case Intrinsic::dx_radians:
1214 Result = expandRadiansIntrinsic(Orig);
1215 break;
1216 case Intrinsic::dx_resource_load_rawbuffer:
1217 if (expandBufferLoadIntrinsic(Orig, /*IsRaw*/ true))
1218 return true;
1219 break;
1220 case Intrinsic::dx_resource_store_rawbuffer:
1221 if (expandBufferStoreIntrinsic(Orig, /*IsRaw*/ true))
1222 return true;
1223 break;
1224 case Intrinsic::dx_resource_load_typedbuffer:
1225 if (expandBufferLoadIntrinsic(Orig, /*IsRaw*/ false))
1226 return true;
1227 break;
1228 case Intrinsic::dx_resource_store_typedbuffer:
1229 if (expandBufferStoreIntrinsic(Orig, /*IsRaw*/ false))
1230 return true;
1231 break;
1232 case Intrinsic::usub_sat:
1233 Result = expandUsubSat(Orig);
1234 break;
1235 case Intrinsic::vector_reduce_add:
1236 case Intrinsic::vector_reduce_fadd:
1237 Result = expandVecReduceAdd(Orig, IntrinsicId);
1238 break;
1239 case Intrinsic::matrix_multiply:
1240 Result = expandMatrixMultiply(Orig);
1241 break;
1242 }
1243 if (Result) {
1244 Orig->replaceAllUsesWith(Result);
1245 Orig->eraseFromParent();
1246 return true;
1247 }
1248 return false;
1249}
1250
1252 for (auto &F : make_early_inc_range(M.functions())) {
1253 if (!isIntrinsicExpansion(F))
1254 continue;
1255 bool IntrinsicExpanded = false;
1256 for (User *U : make_early_inc_range(F.users())) {
1257 auto *IntrinsicCall = dyn_cast<CallInst>(U);
1258 if (!IntrinsicCall)
1259 continue;
1260 IntrinsicExpanded = expandIntrinsic(F, IntrinsicCall);
1261 }
1262 if (F.user_empty() && IntrinsicExpanded)
1263 F.eraseFromParent();
1264 }
1265 return true;
1266}
1267
1274
1278
1280
1282 "DXIL Intrinsic Expansion", false, false)
1284 "DXIL Intrinsic Expansion", false, false)
1285
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Value * expand16BitIsNormal(CallInst *Orig)
static Value * expandNormalizeIntrinsic(CallInst *Orig)
static bool expandIntrinsic(Function &F, CallInst *Orig)
static Value * expandClampIntrinsic(CallInst *Orig, Intrinsic::ID ClampIntrinsic)
static Value * expand16BitIsInf(CallInst *Orig)
static bool expansionIntrinsics(Module &M)
static Value * expand16BitIsFinite(CallInst *Orig)
static Value * expandLerpIntrinsic(CallInst *Orig)
static Value * expandCrossIntrinsic(CallInst *Orig)
static Value * expandUsubSat(CallInst *Orig)
static Value * expandAnyOrAllIntrinsic(CallInst *Orig, Intrinsic::ID IntrinsicId)
static Value * expandVecReduceAdd(CallInst *Orig, Intrinsic::ID IntrinsicId)
static Value * expandAtan2Intrinsic(CallInst *Orig)
static Value * expandLog10Intrinsic(CallInst *Orig)
static Intrinsic::ID getMinForClamp(Intrinsic::ID ClampIntrinsic)
static Value * expandStepIntrinsic(CallInst *Orig)
static Value * expandIntegerDotIntrinsic(CallInst *Orig, Intrinsic::ID DotIntrinsic)
static bool expandBufferStoreIntrinsic(CallInst *Orig, bool IsRaw)
static Value * expandLogIntrinsic(CallInst *Orig, float LogConstVal=numbers::ln2f)
static Value * expandDegreesIntrinsic(CallInst *Orig)
static Value * expandPowIntrinsic(CallInst *Orig, Intrinsic::ID IntrinsicId)
static bool resourceAccessNeeds64BitExpansion(Module *M, Type *OverloadTy, bool IsRaw)
static Value * expandExpIntrinsic(CallInst *Orig)
static Value * expand16BitIsNaN(CallInst *Orig)
static Value * expandSignIntrinsic(CallInst *Orig)
static Intrinsic::ID getMaxForClamp(Intrinsic::ID ClampIntrinsic)
static Value * expandAbs(CallInst *Orig)
static Value * expandFloatDotIntrinsic(CallInst *Orig, Value *A, Value *B)
static Value * expandRadiansIntrinsic(CallInst *Orig)
static bool isIntrinsicExpansion(Function &F)
static bool expandBufferLoadIntrinsic(CallInst *Orig, bool IsRaw)
static Value * expandMatrixMultiply(CallInst *Orig)
static Value * expandIsFPClass(CallInst *Orig)
static Value * expandFunnelShiftIntrinsic(CallInst *Orig)
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#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 SmallVectorImpl< MachineOperand > & Cond
static unsigned getNumElements(Type *Ty)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
Value * RHS
Value * LHS
BinaryOperator * Mul
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
bool isZero() const
Definition APFloat.h:1512
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
void setAttributes(AttributeList A)
Set the attributes for this call.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
void setTailCall(bool IsTc=true)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constants.cpp:74
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:802
Type * getParamType(unsigned i) const
Parameter type accessors.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
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 FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
ModulePass(char &pid)
Definition Pass.h:257
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
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 none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:413
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:295
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:156
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:300
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:427
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Represents a version number in the form major[.minor[.subminor[.build]]].
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
constexpr double inv_pi
constexpr float ln10f
Definition MathExtras.h:50
constexpr float log2ef
Definition MathExtras.h:51
constexpr double pi
constexpr float ln2f
Definition MathExtras.h:49
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
Definition InstrProf.h:296
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:634
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
ModulePass * createDXILIntrinsicExpansionLegacyPass()
Pass to expand intrinsic operations that lack DXIL opCodes.
@ Sub
Subtraction of integers.
constexpr unsigned BitWidth
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
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177