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