LLVM 24.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/APInt.h"
16#include "llvm/ADT/STLExtras.h"
18#include "llvm/CodeGen/Passes.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/IRBuilder.h"
21#include "llvm/IR/InstrTypes.h"
22#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/IntrinsicsDirectX.h"
27#include "llvm/IR/Module.h"
28#include "llvm/IR/PassManager.h"
29#include "llvm/IR/Type.h"
30#include "llvm/Pass.h"
34
35#define DEBUG_TYPE "dxil-intrinsic-expansion"
36
37using namespace llvm;
38
40
41public:
42 bool runOnModule(Module &M) override;
44
45 static char ID; // Pass identification.
46};
47
48static bool resourceAccessNeeds64BitExpansion(Module *M, Type *OverloadTy,
49 bool IsRaw) {
50 if (IsRaw && M->getTargetTriple().getDXILVersion() > VersionTuple(1, 2))
51 return false;
52
53 Type *ScalarTy = OverloadTy->getScalarType();
54 return ScalarTy->isDoubleTy() || ScalarTy->isIntegerTy(64);
55}
56
58 Module *M = Orig->getModule();
59 if (M->getTargetTriple().getDXILVersion() >= VersionTuple(1, 9))
60 return nullptr;
61
62 Value *Val = Orig->getOperand(0);
63 Type *ValTy = Val->getType();
64 if (!ValTy->getScalarType()->isHalfTy())
65 return nullptr;
66
67 IRBuilder<> Builder(Orig);
68 Type *IType = Type::getInt16Ty(M->getContext());
69 Constant *PosInf =
70 ValTy->isVectorTy()
73 cast<FixedVectorType>(ValTy)->getNumElements()),
74 ConstantInt::get(IType, 0x7c00))
75 : ConstantInt::get(IType, 0x7c00);
76
77 Constant *NegInf =
78 ValTy->isVectorTy()
81 cast<FixedVectorType>(ValTy)->getNumElements()),
82 ConstantInt::get(IType, 0xfc00))
83 : ConstantInt::get(IType, 0xfc00);
84
85 Value *IVal = Builder.CreateBitCast(Val, PosInf->getType());
86 Value *B1 = Builder.CreateICmpEQ(IVal, PosInf);
87 Value *B2 = Builder.CreateICmpEQ(IVal, NegInf);
88 Value *B3 = Builder.CreateOr(B1, B2);
89 return B3;
90}
91
93 Module *M = Orig->getModule();
94 if (M->getTargetTriple().getDXILVersion() >= VersionTuple(1, 9))
95 return nullptr;
96
97 Value *Val = Orig->getOperand(0);
98 Type *ValTy = Val->getType();
99 if (!ValTy->getScalarType()->isHalfTy())
100 return nullptr;
101
102 IRBuilder<> Builder(Orig);
103 Type *IType = Type::getInt16Ty(M->getContext());
104
105 Constant *ExpBitMask =
106 ValTy->isVectorTy()
109 cast<FixedVectorType>(ValTy)->getNumElements()),
110 ConstantInt::get(IType, 0x7c00))
111 : ConstantInt::get(IType, 0x7c00);
112 Constant *SigBitMask =
113 ValTy->isVectorTy()
116 cast<FixedVectorType>(ValTy)->getNumElements()),
117 ConstantInt::get(IType, 0x3ff))
118 : ConstantInt::get(IType, 0x3ff);
119
120 Constant *Zero =
121 ValTy->isVectorTy()
124 cast<FixedVectorType>(ValTy)->getNumElements()),
125 ConstantInt::get(IType, 0))
126 : ConstantInt::get(IType, 0);
127
128 Value *IVal = Builder.CreateBitCast(Val, ExpBitMask->getType());
129 Value *Exp = Builder.CreateAnd(IVal, ExpBitMask);
130 Value *B1 = Builder.CreateICmpEQ(Exp, ExpBitMask);
131
132 Value *Sig = Builder.CreateAnd(IVal, SigBitMask);
133 Value *B2 = Builder.CreateICmpNE(Sig, Zero);
134 Value *B3 = Builder.CreateAnd(B1, B2);
135 return B3;
136}
137
139 Module *M = Orig->getModule();
140 if (M->getTargetTriple().getDXILVersion() >= VersionTuple(1, 9))
141 return nullptr;
142
143 Value *Val = Orig->getOperand(0);
144 Type *ValTy = Val->getType();
145 if (!ValTy->getScalarType()->isHalfTy())
146 return nullptr;
147
148 IRBuilder<> Builder(Orig);
149 Type *IType = Type::getInt16Ty(M->getContext());
150
151 Constant *ExpBitMask =
152 ValTy->isVectorTy()
155 cast<FixedVectorType>(ValTy)->getNumElements()),
156 ConstantInt::get(IType, 0x7c00))
157 : ConstantInt::get(IType, 0x7c00);
158
159 Value *IVal = Builder.CreateBitCast(Val, ExpBitMask->getType());
160 Value *Exp = Builder.CreateAnd(IVal, ExpBitMask);
161 Value *B1 = Builder.CreateICmpNE(Exp, ExpBitMask);
162 return B1;
163}
164
166 Module *M = Orig->getModule();
167 if (M->getTargetTriple().getDXILVersion() >= VersionTuple(1, 9))
168 return nullptr;
169
170 Value *Val = Orig->getOperand(0);
171 Type *ValTy = Val->getType();
172 if (!ValTy->getScalarType()->isHalfTy())
173 return nullptr;
174
175 IRBuilder<> Builder(Orig);
176 Type *IType = Type::getInt16Ty(M->getContext());
177
178 Constant *ExpBitMask =
179 ValTy->isVectorTy()
182 cast<FixedVectorType>(ValTy)->getNumElements()),
183 ConstantInt::get(IType, 0x7c00))
184 : ConstantInt::get(IType, 0x7c00);
185 Constant *Zero =
186 ValTy->isVectorTy()
189 cast<FixedVectorType>(ValTy)->getNumElements()),
190 ConstantInt::get(IType, 0))
191 : ConstantInt::get(IType, 0);
192
193 Value *IVal = Builder.CreateBitCast(Val, ExpBitMask->getType());
194 Value *Exp = Builder.CreateAnd(IVal, ExpBitMask);
195 Value *NotAllZeroes = Builder.CreateICmpNE(Exp, Zero);
196 Value *NotAllOnes = Builder.CreateICmpNE(Exp, ExpBitMask);
197 Value *B1 = Builder.CreateAnd(NotAllZeroes, NotAllOnes);
198 return B1;
199}
200
202 switch (F.getIntrinsicID()) {
203 case Intrinsic::assume:
204 case Intrinsic::abs:
205 case Intrinsic::atan2:
206 case Intrinsic::fshl:
207 case Intrinsic::fshr:
208 case Intrinsic::exp:
209 case Intrinsic::is_fpclass:
210 case Intrinsic::log:
211 case Intrinsic::log10:
212 case Intrinsic::pow:
213 case Intrinsic::powi:
214 case Intrinsic::dx_all:
215 case Intrinsic::dx_any:
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 case Intrinsic::matrix_transpose:
235 case Intrinsic::umul_with_overflow:
236 case Intrinsic::smul_with_overflow:
237 case Intrinsic::dx_load_input:
238 case Intrinsic::dx_store_output:
239 return true;
240 case Intrinsic::dx_resource_load_rawbuffer:
242 F.getParent(), F.getReturnType()->getStructElementType(0),
243 /*IsRaw*/ true);
244 case Intrinsic::dx_resource_load_typedbuffer:
246 F.getParent(), F.getReturnType()->getStructElementType(0),
247 /*IsRaw*/ false);
248 case Intrinsic::dx_resource_store_rawbuffer:
250 F.getParent(), F.getFunctionType()->getParamType(3), /*IsRaw*/ true);
251 case Intrinsic::dx_resource_store_typedbuffer:
253 F.getParent(), F.getFunctionType()->getParamType(2), /*IsRaw*/ false);
254 }
255 return false;
256}
257
259 Value *A = Orig->getArgOperand(0);
260 Value *B = Orig->getArgOperand(1);
261 Type *Ty = A->getType();
262
263 IRBuilder<> Builder(Orig);
264
265 Value *Cmp = Builder.CreateICmpULT(A, B, "usub.cmp");
266 Value *Sub = Builder.CreateSub(A, B, "usub.sub");
267 Value *Zero = ConstantInt::get(Ty, 0);
268 return Builder.CreateSelect(Cmp, Zero, Sub, "usub.sat");
269}
270
271// Compute the high N bits of the 2N-bit unsigned product of two N-bit values
272// using only N-bit arithmetic, so we don't introduce a wider integer type that
273// may be unsupported in DXIL.
275 Type *Ty, unsigned BW) {
276 assert(BW % 2 == 0 && "high-half split needs symmetric halves");
277 unsigned Half = BW / 2;
278 Value *HalfShift = ConstantInt::get(Ty, Half);
279 Value *LoMask = ConstantInt::get(Ty, APInt::getLowBitsSet(BW, Half));
280
281 Value *U0 = Builder.CreateAnd(A, LoMask);
282 Value *U1 = Builder.CreateLShr(A, HalfShift);
283 Value *V0 = Builder.CreateAnd(B, LoMask);
284 Value *V1 = Builder.CreateLShr(B, HalfShift);
285
286 Value *W0 = Builder.CreateMul(U0, V0);
287 Value *T = Builder.CreateAdd(Builder.CreateMul(U1, V0),
288 Builder.CreateLShr(W0, HalfShift));
289 Value *W1 = Builder.CreateAnd(T, LoMask);
290 Value *W2 = Builder.CreateLShr(T, HalfShift);
291 W1 = Builder.CreateAdd(Builder.CreateMul(U0, V1), W1);
292 return Builder.CreateAdd(Builder.CreateAdd(Builder.CreateMul(U1, V1), W2),
293 Builder.CreateLShr(W1, HalfShift));
294}
295
296// Expand a {u,s}mul.with.overflow intrinsic. The low half of the result is a
297// plain multiply; overflow is derived from the high half of the double-width
298// product.
300 IRBuilder<> Builder(Orig);
301 Value *A = Orig->getArgOperand(0);
302 Value *B = Orig->getArgOperand(1);
303 Type *Ty = A->getType();
304 unsigned BW = Ty->getScalarSizeInBits();
305
306 Value *Lo;
307 Value *Ov;
308
309 // A plain double-width multiply is simplest, but we avoid it once it would
310 // introduce a 64-bit (or wider) integer, which DXIL does not always support.
311 // For i32 we use the native DXIL IMul/UMul ops, which return the full product
312 // as two i32s; wider types fall back to a same-width high-half computation.
313 if (2 * BW <= 32) {
314 Lo = Builder.CreateMul(A, B);
315 Type *WideTy = Ty->getWithNewBitWidth(2 * BW);
316 Value *WideA =
317 Signed ? Builder.CreateSExt(A, WideTy) : Builder.CreateZExt(A, WideTy);
318 Value *WideB =
319 Signed ? Builder.CreateSExt(B, WideTy) : Builder.CreateZExt(B, WideTy);
320 Value *Wide = Builder.CreateMul(WideA, WideB);
321 if (Signed) {
322 // Overflow when the full product doesn't fit back into BW signed bits.
323 Ov = Builder.CreateICmpNE(Wide, Builder.CreateSExt(Lo, WideTy));
324 } else {
325 Value *Hi = Builder.CreateLShr(Wide, ConstantInt::get(WideTy, BW));
326 Ov = Builder.CreateICmpNE(Hi, ConstantInt::get(WideTy, 0));
327 }
328 } else if (BW == 32) {
329 // IMul/UMul return {high, low}; index 0 is the high 32 bits.
330 Type *ResTy = StructType::get(Ty, Ty);
331 Intrinsic::ID IntrinsicID =
332 Signed ? Intrinsic::dx_imul : Intrinsic::dx_umul;
333 Value *Mul = Builder.CreateIntrinsic(ResTy, IntrinsicID, {A, B});
334 Value *Hi = Builder.CreateExtractValue(Mul, 0);
335 Lo = Builder.CreateExtractValue(Mul, 1);
336 if (Signed)
337 Ov = Builder.CreateICmpNE(
338 Hi, Builder.CreateAShr(Lo, ConstantInt::get(Ty, BW - 1)));
339 else
340 Ov = Builder.CreateICmpNE(Hi, ConstantInt::get(Ty, 0));
341 } else {
342 Lo = Builder.CreateMul(A, B);
343 Value *Hi = createMulHighUnsigned(Builder, A, B, Ty, BW);
344 if (Signed) {
345 // Turn the unsigned high half into the signed one, then overflow means it
346 // isn't the sign extension of the low half.
347 Value *SignShift = ConstantInt::get(Ty, BW - 1);
348 Value *ASign = Builder.CreateAShr(A, SignShift);
349 Value *BSign = Builder.CreateAShr(B, SignShift);
350 Hi = Builder.CreateSub(Hi, Builder.CreateAnd(ASign, B));
351 Hi = Builder.CreateSub(Hi, Builder.CreateAnd(BSign, A));
352 Ov = Builder.CreateICmpNE(Hi, Builder.CreateAShr(Lo, SignShift));
353 } else {
354 Ov = Builder.CreateICmpNE(Hi, ConstantInt::get(Ty, 0));
355 }
356 }
357
358 Value *Agg = PoisonValue::get(Orig->getType());
359 Agg = Builder.CreateInsertValue(Agg, Lo, 0);
360 return Builder.CreateInsertValue(Agg, Ov, 1);
361}
362
363static Value *expandVecReduceAdd(CallInst *Orig, Intrinsic::ID IntrinsicId) {
364 assert(IntrinsicId == Intrinsic::vector_reduce_add ||
365 IntrinsicId == Intrinsic::vector_reduce_fadd);
366
367 IRBuilder<> Builder(Orig);
368 bool IsFAdd = (IntrinsicId == Intrinsic::vector_reduce_fadd);
369
370 Value *X = Orig->getOperand(IsFAdd ? 1 : 0);
371 Type *Ty = X->getType();
372 auto *XVec = dyn_cast<FixedVectorType>(Ty);
373 unsigned XVecSize = XVec->getNumElements();
374 Value *Sum = Builder.CreateExtractElement(X, static_cast<uint64_t>(0));
375
376 // Handle the initial start value for floating-point addition.
377 if (IsFAdd) {
378 Constant *StartValue = dyn_cast<Constant>(Orig->getOperand(0));
379 if (StartValue && !StartValue->isNullValue())
380 Sum = Builder.CreateFAdd(Sum, StartValue);
381 }
382
383 // Accumulate the remaining vector elements.
384 for (unsigned I = 1; I < XVecSize; I++) {
385 Value *Elt = Builder.CreateExtractElement(X, I);
386 if (IsFAdd)
387 Sum = Builder.CreateFAdd(Sum, Elt);
388 else
389 Sum = Builder.CreateAdd(Sum, Elt);
390 }
391
392 return Sum;
393}
394
395static Value *expandAbs(CallInst *Orig) {
396 Value *X = Orig->getOperand(0);
397 IRBuilder<> Builder(Orig);
398 Type *Ty = X->getType();
399 Type *EltTy = Ty->getScalarType();
400 Constant *Zero = Ty->isVectorTy()
403 cast<FixedVectorType>(Ty)->getNumElements()),
404 ConstantInt::get(EltTy, 0))
405 : ConstantInt::get(EltTy, 0);
406 auto *V = Builder.CreateSub(Zero, X);
407 return Builder.CreateIntrinsic(Ty, Intrinsic::smax, {X, V}, nullptr,
408 "dx.max");
409}
410
411// Create appropriate DXIL float dot intrinsic for the given A and B operands
412// The appropriate opcode will be determined by the size of the operands
413// The dot product is placed in the position indicated by Orig
415 Type *ATy = A->getType();
416 [[maybe_unused]] Type *BTy = B->getType();
417 assert(ATy->isVectorTy() && BTy->isVectorTy());
418
419 IRBuilder<> Builder(Orig);
420
421 auto *AVec = dyn_cast<FixedVectorType>(ATy);
422
424
425 Intrinsic::ID DotIntrinsic = Intrinsic::dx_dot4;
426 int NumElts = AVec->getNumElements();
427 switch (NumElts) {
428 case 2:
429 DotIntrinsic = Intrinsic::dx_dot2;
430 break;
431 case 3:
432 DotIntrinsic = Intrinsic::dx_dot3;
433 break;
434 case 4:
435 DotIntrinsic = Intrinsic::dx_dot4;
436 break;
437 default:
439 "Invalid dot product input vector: length is outside 2-4");
440 return nullptr;
441 }
442
444 for (int I = 0; I < NumElts; ++I)
445 Args.push_back(Builder.CreateExtractElement(A, Builder.getInt32(I)));
446 for (int I = 0; I < NumElts; ++I)
447 Args.push_back(Builder.CreateExtractElement(B, Builder.getInt32(I)));
448 return Builder.CreateIntrinsic(ATy->getScalarType(), DotIntrinsic, Args,
449 nullptr, "dot");
450}
451
452// Create the appropriate DXIL float dot intrinsic for the operands of Orig
453// The appropriate opcode will be determined by the size of the operands
454// The dot product is placed in the position indicated by Orig
456 return expandFloatDotIntrinsic(Orig, Orig->getOperand(0),
457 Orig->getOperand(1));
458}
459
460// Expand integer dot product to multiply and add ops
462 Intrinsic::ID DotIntrinsic) {
463 assert(DotIntrinsic == Intrinsic::dx_sdot ||
464 DotIntrinsic == Intrinsic::dx_udot);
465 Value *A = Orig->getOperand(0);
466 Value *B = Orig->getOperand(1);
467 Type *ATy = A->getType();
468 [[maybe_unused]] Type *BTy = B->getType();
469 assert(ATy->isVectorTy() && BTy->isVectorTy());
470
471 IRBuilder<> Builder(Orig);
472
473 auto *AVec = dyn_cast<FixedVectorType>(ATy);
474
476
477 Value *Result;
478 Intrinsic::ID MadIntrinsic = DotIntrinsic == Intrinsic::dx_sdot
479 ? Intrinsic::dx_imad
480 : Intrinsic::dx_umad;
481 Value *Elt0 = Builder.CreateExtractElement(A, (uint64_t)0);
482 Value *Elt1 = Builder.CreateExtractElement(B, (uint64_t)0);
483 Result = Builder.CreateMul(Elt0, Elt1);
484 for (unsigned I = 1; I < AVec->getNumElements(); I++) {
485 Elt0 = Builder.CreateExtractElement(A, I);
486 Elt1 = Builder.CreateExtractElement(B, I);
487 Result = Builder.CreateIntrinsic(Result->getType(), MadIntrinsic,
488 ArrayRef<Value *>{Elt0, Elt1, Result},
489 nullptr, "dx.mad");
490 }
491 return Result;
492}
493
495 Value *X = Orig->getOperand(0);
496 IRBuilder<> Builder(Orig);
497 Type *Ty = X->getType();
498 Type *EltTy = Ty->getScalarType();
499 Constant *Log2eConst =
500 Ty->isVectorTy() ? ConstantVector::getSplat(
502 cast<FixedVectorType>(Ty)->getNumElements()),
503 ConstantFP::get(EltTy, numbers::log2ef))
504 : ConstantFP::get(EltTy, numbers::log2ef);
505 Value *NewX = Builder.CreateFMul(Log2eConst, X);
506 CallInst *Exp2Call = Builder.CreateIntrinsicWithoutFolding(
507 Ty, Intrinsic::exp2, {NewX}, nullptr, "dx.exp2");
508 Exp2Call->setTailCall(Orig->isTailCall());
509 Exp2Call->setAttributes(Orig->getAttributes());
510 return Exp2Call;
511}
512
514 Value *T = Orig->getArgOperand(1);
515 auto *TCI = dyn_cast<ConstantInt>(T);
516
517 // These FPClassTest cases have DXIL opcodes, so they will be handled in
518 // DXIL Op Lowering instead for all non f16 cases.
519 switch (TCI->getZExtValue()) {
521 return expand16BitIsInf(Orig);
523 return expand16BitIsNaN(Orig);
525 return expand16BitIsNormal(Orig);
527 return expand16BitIsFinite(Orig);
528 }
529
530 IRBuilder<> Builder(Orig);
531
532 Value *F = Orig->getArgOperand(0);
533 Type *FTy = F->getType();
534 unsigned FNumElem = 0; // 0 => F is not a vector
535
536 unsigned BitWidth; // Bit width of F or the ElemTy of F
537 Type *BitCastTy; // An IntNTy of the same bitwidth as F or ElemTy of F
538
539 if (auto *FVecTy = dyn_cast<FixedVectorType>(FTy)) {
540 Type *ElemTy = FVecTy->getElementType();
541 FNumElem = FVecTy->getNumElements();
542 BitWidth = ElemTy->getPrimitiveSizeInBits();
543 BitCastTy = FixedVectorType::get(Builder.getIntNTy(BitWidth), FNumElem);
544 } else {
546 BitCastTy = Builder.getIntNTy(BitWidth);
547 }
548
549 Value *FBitCast = Builder.CreateBitCast(F, BitCastTy);
550 switch (TCI->getZExtValue()) {
552 Value *NegZero =
553 ConstantInt::get(Builder.getIntNTy(BitWidth), 1 << (BitWidth - 1),
554 /*IsSigned=*/true);
555 Value *RetVal;
556 if (FNumElem) {
557 Value *NegZeroSplat = Builder.CreateVectorSplat(FNumElem, NegZero);
558 RetVal =
559 Builder.CreateICmpEQ(FBitCast, NegZeroSplat, "is.fpclass.negzero");
560 } else
561 RetVal = Builder.CreateICmpEQ(FBitCast, NegZero, "is.fpclass.negzero");
562 return RetVal;
563 }
564 default:
565 reportFatalUsageError("Unsupported FPClassTest");
566 }
567}
568
570 Intrinsic::ID IntrinsicId) {
571 Value *X = Orig->getOperand(0);
572 IRBuilder<> Builder(Orig);
573 Type *Ty = X->getType();
574 Type *EltTy = Ty->getScalarType();
575
576 auto ApplyOp = [&Builder](Intrinsic::ID IntrinsicId, Value *Result,
577 Value *Elt) {
578 if (IntrinsicId == Intrinsic::dx_any)
579 return Builder.CreateOr(Result, Elt);
580 assert(IntrinsicId == Intrinsic::dx_all);
581 return Builder.CreateAnd(Result, Elt);
582 };
583
584 Value *Result = nullptr;
585 if (!Ty->isVectorTy()) {
586 Result = EltTy->isFloatingPointTy()
587 ? Builder.CreateFCmpUNE(X, ConstantFP::get(EltTy, 0))
588 : Builder.CreateICmpNE(X, ConstantInt::get(EltTy, 0));
589 } else {
590 auto *XVec = dyn_cast<FixedVectorType>(Ty);
591 Value *Cond =
592 EltTy->isFloatingPointTy()
593 ? Builder.CreateFCmpUNE(
595 ElementCount::getFixed(XVec->getNumElements()),
596 ConstantFP::get(EltTy, 0)))
597 : Builder.CreateICmpNE(
599 ElementCount::getFixed(XVec->getNumElements()),
600 ConstantInt::get(EltTy, 0)));
601 Result = Builder.CreateExtractElement(Cond, (uint64_t)0);
602 for (unsigned I = 1; I < XVec->getNumElements(); I++) {
603 Value *Elt = Builder.CreateExtractElement(Cond, I);
604 Result = ApplyOp(IntrinsicId, Result, Elt);
605 }
606 }
607 return Result;
608}
609
611 Value *X = Orig->getOperand(0);
612 Value *Y = Orig->getOperand(1);
613 Value *S = Orig->getOperand(2);
614 IRBuilder<> Builder(Orig);
615 auto *V = Builder.CreateFSub(Y, X);
616 V = Builder.CreateFMul(S, V);
617 return Builder.CreateFAdd(X, V, "dx.lerp");
618}
619
621 float LogConstVal = numbers::ln2f) {
622 Value *X = Orig->getOperand(0);
623 IRBuilder<> Builder(Orig);
624 Type *Ty = X->getType();
625 Type *EltTy = Ty->getScalarType();
626 Constant *Ln2Const =
627 Ty->isVectorTy() ? ConstantVector::getSplat(
629 cast<FixedVectorType>(Ty)->getNumElements()),
630 ConstantFP::get(EltTy, LogConstVal))
631 : ConstantFP::get(EltTy, LogConstVal);
632 CallInst *Log2Call = Builder.CreateIntrinsicWithoutFolding(
633 Ty, Intrinsic::log2, {X}, nullptr, "elt.log2");
634 Log2Call->setTailCall(Orig->isTailCall());
635 Log2Call->setAttributes(Orig->getAttributes());
636 return Builder.CreateFMul(Ln2Const, Log2Call);
637}
641
642// Use dot product of vector operand with itself to calculate the length.
643// Divide the vector by that length to normalize it.
645 Value *X = Orig->getOperand(0);
646 Type *Ty = Orig->getType();
647 Type *EltTy = Ty->getScalarType();
648 IRBuilder<> Builder(Orig);
649
650 auto *XVec = dyn_cast<FixedVectorType>(Ty);
651 if (!XVec) {
652 if (auto *constantFP = dyn_cast<ConstantFP>(X)) {
653 const APFloat &fpVal = constantFP->getValueAPF();
654 if (fpVal.isZero())
655 reportFatalUsageError("Invalid input scalar: length is zero");
656 }
657 return Builder.CreateFDiv(X, X);
658 }
659
660 Value *DotProduct = expandFloatDotIntrinsic(Orig, X, X);
661
662 // verify that the length is non-zero
663 // (if the dot product is non-zero, then the length is non-zero)
664 if (auto *constantFP = dyn_cast<ConstantFP>(DotProduct)) {
665 const APFloat &fpVal = constantFP->getValueAPF();
666 if (fpVal.isZero())
667 reportFatalUsageError("Invalid input vector: length is zero");
668 }
669
670 Value *Multiplicand = Builder.CreateIntrinsic(EltTy, Intrinsic::dx_rsqrt,
671 ArrayRef<Value *>{DotProduct},
672 nullptr, "dx.rsqrt");
673
674 Value *MultiplicandVec =
675 Builder.CreateVectorSplat(XVec->getNumElements(), Multiplicand);
676 return Builder.CreateFMul(X, MultiplicandVec);
677}
678
680 Value *Y = Orig->getOperand(0);
681 Value *X = Orig->getOperand(1);
682 Type *Ty = X->getType();
683 IRBuilder<> Builder(Orig);
684 Builder.setFastMathFlags(Orig->getFastMathFlags());
685
686 Value *Tan = Builder.CreateFDiv(Y, X);
687
688 CallInst *Atan = Builder.CreateIntrinsicWithoutFolding(
689 Ty, Intrinsic::atan, {Tan}, nullptr, "Elt.Atan");
690 Atan->setTailCall(Orig->isTailCall());
691 Atan->setAttributes(Orig->getAttributes());
692
693 // Modify atan result based on https://en.wikipedia.org/wiki/Atan2.
694 Constant *Pi = ConstantFP::get(Ty, llvm::numbers::pi);
695 Constant *HalfPi = ConstantFP::get(Ty, llvm::numbers::pi / 2);
696 Constant *NegHalfPi = ConstantFP::get(Ty, -llvm::numbers::pi / 2);
697 Constant *Zero = ConstantFP::get(Ty, 0);
698 Value *AtanAddPi = Builder.CreateFAdd(Atan, Pi);
699 Value *AtanSubPi = Builder.CreateFSub(Atan, Pi);
700
701 // x > 0 -> atan.
702 Value *Result = Atan;
703 Value *XLt0 = Builder.CreateFCmpOLT(X, Zero);
704 Value *XEq0 = Builder.CreateFCmpOEQ(X, Zero);
705 Value *YGe0 = Builder.CreateFCmpOGE(Y, Zero);
706 Value *YLt0 = Builder.CreateFCmpOLT(Y, Zero);
707
708 // x < 0, y >= 0 -> atan + pi.
709 Value *XLt0AndYGe0 = Builder.CreateAnd(XLt0, YGe0);
710 Result = Builder.CreateSelect(XLt0AndYGe0, AtanAddPi, Result);
711
712 // x < 0, y < 0 -> atan - pi.
713 Value *XLt0AndYLt0 = Builder.CreateAnd(XLt0, YLt0);
714 Result = Builder.CreateSelect(XLt0AndYLt0, AtanSubPi, Result);
715
716 // x == 0, y < 0 -> -pi/2
717 Value *XEq0AndYLt0 = Builder.CreateAnd(XEq0, YLt0);
718 Result = Builder.CreateSelect(XEq0AndYLt0, NegHalfPi, Result);
719
720 // x == 0, y > 0 -> pi/2
721 Value *XEq0AndYGe0 = Builder.CreateAnd(XEq0, YGe0);
722 Result = Builder.CreateSelect(XEq0AndYGe0, HalfPi, Result);
723
724 return Result;
725}
726
727template <bool LeftFunnel>
729 Type *Ty = Orig->getType();
730 Value *A = Orig->getOperand(0);
731 Value *B = Orig->getOperand(1);
732 Value *Shift = Orig->getOperand(2);
733
734 IRBuilder<> Builder(Orig);
735
736 unsigned BitWidth = Ty->getScalarSizeInBits();
738 "Can't use Mask to compute modulo and inverse");
739
740 // Note: if (Shift % BitWidth) == 0 then (BitWidth - Shift) == BitWidth,
741 // shifting by the bitwidth for shl/lshr returns a poisoned result. As such,
742 // we implement the same formula as LegalizerHelper::lowerFunnelShiftAsShifts.
743 //
744 // The funnel shift is expanded like so:
745 // fshl
746 // -> msb_extract((concat(A, B) << (Shift % BitWidth)), BitWidth)
747 // -> A << (Shift % BitWidth) | B >> 1 >> (BitWidth - 1 - (Shift % BitWidth))
748 // fshr
749 // -> lsb_extract((concat(A, B) >> (Shift % BitWidth), BitWidth))
750 // -> A << 1 << (BitWidth - 1 - (Shift % BitWidth)) | B >> (Shift % BitWidth)
751
752 // (BitWidth - 1) -> Mask
753 Constant *Mask = ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1);
754
755 // Shift % BitWidth
756 // -> Shift & (BitWidth - 1)
757 // -> Shift & Mask
758 Value *MaskedShift = Builder.CreateAnd(Shift, Mask);
759
760 // (BitWidth - 1) - (Shift % BitWidth)
761 // -> ~Shift & (BitWidth - 1)
762 // -> ~Shift & Mask
763 Value *NotShift = Builder.CreateNot(Shift);
764 Value *InverseShift = Builder.CreateAnd(NotShift, Mask);
765
766 Constant *One = ConstantInt::get(Ty, 1);
767 Value *ShiftedA;
768 Value *ShiftedB;
769
770 if (LeftFunnel) {
771 ShiftedA = Builder.CreateShl(A, MaskedShift);
772 Value *ShiftB1 = Builder.CreateLShr(B, One);
773 ShiftedB = Builder.CreateLShr(ShiftB1, InverseShift);
774 } else {
775 Value *ShiftA1 = Builder.CreateShl(A, One);
776 ShiftedA = Builder.CreateShl(ShiftA1, InverseShift);
777 ShiftedB = Builder.CreateLShr(B, MaskedShift);
778 }
779
780 Value *Result = Builder.CreateOr(ShiftedA, ShiftedB);
781 return Result;
782}
783
784static Value *expandPowIntrinsic(CallInst *Orig, Intrinsic::ID IntrinsicId) {
785
786 Value *X = Orig->getOperand(0);
787 Value *Y = Orig->getOperand(1);
788 Type *Ty = X->getType();
789 IRBuilder<> Builder(Orig);
790
791 if (IntrinsicId == Intrinsic::powi)
792 Y = Builder.CreateSIToFP(Y, Ty);
793
794 Value *Log2Call =
795 Builder.CreateIntrinsic(Ty, Intrinsic::log2, {X}, nullptr, "elt.log2");
796 auto *Mul = Builder.CreateFMul(Log2Call, Y);
797 CallInst *Exp2Call = Builder.CreateIntrinsicWithoutFolding(
798 Ty, Intrinsic::exp2, {Mul}, nullptr, "elt.exp2");
799 Exp2Call->setTailCall(Orig->isTailCall());
800 Exp2Call->setAttributes(Orig->getAttributes());
801 return Exp2Call;
802}
803
805
806 Value *X = Orig->getOperand(0);
807 Value *Y = Orig->getOperand(1);
808 Type *Ty = X->getType();
809 IRBuilder<> Builder(Orig);
810
811 Constant *One = ConstantFP::get(Ty->getScalarType(), 1.0);
812 Constant *Zero = ConstantFP::get(Ty->getScalarType(), 0.0);
813 Value *Cond = Builder.CreateFCmpOLT(Y, X);
814
815 if (Ty != Ty->getScalarType()) {
816 auto *XVec = dyn_cast<FixedVectorType>(Ty);
818 ElementCount::getFixed(XVec->getNumElements()), One);
820 ElementCount::getFixed(XVec->getNumElements()), Zero);
821 }
822
823 return Builder.CreateSelect(Cond, Zero, One);
824}
825
827 Value *X = Orig->getOperand(0);
828 Type *Ty = X->getType();
829 IRBuilder<> Builder(Orig);
830 Value *PiOver180 = ConstantFP::get(Ty, llvm::numbers::pi / 180.0);
831 return Builder.CreateFMul(X, PiOver180);
832}
833
834static bool expandBufferLoadIntrinsic(CallInst *Orig, bool IsRaw) {
835 IRBuilder<> Builder(Orig);
836
837 Type *BufferTy = Orig->getType()->getStructElementType(0);
838 Type *ScalarTy = BufferTy->getScalarType();
839 bool IsDouble = ScalarTy->isDoubleTy();
840 assert(IsDouble || ScalarTy->isIntegerTy(64) &&
841 "Only expand double or int64 scalars or vectors");
842 bool IsVector = false;
843 unsigned ExtractNum = 2;
844 if (auto *VT = dyn_cast<FixedVectorType>(BufferTy)) {
845 ExtractNum = 2 * VT->getNumElements();
846 IsVector = true;
847 assert(IsRaw || ExtractNum == 4 && "TypedBufferLoad vector must be size 2");
848 }
849
851 Value *Result = PoisonValue::get(BufferTy);
852 unsigned Base = 0;
853 // If we need to extract more than 4 i32; we need to break it up into
854 // more than one load. LoadNum tells us how many i32s we are loading in
855 // each load
856 while (ExtractNum > 0) {
857 unsigned LoadNum = std::min(ExtractNum, 4u);
858 Type *Ty = VectorType::get(Builder.getInt32Ty(), LoadNum, false);
859
860 Type *LoadType = StructType::get(Ty, Builder.getInt1Ty());
861 Intrinsic::ID LoadIntrinsic = Intrinsic::dx_resource_load_typedbuffer;
862 SmallVector<Value *, 3> Args = {Orig->getOperand(0), Orig->getOperand(1)};
863 if (IsRaw) {
864 LoadIntrinsic = Intrinsic::dx_resource_load_rawbuffer;
865 Value *Tmp = Builder.getInt32(4 * Base * 2);
866 Args.push_back(Builder.CreateAdd(Orig->getOperand(2), Tmp));
867 }
868
869 Value *Load = Builder.CreateIntrinsic(LoadType, LoadIntrinsic, Args);
870 Loads.push_back(Load);
871
872 // extract the buffer load's result
873 Value *Extract = Builder.CreateExtractValue(Load, {0});
874
875 SmallVector<Value *> ExtractElements;
876 for (unsigned I = 0; I < LoadNum; ++I)
877 ExtractElements.push_back(
878 Builder.CreateExtractElement(Extract, Builder.getInt32(I)));
879
880 // combine into double(s) or int64(s)
881 for (unsigned I = 0; I < LoadNum; I += 2) {
882 Value *Combined = nullptr;
883 if (IsDouble)
884 // For doubles, use dx_asdouble intrinsic
885 Combined = Builder.CreateIntrinsic(
886 Builder.getDoubleTy(), Intrinsic::dx_asdouble,
887 {ExtractElements[I], ExtractElements[I + 1]});
888 else {
889 // For int64, manually combine two int32s
890 // First, zero-extend both values to i64
891 Value *Lo =
892 Builder.CreateZExt(ExtractElements[I], Builder.getInt64Ty());
893 Value *Hi =
894 Builder.CreateZExt(ExtractElements[I + 1], Builder.getInt64Ty());
895 // Shift the high bits left by 32 bits
896 Value *ShiftedHi = Builder.CreateShl(Hi, Builder.getInt64(32));
897 // OR the high and low bits together
898 Combined = Builder.CreateOr(Lo, ShiftedHi);
899 }
900
901 if (IsVector)
902 Result = Builder.CreateInsertElement(Result, Combined,
903 Builder.getInt32((I / 2) + Base));
904 else
905 Result = Combined;
906 }
907
908 ExtractNum -= LoadNum;
909 Base += LoadNum / 2;
910 }
911
912 Value *CheckBit = nullptr;
913 for (User *U : make_early_inc_range(Orig->users())) {
914 // If it's not a ExtractValueInst, we don't know how to
915 // handle it
916 auto *EVI = dyn_cast<ExtractValueInst>(U);
917 if (!EVI)
918 llvm_unreachable("Unexpected user of typedbufferload");
919
920 ArrayRef<unsigned> Indices = EVI->getIndices();
921 assert(Indices.size() == 1);
922
923 if (Indices[0] == 0) {
924 // Use of the value(s)
925 EVI->replaceAllUsesWith(Result);
926 } else {
927 // Use of the check bit
928 assert(Indices[0] == 1 && "Unexpected type for typedbufferload");
929 // Note: This does not always match the historical behaviour of DXC.
930 // See https://github.com/microsoft/DirectXShaderCompiler/issues/7622
931 if (!CheckBit) {
932 SmallVector<Value *, 2> CheckBits;
933 for (Value *L : Loads)
934 CheckBits.push_back(Builder.CreateExtractValue(L, {1}));
935 CheckBit = Builder.CreateAnd(CheckBits);
936 }
937 EVI->replaceAllUsesWith(CheckBit);
938 }
939 EVI->eraseFromParent();
940 }
941 Orig->eraseFromParent();
942 return true;
943}
944
945static bool expandBufferStoreIntrinsic(CallInst *Orig, bool IsRaw) {
946 IRBuilder<> Builder(Orig);
947
948 unsigned ValIndex = IsRaw ? 3 : 2;
949 Type *BufferTy = Orig->getFunctionType()->getParamType(ValIndex);
950 Type *ScalarTy = BufferTy->getScalarType();
951 bool IsDouble = ScalarTy->isDoubleTy();
952 assert((IsDouble || ScalarTy->isIntegerTy(64)) &&
953 "Only expand double or int64 scalars or vectors");
954
955 // Determine if we're dealing with a vector or scalar
956 bool IsVector = false;
957 unsigned ExtractNum = 2;
958 unsigned VecLen = 0;
959 if (auto *VT = dyn_cast<FixedVectorType>(BufferTy)) {
960 VecLen = VT->getNumElements();
961 assert(IsRaw || VecLen == 2 && "TypedBufferStore vector must be size 2");
962 ExtractNum = VecLen * 2;
963 IsVector = true;
964 }
965
966 // Create the appropriate vector type for the result
967 Type *Int32Ty = Builder.getInt32Ty();
968 Type *ResultTy = VectorType::get(Int32Ty, ExtractNum, false);
969 Value *Val = PoisonValue::get(ResultTy);
970
971 Type *SplitElementTy = Int32Ty;
972 if (IsVector)
973 SplitElementTy = VectorType::get(SplitElementTy, VecLen, false);
974
975 Value *LowBits = nullptr;
976 Value *HighBits = nullptr;
977 // Split the 64-bit values into 32-bit components
978 if (IsDouble) {
979 auto *SplitTy = llvm::StructType::get(SplitElementTy, SplitElementTy);
980 Value *Split = Builder.CreateIntrinsic(SplitTy, Intrinsic::dx_splitdouble,
981 {Orig->getOperand(ValIndex)});
982 LowBits = Builder.CreateExtractValue(Split, 0);
983 HighBits = Builder.CreateExtractValue(Split, 1);
984 } else {
985 // Handle int64 type(s)
986 Value *InputVal = Orig->getOperand(ValIndex);
987 Constant *ShiftAmt = Builder.getInt64(32);
988 if (IsVector)
989 ShiftAmt =
991
992 // Split into low and high 32-bit parts
993 LowBits = Builder.CreateTrunc(InputVal, SplitElementTy);
994 Value *ShiftedVal = Builder.CreateLShr(InputVal, ShiftAmt);
995 HighBits = Builder.CreateTrunc(ShiftedVal, SplitElementTy);
996 }
997
998 if (IsVector) {
1000 for (unsigned I = 0; I < VecLen; ++I) {
1001 Mask.push_back(I);
1002 Mask.push_back(I + VecLen);
1003 }
1004 Val = Builder.CreateShuffleVector(LowBits, HighBits, Mask);
1005 } else {
1006 Val = Builder.CreateInsertElement(Val, LowBits, Builder.getInt32(0));
1007 Val = Builder.CreateInsertElement(Val, HighBits, Builder.getInt32(1));
1008 }
1009
1010 // If we need to extract more than 4 i32; we need to break it up into
1011 // more than one store. StoreNum tells us how many i32s we are storing in
1012 // each store
1013 unsigned Base = 0;
1014 while (ExtractNum > 0) {
1015 unsigned StoreNum = std::min(ExtractNum, 4u);
1016
1017 Intrinsic::ID StoreIntrinsic = Intrinsic::dx_resource_store_typedbuffer;
1018 SmallVector<Value *, 4> Args = {Orig->getOperand(0), Orig->getOperand(1)};
1019 if (IsRaw) {
1020 StoreIntrinsic = Intrinsic::dx_resource_store_rawbuffer;
1021 Value *Tmp = Builder.getInt32(4 * Base);
1022 Args.push_back(Builder.CreateAdd(Orig->getOperand(2), Tmp));
1023 }
1024
1026 for (unsigned I = 0; I < StoreNum; ++I) {
1027 Mask.push_back(Base + I);
1028 }
1029
1030 Value *SubVal = Val;
1031 if (VecLen > 2)
1032 SubVal = Builder.CreateShuffleVector(Val, Mask);
1033
1034 Args.push_back(SubVal);
1035 // Create the final intrinsic call
1036 Builder.CreateIntrinsic(Builder.getVoidTy(), StoreIntrinsic, Args);
1037
1038 ExtractNum -= StoreNum;
1039 Base += StoreNum;
1040 }
1041 Orig->eraseFromParent();
1042 return true;
1043}
1044
1046 if (ClampIntrinsic == Intrinsic::dx_uclamp)
1047 return Intrinsic::umax;
1048 if (ClampIntrinsic == Intrinsic::dx_sclamp)
1049 return Intrinsic::smax;
1050 assert(ClampIntrinsic == Intrinsic::dx_nclamp);
1051 return Intrinsic::maxnum;
1052}
1053
1055 if (ClampIntrinsic == Intrinsic::dx_uclamp)
1056 return Intrinsic::umin;
1057 if (ClampIntrinsic == Intrinsic::dx_sclamp)
1058 return Intrinsic::smin;
1059 assert(ClampIntrinsic == Intrinsic::dx_nclamp);
1060 return Intrinsic::minnum;
1061}
1062
1064 Intrinsic::ID ClampIntrinsic) {
1065 Value *X = Orig->getOperand(0);
1066 Value *Min = Orig->getOperand(1);
1067 Value *Max = Orig->getOperand(2);
1068 Type *Ty = X->getType();
1069 IRBuilder<> Builder(Orig);
1070 auto *MaxCall = Builder.CreateIntrinsic(Ty, getMaxForClamp(ClampIntrinsic),
1071 {X, Min}, nullptr, "dx.max");
1072 return Builder.CreateIntrinsic(Ty, getMinForClamp(ClampIntrinsic),
1073 {MaxCall, Max}, nullptr, "dx.min");
1074}
1075
1077 Value *X = Orig->getOperand(0);
1078 Type *Ty = X->getType();
1079 IRBuilder<> Builder(Orig);
1080 Value *DegreesRatio = ConstantFP::get(Ty, 180.0 * llvm::numbers::inv_pi);
1081 return Builder.CreateFMul(X, DegreesRatio);
1082}
1083
1085 Value *X = Orig->getOperand(0);
1086 Type *Ty = X->getType();
1087 Type *ScalarTy = Ty->getScalarType();
1088 Type *RetTy = Orig->getType();
1089 Constant *Zero = Constant::getNullValue(Ty);
1090
1091 IRBuilder<> Builder(Orig);
1092
1093 Value *GT;
1094 Value *LT;
1095 if (ScalarTy->isFloatingPointTy()) {
1096 GT = Builder.CreateFCmpOLT(Zero, X);
1097 LT = Builder.CreateFCmpOLT(X, Zero);
1098 } else {
1099 assert(ScalarTy->isIntegerTy());
1100 GT = Builder.CreateICmpSLT(Zero, X);
1101 LT = Builder.CreateICmpSLT(X, Zero);
1102 }
1103
1104 Value *ZextGT = Builder.CreateZExt(GT, RetTy);
1105 Value *ZextLT = Builder.CreateZExt(LT, RetTy);
1106
1107 return Builder.CreateSub(ZextGT, ZextLT);
1108}
1109
1110// Expand llvm.matrix.multiply by extracting row/column vectors and computing
1111// dot products.
1112// Result[r,c] = dot(row_r(LHS), col_c(RHS))
1113// Element (r,c) is at index c*NumRows + r (column-major).
1115 Value *LHS = Orig->getArgOperand(0);
1116 Value *RHS = Orig->getArgOperand(1);
1117 unsigned LHSRows = cast<ConstantInt>(Orig->getArgOperand(2))->getZExtValue();
1118 unsigned LHSCols = cast<ConstantInt>(Orig->getArgOperand(3))->getZExtValue();
1119 unsigned RHSCols = cast<ConstantInt>(Orig->getArgOperand(4))->getZExtValue();
1120
1121 auto *RetTy = cast<FixedVectorType>(Orig->getType());
1122 Type *EltTy = RetTy->getElementType();
1123 bool IsFP = EltTy->isFloatingPointTy();
1124
1125 IRBuilder<> Builder(Orig);
1126
1127 // Column-major indexing:
1128 // LHS row R, element K: index = K * LHSRows + R
1129 // RHS col C, element K: index = C * LHSCols + K
1130 Value *Result = PoisonValue::get(RetTy);
1131
1132 // Extract all scalar elements from LHS and RHS once, then reuse them.
1133 unsigned LHSSize = LHSRows * LHSCols;
1134 unsigned RHSSize = LHSCols * RHSCols;
1135 SmallVector<Value *, 16> LHSElts(LHSSize);
1136 SmallVector<Value *, 16> RHSElts(RHSSize);
1137 for (unsigned I = 0; I < LHSSize; ++I)
1138 LHSElts[I] = Builder.CreateExtractElement(LHS, I);
1139 for (unsigned I = 0; I < RHSSize; ++I)
1140 RHSElts[I] = Builder.CreateExtractElement(RHS, I);
1141
1142 // Choose the appropriate scalar-arg dot intrinsic for floats.
1143 // K=1 and double types use scalar expansion instead.
1145 bool UseScalarFP = IsFP && (EltTy->isDoubleTy() || LHSCols == 1);
1146 if (IsFP && !UseScalarFP) {
1147 switch (LHSCols) {
1148 case 2:
1149 FloatDotID = Intrinsic::dx_dot2;
1150 break;
1151 case 3:
1152 FloatDotID = Intrinsic::dx_dot3;
1153 break;
1154 case 4:
1155 FloatDotID = Intrinsic::dx_dot4;
1156 break;
1157 default:
1159 "Invalid matrix inner dimension for dot product: must be 2-4");
1160 return nullptr;
1161 }
1162 }
1163
1164 for (unsigned C = 0; C < RHSCols; ++C) {
1165 for (unsigned R = 0; R < LHSRows; ++R) {
1166 // Gather row R from LHS and column C from RHS.
1167 SmallVector<Value *, 4> RowElts, ColElts;
1168 for (unsigned K = 0; K < LHSCols; ++K) {
1169 RowElts.push_back(LHSElts[K * LHSRows + R]);
1170 ColElts.push_back(RHSElts[C * LHSCols + K]);
1171 }
1172
1173 Value *Dot;
1174 if (UseScalarFP) {
1175 // Scalar fmul+fmuladd expansion for double types and K=1.
1176 Dot = Builder.CreateFMul(RowElts[0], ColElts[0]);
1177 for (unsigned K = 1; K < LHSCols; ++K)
1178 Dot = Builder.CreateIntrinsic(EltTy, Intrinsic::fmuladd,
1179 {RowElts[K], ColElts[K], Dot});
1180 } else if (IsFP) {
1181 // Emit scalar-arg DXIL dot directly (dx.dot2/dx.dot3/dx.dot4).
1183 Args.append(RowElts.begin(), RowElts.end());
1184 Args.append(ColElts.begin(), ColElts.end());
1185 Dot = Builder.CreateIntrinsic(EltTy, FloatDotID, Args);
1186 } else {
1187 // Integer: emit multiply + imad chain.
1188 Dot = Builder.CreateMul(RowElts[0], ColElts[0]);
1189 for (unsigned K = 1; K < LHSCols; ++K)
1190 Dot = Builder.CreateIntrinsic(EltTy, Intrinsic::dx_imad,
1191 {RowElts[K], ColElts[K], Dot});
1192 }
1193 unsigned ResIdx = C * LHSRows + R;
1194 Result = Builder.CreateInsertElement(Result, Dot, ResIdx);
1195 }
1196 }
1197 return Result;
1198}
1199
1200// Expand llvm.matrix.transpose as a shufflevector that permutes elements
1201// from column-major source to column-major transposed layout.
1202// Element (r,c) at index c*Rows + r moves to index r*Cols + c.
1204 Value *Mat = Orig->getArgOperand(0);
1205 unsigned Rows = cast<ConstantInt>(Orig->getArgOperand(1))->getZExtValue();
1206 unsigned Cols = cast<ConstantInt>(Orig->getArgOperand(2))->getZExtValue();
1207
1208 unsigned NumElts = Rows * Cols;
1209 SmallVector<int, 16> Mask(NumElts);
1210 for (unsigned I = 0; I < NumElts; ++I)
1211 Mask[I] = (I % Cols) * Rows + (I / Cols);
1212
1213 IRBuilder<> Builder(Orig);
1214 return Builder.CreateShuffleVector(Mat, Mask);
1215}
1216
1217// Scalarize a vector int_dx_store_output call into per-component scalar calls.
1218// The DXIL StoreOutput op is per-component; vector intrinsics are split here
1219// so that DXILOpLowering sees only scalar variants.
1220static bool expandStoreOutput(CallInst *Orig) {
1221 auto *VT = dyn_cast<FixedVectorType>(Orig->getArgOperand(4)->getType());
1222 if (!VT)
1223 return false; // already scalar, nothing to expand
1224
1225 IRBuilder<> Builder(Orig);
1226 Module *M = Orig->getModule();
1227 Type *Int8Ty = Builder.getInt8Ty();
1228 Type *Int32Ty = Builder.getInt32Ty();
1229 Type *ScalarTy = VT->getElementType();
1230 unsigned NumElems = VT->getNumElements();
1231
1232 Value *SigpointId = Orig->getArgOperand(0);
1233 Value *SigElementId = Orig->getArgOperand(1);
1234 Value *RowIndex = Orig->getArgOperand(2);
1235 Value *StartCol = Orig->getArgOperand(3); // i8
1236 Value *Data = Orig->getArgOperand(4);
1237 Value *StartColI32 = Builder.CreateZExt(StartCol, Int32Ty);
1238
1240 M, Intrinsic::dx_store_output, {ScalarTy});
1241
1242 for (unsigned I = 0; I < NumElems; ++I) {
1243 Value *Scalar =
1244 Builder.CreateExtractElement(Data, ConstantInt::get(Int32Ty, I));
1245 Value *ColIdx =
1246 Builder.CreateAdd(StartColI32, ConstantInt::get(Int32Ty, I));
1247 Value *ColI8 = Builder.CreateTrunc(ColIdx, Int8Ty);
1248 Builder.CreateCall(ScalarFn,
1249 {SigpointId, SigElementId, RowIndex, ColI8, Scalar});
1250 }
1251
1252 Orig->eraseFromParent();
1253 return true;
1254}
1255
1256// Scalarize a vector int_dx_load_input call into per-component scalar calls
1257// and reassemble the vector. The DXIL LoadInput op is per-component.
1259 auto *VT = dyn_cast<FixedVectorType>(Orig->getType());
1260 if (!VT)
1261 return nullptr; // already scalar, nothing to expand
1262
1263 IRBuilder<> Builder(Orig);
1264 Module *M = Orig->getModule();
1265 Type *Int8Ty = Builder.getInt8Ty();
1266 Type *Int32Ty = Builder.getInt32Ty();
1267 Type *ScalarTy = VT->getElementType();
1268 unsigned NumElems = VT->getNumElements();
1269
1270 Value *SigpointId = Orig->getArgOperand(0);
1271 Value *SigElementId = Orig->getArgOperand(1);
1272 Value *RowIndex = Orig->getArgOperand(2);
1273 Value *StartCol = Orig->getArgOperand(3); // i8
1274 Value *GsVertexOrPrimIndex = Orig->getArgOperand(4);
1275 Value *StartColI32 = Builder.CreateZExt(StartCol, Int32Ty);
1276
1278 M, Intrinsic::dx_load_input, {ScalarTy});
1279
1280 Value *Vec = PoisonValue::get(VT);
1281 for (unsigned I = 0; I < NumElems; ++I) {
1282 Value *ColIdx =
1283 Builder.CreateAdd(StartColI32, ConstantInt::get(Int32Ty, I));
1284 Value *ColI8 = Builder.CreateTrunc(ColIdx, Int8Ty);
1285 Value *Scalar =
1286 Builder.CreateCall(ScalarFn, {SigpointId, SigElementId, RowIndex, ColI8,
1287 GsVertexOrPrimIndex});
1288 Vec =
1289 Builder.CreateInsertElement(Vec, Scalar, ConstantInt::get(Int32Ty, I));
1290 }
1291
1292 return Vec;
1293}
1294
1295static bool expandIntrinsic(Function &F, CallInst *Orig) {
1296 Value *Result = nullptr;
1297 Intrinsic::ID IntrinsicId = F.getIntrinsicID();
1298 switch (IntrinsicId) {
1299 case Intrinsic::abs:
1300 Result = expandAbs(Orig);
1301 break;
1302 case Intrinsic::assume:
1303 Orig->eraseFromParent();
1304 return true;
1305 case Intrinsic::atan2:
1306 Result = expandAtan2Intrinsic(Orig);
1307 break;
1308 case Intrinsic::fshl:
1309 Result = expandFunnelShiftIntrinsic<true>(Orig);
1310 break;
1311 case Intrinsic::fshr:
1312 Result = expandFunnelShiftIntrinsic<false>(Orig);
1313 break;
1314 case Intrinsic::exp:
1315 Result = expandExpIntrinsic(Orig);
1316 break;
1317 case Intrinsic::is_fpclass:
1318 Result = expandIsFPClass(Orig);
1319 break;
1320 case Intrinsic::log:
1321 Result = expandLogIntrinsic(Orig);
1322 break;
1323 case Intrinsic::log10:
1324 Result = expandLog10Intrinsic(Orig);
1325 break;
1326 case Intrinsic::pow:
1327 case Intrinsic::powi:
1328 Result = expandPowIntrinsic(Orig, IntrinsicId);
1329 break;
1330 case Intrinsic::dx_all:
1331 case Intrinsic::dx_any:
1332 Result = expandAnyOrAllIntrinsic(Orig, IntrinsicId);
1333 break;
1334 case Intrinsic::dx_uclamp:
1335 case Intrinsic::dx_sclamp:
1336 case Intrinsic::dx_nclamp:
1337 Result = expandClampIntrinsic(Orig, IntrinsicId);
1338 break;
1339 case Intrinsic::dx_degrees:
1340 Result = expandDegreesIntrinsic(Orig);
1341 break;
1342 case Intrinsic::dx_isinf:
1343 Result = expand16BitIsInf(Orig);
1344 break;
1345 case Intrinsic::dx_isnan:
1346 Result = expand16BitIsNaN(Orig);
1347 break;
1348 case Intrinsic::dx_lerp:
1349 Result = expandLerpIntrinsic(Orig);
1350 break;
1351 case Intrinsic::dx_normalize:
1352 Result = expandNormalizeIntrinsic(Orig);
1353 break;
1354 case Intrinsic::dx_fdot:
1355 Result = expandFloatDotIntrinsic(Orig);
1356 break;
1357 case Intrinsic::dx_sdot:
1358 case Intrinsic::dx_udot:
1359 Result = expandIntegerDotIntrinsic(Orig, IntrinsicId);
1360 break;
1361 case Intrinsic::dx_sign:
1362 Result = expandSignIntrinsic(Orig);
1363 break;
1364 case Intrinsic::dx_step:
1365 Result = expandStepIntrinsic(Orig);
1366 break;
1367 case Intrinsic::dx_radians:
1368 Result = expandRadiansIntrinsic(Orig);
1369 break;
1370 case Intrinsic::dx_load_input:
1371 Result = expandLoadInput(Orig);
1372 break;
1373 case Intrinsic::dx_store_output:
1374 if (expandStoreOutput(Orig))
1375 return true;
1376 break;
1377 case Intrinsic::dx_resource_load_rawbuffer:
1378 if (expandBufferLoadIntrinsic(Orig, /*IsRaw*/ true))
1379 return true;
1380 break;
1381 case Intrinsic::dx_resource_store_rawbuffer:
1382 if (expandBufferStoreIntrinsic(Orig, /*IsRaw*/ true))
1383 return true;
1384 break;
1385 case Intrinsic::dx_resource_load_typedbuffer:
1386 if (expandBufferLoadIntrinsic(Orig, /*IsRaw*/ false))
1387 return true;
1388 break;
1389 case Intrinsic::dx_resource_store_typedbuffer:
1390 if (expandBufferStoreIntrinsic(Orig, /*IsRaw*/ false))
1391 return true;
1392 break;
1393 case Intrinsic::usub_sat:
1394 Result = expandUsubSat(Orig);
1395 break;
1396 case Intrinsic::umul_with_overflow:
1397 case Intrinsic::smul_with_overflow:
1398 Result = expandMulWithOverflow(Orig, /*Signed=*/IntrinsicId ==
1399 Intrinsic::smul_with_overflow);
1400 break;
1401 case Intrinsic::vector_reduce_add:
1402 case Intrinsic::vector_reduce_fadd:
1403 Result = expandVecReduceAdd(Orig, IntrinsicId);
1404 break;
1405 case Intrinsic::matrix_multiply:
1406 Result = expandMatrixMultiply(Orig);
1407 break;
1408 case Intrinsic::matrix_transpose:
1409 Result = expandMatrixTranspose(Orig);
1410 break;
1411 }
1412 if (Result) {
1413 Orig->replaceAllUsesWith(Result);
1414 Orig->eraseFromParent();
1415 return true;
1416 }
1417 return false;
1418}
1419
1421 for (auto &F : make_early_inc_range(M.functions())) {
1422 if (!isIntrinsicExpansion(F))
1423 continue;
1424 bool IntrinsicExpanded = false;
1425 for (User *U : make_early_inc_range(F.users())) {
1426 auto *IntrinsicCall = dyn_cast<CallInst>(U);
1427 if (!IntrinsicCall)
1428 continue;
1429 IntrinsicExpanded = expandIntrinsic(F, IntrinsicCall);
1430 }
1431 if (F.user_empty() && IntrinsicExpanded)
1432 F.eraseFromParent();
1433 }
1434 return true;
1435}
1436
1443
1447
1449
1451 "DXIL Intrinsic Expansion", false, false)
1453 "DXIL Intrinsic Expansion", false, false)
1454
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< 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 Value * createMulHighUnsigned(IRBuilder<> &Builder, Value *A, Value *B, Type *Ty, unsigned BW)
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 * expandLoadInput(CallInst *Orig)
static Value * expandLerpIntrinsic(CallInst *Orig)
static Value * expandUsubSat(CallInst *Orig)
static Value * expandAnyOrAllIntrinsic(CallInst *Orig, Intrinsic::ID IntrinsicId)
static bool expandStoreOutput(CallInst *Orig)
static Value * expandMatrixTranspose(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 * expandMulWithOverflow(CallInst *Orig, bool Signed)
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
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:1571
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
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
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:867
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:2893
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:477
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
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
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
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
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:553
iterator_range< user_iterator > users()
Definition Value.h:426
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.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
constexpr double inv_pi
constexpr float ln10f
Definition MathExtras.h:51
constexpr float log2ef
Definition MathExtras.h:52
constexpr double pi
constexpr float ln2f
Definition MathExtras.h:50
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
@ Load
The value being inserted comes from a load (InsertElement only).
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:280
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