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