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::dx_interlocked_add:
231 case Intrinsic::usub_sat:
232 case Intrinsic::vector_reduce_add:
233 case Intrinsic::vector_reduce_fadd:
234 case Intrinsic::matrix_multiply:
235 case Intrinsic::matrix_transpose:
236 return true;
237 case Intrinsic::dx_resource_load_rawbuffer:
239 F.getParent(), F.getReturnType()->getStructElementType(0),
240 /*IsRaw*/ true);
241 case Intrinsic::dx_resource_load_typedbuffer:
243 F.getParent(), F.getReturnType()->getStructElementType(0),
244 /*IsRaw*/ false);
245 case Intrinsic::dx_resource_store_rawbuffer:
247 F.getParent(), F.getFunctionType()->getParamType(3), /*IsRaw*/ true);
248 case Intrinsic::dx_resource_store_typedbuffer:
250 F.getParent(), F.getFunctionType()->getParamType(2), /*IsRaw*/ false);
251 }
252 return false;
253}
254
256 Value *A = Orig->getArgOperand(0);
257 Value *B = Orig->getArgOperand(1);
258 Type *Ty = A->getType();
259
260 IRBuilder<> Builder(Orig);
261
262 Value *Cmp = Builder.CreateICmpULT(A, B, "usub.cmp");
263 Value *Sub = Builder.CreateSub(A, B, "usub.sub");
264 Value *Zero = ConstantInt::get(Ty, 0);
265 return Builder.CreateSelect(Cmp, Zero, Sub, "usub.sat");
266}
267
268static Value *expandVecReduceAdd(CallInst *Orig, Intrinsic::ID IntrinsicId) {
269 assert(IntrinsicId == Intrinsic::vector_reduce_add ||
270 IntrinsicId == Intrinsic::vector_reduce_fadd);
271
272 IRBuilder<> Builder(Orig);
273 bool IsFAdd = (IntrinsicId == Intrinsic::vector_reduce_fadd);
274
275 Value *X = Orig->getOperand(IsFAdd ? 1 : 0);
276 Type *Ty = X->getType();
277 auto *XVec = dyn_cast<FixedVectorType>(Ty);
278 unsigned XVecSize = XVec->getNumElements();
279 Value *Sum = Builder.CreateExtractElement(X, static_cast<uint64_t>(0));
280
281 // Handle the initial start value for floating-point addition.
282 if (IsFAdd) {
283 Constant *StartValue = dyn_cast<Constant>(Orig->getOperand(0));
284 if (StartValue && !StartValue->isNullValue())
285 Sum = Builder.CreateFAdd(Sum, StartValue);
286 }
287
288 // Accumulate the remaining vector elements.
289 for (unsigned I = 1; I < XVecSize; I++) {
290 Value *Elt = Builder.CreateExtractElement(X, I);
291 if (IsFAdd)
292 Sum = Builder.CreateFAdd(Sum, Elt);
293 else
294 Sum = Builder.CreateAdd(Sum, Elt);
295 }
296
297 return Sum;
298}
299
300static Value *expandAbs(CallInst *Orig) {
301 Value *X = Orig->getOperand(0);
302 IRBuilder<> Builder(Orig);
303 Type *Ty = X->getType();
304 Type *EltTy = Ty->getScalarType();
305 Constant *Zero = Ty->isVectorTy()
309 ConstantInt::get(EltTy, 0))
310 : ConstantInt::get(EltTy, 0);
311 auto *V = Builder.CreateSub(Zero, X);
312 return Builder.CreateIntrinsic(Ty, Intrinsic::smax, {X, V}, nullptr,
313 "dx.max");
314}
315
317
318 VectorType *VT = cast<VectorType>(Orig->getType());
320 reportFatalUsageError("return vector must have exactly 3 elements");
321
322 Value *op0 = Orig->getOperand(0);
323 Value *op1 = Orig->getOperand(1);
324 IRBuilder<> Builder(Orig);
325
326 Value *op0_x = Builder.CreateExtractElement(op0, (uint64_t)0, "x0");
327 Value *op0_y = Builder.CreateExtractElement(op0, 1, "x1");
328 Value *op0_z = Builder.CreateExtractElement(op0, 2, "x2");
329
330 Value *op1_x = Builder.CreateExtractElement(op1, (uint64_t)0, "y0");
331 Value *op1_y = Builder.CreateExtractElement(op1, 1, "y1");
332 Value *op1_z = Builder.CreateExtractElement(op1, 2, "y2");
333
334 auto MulSub = [&](Value *x0, Value *y0, Value *x1, Value *y1) -> Value * {
335 Value *xy = Builder.CreateFMul(x0, y1);
336 Value *yx = Builder.CreateFMul(y0, x1);
337 return Builder.CreateFSub(xy, yx, Orig->getName());
338 };
339
340 Value *yz_zy = MulSub(op0_y, op0_z, op1_y, op1_z);
341 Value *zx_xz = MulSub(op0_z, op0_x, op1_z, op1_x);
342 Value *xy_yx = MulSub(op0_x, op0_y, op1_x, op1_y);
343
344 Value *cross = PoisonValue::get(VT);
345 cross = Builder.CreateInsertElement(cross, yz_zy, (uint64_t)0);
346 cross = Builder.CreateInsertElement(cross, zx_xz, 1);
347 cross = Builder.CreateInsertElement(cross, xy_yx, 2);
348 return cross;
349}
350
351// Create appropriate DXIL float dot intrinsic for the given A and B operands
352// The appropriate opcode will be determined by the size of the operands
353// The dot product is placed in the position indicated by Orig
355 Type *ATy = A->getType();
356 [[maybe_unused]] Type *BTy = B->getType();
357 assert(ATy->isVectorTy() && BTy->isVectorTy());
358
359 IRBuilder<> Builder(Orig);
360
361 auto *AVec = dyn_cast<FixedVectorType>(ATy);
362
364
365 Intrinsic::ID DotIntrinsic = Intrinsic::dx_dot4;
366 int NumElts = AVec->getNumElements();
367 switch (NumElts) {
368 case 2:
369 DotIntrinsic = Intrinsic::dx_dot2;
370 break;
371 case 3:
372 DotIntrinsic = Intrinsic::dx_dot3;
373 break;
374 case 4:
375 DotIntrinsic = Intrinsic::dx_dot4;
376 break;
377 default:
379 "Invalid dot product input vector: length is outside 2-4");
380 return nullptr;
381 }
382
384 for (int I = 0; I < NumElts; ++I)
385 Args.push_back(Builder.CreateExtractElement(A, Builder.getInt32(I)));
386 for (int I = 0; I < NumElts; ++I)
387 Args.push_back(Builder.CreateExtractElement(B, Builder.getInt32(I)));
388 return Builder.CreateIntrinsic(ATy->getScalarType(), DotIntrinsic, Args,
389 nullptr, "dot");
390}
391
392// Create the appropriate DXIL float dot intrinsic for the operands of Orig
393// The appropriate opcode will be determined by the size of the operands
394// The dot product is placed in the position indicated by Orig
396 return expandFloatDotIntrinsic(Orig, Orig->getOperand(0),
397 Orig->getOperand(1));
398}
399
400// Expand integer dot product to multiply and add ops
402 Intrinsic::ID DotIntrinsic) {
403 assert(DotIntrinsic == Intrinsic::dx_sdot ||
404 DotIntrinsic == Intrinsic::dx_udot);
405 Value *A = Orig->getOperand(0);
406 Value *B = Orig->getOperand(1);
407 Type *ATy = A->getType();
408 [[maybe_unused]] Type *BTy = B->getType();
409 assert(ATy->isVectorTy() && BTy->isVectorTy());
410
411 IRBuilder<> Builder(Orig);
412
413 auto *AVec = dyn_cast<FixedVectorType>(ATy);
414
416
417 Value *Result;
418 Intrinsic::ID MadIntrinsic = DotIntrinsic == Intrinsic::dx_sdot
419 ? Intrinsic::dx_imad
420 : Intrinsic::dx_umad;
421 Value *Elt0 = Builder.CreateExtractElement(A, (uint64_t)0);
422 Value *Elt1 = Builder.CreateExtractElement(B, (uint64_t)0);
423 Result = Builder.CreateMul(Elt0, Elt1);
424 for (unsigned I = 1; I < AVec->getNumElements(); I++) {
425 Elt0 = Builder.CreateExtractElement(A, I);
426 Elt1 = Builder.CreateExtractElement(B, I);
427 Result = Builder.CreateIntrinsic(Result->getType(), MadIntrinsic,
428 ArrayRef<Value *>{Elt0, Elt1, Result},
429 nullptr, "dx.mad");
430 }
431 return Result;
432}
433
435 Value *X = Orig->getOperand(0);
436 IRBuilder<> Builder(Orig);
437 Type *Ty = X->getType();
438 Type *EltTy = Ty->getScalarType();
439 Constant *Log2eConst =
440 Ty->isVectorTy() ? ConstantVector::getSplat(
443 ConstantFP::get(EltTy, numbers::log2ef))
444 : ConstantFP::get(EltTy, numbers::log2ef);
445 Value *NewX = Builder.CreateFMul(Log2eConst, X);
446 auto *Exp2Call =
447 Builder.CreateIntrinsic(Ty, Intrinsic::exp2, {NewX}, nullptr, "dx.exp2");
448 Exp2Call->setTailCall(Orig->isTailCall());
449 Exp2Call->setAttributes(Orig->getAttributes());
450 return Exp2Call;
451}
452
454 Value *T = Orig->getArgOperand(1);
455 auto *TCI = dyn_cast<ConstantInt>(T);
456
457 // These FPClassTest cases have DXIL opcodes, so they will be handled in
458 // DXIL Op Lowering instead for all non f16 cases.
459 switch (TCI->getZExtValue()) {
461 return expand16BitIsInf(Orig);
463 return expand16BitIsNaN(Orig);
465 return expand16BitIsNormal(Orig);
467 return expand16BitIsFinite(Orig);
468 }
469
470 IRBuilder<> Builder(Orig);
471
472 Value *F = Orig->getArgOperand(0);
473 Type *FTy = F->getType();
474 unsigned FNumElem = 0; // 0 => F is not a vector
475
476 unsigned BitWidth; // Bit width of F or the ElemTy of F
477 Type *BitCastTy; // An IntNTy of the same bitwidth as F or ElemTy of F
478
479 if (auto *FVecTy = dyn_cast<FixedVectorType>(FTy)) {
480 Type *ElemTy = FVecTy->getElementType();
481 FNumElem = FVecTy->getNumElements();
482 BitWidth = ElemTy->getPrimitiveSizeInBits();
483 BitCastTy = FixedVectorType::get(Builder.getIntNTy(BitWidth), FNumElem);
484 } else {
486 BitCastTy = Builder.getIntNTy(BitWidth);
487 }
488
489 Value *FBitCast = Builder.CreateBitCast(F, BitCastTy);
490 switch (TCI->getZExtValue()) {
492 Value *NegZero =
493 ConstantInt::get(Builder.getIntNTy(BitWidth), 1 << (BitWidth - 1),
494 /*IsSigned=*/true);
495 Value *RetVal;
496 if (FNumElem) {
497 Value *NegZeroSplat = Builder.CreateVectorSplat(FNumElem, NegZero);
498 RetVal =
499 Builder.CreateICmpEQ(FBitCast, NegZeroSplat, "is.fpclass.negzero");
500 } else
501 RetVal = Builder.CreateICmpEQ(FBitCast, NegZero, "is.fpclass.negzero");
502 return RetVal;
503 }
504 default:
505 reportFatalUsageError("Unsupported FPClassTest");
506 }
507}
508
510 Intrinsic::ID IntrinsicId) {
511 Value *X = Orig->getOperand(0);
512 IRBuilder<> Builder(Orig);
513 Type *Ty = X->getType();
514 Type *EltTy = Ty->getScalarType();
515
516 auto ApplyOp = [&Builder](Intrinsic::ID IntrinsicId, Value *Result,
517 Value *Elt) {
518 if (IntrinsicId == Intrinsic::dx_any)
519 return Builder.CreateOr(Result, Elt);
520 assert(IntrinsicId == Intrinsic::dx_all);
521 return Builder.CreateAnd(Result, Elt);
522 };
523
524 Value *Result = nullptr;
525 if (!Ty->isVectorTy()) {
526 Result = EltTy->isFloatingPointTy()
527 ? Builder.CreateFCmpUNE(X, ConstantFP::get(EltTy, 0))
528 : Builder.CreateICmpNE(X, ConstantInt::get(EltTy, 0));
529 } else {
530 auto *XVec = dyn_cast<FixedVectorType>(Ty);
531 Value *Cond =
532 EltTy->isFloatingPointTy()
533 ? Builder.CreateFCmpUNE(
535 ElementCount::getFixed(XVec->getNumElements()),
536 ConstantFP::get(EltTy, 0)))
537 : Builder.CreateICmpNE(
539 ElementCount::getFixed(XVec->getNumElements()),
540 ConstantInt::get(EltTy, 0)));
541 Result = Builder.CreateExtractElement(Cond, (uint64_t)0);
542 for (unsigned I = 1; I < XVec->getNumElements(); I++) {
543 Value *Elt = Builder.CreateExtractElement(Cond, I);
544 Result = ApplyOp(IntrinsicId, Result, Elt);
545 }
546 }
547 return Result;
548}
549
551 Value *X = Orig->getOperand(0);
552 Value *Y = Orig->getOperand(1);
553 Value *S = Orig->getOperand(2);
554 IRBuilder<> Builder(Orig);
555 auto *V = Builder.CreateFSub(Y, X);
556 V = Builder.CreateFMul(S, V);
557 return Builder.CreateFAdd(X, V, "dx.lerp");
558}
559
561 float LogConstVal = numbers::ln2f) {
562 Value *X = Orig->getOperand(0);
563 IRBuilder<> Builder(Orig);
564 Type *Ty = X->getType();
565 Type *EltTy = Ty->getScalarType();
566 Constant *Ln2Const =
567 Ty->isVectorTy() ? ConstantVector::getSplat(
570 ConstantFP::get(EltTy, LogConstVal))
571 : ConstantFP::get(EltTy, LogConstVal);
572 auto *Log2Call =
573 Builder.CreateIntrinsic(Ty, Intrinsic::log2, {X}, nullptr, "elt.log2");
574 Log2Call->setTailCall(Orig->isTailCall());
575 Log2Call->setAttributes(Orig->getAttributes());
576 return Builder.CreateFMul(Ln2Const, Log2Call);
577}
581
582// Use dot product of vector operand with itself to calculate the length.
583// Divide the vector by that length to normalize it.
585 Value *X = Orig->getOperand(0);
586 Type *Ty = Orig->getType();
587 Type *EltTy = Ty->getScalarType();
588 IRBuilder<> Builder(Orig);
589
590 auto *XVec = dyn_cast<FixedVectorType>(Ty);
591 if (!XVec) {
592 if (auto *constantFP = dyn_cast<ConstantFP>(X)) {
593 const APFloat &fpVal = constantFP->getValueAPF();
594 if (fpVal.isZero())
595 reportFatalUsageError("Invalid input scalar: length is zero");
596 }
597 return Builder.CreateFDiv(X, X);
598 }
599
600 Value *DotProduct = expandFloatDotIntrinsic(Orig, X, X);
601
602 // verify that the length is non-zero
603 // (if the dot product is non-zero, then the length is non-zero)
604 if (auto *constantFP = dyn_cast<ConstantFP>(DotProduct)) {
605 const APFloat &fpVal = constantFP->getValueAPF();
606 if (fpVal.isZero())
607 reportFatalUsageError("Invalid input vector: length is zero");
608 }
609
610 Value *Multiplicand = Builder.CreateIntrinsic(EltTy, Intrinsic::dx_rsqrt,
611 ArrayRef<Value *>{DotProduct},
612 nullptr, "dx.rsqrt");
613
614 Value *MultiplicandVec =
615 Builder.CreateVectorSplat(XVec->getNumElements(), Multiplicand);
616 return Builder.CreateFMul(X, MultiplicandVec);
617}
618
620 Value *Y = Orig->getOperand(0);
621 Value *X = Orig->getOperand(1);
622 Type *Ty = X->getType();
623 IRBuilder<> Builder(Orig);
624 Builder.setFastMathFlags(Orig->getFastMathFlags());
625
626 Value *Tan = Builder.CreateFDiv(Y, X);
627
628 CallInst *Atan =
629 Builder.CreateIntrinsic(Ty, Intrinsic::atan, {Tan}, nullptr, "Elt.Atan");
630 Atan->setTailCall(Orig->isTailCall());
631 Atan->setAttributes(Orig->getAttributes());
632
633 // Modify atan result based on https://en.wikipedia.org/wiki/Atan2.
634 Constant *Pi = ConstantFP::get(Ty, llvm::numbers::pi);
635 Constant *HalfPi = ConstantFP::get(Ty, llvm::numbers::pi / 2);
636 Constant *NegHalfPi = ConstantFP::get(Ty, -llvm::numbers::pi / 2);
637 Constant *Zero = ConstantFP::get(Ty, 0);
638 Value *AtanAddPi = Builder.CreateFAdd(Atan, Pi);
639 Value *AtanSubPi = Builder.CreateFSub(Atan, Pi);
640
641 // x > 0 -> atan.
642 Value *Result = Atan;
643 Value *XLt0 = Builder.CreateFCmpOLT(X, Zero);
644 Value *XEq0 = Builder.CreateFCmpOEQ(X, Zero);
645 Value *YGe0 = Builder.CreateFCmpOGE(Y, Zero);
646 Value *YLt0 = Builder.CreateFCmpOLT(Y, Zero);
647
648 // x < 0, y >= 0 -> atan + pi.
649 Value *XLt0AndYGe0 = Builder.CreateAnd(XLt0, YGe0);
650 Result = Builder.CreateSelect(XLt0AndYGe0, AtanAddPi, Result);
651
652 // x < 0, y < 0 -> atan - pi.
653 Value *XLt0AndYLt0 = Builder.CreateAnd(XLt0, YLt0);
654 Result = Builder.CreateSelect(XLt0AndYLt0, AtanSubPi, Result);
655
656 // x == 0, y < 0 -> -pi/2
657 Value *XEq0AndYLt0 = Builder.CreateAnd(XEq0, YLt0);
658 Result = Builder.CreateSelect(XEq0AndYLt0, NegHalfPi, Result);
659
660 // x == 0, y > 0 -> pi/2
661 Value *XEq0AndYGe0 = Builder.CreateAnd(XEq0, YGe0);
662 Result = Builder.CreateSelect(XEq0AndYGe0, HalfPi, Result);
663
664 return Result;
665}
666
667template <bool LeftFunnel>
669 Type *Ty = Orig->getType();
670 Value *A = Orig->getOperand(0);
671 Value *B = Orig->getOperand(1);
672 Value *Shift = Orig->getOperand(2);
673
674 IRBuilder<> Builder(Orig);
675
676 unsigned BitWidth = Ty->getScalarSizeInBits();
678 "Can't use Mask to compute modulo and inverse");
679
680 // Note: if (Shift % BitWidth) == 0 then (BitWidth - Shift) == BitWidth,
681 // shifting by the bitwidth for shl/lshr returns a poisoned result. As such,
682 // we implement the same formula as LegalizerHelper::lowerFunnelShiftAsShifts.
683 //
684 // The funnel shift is expanded like so:
685 // fshl
686 // -> msb_extract((concat(A, B) << (Shift % BitWidth)), BitWidth)
687 // -> A << (Shift % BitWidth) | B >> 1 >> (BitWidth - 1 - (Shift % BitWidth))
688 // fshr
689 // -> lsb_extract((concat(A, B) >> (Shift % BitWidth), BitWidth))
690 // -> A << 1 << (BitWidth - 1 - (Shift % BitWidth)) | B >> (Shift % BitWidth)
691
692 // (BitWidth - 1) -> Mask
693 Constant *Mask = ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1);
694
695 // Shift % BitWidth
696 // -> Shift & (BitWidth - 1)
697 // -> Shift & Mask
698 Value *MaskedShift = Builder.CreateAnd(Shift, Mask);
699
700 // (BitWidth - 1) - (Shift % BitWidth)
701 // -> ~Shift & (BitWidth - 1)
702 // -> ~Shift & Mask
703 Value *NotShift = Builder.CreateNot(Shift);
704 Value *InverseShift = Builder.CreateAnd(NotShift, Mask);
705
706 Constant *One = ConstantInt::get(Ty, 1);
707 Value *ShiftedA;
708 Value *ShiftedB;
709
710 if (LeftFunnel) {
711 ShiftedA = Builder.CreateShl(A, MaskedShift);
712 Value *ShiftB1 = Builder.CreateLShr(B, One);
713 ShiftedB = Builder.CreateLShr(ShiftB1, InverseShift);
714 } else {
715 Value *ShiftA1 = Builder.CreateShl(A, One);
716 ShiftedA = Builder.CreateShl(ShiftA1, InverseShift);
717 ShiftedB = Builder.CreateLShr(B, MaskedShift);
718 }
719
720 Value *Result = Builder.CreateOr(ShiftedA, ShiftedB);
721 return Result;
722}
723
724static Value *expandPowIntrinsic(CallInst *Orig, Intrinsic::ID IntrinsicId) {
725
726 Value *X = Orig->getOperand(0);
727 Value *Y = Orig->getOperand(1);
728 Type *Ty = X->getType();
729 IRBuilder<> Builder(Orig);
730
731 if (IntrinsicId == Intrinsic::powi)
732 Y = Builder.CreateSIToFP(Y, Ty);
733
734 auto *Log2Call =
735 Builder.CreateIntrinsic(Ty, Intrinsic::log2, {X}, nullptr, "elt.log2");
736 auto *Mul = Builder.CreateFMul(Log2Call, Y);
737 auto *Exp2Call =
738 Builder.CreateIntrinsic(Ty, Intrinsic::exp2, {Mul}, nullptr, "elt.exp2");
739 Exp2Call->setTailCall(Orig->isTailCall());
740 Exp2Call->setAttributes(Orig->getAttributes());
741 return Exp2Call;
742}
743
745
746 Value *X = Orig->getOperand(0);
747 Value *Y = Orig->getOperand(1);
748 Type *Ty = X->getType();
749 IRBuilder<> Builder(Orig);
750
751 Constant *One = ConstantFP::get(Ty->getScalarType(), 1.0);
752 Constant *Zero = ConstantFP::get(Ty->getScalarType(), 0.0);
753 Value *Cond = Builder.CreateFCmpOLT(Y, X);
754
755 if (Ty != Ty->getScalarType()) {
756 auto *XVec = dyn_cast<FixedVectorType>(Ty);
758 ElementCount::getFixed(XVec->getNumElements()), One);
760 ElementCount::getFixed(XVec->getNumElements()), Zero);
761 }
762
763 return Builder.CreateSelect(Cond, Zero, One);
764}
765
767 Value *X = Orig->getOperand(0);
768 Type *Ty = X->getType();
769 IRBuilder<> Builder(Orig);
770 Value *PiOver180 = ConstantFP::get(Ty, llvm::numbers::pi / 180.0);
771 return Builder.CreateFMul(X, PiOver180);
772}
773
775 // Lower @llvm.dx.interlocked.add(ptr, val) to `atomicrmw add ptr, val
776 // monotonic`. HLSL Interlocked operations imply no fence/barrier, which maps
777 // to monotonic ordering. The instruction's result is the old value, matching
778 // the intrinsic's return value.
779 Value *Ptr = Orig->getArgOperand(0);
780 Value *Val = Orig->getArgOperand(1);
781 IRBuilder<> Builder(Orig);
782 return Builder.CreateAtomicRMW(AtomicRMWInst::Add, Ptr, Val, MaybeAlign(),
784}
785
786static bool expandBufferLoadIntrinsic(CallInst *Orig, bool IsRaw) {
787 IRBuilder<> Builder(Orig);
788
789 Type *BufferTy = Orig->getType()->getStructElementType(0);
790 Type *ScalarTy = BufferTy->getScalarType();
791 bool IsDouble = ScalarTy->isDoubleTy();
792 assert(IsDouble || ScalarTy->isIntegerTy(64) &&
793 "Only expand double or int64 scalars or vectors");
794 bool IsVector = false;
795 unsigned ExtractNum = 2;
796 if (auto *VT = dyn_cast<FixedVectorType>(BufferTy)) {
797 ExtractNum = 2 * VT->getNumElements();
798 IsVector = true;
799 assert(IsRaw || ExtractNum == 4 && "TypedBufferLoad vector must be size 2");
800 }
801
803 Value *Result = PoisonValue::get(BufferTy);
804 unsigned Base = 0;
805 // If we need to extract more than 4 i32; we need to break it up into
806 // more than one load. LoadNum tells us how many i32s we are loading in
807 // each load
808 while (ExtractNum > 0) {
809 unsigned LoadNum = std::min(ExtractNum, 4u);
810 Type *Ty = VectorType::get(Builder.getInt32Ty(), LoadNum, false);
811
812 Type *LoadType = StructType::get(Ty, Builder.getInt1Ty());
813 Intrinsic::ID LoadIntrinsic = Intrinsic::dx_resource_load_typedbuffer;
814 SmallVector<Value *, 3> Args = {Orig->getOperand(0), Orig->getOperand(1)};
815 if (IsRaw) {
816 LoadIntrinsic = Intrinsic::dx_resource_load_rawbuffer;
817 Value *Tmp = Builder.getInt32(4 * Base * 2);
818 Args.push_back(Builder.CreateAdd(Orig->getOperand(2), Tmp));
819 }
820
821 CallInst *Load = Builder.CreateIntrinsic(LoadType, LoadIntrinsic, Args);
822 Loads.push_back(Load);
823
824 // extract the buffer load's result
825 Value *Extract = Builder.CreateExtractValue(Load, {0});
826
827 SmallVector<Value *> ExtractElements;
828 for (unsigned I = 0; I < LoadNum; ++I)
829 ExtractElements.push_back(
830 Builder.CreateExtractElement(Extract, Builder.getInt32(I)));
831
832 // combine into double(s) or int64(s)
833 for (unsigned I = 0; I < LoadNum; I += 2) {
834 Value *Combined = nullptr;
835 if (IsDouble)
836 // For doubles, use dx_asdouble intrinsic
837 Combined = Builder.CreateIntrinsic(
838 Builder.getDoubleTy(), Intrinsic::dx_asdouble,
839 {ExtractElements[I], ExtractElements[I + 1]});
840 else {
841 // For int64, manually combine two int32s
842 // First, zero-extend both values to i64
843 Value *Lo =
844 Builder.CreateZExt(ExtractElements[I], Builder.getInt64Ty());
845 Value *Hi =
846 Builder.CreateZExt(ExtractElements[I + 1], Builder.getInt64Ty());
847 // Shift the high bits left by 32 bits
848 Value *ShiftedHi = Builder.CreateShl(Hi, Builder.getInt64(32));
849 // OR the high and low bits together
850 Combined = Builder.CreateOr(Lo, ShiftedHi);
851 }
852
853 if (IsVector)
854 Result = Builder.CreateInsertElement(Result, Combined,
855 Builder.getInt32((I / 2) + Base));
856 else
857 Result = Combined;
858 }
859
860 ExtractNum -= LoadNum;
861 Base += LoadNum / 2;
862 }
863
864 Value *CheckBit = nullptr;
865 for (User *U : make_early_inc_range(Orig->users())) {
866 // If it's not a ExtractValueInst, we don't know how to
867 // handle it
868 auto *EVI = dyn_cast<ExtractValueInst>(U);
869 if (!EVI)
870 llvm_unreachable("Unexpected user of typedbufferload");
871
872 ArrayRef<unsigned> Indices = EVI->getIndices();
873 assert(Indices.size() == 1);
874
875 if (Indices[0] == 0) {
876 // Use of the value(s)
877 EVI->replaceAllUsesWith(Result);
878 } else {
879 // Use of the check bit
880 assert(Indices[0] == 1 && "Unexpected type for typedbufferload");
881 // Note: This does not always match the historical behaviour of DXC.
882 // See https://github.com/microsoft/DirectXShaderCompiler/issues/7622
883 if (!CheckBit) {
884 SmallVector<Value *, 2> CheckBits;
885 for (Value *L : Loads)
886 CheckBits.push_back(Builder.CreateExtractValue(L, {1}));
887 CheckBit = Builder.CreateAnd(CheckBits);
888 }
889 EVI->replaceAllUsesWith(CheckBit);
890 }
891 EVI->eraseFromParent();
892 }
893 Orig->eraseFromParent();
894 return true;
895}
896
897static bool expandBufferStoreIntrinsic(CallInst *Orig, bool IsRaw) {
898 IRBuilder<> Builder(Orig);
899
900 unsigned ValIndex = IsRaw ? 3 : 2;
901 Type *BufferTy = Orig->getFunctionType()->getParamType(ValIndex);
902 Type *ScalarTy = BufferTy->getScalarType();
903 bool IsDouble = ScalarTy->isDoubleTy();
904 assert((IsDouble || ScalarTy->isIntegerTy(64)) &&
905 "Only expand double or int64 scalars or vectors");
906
907 // Determine if we're dealing with a vector or scalar
908 bool IsVector = false;
909 unsigned ExtractNum = 2;
910 unsigned VecLen = 0;
911 if (auto *VT = dyn_cast<FixedVectorType>(BufferTy)) {
912 VecLen = VT->getNumElements();
913 assert(IsRaw || VecLen == 2 && "TypedBufferStore vector must be size 2");
914 ExtractNum = VecLen * 2;
915 IsVector = true;
916 }
917
918 // Create the appropriate vector type for the result
919 Type *Int32Ty = Builder.getInt32Ty();
920 Type *ResultTy = VectorType::get(Int32Ty, ExtractNum, false);
921 Value *Val = PoisonValue::get(ResultTy);
922
923 Type *SplitElementTy = Int32Ty;
924 if (IsVector)
925 SplitElementTy = VectorType::get(SplitElementTy, VecLen, false);
926
927 Value *LowBits = nullptr;
928 Value *HighBits = nullptr;
929 // Split the 64-bit values into 32-bit components
930 if (IsDouble) {
931 auto *SplitTy = llvm::StructType::get(SplitElementTy, SplitElementTy);
932 Value *Split = Builder.CreateIntrinsic(SplitTy, Intrinsic::dx_splitdouble,
933 {Orig->getOperand(ValIndex)});
934 LowBits = Builder.CreateExtractValue(Split, 0);
935 HighBits = Builder.CreateExtractValue(Split, 1);
936 } else {
937 // Handle int64 type(s)
938 Value *InputVal = Orig->getOperand(ValIndex);
939 Constant *ShiftAmt = Builder.getInt64(32);
940 if (IsVector)
941 ShiftAmt =
943
944 // Split into low and high 32-bit parts
945 LowBits = Builder.CreateTrunc(InputVal, SplitElementTy);
946 Value *ShiftedVal = Builder.CreateLShr(InputVal, ShiftAmt);
947 HighBits = Builder.CreateTrunc(ShiftedVal, SplitElementTy);
948 }
949
950 if (IsVector) {
952 for (unsigned I = 0; I < VecLen; ++I) {
953 Mask.push_back(I);
954 Mask.push_back(I + VecLen);
955 }
956 Val = Builder.CreateShuffleVector(LowBits, HighBits, Mask);
957 } else {
958 Val = Builder.CreateInsertElement(Val, LowBits, Builder.getInt32(0));
959 Val = Builder.CreateInsertElement(Val, HighBits, Builder.getInt32(1));
960 }
961
962 // If we need to extract more than 4 i32; we need to break it up into
963 // more than one store. StoreNum tells us how many i32s we are storing in
964 // each store
965 unsigned Base = 0;
966 while (ExtractNum > 0) {
967 unsigned StoreNum = std::min(ExtractNum, 4u);
968
969 Intrinsic::ID StoreIntrinsic = Intrinsic::dx_resource_store_typedbuffer;
970 SmallVector<Value *, 4> Args = {Orig->getOperand(0), Orig->getOperand(1)};
971 if (IsRaw) {
972 StoreIntrinsic = Intrinsic::dx_resource_store_rawbuffer;
973 Value *Tmp = Builder.getInt32(4 * Base);
974 Args.push_back(Builder.CreateAdd(Orig->getOperand(2), Tmp));
975 }
976
978 for (unsigned I = 0; I < StoreNum; ++I) {
979 Mask.push_back(Base + I);
980 }
981
982 Value *SubVal = Val;
983 if (VecLen > 2)
984 SubVal = Builder.CreateShuffleVector(Val, Mask);
985
986 Args.push_back(SubVal);
987 // Create the final intrinsic call
988 Builder.CreateIntrinsic(Builder.getVoidTy(), StoreIntrinsic, Args);
989
990 ExtractNum -= StoreNum;
991 Base += StoreNum;
992 }
993 Orig->eraseFromParent();
994 return true;
995}
996
998 if (ClampIntrinsic == Intrinsic::dx_uclamp)
999 return Intrinsic::umax;
1000 if (ClampIntrinsic == Intrinsic::dx_sclamp)
1001 return Intrinsic::smax;
1002 assert(ClampIntrinsic == Intrinsic::dx_nclamp);
1003 return Intrinsic::maxnum;
1004}
1005
1007 if (ClampIntrinsic == Intrinsic::dx_uclamp)
1008 return Intrinsic::umin;
1009 if (ClampIntrinsic == Intrinsic::dx_sclamp)
1010 return Intrinsic::smin;
1011 assert(ClampIntrinsic == Intrinsic::dx_nclamp);
1012 return Intrinsic::minnum;
1013}
1014
1016 Intrinsic::ID ClampIntrinsic) {
1017 Value *X = Orig->getOperand(0);
1018 Value *Min = Orig->getOperand(1);
1019 Value *Max = Orig->getOperand(2);
1020 Type *Ty = X->getType();
1021 IRBuilder<> Builder(Orig);
1022 auto *MaxCall = Builder.CreateIntrinsic(Ty, getMaxForClamp(ClampIntrinsic),
1023 {X, Min}, nullptr, "dx.max");
1024 return Builder.CreateIntrinsic(Ty, getMinForClamp(ClampIntrinsic),
1025 {MaxCall, Max}, nullptr, "dx.min");
1026}
1027
1029 Value *X = Orig->getOperand(0);
1030 Type *Ty = X->getType();
1031 IRBuilder<> Builder(Orig);
1032 Value *DegreesRatio = ConstantFP::get(Ty, 180.0 * llvm::numbers::inv_pi);
1033 return Builder.CreateFMul(X, DegreesRatio);
1034}
1035
1037 Value *X = Orig->getOperand(0);
1038 Type *Ty = X->getType();
1039 Type *ScalarTy = Ty->getScalarType();
1040 Type *RetTy = Orig->getType();
1041 Constant *Zero = Constant::getNullValue(Ty);
1042
1043 IRBuilder<> Builder(Orig);
1044
1045 Value *GT;
1046 Value *LT;
1047 if (ScalarTy->isFloatingPointTy()) {
1048 GT = Builder.CreateFCmpOLT(Zero, X);
1049 LT = Builder.CreateFCmpOLT(X, Zero);
1050 } else {
1051 assert(ScalarTy->isIntegerTy());
1052 GT = Builder.CreateICmpSLT(Zero, X);
1053 LT = Builder.CreateICmpSLT(X, Zero);
1054 }
1055
1056 Value *ZextGT = Builder.CreateZExt(GT, RetTy);
1057 Value *ZextLT = Builder.CreateZExt(LT, RetTy);
1058
1059 return Builder.CreateSub(ZextGT, ZextLT);
1060}
1061
1062// Expand llvm.matrix.multiply by extracting row/column vectors and computing
1063// dot products.
1064// Result[r,c] = dot(row_r(LHS), col_c(RHS))
1065// Element (r,c) is at index c*NumRows + r (column-major).
1067 Value *LHS = Orig->getArgOperand(0);
1068 Value *RHS = Orig->getArgOperand(1);
1069 unsigned LHSRows = cast<ConstantInt>(Orig->getArgOperand(2))->getZExtValue();
1070 unsigned LHSCols = cast<ConstantInt>(Orig->getArgOperand(3))->getZExtValue();
1071 unsigned RHSCols = cast<ConstantInt>(Orig->getArgOperand(4))->getZExtValue();
1072
1073 auto *RetTy = cast<FixedVectorType>(Orig->getType());
1074 Type *EltTy = RetTy->getElementType();
1075 bool IsFP = EltTy->isFloatingPointTy();
1076
1077 IRBuilder<> Builder(Orig);
1078
1079 // Column-major indexing:
1080 // LHS row R, element K: index = K * LHSRows + R
1081 // RHS col C, element K: index = C * LHSCols + K
1082 Value *Result = PoisonValue::get(RetTy);
1083
1084 // Extract all scalar elements from LHS and RHS once, then reuse them.
1085 unsigned LHSSize = LHSRows * LHSCols;
1086 unsigned RHSSize = LHSCols * RHSCols;
1087 SmallVector<Value *, 16> LHSElts(LHSSize);
1088 SmallVector<Value *, 16> RHSElts(RHSSize);
1089 for (unsigned I = 0; I < LHSSize; ++I)
1090 LHSElts[I] = Builder.CreateExtractElement(LHS, I);
1091 for (unsigned I = 0; I < RHSSize; ++I)
1092 RHSElts[I] = Builder.CreateExtractElement(RHS, I);
1093
1094 // Choose the appropriate scalar-arg dot intrinsic for floats.
1095 // K=1 and double types use scalar expansion instead.
1097 bool UseScalarFP = IsFP && (EltTy->isDoubleTy() || LHSCols == 1);
1098 if (IsFP && !UseScalarFP) {
1099 switch (LHSCols) {
1100 case 2:
1101 FloatDotID = Intrinsic::dx_dot2;
1102 break;
1103 case 3:
1104 FloatDotID = Intrinsic::dx_dot3;
1105 break;
1106 case 4:
1107 FloatDotID = Intrinsic::dx_dot4;
1108 break;
1109 default:
1111 "Invalid matrix inner dimension for dot product: must be 2-4");
1112 return nullptr;
1113 }
1114 }
1115
1116 for (unsigned C = 0; C < RHSCols; ++C) {
1117 for (unsigned R = 0; R < LHSRows; ++R) {
1118 // Gather row R from LHS and column C from RHS.
1119 SmallVector<Value *, 4> RowElts, ColElts;
1120 for (unsigned K = 0; K < LHSCols; ++K) {
1121 RowElts.push_back(LHSElts[K * LHSRows + R]);
1122 ColElts.push_back(RHSElts[C * LHSCols + K]);
1123 }
1124
1125 Value *Dot;
1126 if (UseScalarFP) {
1127 // Scalar fmul+fmuladd expansion for double types and K=1.
1128 Dot = Builder.CreateFMul(RowElts[0], ColElts[0]);
1129 for (unsigned K = 1; K < LHSCols; ++K)
1130 Dot = Builder.CreateIntrinsic(EltTy, Intrinsic::fmuladd,
1131 {RowElts[K], ColElts[K], Dot});
1132 } else if (IsFP) {
1133 // Emit scalar-arg DXIL dot directly (dx.dot2/dx.dot3/dx.dot4).
1135 Args.append(RowElts.begin(), RowElts.end());
1136 Args.append(ColElts.begin(), ColElts.end());
1137 Dot = Builder.CreateIntrinsic(EltTy, FloatDotID, Args);
1138 } else {
1139 // Integer: emit multiply + imad chain.
1140 Dot = Builder.CreateMul(RowElts[0], ColElts[0]);
1141 for (unsigned K = 1; K < LHSCols; ++K)
1142 Dot = Builder.CreateIntrinsic(EltTy, Intrinsic::dx_imad,
1143 {RowElts[K], ColElts[K], Dot});
1144 }
1145 unsigned ResIdx = C * LHSRows + R;
1146 Result = Builder.CreateInsertElement(Result, Dot, ResIdx);
1147 }
1148 }
1149 return Result;
1150}
1151
1152// Expand llvm.matrix.transpose as a shufflevector that permutes elements
1153// from column-major source to column-major transposed layout.
1154// Element (r,c) at index c*Rows + r moves to index r*Cols + c.
1156 Value *Mat = Orig->getArgOperand(0);
1157 unsigned Rows = cast<ConstantInt>(Orig->getArgOperand(1))->getZExtValue();
1158 unsigned Cols = cast<ConstantInt>(Orig->getArgOperand(2))->getZExtValue();
1159
1160 unsigned NumElts = Rows * Cols;
1161 SmallVector<int, 16> Mask(NumElts);
1162 for (unsigned I = 0; I < NumElts; ++I)
1163 Mask[I] = (I % Cols) * Rows + (I / Cols);
1164
1165 IRBuilder<> Builder(Orig);
1166 return Builder.CreateShuffleVector(Mat, Mask);
1167}
1168
1169static bool expandIntrinsic(Function &F, CallInst *Orig) {
1170 Value *Result = nullptr;
1171 Intrinsic::ID IntrinsicId = F.getIntrinsicID();
1172 switch (IntrinsicId) {
1173 case Intrinsic::abs:
1174 Result = expandAbs(Orig);
1175 break;
1176 case Intrinsic::assume:
1177 Orig->eraseFromParent();
1178 return true;
1179 case Intrinsic::atan2:
1180 Result = expandAtan2Intrinsic(Orig);
1181 break;
1182 case Intrinsic::fshl:
1183 Result = expandFunnelShiftIntrinsic<true>(Orig);
1184 break;
1185 case Intrinsic::fshr:
1186 Result = expandFunnelShiftIntrinsic<false>(Orig);
1187 break;
1188 case Intrinsic::exp:
1189 Result = expandExpIntrinsic(Orig);
1190 break;
1191 case Intrinsic::is_fpclass:
1192 Result = expandIsFPClass(Orig);
1193 break;
1194 case Intrinsic::log:
1195 Result = expandLogIntrinsic(Orig);
1196 break;
1197 case Intrinsic::log10:
1198 Result = expandLog10Intrinsic(Orig);
1199 break;
1200 case Intrinsic::pow:
1201 case Intrinsic::powi:
1202 Result = expandPowIntrinsic(Orig, IntrinsicId);
1203 break;
1204 case Intrinsic::dx_all:
1205 case Intrinsic::dx_any:
1206 Result = expandAnyOrAllIntrinsic(Orig, IntrinsicId);
1207 break;
1208 case Intrinsic::dx_cross:
1209 Result = expandCrossIntrinsic(Orig);
1210 break;
1211 case Intrinsic::dx_uclamp:
1212 case Intrinsic::dx_sclamp:
1213 case Intrinsic::dx_nclamp:
1214 Result = expandClampIntrinsic(Orig, IntrinsicId);
1215 break;
1216 case Intrinsic::dx_degrees:
1217 Result = expandDegreesIntrinsic(Orig);
1218 break;
1219 case Intrinsic::dx_isinf:
1220 Result = expand16BitIsInf(Orig);
1221 break;
1222 case Intrinsic::dx_isnan:
1223 Result = expand16BitIsNaN(Orig);
1224 break;
1225 case Intrinsic::dx_lerp:
1226 Result = expandLerpIntrinsic(Orig);
1227 break;
1228 case Intrinsic::dx_normalize:
1229 Result = expandNormalizeIntrinsic(Orig);
1230 break;
1231 case Intrinsic::dx_fdot:
1232 Result = expandFloatDotIntrinsic(Orig);
1233 break;
1234 case Intrinsic::dx_sdot:
1235 case Intrinsic::dx_udot:
1236 Result = expandIntegerDotIntrinsic(Orig, IntrinsicId);
1237 break;
1238 case Intrinsic::dx_sign:
1239 Result = expandSignIntrinsic(Orig);
1240 break;
1241 case Intrinsic::dx_step:
1242 Result = expandStepIntrinsic(Orig);
1243 break;
1244 case Intrinsic::dx_radians:
1245 Result = expandRadiansIntrinsic(Orig);
1246 break;
1247 case Intrinsic::dx_interlocked_add:
1248 Result = expandInterlockedAddIntrinsic(Orig);
1249 break;
1250 case Intrinsic::dx_resource_load_rawbuffer:
1251 if (expandBufferLoadIntrinsic(Orig, /*IsRaw*/ true))
1252 return true;
1253 break;
1254 case Intrinsic::dx_resource_store_rawbuffer:
1255 if (expandBufferStoreIntrinsic(Orig, /*IsRaw*/ true))
1256 return true;
1257 break;
1258 case Intrinsic::dx_resource_load_typedbuffer:
1259 if (expandBufferLoadIntrinsic(Orig, /*IsRaw*/ false))
1260 return true;
1261 break;
1262 case Intrinsic::dx_resource_store_typedbuffer:
1263 if (expandBufferStoreIntrinsic(Orig, /*IsRaw*/ false))
1264 return true;
1265 break;
1266 case Intrinsic::usub_sat:
1267 Result = expandUsubSat(Orig);
1268 break;
1269 case Intrinsic::vector_reduce_add:
1270 case Intrinsic::vector_reduce_fadd:
1271 Result = expandVecReduceAdd(Orig, IntrinsicId);
1272 break;
1273 case Intrinsic::matrix_multiply:
1274 Result = expandMatrixMultiply(Orig);
1275 break;
1276 case Intrinsic::matrix_transpose:
1277 Result = expandMatrixTranspose(Orig);
1278 break;
1279 }
1280 if (Result) {
1281 Orig->replaceAllUsesWith(Result);
1282 Orig->eraseFromParent();
1283 return true;
1284 }
1285 return false;
1286}
1287
1289 for (auto &F : make_early_inc_range(M.functions())) {
1290 if (!isIntrinsicExpansion(F))
1291 continue;
1292 bool IntrinsicExpanded = false;
1293 for (User *U : make_early_inc_range(F.users())) {
1294 auto *IntrinsicCall = dyn_cast<CallInst>(U);
1295 if (!IntrinsicCall)
1296 continue;
1297 IntrinsicExpanded = expandIntrinsic(F, IntrinsicCall);
1298 }
1299 if (F.user_empty() && IntrinsicExpanded)
1300 F.eraseFromParent();
1301 }
1302 return true;
1303}
1304
1311
1315
1317
1319 "DXIL Intrinsic Expansion", false, false)
1321 "DXIL Intrinsic Expansion", false, false)
1322
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define X(NUM, ENUM, NAME)
Definition ELF.h:853
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 * expandMatrixTranspose(CallInst *Orig)
static Value * expandInterlockedAddIntrinsic(CallInst *Orig)
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")
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:1534
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
@ Add
*p = old + v
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
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
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:869
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:2868
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:479
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
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:308
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
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:255
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:552
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
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.
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:328
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
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
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106