xref: /llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp (revision 9ad09b2930ef2e95bf8772c91f623881d1c14733)
1 //===-- AMDGPUCodeGenPrepare.cpp ------------------------------------------===//
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
10 /// This pass does misc. AMDGPU optimizations on IR before instruction
11 /// selection.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPU.h"
16 #include "AMDGPUTargetMachine.h"
17 #include "SIModeRegisterDefaults.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/UniformityAnalysis.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/CodeGen/TargetPassConfig.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/InstVisitor.h"
27 #include "llvm/IR/IntrinsicsAMDGPU.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/InitializePasses.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/KnownBits.h"
32 #include "llvm/Transforms/Utils/IntegerDivision.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 
35 #define DEBUG_TYPE "amdgpu-codegenprepare"
36 
37 using namespace llvm;
38 using namespace llvm::PatternMatch;
39 
40 namespace {
41 
42 static cl::opt<bool> WidenLoads(
43   "amdgpu-codegenprepare-widen-constant-loads",
44   cl::desc("Widen sub-dword constant address space loads in AMDGPUCodeGenPrepare"),
45   cl::ReallyHidden,
46   cl::init(false));
47 
48 static cl::opt<bool> Widen16BitOps(
49   "amdgpu-codegenprepare-widen-16-bit-ops",
50   cl::desc("Widen uniform 16-bit instructions to 32-bit in AMDGPUCodeGenPrepare"),
51   cl::ReallyHidden,
52   cl::init(true));
53 
54 static cl::opt<bool>
55     BreakLargePHIs("amdgpu-codegenprepare-break-large-phis",
56                    cl::desc("Break large PHI nodes for DAGISel"),
57                    cl::ReallyHidden, cl::init(true));
58 
59 static cl::opt<bool>
60     ForceBreakLargePHIs("amdgpu-codegenprepare-force-break-large-phis",
61                         cl::desc("For testing purposes, always break large "
62                                  "PHIs even if it isn't profitable."),
63                         cl::ReallyHidden, cl::init(false));
64 
65 static cl::opt<unsigned> BreakLargePHIsThreshold(
66     "amdgpu-codegenprepare-break-large-phis-threshold",
67     cl::desc("Minimum type size in bits for breaking large PHI nodes"),
68     cl::ReallyHidden, cl::init(32));
69 
70 static cl::opt<bool> UseMul24Intrin(
71   "amdgpu-codegenprepare-mul24",
72   cl::desc("Introduce mul24 intrinsics in AMDGPUCodeGenPrepare"),
73   cl::ReallyHidden,
74   cl::init(true));
75 
76 // Legalize 64-bit division by using the generic IR expansion.
77 static cl::opt<bool> ExpandDiv64InIR(
78   "amdgpu-codegenprepare-expand-div64",
79   cl::desc("Expand 64-bit division in AMDGPUCodeGenPrepare"),
80   cl::ReallyHidden,
81   cl::init(false));
82 
83 // Leave all division operations as they are. This supersedes ExpandDiv64InIR
84 // and is used for testing the legalizer.
85 static cl::opt<bool> DisableIDivExpand(
86   "amdgpu-codegenprepare-disable-idiv-expansion",
87   cl::desc("Prevent expanding integer division in AMDGPUCodeGenPrepare"),
88   cl::ReallyHidden,
89   cl::init(false));
90 
91 // Disable processing of fdiv so we can better test the backend implementations.
92 static cl::opt<bool> DisableFDivExpand(
93   "amdgpu-codegenprepare-disable-fdiv-expansion",
94   cl::desc("Prevent expanding floating point division in AMDGPUCodeGenPrepare"),
95   cl::ReallyHidden,
96   cl::init(false));
97 
98 static bool hasUnsafeFPMath(const Function &F) {
99   return F.getFnAttribute("unsafe-fp-math").getValueAsBool();
100 }
101 
102 class AMDGPUCodeGenPrepareImpl
103     : public InstVisitor<AMDGPUCodeGenPrepareImpl, bool> {
104 public:
105   Function &F;
106   const GCNSubtarget &ST;
107   const AMDGPUTargetMachine &TM;
108   const TargetLibraryInfo *TLI;
109   AssumptionCache *AC;
110   const DominatorTree *DT;
111   const UniformityInfo &UA;
112   const DataLayout &DL;
113   const bool HasUnsafeFPMath;
114   const bool HasFP32DenormalFlush;
115   bool FlowChanged = false;
116   mutable Function *SqrtF32 = nullptr;
117   mutable Function *LdexpF32 = nullptr;
118 
119   DenseMap<const PHINode *, bool> BreakPhiNodesCache;
120 
121   AMDGPUCodeGenPrepareImpl(Function &F, const AMDGPUTargetMachine &TM,
122                            const TargetLibraryInfo *TLI, AssumptionCache *AC,
123                            const DominatorTree *DT, const UniformityInfo &UA)
124       : F(F), ST(TM.getSubtarget<GCNSubtarget>(F)), TM(TM), TLI(TLI), AC(AC),
125         DT(DT), UA(UA), DL(F.getDataLayout()),
126         HasUnsafeFPMath(hasUnsafeFPMath(F)),
127         HasFP32DenormalFlush(SIModeRegisterDefaults(F, ST).FP32Denormals ==
128                              DenormalMode::getPreserveSign()) {}
129 
130   Function *getSqrtF32() const {
131     if (SqrtF32)
132       return SqrtF32;
133 
134     LLVMContext &Ctx = F.getContext();
135     SqrtF32 = Intrinsic::getOrInsertDeclaration(
136         F.getParent(), Intrinsic::amdgcn_sqrt, {Type::getFloatTy(Ctx)});
137     return SqrtF32;
138   }
139 
140   Function *getLdexpF32() const {
141     if (LdexpF32)
142       return LdexpF32;
143 
144     LLVMContext &Ctx = F.getContext();
145     LdexpF32 = Intrinsic::getOrInsertDeclaration(
146         F.getParent(), Intrinsic::ldexp,
147         {Type::getFloatTy(Ctx), Type::getInt32Ty(Ctx)});
148     return LdexpF32;
149   }
150 
151   bool canBreakPHINode(const PHINode &I);
152 
153   /// Copies exact/nsw/nuw flags (if any) from binary operation \p I to
154   /// binary operation \p V.
155   ///
156   /// \returns Binary operation \p V.
157   /// \returns \p T's base element bit width.
158   unsigned getBaseElementBitWidth(const Type *T) const;
159 
160   /// \returns Equivalent 32 bit integer type for given type \p T. For example,
161   /// if \p T is i7, then i32 is returned; if \p T is <3 x i12>, then <3 x i32>
162   /// is returned.
163   Type *getI32Ty(IRBuilder<> &B, const Type *T) const;
164 
165   /// \returns True if binary operation \p I is a signed binary operation, false
166   /// otherwise.
167   bool isSigned(const BinaryOperator &I) const;
168 
169   /// \returns True if the condition of 'select' operation \p I comes from a
170   /// signed 'icmp' operation, false otherwise.
171   bool isSigned(const SelectInst &I) const;
172 
173   /// \returns True if type \p T needs to be promoted to 32 bit integer type,
174   /// false otherwise.
175   bool needsPromotionToI32(const Type *T) const;
176 
177   /// Return true if \p T is a legal scalar floating point type.
178   bool isLegalFloatingTy(const Type *T) const;
179 
180   /// Wrapper to pass all the arguments to computeKnownFPClass
181   KnownFPClass computeKnownFPClass(const Value *V, FPClassTest Interested,
182                                    const Instruction *CtxI) const {
183     return llvm::computeKnownFPClass(V, DL, Interested, 0, TLI, AC, CtxI, DT);
184   }
185 
186   bool canIgnoreDenormalInput(const Value *V, const Instruction *CtxI) const {
187     return HasFP32DenormalFlush ||
188            computeKnownFPClass(V, fcSubnormal, CtxI).isKnownNeverSubnormal();
189   }
190 
191   /// Promotes uniform binary operation \p I to equivalent 32 bit binary
192   /// operation.
193   ///
194   /// \details \p I's base element bit width must be greater than 1 and less
195   /// than or equal 16. Promotion is done by sign or zero extending operands to
196   /// 32 bits, replacing \p I with equivalent 32 bit binary operation, and
197   /// truncating the result of 32 bit binary operation back to \p I's original
198   /// type. Division operation is not promoted.
199   ///
200   /// \returns True if \p I is promoted to equivalent 32 bit binary operation,
201   /// false otherwise.
202   bool promoteUniformOpToI32(BinaryOperator &I) const;
203 
204   /// Promotes uniform 'icmp' operation \p I to 32 bit 'icmp' operation.
205   ///
206   /// \details \p I's base element bit width must be greater than 1 and less
207   /// than or equal 16. Promotion is done by sign or zero extending operands to
208   /// 32 bits, and replacing \p I with 32 bit 'icmp' operation.
209   ///
210   /// \returns True.
211   bool promoteUniformOpToI32(ICmpInst &I) const;
212 
213   /// Promotes uniform 'select' operation \p I to 32 bit 'select'
214   /// operation.
215   ///
216   /// \details \p I's base element bit width must be greater than 1 and less
217   /// than or equal 16. Promotion is done by sign or zero extending operands to
218   /// 32 bits, replacing \p I with 32 bit 'select' operation, and truncating the
219   /// result of 32 bit 'select' operation back to \p I's original type.
220   ///
221   /// \returns True.
222   bool promoteUniformOpToI32(SelectInst &I) const;
223 
224   /// Promotes uniform 'bitreverse' intrinsic \p I to 32 bit 'bitreverse'
225   /// intrinsic.
226   ///
227   /// \details \p I's base element bit width must be greater than 1 and less
228   /// than or equal 16. Promotion is done by zero extending the operand to 32
229   /// bits, replacing \p I with 32 bit 'bitreverse' intrinsic, shifting the
230   /// result of 32 bit 'bitreverse' intrinsic to the right with zero fill (the
231   /// shift amount is 32 minus \p I's base element bit width), and truncating
232   /// the result of the shift operation back to \p I's original type.
233   ///
234   /// \returns True.
235   bool promoteUniformBitreverseToI32(IntrinsicInst &I) const;
236 
237   /// \returns The minimum number of bits needed to store the value of \Op as an
238   /// unsigned integer. Truncating to this size and then zero-extending to
239   /// the original will not change the value.
240   unsigned numBitsUnsigned(Value *Op) const;
241 
242   /// \returns The minimum number of bits needed to store the value of \Op as a
243   /// signed integer. Truncating to this size and then sign-extending to
244   /// the original size will not change the value.
245   unsigned numBitsSigned(Value *Op) const;
246 
247   /// Replace mul instructions with llvm.amdgcn.mul.u24 or llvm.amdgcn.mul.s24.
248   /// SelectionDAG has an issue where an and asserting the bits are known
249   bool replaceMulWithMul24(BinaryOperator &I) const;
250 
251   /// Perform same function as equivalently named function in DAGCombiner. Since
252   /// we expand some divisions here, we need to perform this before obscuring.
253   bool foldBinOpIntoSelect(BinaryOperator &I) const;
254 
255   bool divHasSpecialOptimization(BinaryOperator &I,
256                                  Value *Num, Value *Den) const;
257   int getDivNumBits(BinaryOperator &I,
258                     Value *Num, Value *Den,
259                     unsigned AtLeast, bool Signed) const;
260 
261   /// Expands 24 bit div or rem.
262   Value* expandDivRem24(IRBuilder<> &Builder, BinaryOperator &I,
263                         Value *Num, Value *Den,
264                         bool IsDiv, bool IsSigned) const;
265 
266   Value *expandDivRem24Impl(IRBuilder<> &Builder, BinaryOperator &I,
267                             Value *Num, Value *Den, unsigned NumBits,
268                             bool IsDiv, bool IsSigned) const;
269 
270   /// Expands 32 bit div or rem.
271   Value* expandDivRem32(IRBuilder<> &Builder, BinaryOperator &I,
272                         Value *Num, Value *Den) const;
273 
274   Value *shrinkDivRem64(IRBuilder<> &Builder, BinaryOperator &I,
275                         Value *Num, Value *Den) const;
276   void expandDivRem64(BinaryOperator &I) const;
277 
278   /// Widen a scalar load.
279   ///
280   /// \details \p Widen scalar load for uniform, small type loads from constant
281   //  memory / to a full 32-bits and then truncate the input to allow a scalar
282   //  load instead of a vector load.
283   //
284   /// \returns True.
285 
286   bool canWidenScalarExtLoad(LoadInst &I) const;
287 
288   Value *matchFractPat(IntrinsicInst &I);
289   Value *applyFractPat(IRBuilder<> &Builder, Value *FractArg);
290 
291   bool canOptimizeWithRsq(const FPMathOperator *SqrtOp, FastMathFlags DivFMF,
292                           FastMathFlags SqrtFMF) const;
293 
294   Value *optimizeWithRsq(IRBuilder<> &Builder, Value *Num, Value *Den,
295                          FastMathFlags DivFMF, FastMathFlags SqrtFMF,
296                          const Instruction *CtxI) const;
297 
298   Value *optimizeWithRcp(IRBuilder<> &Builder, Value *Num, Value *Den,
299                          FastMathFlags FMF, const Instruction *CtxI) const;
300   Value *optimizeWithFDivFast(IRBuilder<> &Builder, Value *Num, Value *Den,
301                               float ReqdAccuracy) const;
302 
303   Value *visitFDivElement(IRBuilder<> &Builder, Value *Num, Value *Den,
304                           FastMathFlags DivFMF, FastMathFlags SqrtFMF,
305                           Value *RsqOp, const Instruction *FDiv,
306                           float ReqdAccuracy) const;
307 
308   std::pair<Value *, Value *> getFrexpResults(IRBuilder<> &Builder,
309                                               Value *Src) const;
310 
311   Value *emitRcpIEEE1ULP(IRBuilder<> &Builder, Value *Src,
312                          bool IsNegative) const;
313   Value *emitFrexpDiv(IRBuilder<> &Builder, Value *LHS, Value *RHS,
314                       FastMathFlags FMF) const;
315   Value *emitSqrtIEEE2ULP(IRBuilder<> &Builder, Value *Src,
316                           FastMathFlags FMF) const;
317 
318 public:
319   bool visitFDiv(BinaryOperator &I);
320 
321   bool visitInstruction(Instruction &I) { return false; }
322   bool visitBinaryOperator(BinaryOperator &I);
323   bool visitLoadInst(LoadInst &I);
324   bool visitICmpInst(ICmpInst &I);
325   bool visitSelectInst(SelectInst &I);
326   bool visitPHINode(PHINode &I);
327   bool visitAddrSpaceCastInst(AddrSpaceCastInst &I);
328 
329   bool visitIntrinsicInst(IntrinsicInst &I);
330   bool visitBitreverseIntrinsicInst(IntrinsicInst &I);
331   bool visitMinNum(IntrinsicInst &I);
332   bool visitSqrt(IntrinsicInst &I);
333   bool run();
334 };
335 
336 class AMDGPUCodeGenPrepare : public FunctionPass {
337 public:
338   static char ID;
339   AMDGPUCodeGenPrepare() : FunctionPass(ID) {
340     initializeAMDGPUCodeGenPreparePass(*PassRegistry::getPassRegistry());
341   }
342   void getAnalysisUsage(AnalysisUsage &AU) const override {
343     AU.addRequired<AssumptionCacheTracker>();
344     AU.addRequired<UniformityInfoWrapperPass>();
345     AU.addRequired<TargetLibraryInfoWrapperPass>();
346 
347     // FIXME: Division expansion needs to preserve the dominator tree.
348     if (!ExpandDiv64InIR)
349       AU.setPreservesAll();
350   }
351   bool runOnFunction(Function &F) override;
352   StringRef getPassName() const override { return "AMDGPU IR optimizations"; }
353 };
354 
355 } // end anonymous namespace
356 
357 bool AMDGPUCodeGenPrepareImpl::run() {
358   BreakPhiNodesCache.clear();
359   bool MadeChange = false;
360 
361   Function::iterator NextBB;
362   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; FI = NextBB) {
363     BasicBlock *BB = &*FI;
364     NextBB = std::next(FI);
365 
366     BasicBlock::iterator Next;
367     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;
368          I = Next) {
369       Next = std::next(I);
370 
371       MadeChange |= visit(*I);
372 
373       if (Next != E) { // Control flow changed
374         BasicBlock *NextInstBB = Next->getParent();
375         if (NextInstBB != BB) {
376           BB = NextInstBB;
377           E = BB->end();
378           FE = F.end();
379         }
380       }
381     }
382   }
383   return MadeChange;
384 }
385 
386 unsigned AMDGPUCodeGenPrepareImpl::getBaseElementBitWidth(const Type *T) const {
387   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
388 
389   if (T->isIntegerTy())
390     return T->getIntegerBitWidth();
391   return cast<VectorType>(T)->getElementType()->getIntegerBitWidth();
392 }
393 
394 Type *AMDGPUCodeGenPrepareImpl::getI32Ty(IRBuilder<> &B, const Type *T) const {
395   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
396 
397   if (T->isIntegerTy())
398     return B.getInt32Ty();
399   return FixedVectorType::get(B.getInt32Ty(), cast<FixedVectorType>(T));
400 }
401 
402 bool AMDGPUCodeGenPrepareImpl::isSigned(const BinaryOperator &I) const {
403   return I.getOpcode() == Instruction::AShr ||
404       I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::SRem;
405 }
406 
407 bool AMDGPUCodeGenPrepareImpl::isSigned(const SelectInst &I) const {
408   return isa<ICmpInst>(I.getOperand(0)) ?
409       cast<ICmpInst>(I.getOperand(0))->isSigned() : false;
410 }
411 
412 bool AMDGPUCodeGenPrepareImpl::needsPromotionToI32(const Type *T) const {
413   if (!Widen16BitOps)
414     return false;
415 
416   const IntegerType *IntTy = dyn_cast<IntegerType>(T);
417   if (IntTy && IntTy->getBitWidth() > 1 && IntTy->getBitWidth() <= 16)
418     return true;
419 
420   if (const VectorType *VT = dyn_cast<VectorType>(T)) {
421     // TODO: The set of packed operations is more limited, so may want to
422     // promote some anyway.
423     if (ST.hasVOP3PInsts())
424       return false;
425 
426     return needsPromotionToI32(VT->getElementType());
427   }
428 
429   return false;
430 }
431 
432 bool AMDGPUCodeGenPrepareImpl::isLegalFloatingTy(const Type *Ty) const {
433   return Ty->isFloatTy() || Ty->isDoubleTy() ||
434          (Ty->isHalfTy() && ST.has16BitInsts());
435 }
436 
437 // Return true if the op promoted to i32 should have nsw set.
438 static bool promotedOpIsNSW(const Instruction &I) {
439   switch (I.getOpcode()) {
440   case Instruction::Shl:
441   case Instruction::Add:
442   case Instruction::Sub:
443     return true;
444   case Instruction::Mul:
445     return I.hasNoUnsignedWrap();
446   default:
447     return false;
448   }
449 }
450 
451 // Return true if the op promoted to i32 should have nuw set.
452 static bool promotedOpIsNUW(const Instruction &I) {
453   switch (I.getOpcode()) {
454   case Instruction::Shl:
455   case Instruction::Add:
456   case Instruction::Mul:
457     return true;
458   case Instruction::Sub:
459     return I.hasNoUnsignedWrap();
460   default:
461     return false;
462   }
463 }
464 
465 bool AMDGPUCodeGenPrepareImpl::canWidenScalarExtLoad(LoadInst &I) const {
466   Type *Ty = I.getType();
467   int TySize = DL.getTypeSizeInBits(Ty);
468   Align Alignment = DL.getValueOrABITypeAlignment(I.getAlign(), Ty);
469 
470   return I.isSimple() && TySize < 32 && Alignment >= 4 && UA.isUniform(&I);
471 }
472 
473 bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(BinaryOperator &I) const {
474   assert(needsPromotionToI32(I.getType()) &&
475          "I does not need promotion to i32");
476 
477   if (I.getOpcode() == Instruction::SDiv ||
478       I.getOpcode() == Instruction::UDiv ||
479       I.getOpcode() == Instruction::SRem ||
480       I.getOpcode() == Instruction::URem)
481     return false;
482 
483   IRBuilder<> Builder(&I);
484   Builder.SetCurrentDebugLocation(I.getDebugLoc());
485 
486   Type *I32Ty = getI32Ty(Builder, I.getType());
487   Value *ExtOp0 = nullptr;
488   Value *ExtOp1 = nullptr;
489   Value *ExtRes = nullptr;
490   Value *TruncRes = nullptr;
491 
492   if (isSigned(I)) {
493     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
494     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
495   } else {
496     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
497     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
498   }
499 
500   ExtRes = Builder.CreateBinOp(I.getOpcode(), ExtOp0, ExtOp1);
501   if (Instruction *Inst = dyn_cast<Instruction>(ExtRes)) {
502     if (promotedOpIsNSW(cast<Instruction>(I)))
503       Inst->setHasNoSignedWrap();
504 
505     if (promotedOpIsNUW(cast<Instruction>(I)))
506       Inst->setHasNoUnsignedWrap();
507 
508     if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
509       Inst->setIsExact(ExactOp->isExact());
510   }
511 
512   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
513 
514   I.replaceAllUsesWith(TruncRes);
515   I.eraseFromParent();
516 
517   return true;
518 }
519 
520 bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(ICmpInst &I) const {
521   assert(needsPromotionToI32(I.getOperand(0)->getType()) &&
522          "I does not need promotion to i32");
523 
524   IRBuilder<> Builder(&I);
525   Builder.SetCurrentDebugLocation(I.getDebugLoc());
526 
527   Type *I32Ty = getI32Ty(Builder, I.getOperand(0)->getType());
528   Value *ExtOp0 = nullptr;
529   Value *ExtOp1 = nullptr;
530   Value *NewICmp  = nullptr;
531 
532   if (I.isSigned()) {
533     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
534     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
535   } else {
536     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
537     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
538   }
539   NewICmp = Builder.CreateICmp(I.getPredicate(), ExtOp0, ExtOp1);
540 
541   I.replaceAllUsesWith(NewICmp);
542   I.eraseFromParent();
543 
544   return true;
545 }
546 
547 bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(SelectInst &I) const {
548   assert(needsPromotionToI32(I.getType()) &&
549          "I does not need promotion to i32");
550 
551   IRBuilder<> Builder(&I);
552   Builder.SetCurrentDebugLocation(I.getDebugLoc());
553 
554   Type *I32Ty = getI32Ty(Builder, I.getType());
555   Value *ExtOp1 = nullptr;
556   Value *ExtOp2 = nullptr;
557   Value *ExtRes = nullptr;
558   Value *TruncRes = nullptr;
559 
560   if (isSigned(I)) {
561     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
562     ExtOp2 = Builder.CreateSExt(I.getOperand(2), I32Ty);
563   } else {
564     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
565     ExtOp2 = Builder.CreateZExt(I.getOperand(2), I32Ty);
566   }
567   ExtRes = Builder.CreateSelect(I.getOperand(0), ExtOp1, ExtOp2);
568   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
569 
570   I.replaceAllUsesWith(TruncRes);
571   I.eraseFromParent();
572 
573   return true;
574 }
575 
576 bool AMDGPUCodeGenPrepareImpl::promoteUniformBitreverseToI32(
577     IntrinsicInst &I) const {
578   assert(I.getIntrinsicID() == Intrinsic::bitreverse &&
579          "I must be bitreverse intrinsic");
580   assert(needsPromotionToI32(I.getType()) &&
581          "I does not need promotion to i32");
582 
583   IRBuilder<> Builder(&I);
584   Builder.SetCurrentDebugLocation(I.getDebugLoc());
585 
586   Type *I32Ty = getI32Ty(Builder, I.getType());
587   Value *ExtOp = Builder.CreateZExt(I.getOperand(0), I32Ty);
588   Value *ExtRes =
589       Builder.CreateIntrinsic(Intrinsic::bitreverse, {I32Ty}, {ExtOp});
590   Value *LShrOp =
591       Builder.CreateLShr(ExtRes, 32 - getBaseElementBitWidth(I.getType()));
592   Value *TruncRes =
593       Builder.CreateTrunc(LShrOp, I.getType());
594 
595   I.replaceAllUsesWith(TruncRes);
596   I.eraseFromParent();
597 
598   return true;
599 }
600 
601 unsigned AMDGPUCodeGenPrepareImpl::numBitsUnsigned(Value *Op) const {
602   return computeKnownBits(Op, DL, 0, AC).countMaxActiveBits();
603 }
604 
605 unsigned AMDGPUCodeGenPrepareImpl::numBitsSigned(Value *Op) const {
606   return ComputeMaxSignificantBits(Op, DL, 0, AC);
607 }
608 
609 static void extractValues(IRBuilder<> &Builder,
610                           SmallVectorImpl<Value *> &Values, Value *V) {
611   auto *VT = dyn_cast<FixedVectorType>(V->getType());
612   if (!VT) {
613     Values.push_back(V);
614     return;
615   }
616 
617   for (int I = 0, E = VT->getNumElements(); I != E; ++I)
618     Values.push_back(Builder.CreateExtractElement(V, I));
619 }
620 
621 static Value *insertValues(IRBuilder<> &Builder,
622                            Type *Ty,
623                            SmallVectorImpl<Value *> &Values) {
624   if (!Ty->isVectorTy()) {
625     assert(Values.size() == 1);
626     return Values[0];
627   }
628 
629   Value *NewVal = PoisonValue::get(Ty);
630   for (int I = 0, E = Values.size(); I != E; ++I)
631     NewVal = Builder.CreateInsertElement(NewVal, Values[I], I);
632 
633   return NewVal;
634 }
635 
636 bool AMDGPUCodeGenPrepareImpl::replaceMulWithMul24(BinaryOperator &I) const {
637   if (I.getOpcode() != Instruction::Mul)
638     return false;
639 
640   Type *Ty = I.getType();
641   unsigned Size = Ty->getScalarSizeInBits();
642   if (Size <= 16 && ST.has16BitInsts())
643     return false;
644 
645   // Prefer scalar if this could be s_mul_i32
646   if (UA.isUniform(&I))
647     return false;
648 
649   Value *LHS = I.getOperand(0);
650   Value *RHS = I.getOperand(1);
651   IRBuilder<> Builder(&I);
652   Builder.SetCurrentDebugLocation(I.getDebugLoc());
653 
654   unsigned LHSBits = 0, RHSBits = 0;
655   bool IsSigned = false;
656 
657   if (ST.hasMulU24() && (LHSBits = numBitsUnsigned(LHS)) <= 24 &&
658       (RHSBits = numBitsUnsigned(RHS)) <= 24) {
659     IsSigned = false;
660 
661   } else if (ST.hasMulI24() && (LHSBits = numBitsSigned(LHS)) <= 24 &&
662              (RHSBits = numBitsSigned(RHS)) <= 24) {
663     IsSigned = true;
664 
665   } else
666     return false;
667 
668   SmallVector<Value *, 4> LHSVals;
669   SmallVector<Value *, 4> RHSVals;
670   SmallVector<Value *, 4> ResultVals;
671   extractValues(Builder, LHSVals, LHS);
672   extractValues(Builder, RHSVals, RHS);
673 
674   IntegerType *I32Ty = Builder.getInt32Ty();
675   IntegerType *IntrinTy = Size > 32 ? Builder.getInt64Ty() : I32Ty;
676   Type *DstTy = LHSVals[0]->getType();
677 
678   for (int I = 0, E = LHSVals.size(); I != E; ++I) {
679     Value *LHS = IsSigned ? Builder.CreateSExtOrTrunc(LHSVals[I], I32Ty)
680                           : Builder.CreateZExtOrTrunc(LHSVals[I], I32Ty);
681     Value *RHS = IsSigned ? Builder.CreateSExtOrTrunc(RHSVals[I], I32Ty)
682                           : Builder.CreateZExtOrTrunc(RHSVals[I], I32Ty);
683     Intrinsic::ID ID =
684         IsSigned ? Intrinsic::amdgcn_mul_i24 : Intrinsic::amdgcn_mul_u24;
685     Value *Result = Builder.CreateIntrinsic(ID, {IntrinTy}, {LHS, RHS});
686     Result = IsSigned ? Builder.CreateSExtOrTrunc(Result, DstTy)
687                       : Builder.CreateZExtOrTrunc(Result, DstTy);
688     ResultVals.push_back(Result);
689   }
690 
691   Value *NewVal = insertValues(Builder, Ty, ResultVals);
692   NewVal->takeName(&I);
693   I.replaceAllUsesWith(NewVal);
694   I.eraseFromParent();
695 
696   return true;
697 }
698 
699 // Find a select instruction, which may have been casted. This is mostly to deal
700 // with cases where i16 selects were promoted here to i32.
701 static SelectInst *findSelectThroughCast(Value *V, CastInst *&Cast) {
702   Cast = nullptr;
703   if (SelectInst *Sel = dyn_cast<SelectInst>(V))
704     return Sel;
705 
706   if ((Cast = dyn_cast<CastInst>(V))) {
707     if (SelectInst *Sel = dyn_cast<SelectInst>(Cast->getOperand(0)))
708       return Sel;
709   }
710 
711   return nullptr;
712 }
713 
714 bool AMDGPUCodeGenPrepareImpl::foldBinOpIntoSelect(BinaryOperator &BO) const {
715   // Don't do this unless the old select is going away. We want to eliminate the
716   // binary operator, not replace a binop with a select.
717   int SelOpNo = 0;
718 
719   CastInst *CastOp;
720 
721   // TODO: Should probably try to handle some cases with multiple
722   // users. Duplicating the select may be profitable for division.
723   SelectInst *Sel = findSelectThroughCast(BO.getOperand(0), CastOp);
724   if (!Sel || !Sel->hasOneUse()) {
725     SelOpNo = 1;
726     Sel = findSelectThroughCast(BO.getOperand(1), CastOp);
727   }
728 
729   if (!Sel || !Sel->hasOneUse())
730     return false;
731 
732   Constant *CT = dyn_cast<Constant>(Sel->getTrueValue());
733   Constant *CF = dyn_cast<Constant>(Sel->getFalseValue());
734   Constant *CBO = dyn_cast<Constant>(BO.getOperand(SelOpNo ^ 1));
735   if (!CBO || !CT || !CF)
736     return false;
737 
738   if (CastOp) {
739     if (!CastOp->hasOneUse())
740       return false;
741     CT = ConstantFoldCastOperand(CastOp->getOpcode(), CT, BO.getType(), DL);
742     CF = ConstantFoldCastOperand(CastOp->getOpcode(), CF, BO.getType(), DL);
743   }
744 
745   // TODO: Handle special 0/-1 cases DAG combine does, although we only really
746   // need to handle divisions here.
747   Constant *FoldedT =
748       SelOpNo ? ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CT, DL)
749               : ConstantFoldBinaryOpOperands(BO.getOpcode(), CT, CBO, DL);
750   if (!FoldedT || isa<ConstantExpr>(FoldedT))
751     return false;
752 
753   Constant *FoldedF =
754       SelOpNo ? ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CF, DL)
755               : ConstantFoldBinaryOpOperands(BO.getOpcode(), CF, CBO, DL);
756   if (!FoldedF || isa<ConstantExpr>(FoldedF))
757     return false;
758 
759   IRBuilder<> Builder(&BO);
760   Builder.SetCurrentDebugLocation(BO.getDebugLoc());
761   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&BO))
762     Builder.setFastMathFlags(FPOp->getFastMathFlags());
763 
764   Value *NewSelect = Builder.CreateSelect(Sel->getCondition(),
765                                           FoldedT, FoldedF);
766   NewSelect->takeName(&BO);
767   BO.replaceAllUsesWith(NewSelect);
768   BO.eraseFromParent();
769   if (CastOp)
770     CastOp->eraseFromParent();
771   Sel->eraseFromParent();
772   return true;
773 }
774 
775 std::pair<Value *, Value *>
776 AMDGPUCodeGenPrepareImpl::getFrexpResults(IRBuilder<> &Builder,
777                                           Value *Src) const {
778   Type *Ty = Src->getType();
779   Value *Frexp = Builder.CreateIntrinsic(Intrinsic::frexp,
780                                          {Ty, Builder.getInt32Ty()}, Src);
781   Value *FrexpMant = Builder.CreateExtractValue(Frexp, {0});
782 
783   // Bypass the bug workaround for the exponent result since it doesn't matter.
784   // TODO: Does the bug workaround even really need to consider the exponent
785   // result? It's unspecified by the spec.
786 
787   Value *FrexpExp =
788       ST.hasFractBug()
789           ? Builder.CreateIntrinsic(Intrinsic::amdgcn_frexp_exp,
790                                     {Builder.getInt32Ty(), Ty}, Src)
791           : Builder.CreateExtractValue(Frexp, {1});
792   return {FrexpMant, FrexpExp};
793 }
794 
795 /// Emit an expansion of 1.0 / Src good for 1ulp that supports denormals.
796 Value *AMDGPUCodeGenPrepareImpl::emitRcpIEEE1ULP(IRBuilder<> &Builder,
797                                                  Value *Src,
798                                                  bool IsNegative) const {
799   // Same as for 1.0, but expand the sign out of the constant.
800   // -1.0 / x -> rcp (fneg x)
801   if (IsNegative)
802     Src = Builder.CreateFNeg(Src);
803 
804   // The rcp instruction doesn't support denormals, so scale the input
805   // out of the denormal range and convert at the end.
806   //
807   // Expand as 2^-n * (1.0 / (x * 2^n))
808 
809   // TODO: Skip scaling if input is known never denormal and the input
810   // range won't underflow to denormal. The hard part is knowing the
811   // result. We need a range check, the result could be denormal for
812   // 0x1p+126 < den <= 0x1p+127.
813   auto [FrexpMant, FrexpExp] = getFrexpResults(Builder, Src);
814   Value *ScaleFactor = Builder.CreateNeg(FrexpExp);
815   Value *Rcp = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, FrexpMant);
816   return Builder.CreateCall(getLdexpF32(), {Rcp, ScaleFactor});
817 }
818 
819 /// Emit a 2ulp expansion for fdiv by using frexp for input scaling.
820 Value *AMDGPUCodeGenPrepareImpl::emitFrexpDiv(IRBuilder<> &Builder, Value *LHS,
821                                               Value *RHS,
822                                               FastMathFlags FMF) const {
823   // If we have have to work around the fract/frexp bug, we're worse off than
824   // using the fdiv.fast expansion. The full safe expansion is faster if we have
825   // fast FMA.
826   if (HasFP32DenormalFlush && ST.hasFractBug() && !ST.hasFastFMAF32() &&
827       (!FMF.noNaNs() || !FMF.noInfs()))
828     return nullptr;
829 
830   // We're scaling the LHS to avoid a denormal input, and scale the denominator
831   // to avoid large values underflowing the result.
832   auto [FrexpMantRHS, FrexpExpRHS] = getFrexpResults(Builder, RHS);
833 
834   Value *Rcp =
835       Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, FrexpMantRHS);
836 
837   auto [FrexpMantLHS, FrexpExpLHS] = getFrexpResults(Builder, LHS);
838   Value *Mul = Builder.CreateFMul(FrexpMantLHS, Rcp);
839 
840   // We multiplied by 2^N/2^M, so we need to multiply by 2^(N-M) to scale the
841   // result.
842   Value *ExpDiff = Builder.CreateSub(FrexpExpLHS, FrexpExpRHS);
843   return Builder.CreateCall(getLdexpF32(), {Mul, ExpDiff});
844 }
845 
846 /// Emit a sqrt that handles denormals and is accurate to 2ulp.
847 Value *AMDGPUCodeGenPrepareImpl::emitSqrtIEEE2ULP(IRBuilder<> &Builder,
848                                                   Value *Src,
849                                                   FastMathFlags FMF) const {
850   Type *Ty = Src->getType();
851   APFloat SmallestNormal =
852       APFloat::getSmallestNormalized(Ty->getFltSemantics());
853   Value *NeedScale =
854       Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
855 
856   ConstantInt *Zero = Builder.getInt32(0);
857   Value *InputScaleFactor =
858       Builder.CreateSelect(NeedScale, Builder.getInt32(32), Zero);
859 
860   Value *Scaled = Builder.CreateCall(getLdexpF32(), {Src, InputScaleFactor});
861 
862   Value *Sqrt = Builder.CreateCall(getSqrtF32(), Scaled);
863 
864   Value *OutputScaleFactor =
865       Builder.CreateSelect(NeedScale, Builder.getInt32(-16), Zero);
866   return Builder.CreateCall(getLdexpF32(), {Sqrt, OutputScaleFactor});
867 }
868 
869 /// Emit an expansion of 1.0 / sqrt(Src) good for 1ulp that supports denormals.
870 static Value *emitRsqIEEE1ULP(IRBuilder<> &Builder, Value *Src,
871                               bool IsNegative) {
872   // bool need_scale = x < 0x1p-126f;
873   // float input_scale = need_scale ? 0x1.0p+24f : 1.0f;
874   // float output_scale = need_scale ? 0x1.0p+12f : 1.0f;
875   // rsq(x * input_scale) * output_scale;
876 
877   Type *Ty = Src->getType();
878   APFloat SmallestNormal =
879       APFloat::getSmallestNormalized(Ty->getFltSemantics());
880   Value *NeedScale =
881       Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
882   Constant *One = ConstantFP::get(Ty, 1.0);
883   Constant *InputScale = ConstantFP::get(Ty, 0x1.0p+24);
884   Constant *OutputScale =
885       ConstantFP::get(Ty, IsNegative ? -0x1.0p+12 : 0x1.0p+12);
886 
887   Value *InputScaleFactor = Builder.CreateSelect(NeedScale, InputScale, One);
888 
889   Value *ScaledInput = Builder.CreateFMul(Src, InputScaleFactor);
890   Value *Rsq = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, ScaledInput);
891   Value *OutputScaleFactor = Builder.CreateSelect(
892       NeedScale, OutputScale, IsNegative ? ConstantFP::get(Ty, -1.0) : One);
893 
894   return Builder.CreateFMul(Rsq, OutputScaleFactor);
895 }
896 
897 bool AMDGPUCodeGenPrepareImpl::canOptimizeWithRsq(const FPMathOperator *SqrtOp,
898                                                   FastMathFlags DivFMF,
899                                                   FastMathFlags SqrtFMF) const {
900   // The rsqrt contraction increases accuracy from ~2ulp to ~1ulp.
901   if (!DivFMF.allowContract() || !SqrtFMF.allowContract())
902     return false;
903 
904   // v_rsq_f32 gives 1ulp
905   return SqrtFMF.approxFunc() || HasUnsafeFPMath ||
906          SqrtOp->getFPAccuracy() >= 1.0f;
907 }
908 
909 Value *AMDGPUCodeGenPrepareImpl::optimizeWithRsq(
910     IRBuilder<> &Builder, Value *Num, Value *Den, const FastMathFlags DivFMF,
911     const FastMathFlags SqrtFMF, const Instruction *CtxI) const {
912   // The rsqrt contraction increases accuracy from ~2ulp to ~1ulp.
913   assert(DivFMF.allowContract() && SqrtFMF.allowContract());
914 
915   // rsq_f16 is accurate to 0.51 ulp.
916   // rsq_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
917   // rsq_f64 is never accurate.
918   const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num);
919   if (!CLHS)
920     return nullptr;
921 
922   assert(Den->getType()->isFloatTy());
923 
924   bool IsNegative = false;
925 
926   // TODO: Handle other numerator values with arcp.
927   if (CLHS->isExactlyValue(1.0) || (IsNegative = CLHS->isExactlyValue(-1.0))) {
928     // Add in the sqrt flags.
929     IRBuilder<>::FastMathFlagGuard Guard(Builder);
930     Builder.setFastMathFlags(DivFMF | SqrtFMF);
931 
932     if ((DivFMF.approxFunc() && SqrtFMF.approxFunc()) || HasUnsafeFPMath ||
933         canIgnoreDenormalInput(Den, CtxI)) {
934       Value *Result = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, Den);
935       // -1.0 / sqrt(x) -> fneg(rsq(x))
936       return IsNegative ? Builder.CreateFNeg(Result) : Result;
937     }
938 
939     return emitRsqIEEE1ULP(Builder, Den, IsNegative);
940   }
941 
942   return nullptr;
943 }
944 
945 // Optimize fdiv with rcp:
946 //
947 // 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
948 //               allowed with unsafe-fp-math or afn.
949 //
950 // a/b -> a*rcp(b) when arcp is allowed, and we only need provide ULP 1.0
951 Value *
952 AMDGPUCodeGenPrepareImpl::optimizeWithRcp(IRBuilder<> &Builder, Value *Num,
953                                           Value *Den, FastMathFlags FMF,
954                                           const Instruction *CtxI) const {
955   // rcp_f16 is accurate to 0.51 ulp.
956   // rcp_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
957   // rcp_f64 is never accurate.
958   assert(Den->getType()->isFloatTy());
959 
960   if (const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num)) {
961     bool IsNegative = false;
962     if (CLHS->isExactlyValue(1.0) ||
963         (IsNegative = CLHS->isExactlyValue(-1.0))) {
964       Value *Src = Den;
965 
966       if (HasFP32DenormalFlush || FMF.approxFunc()) {
967         // -1.0 / x -> 1.0 / fneg(x)
968         if (IsNegative)
969           Src = Builder.CreateFNeg(Src);
970 
971         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
972         // the CI documentation has a worst case error of 1 ulp.
973         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK
974         // to use it as long as we aren't trying to use denormals.
975         //
976         // v_rcp_f16 and v_rsq_f16 DO support denormals.
977 
978         // NOTE: v_sqrt and v_rcp will be combined to v_rsq later. So we don't
979         //       insert rsq intrinsic here.
980 
981         // 1.0 / x -> rcp(x)
982         return Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, Src);
983       }
984 
985       // TODO: If the input isn't denormal, and we know the input exponent isn't
986       // big enough to introduce a denormal we can avoid the scaling.
987       return emitRcpIEEE1ULP(Builder, Src, IsNegative);
988     }
989   }
990 
991   if (FMF.allowReciprocal()) {
992     // x / y -> x * (1.0 / y)
993 
994     // TODO: Could avoid denormal scaling and use raw rcp if we knew the output
995     // will never underflow.
996     if (HasFP32DenormalFlush || FMF.approxFunc()) {
997       Value *Recip = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, Den);
998       return Builder.CreateFMul(Num, Recip);
999     }
1000 
1001     Value *Recip = emitRcpIEEE1ULP(Builder, Den, false);
1002     return Builder.CreateFMul(Num, Recip);
1003   }
1004 
1005   return nullptr;
1006 }
1007 
1008 // optimize with fdiv.fast:
1009 //
1010 // a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
1011 //
1012 // 1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
1013 //
1014 // NOTE: optimizeWithRcp should be tried first because rcp is the preference.
1015 Value *AMDGPUCodeGenPrepareImpl::optimizeWithFDivFast(
1016     IRBuilder<> &Builder, Value *Num, Value *Den, float ReqdAccuracy) const {
1017   // fdiv.fast can achieve 2.5 ULP accuracy.
1018   if (ReqdAccuracy < 2.5f)
1019     return nullptr;
1020 
1021   // Only have fdiv.fast for f32.
1022   assert(Den->getType()->isFloatTy());
1023 
1024   bool NumIsOne = false;
1025   if (const ConstantFP *CNum = dyn_cast<ConstantFP>(Num)) {
1026     if (CNum->isExactlyValue(+1.0) || CNum->isExactlyValue(-1.0))
1027       NumIsOne = true;
1028   }
1029 
1030   // fdiv does not support denormals. But 1.0/x is always fine to use it.
1031   //
1032   // TODO: This works for any value with a specific known exponent range, don't
1033   // just limit to constant 1.
1034   if (!HasFP32DenormalFlush && !NumIsOne)
1035     return nullptr;
1036 
1037   return Builder.CreateIntrinsic(Intrinsic::amdgcn_fdiv_fast, {}, {Num, Den});
1038 }
1039 
1040 Value *AMDGPUCodeGenPrepareImpl::visitFDivElement(
1041     IRBuilder<> &Builder, Value *Num, Value *Den, FastMathFlags DivFMF,
1042     FastMathFlags SqrtFMF, Value *RsqOp, const Instruction *FDivInst,
1043     float ReqdDivAccuracy) const {
1044   if (RsqOp) {
1045     Value *Rsq =
1046         optimizeWithRsq(Builder, Num, RsqOp, DivFMF, SqrtFMF, FDivInst);
1047     if (Rsq)
1048       return Rsq;
1049   }
1050 
1051   Value *Rcp = optimizeWithRcp(Builder, Num, Den, DivFMF, FDivInst);
1052   if (Rcp)
1053     return Rcp;
1054 
1055   // In the basic case fdiv_fast has the same instruction count as the frexp div
1056   // expansion. Slightly prefer fdiv_fast since it ends in an fmul that can
1057   // potentially be fused into a user. Also, materialization of the constants
1058   // can be reused for multiple instances.
1059   Value *FDivFast = optimizeWithFDivFast(Builder, Num, Den, ReqdDivAccuracy);
1060   if (FDivFast)
1061     return FDivFast;
1062 
1063   return emitFrexpDiv(Builder, Num, Den, DivFMF);
1064 }
1065 
1066 // Optimizations is performed based on fpmath, fast math flags as well as
1067 // denormals to optimize fdiv with either rcp or fdiv.fast.
1068 //
1069 // With rcp:
1070 //   1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
1071 //                 allowed with unsafe-fp-math or afn.
1072 //
1073 //   a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
1074 //
1075 // With fdiv.fast:
1076 //   a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
1077 //
1078 //   1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
1079 //
1080 // NOTE: rcp is the preference in cases that both are legal.
1081 bool AMDGPUCodeGenPrepareImpl::visitFDiv(BinaryOperator &FDiv) {
1082   if (DisableFDivExpand)
1083     return false;
1084 
1085   Type *Ty = FDiv.getType()->getScalarType();
1086   if (!Ty->isFloatTy())
1087     return false;
1088 
1089   // The f64 rcp/rsq approximations are pretty inaccurate. We can do an
1090   // expansion around them in codegen. f16 is good enough to always use.
1091 
1092   const FPMathOperator *FPOp = cast<const FPMathOperator>(&FDiv);
1093   const FastMathFlags DivFMF = FPOp->getFastMathFlags();
1094   const float ReqdAccuracy = FPOp->getFPAccuracy();
1095 
1096   FastMathFlags SqrtFMF;
1097 
1098   Value *Num = FDiv.getOperand(0);
1099   Value *Den = FDiv.getOperand(1);
1100 
1101   Value *RsqOp = nullptr;
1102   auto *DenII = dyn_cast<IntrinsicInst>(Den);
1103   if (DenII && DenII->getIntrinsicID() == Intrinsic::sqrt &&
1104       DenII->hasOneUse()) {
1105     const auto *SqrtOp = cast<FPMathOperator>(DenII);
1106     SqrtFMF = SqrtOp->getFastMathFlags();
1107     if (canOptimizeWithRsq(SqrtOp, DivFMF, SqrtFMF))
1108       RsqOp = SqrtOp->getOperand(0);
1109   }
1110 
1111   // Inaccurate rcp is allowed with unsafe-fp-math or afn.
1112   //
1113   // Defer to codegen to handle this.
1114   //
1115   // TODO: Decide on an interpretation for interactions between afn + arcp +
1116   // !fpmath, and make it consistent between here and codegen. For now, defer
1117   // expansion of afn to codegen. The current interpretation is so aggressive we
1118   // don't need any pre-consideration here when we have better information. A
1119   // more conservative interpretation could use handling here.
1120   const bool AllowInaccurateRcp = HasUnsafeFPMath || DivFMF.approxFunc();
1121   if (!RsqOp && AllowInaccurateRcp)
1122     return false;
1123 
1124   // Defer the correct implementations to codegen.
1125   if (ReqdAccuracy < 1.0f)
1126     return false;
1127 
1128   IRBuilder<> Builder(FDiv.getParent(), std::next(FDiv.getIterator()));
1129   Builder.setFastMathFlags(DivFMF);
1130   Builder.SetCurrentDebugLocation(FDiv.getDebugLoc());
1131 
1132   SmallVector<Value *, 4> NumVals;
1133   SmallVector<Value *, 4> DenVals;
1134   SmallVector<Value *, 4> RsqDenVals;
1135   extractValues(Builder, NumVals, Num);
1136   extractValues(Builder, DenVals, Den);
1137 
1138   if (RsqOp)
1139     extractValues(Builder, RsqDenVals, RsqOp);
1140 
1141   SmallVector<Value *, 4> ResultVals(NumVals.size());
1142   for (int I = 0, E = NumVals.size(); I != E; ++I) {
1143     Value *NumElt = NumVals[I];
1144     Value *DenElt = DenVals[I];
1145     Value *RsqDenElt = RsqOp ? RsqDenVals[I] : nullptr;
1146 
1147     Value *NewElt =
1148         visitFDivElement(Builder, NumElt, DenElt, DivFMF, SqrtFMF, RsqDenElt,
1149                          cast<Instruction>(FPOp), ReqdAccuracy);
1150     if (!NewElt) {
1151       // Keep the original, but scalarized.
1152 
1153       // This has the unfortunate side effect of sometimes scalarizing when
1154       // we're not going to do anything.
1155       NewElt = Builder.CreateFDiv(NumElt, DenElt);
1156       if (auto *NewEltInst = dyn_cast<Instruction>(NewElt))
1157         NewEltInst->copyMetadata(FDiv);
1158     }
1159 
1160     ResultVals[I] = NewElt;
1161   }
1162 
1163   Value *NewVal = insertValues(Builder, FDiv.getType(), ResultVals);
1164 
1165   if (NewVal) {
1166     FDiv.replaceAllUsesWith(NewVal);
1167     NewVal->takeName(&FDiv);
1168     RecursivelyDeleteTriviallyDeadInstructions(&FDiv, TLI);
1169   }
1170 
1171   return true;
1172 }
1173 
1174 static std::pair<Value*, Value*> getMul64(IRBuilder<> &Builder,
1175                                           Value *LHS, Value *RHS) {
1176   Type *I32Ty = Builder.getInt32Ty();
1177   Type *I64Ty = Builder.getInt64Ty();
1178 
1179   Value *LHS_EXT64 = Builder.CreateZExt(LHS, I64Ty);
1180   Value *RHS_EXT64 = Builder.CreateZExt(RHS, I64Ty);
1181   Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64);
1182   Value *Lo = Builder.CreateTrunc(MUL64, I32Ty);
1183   Value *Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32));
1184   Hi = Builder.CreateTrunc(Hi, I32Ty);
1185   return std::pair(Lo, Hi);
1186 }
1187 
1188 static Value* getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS) {
1189   return getMul64(Builder, LHS, RHS).second;
1190 }
1191 
1192 /// Figure out how many bits are really needed for this division. \p AtLeast is
1193 /// an optimization hint to bypass the second ComputeNumSignBits call if we the
1194 /// first one is insufficient. Returns -1 on failure.
1195 int AMDGPUCodeGenPrepareImpl::getDivNumBits(BinaryOperator &I, Value *Num,
1196                                             Value *Den, unsigned AtLeast,
1197                                             bool IsSigned) const {
1198   unsigned LHSSignBits = ComputeNumSignBits(Num, DL, 0, AC, &I);
1199   if (LHSSignBits < AtLeast)
1200     return -1;
1201 
1202   unsigned RHSSignBits = ComputeNumSignBits(Den, DL, 0, AC, &I);
1203   if (RHSSignBits < AtLeast)
1204     return -1;
1205 
1206   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
1207   unsigned DivBits = Num->getType()->getScalarSizeInBits() - SignBits;
1208   if (IsSigned)
1209     ++DivBits;
1210   return DivBits;
1211 }
1212 
1213 // The fractional part of a float is enough to accurately represent up to
1214 // a 24-bit signed integer.
1215 Value *AMDGPUCodeGenPrepareImpl::expandDivRem24(IRBuilder<> &Builder,
1216                                                 BinaryOperator &I, Value *Num,
1217                                                 Value *Den, bool IsDiv,
1218                                                 bool IsSigned) const {
1219   unsigned SSBits = Num->getType()->getScalarSizeInBits();
1220   // If Num bits <= 24, assume 0 signbits.
1221   unsigned AtLeast = (SSBits <= 24) ? 0 : (SSBits - 24 + IsSigned);
1222   int DivBits = getDivNumBits(I, Num, Den, AtLeast, IsSigned);
1223   if (DivBits == -1)
1224     return nullptr;
1225   return expandDivRem24Impl(Builder, I, Num, Den, DivBits, IsDiv, IsSigned);
1226 }
1227 
1228 Value *AMDGPUCodeGenPrepareImpl::expandDivRem24Impl(
1229     IRBuilder<> &Builder, BinaryOperator &I, Value *Num, Value *Den,
1230     unsigned DivBits, bool IsDiv, bool IsSigned) const {
1231   Type *I32Ty = Builder.getInt32Ty();
1232   Num = Builder.CreateTrunc(Num, I32Ty);
1233   Den = Builder.CreateTrunc(Den, I32Ty);
1234 
1235   Type *F32Ty = Builder.getFloatTy();
1236   ConstantInt *One = Builder.getInt32(1);
1237   Value *JQ = One;
1238 
1239   if (IsSigned) {
1240     // char|short jq = ia ^ ib;
1241     JQ = Builder.CreateXor(Num, Den);
1242 
1243     // jq = jq >> (bitsize - 2)
1244     JQ = Builder.CreateAShr(JQ, Builder.getInt32(30));
1245 
1246     // jq = jq | 0x1
1247     JQ = Builder.CreateOr(JQ, One);
1248   }
1249 
1250   // int ia = (int)LHS;
1251   Value *IA = Num;
1252 
1253   // int ib, (int)RHS;
1254   Value *IB = Den;
1255 
1256   // float fa = (float)ia;
1257   Value *FA = IsSigned ? Builder.CreateSIToFP(IA, F32Ty)
1258                        : Builder.CreateUIToFP(IA, F32Ty);
1259 
1260   // float fb = (float)ib;
1261   Value *FB = IsSigned ? Builder.CreateSIToFP(IB,F32Ty)
1262                        : Builder.CreateUIToFP(IB,F32Ty);
1263 
1264   Value *RCP = Builder.CreateIntrinsic(Intrinsic::amdgcn_rcp,
1265                                        Builder.getFloatTy(), {FB});
1266   Value *FQM = Builder.CreateFMul(FA, RCP);
1267 
1268   // fq = trunc(fqm);
1269   CallInst *FQ = Builder.CreateUnaryIntrinsic(Intrinsic::trunc, FQM);
1270   FQ->copyFastMathFlags(Builder.getFastMathFlags());
1271 
1272   // float fqneg = -fq;
1273   Value *FQNeg = Builder.CreateFNeg(FQ);
1274 
1275   // float fr = mad(fqneg, fb, fa);
1276   auto FMAD = !ST.hasMadMacF32Insts()
1277                   ? Intrinsic::fma
1278                   : (Intrinsic::ID)Intrinsic::amdgcn_fmad_ftz;
1279   Value *FR = Builder.CreateIntrinsic(FMAD,
1280                                       {FQNeg->getType()}, {FQNeg, FB, FA}, FQ);
1281 
1282   // int iq = (int)fq;
1283   Value *IQ = IsSigned ? Builder.CreateFPToSI(FQ, I32Ty)
1284                        : Builder.CreateFPToUI(FQ, I32Ty);
1285 
1286   // fr = fabs(fr);
1287   FR = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FR, FQ);
1288 
1289   // fb = fabs(fb);
1290   FB = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FB, FQ);
1291 
1292   // int cv = fr >= fb;
1293   Value *CV = Builder.CreateFCmpOGE(FR, FB);
1294 
1295   // jq = (cv ? jq : 0);
1296   JQ = Builder.CreateSelect(CV, JQ, Builder.getInt32(0));
1297 
1298   // dst = iq + jq;
1299   Value *Div = Builder.CreateAdd(IQ, JQ);
1300 
1301   Value *Res = Div;
1302   if (!IsDiv) {
1303     // Rem needs compensation, it's easier to recompute it
1304     Value *Rem = Builder.CreateMul(Div, Den);
1305     Res = Builder.CreateSub(Num, Rem);
1306   }
1307 
1308   if (DivBits != 0 && DivBits < 32) {
1309     // Extend in register from the number of bits this divide really is.
1310     if (IsSigned) {
1311       int InRegBits = 32 - DivBits;
1312 
1313       Res = Builder.CreateShl(Res, InRegBits);
1314       Res = Builder.CreateAShr(Res, InRegBits);
1315     } else {
1316       ConstantInt *TruncMask
1317         = Builder.getInt32((UINT64_C(1) << DivBits) - 1);
1318       Res = Builder.CreateAnd(Res, TruncMask);
1319     }
1320   }
1321 
1322   return Res;
1323 }
1324 
1325 // Try to recognize special cases the DAG will emit special, better expansions
1326 // than the general expansion we do here.
1327 
1328 // TODO: It would be better to just directly handle those optimizations here.
1329 bool AMDGPUCodeGenPrepareImpl::divHasSpecialOptimization(BinaryOperator &I,
1330                                                          Value *Num,
1331                                                          Value *Den) const {
1332   if (Constant *C = dyn_cast<Constant>(Den)) {
1333     // Arbitrary constants get a better expansion as long as a wider mulhi is
1334     // legal.
1335     if (C->getType()->getScalarSizeInBits() <= 32)
1336       return true;
1337 
1338     // TODO: Sdiv check for not exact for some reason.
1339 
1340     // If there's no wider mulhi, there's only a better expansion for powers of
1341     // two.
1342     // TODO: Should really know for each vector element.
1343     if (isKnownToBeAPowerOfTwo(C, DL, true, 0, AC, &I, DT))
1344       return true;
1345 
1346     return false;
1347   }
1348 
1349   if (BinaryOperator *BinOpDen = dyn_cast<BinaryOperator>(Den)) {
1350     // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1351     if (BinOpDen->getOpcode() == Instruction::Shl &&
1352         isa<Constant>(BinOpDen->getOperand(0)) &&
1353         isKnownToBeAPowerOfTwo(BinOpDen->getOperand(0), DL, true, 0, AC, &I,
1354                                DT)) {
1355       return true;
1356     }
1357   }
1358 
1359   return false;
1360 }
1361 
1362 static Value *getSign32(Value *V, IRBuilder<> &Builder, const DataLayout DL) {
1363   // Check whether the sign can be determined statically.
1364   KnownBits Known = computeKnownBits(V, DL);
1365   if (Known.isNegative())
1366     return Constant::getAllOnesValue(V->getType());
1367   if (Known.isNonNegative())
1368     return Constant::getNullValue(V->getType());
1369   return Builder.CreateAShr(V, Builder.getInt32(31));
1370 }
1371 
1372 Value *AMDGPUCodeGenPrepareImpl::expandDivRem32(IRBuilder<> &Builder,
1373                                                 BinaryOperator &I, Value *X,
1374                                                 Value *Y) const {
1375   Instruction::BinaryOps Opc = I.getOpcode();
1376   assert(Opc == Instruction::URem || Opc == Instruction::UDiv ||
1377          Opc == Instruction::SRem || Opc == Instruction::SDiv);
1378 
1379   FastMathFlags FMF;
1380   FMF.setFast();
1381   Builder.setFastMathFlags(FMF);
1382 
1383   if (divHasSpecialOptimization(I, X, Y))
1384     return nullptr;  // Keep it for later optimization.
1385 
1386   bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv;
1387   bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv;
1388 
1389   Type *Ty = X->getType();
1390   Type *I32Ty = Builder.getInt32Ty();
1391   Type *F32Ty = Builder.getFloatTy();
1392 
1393   if (Ty->getScalarSizeInBits() != 32) {
1394     if (IsSigned) {
1395       X = Builder.CreateSExtOrTrunc(X, I32Ty);
1396       Y = Builder.CreateSExtOrTrunc(Y, I32Ty);
1397     } else {
1398       X = Builder.CreateZExtOrTrunc(X, I32Ty);
1399       Y = Builder.CreateZExtOrTrunc(Y, I32Ty);
1400     }
1401   }
1402 
1403   if (Value *Res = expandDivRem24(Builder, I, X, Y, IsDiv, IsSigned)) {
1404     return IsSigned ? Builder.CreateSExtOrTrunc(Res, Ty) :
1405                       Builder.CreateZExtOrTrunc(Res, Ty);
1406   }
1407 
1408   ConstantInt *Zero = Builder.getInt32(0);
1409   ConstantInt *One = Builder.getInt32(1);
1410 
1411   Value *Sign = nullptr;
1412   if (IsSigned) {
1413     Value *SignX = getSign32(X, Builder, DL);
1414     Value *SignY = getSign32(Y, Builder, DL);
1415     // Remainder sign is the same as LHS
1416     Sign = IsDiv ? Builder.CreateXor(SignX, SignY) : SignX;
1417 
1418     X = Builder.CreateAdd(X, SignX);
1419     Y = Builder.CreateAdd(Y, SignY);
1420 
1421     X = Builder.CreateXor(X, SignX);
1422     Y = Builder.CreateXor(Y, SignY);
1423   }
1424 
1425   // The algorithm here is based on ideas from "Software Integer Division", Tom
1426   // Rodeheffer, August 2008.
1427   //
1428   // unsigned udiv(unsigned x, unsigned y) {
1429   //   // Initial estimate of inv(y). The constant is less than 2^32 to ensure
1430   //   // that this is a lower bound on inv(y), even if some of the calculations
1431   //   // round up.
1432   //   unsigned z = (unsigned)((4294967296.0 - 512.0) * v_rcp_f32((float)y));
1433   //
1434   //   // One round of UNR (Unsigned integer Newton-Raphson) to improve z.
1435   //   // Empirically this is guaranteed to give a "two-y" lower bound on
1436   //   // inv(y).
1437   //   z += umulh(z, -y * z);
1438   //
1439   //   // Quotient/remainder estimate.
1440   //   unsigned q = umulh(x, z);
1441   //   unsigned r = x - q * y;
1442   //
1443   //   // Two rounds of quotient/remainder refinement.
1444   //   if (r >= y) {
1445   //     ++q;
1446   //     r -= y;
1447   //   }
1448   //   if (r >= y) {
1449   //     ++q;
1450   //     r -= y;
1451   //   }
1452   //
1453   //   return q;
1454   // }
1455 
1456   // Initial estimate of inv(y).
1457   Value *FloatY = Builder.CreateUIToFP(Y, F32Ty);
1458   Value *RcpY = Builder.CreateIntrinsic(Intrinsic::amdgcn_rcp, F32Ty, {FloatY});
1459   Constant *Scale = ConstantFP::get(F32Ty, llvm::bit_cast<float>(0x4F7FFFFE));
1460   Value *ScaledY = Builder.CreateFMul(RcpY, Scale);
1461   Value *Z = Builder.CreateFPToUI(ScaledY, I32Ty);
1462 
1463   // One round of UNR.
1464   Value *NegY = Builder.CreateSub(Zero, Y);
1465   Value *NegYZ = Builder.CreateMul(NegY, Z);
1466   Z = Builder.CreateAdd(Z, getMulHu(Builder, Z, NegYZ));
1467 
1468   // Quotient/remainder estimate.
1469   Value *Q = getMulHu(Builder, X, Z);
1470   Value *R = Builder.CreateSub(X, Builder.CreateMul(Q, Y));
1471 
1472   // First quotient/remainder refinement.
1473   Value *Cond = Builder.CreateICmpUGE(R, Y);
1474   if (IsDiv)
1475     Q = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
1476   R = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
1477 
1478   // Second quotient/remainder refinement.
1479   Cond = Builder.CreateICmpUGE(R, Y);
1480   Value *Res;
1481   if (IsDiv)
1482     Res = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
1483   else
1484     Res = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
1485 
1486   if (IsSigned) {
1487     Res = Builder.CreateXor(Res, Sign);
1488     Res = Builder.CreateSub(Res, Sign);
1489     Res = Builder.CreateSExtOrTrunc(Res, Ty);
1490   } else {
1491     Res = Builder.CreateZExtOrTrunc(Res, Ty);
1492   }
1493   return Res;
1494 }
1495 
1496 Value *AMDGPUCodeGenPrepareImpl::shrinkDivRem64(IRBuilder<> &Builder,
1497                                                 BinaryOperator &I, Value *Num,
1498                                                 Value *Den) const {
1499   if (!ExpandDiv64InIR && divHasSpecialOptimization(I, Num, Den))
1500     return nullptr;  // Keep it for later optimization.
1501 
1502   Instruction::BinaryOps Opc = I.getOpcode();
1503 
1504   bool IsDiv = Opc == Instruction::SDiv || Opc == Instruction::UDiv;
1505   bool IsSigned = Opc == Instruction::SDiv || Opc == Instruction::SRem;
1506 
1507   int NumDivBits = getDivNumBits(I, Num, Den, 32, IsSigned);
1508   if (NumDivBits == -1)
1509     return nullptr;
1510 
1511   Value *Narrowed = nullptr;
1512   if (NumDivBits <= 24) {
1513     Narrowed = expandDivRem24Impl(Builder, I, Num, Den, NumDivBits,
1514                                   IsDiv, IsSigned);
1515   } else if (NumDivBits <= 32) {
1516     Narrowed = expandDivRem32(Builder, I, Num, Den);
1517   }
1518 
1519   if (Narrowed) {
1520     return IsSigned ? Builder.CreateSExt(Narrowed, Num->getType()) :
1521                       Builder.CreateZExt(Narrowed, Num->getType());
1522   }
1523 
1524   return nullptr;
1525 }
1526 
1527 void AMDGPUCodeGenPrepareImpl::expandDivRem64(BinaryOperator &I) const {
1528   Instruction::BinaryOps Opc = I.getOpcode();
1529   // Do the general expansion.
1530   if (Opc == Instruction::UDiv || Opc == Instruction::SDiv) {
1531     expandDivisionUpTo64Bits(&I);
1532     return;
1533   }
1534 
1535   if (Opc == Instruction::URem || Opc == Instruction::SRem) {
1536     expandRemainderUpTo64Bits(&I);
1537     return;
1538   }
1539 
1540   llvm_unreachable("not a division");
1541 }
1542 
1543 bool AMDGPUCodeGenPrepareImpl::visitBinaryOperator(BinaryOperator &I) {
1544   if (foldBinOpIntoSelect(I))
1545     return true;
1546 
1547   if (ST.has16BitInsts() && needsPromotionToI32(I.getType()) &&
1548       UA.isUniform(&I) && promoteUniformOpToI32(I))
1549     return true;
1550 
1551   if (UseMul24Intrin && replaceMulWithMul24(I))
1552     return true;
1553 
1554   bool Changed = false;
1555   Instruction::BinaryOps Opc = I.getOpcode();
1556   Type *Ty = I.getType();
1557   Value *NewDiv = nullptr;
1558   unsigned ScalarSize = Ty->getScalarSizeInBits();
1559 
1560   SmallVector<BinaryOperator *, 8> Div64ToExpand;
1561 
1562   if ((Opc == Instruction::URem || Opc == Instruction::UDiv ||
1563        Opc == Instruction::SRem || Opc == Instruction::SDiv) &&
1564       ScalarSize <= 64 &&
1565       !DisableIDivExpand) {
1566     Value *Num = I.getOperand(0);
1567     Value *Den = I.getOperand(1);
1568     IRBuilder<> Builder(&I);
1569     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1570 
1571     if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1572       NewDiv = PoisonValue::get(VT);
1573 
1574       for (unsigned N = 0, E = VT->getNumElements(); N != E; ++N) {
1575         Value *NumEltN = Builder.CreateExtractElement(Num, N);
1576         Value *DenEltN = Builder.CreateExtractElement(Den, N);
1577 
1578         Value *NewElt;
1579         if (ScalarSize <= 32) {
1580           NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN);
1581           if (!NewElt)
1582             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1583         } else {
1584           // See if this 64-bit division can be shrunk to 32/24-bits before
1585           // producing the general expansion.
1586           NewElt = shrinkDivRem64(Builder, I, NumEltN, DenEltN);
1587           if (!NewElt) {
1588             // The general 64-bit expansion introduces control flow and doesn't
1589             // return the new value. Just insert a scalar copy and defer
1590             // expanding it.
1591             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1592             Div64ToExpand.push_back(cast<BinaryOperator>(NewElt));
1593           }
1594         }
1595 
1596         if (auto *NewEltI = dyn_cast<Instruction>(NewElt))
1597           NewEltI->copyIRFlags(&I);
1598 
1599         NewDiv = Builder.CreateInsertElement(NewDiv, NewElt, N);
1600       }
1601     } else {
1602       if (ScalarSize <= 32)
1603         NewDiv = expandDivRem32(Builder, I, Num, Den);
1604       else {
1605         NewDiv = shrinkDivRem64(Builder, I, Num, Den);
1606         if (!NewDiv)
1607           Div64ToExpand.push_back(&I);
1608       }
1609     }
1610 
1611     if (NewDiv) {
1612       I.replaceAllUsesWith(NewDiv);
1613       I.eraseFromParent();
1614       Changed = true;
1615     }
1616   }
1617 
1618   if (ExpandDiv64InIR) {
1619     // TODO: We get much worse code in specially handled constant cases.
1620     for (BinaryOperator *Div : Div64ToExpand) {
1621       expandDivRem64(*Div);
1622       FlowChanged = true;
1623       Changed = true;
1624     }
1625   }
1626 
1627   return Changed;
1628 }
1629 
1630 bool AMDGPUCodeGenPrepareImpl::visitLoadInst(LoadInst &I) {
1631   if (!WidenLoads)
1632     return false;
1633 
1634   if ((I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
1635        I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
1636       canWidenScalarExtLoad(I)) {
1637     IRBuilder<> Builder(&I);
1638     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1639 
1640     Type *I32Ty = Builder.getInt32Ty();
1641     LoadInst *WidenLoad = Builder.CreateLoad(I32Ty, I.getPointerOperand());
1642     WidenLoad->copyMetadata(I);
1643 
1644     // If we have range metadata, we need to convert the type, and not make
1645     // assumptions about the high bits.
1646     if (auto *Range = WidenLoad->getMetadata(LLVMContext::MD_range)) {
1647       ConstantInt *Lower =
1648         mdconst::extract<ConstantInt>(Range->getOperand(0));
1649 
1650       if (Lower->isNullValue()) {
1651         WidenLoad->setMetadata(LLVMContext::MD_range, nullptr);
1652       } else {
1653         Metadata *LowAndHigh[] = {
1654           ConstantAsMetadata::get(ConstantInt::get(I32Ty, Lower->getValue().zext(32))),
1655           // Don't make assumptions about the high bits.
1656           ConstantAsMetadata::get(ConstantInt::get(I32Ty, 0))
1657         };
1658 
1659         WidenLoad->setMetadata(LLVMContext::MD_range,
1660                                MDNode::get(F.getContext(), LowAndHigh));
1661       }
1662     }
1663 
1664     int TySize = DL.getTypeSizeInBits(I.getType());
1665     Type *IntNTy = Builder.getIntNTy(TySize);
1666     Value *ValTrunc = Builder.CreateTrunc(WidenLoad, IntNTy);
1667     Value *ValOrig = Builder.CreateBitCast(ValTrunc, I.getType());
1668     I.replaceAllUsesWith(ValOrig);
1669     I.eraseFromParent();
1670     return true;
1671   }
1672 
1673   return false;
1674 }
1675 
1676 bool AMDGPUCodeGenPrepareImpl::visitICmpInst(ICmpInst &I) {
1677   bool Changed = false;
1678 
1679   if (ST.has16BitInsts() && needsPromotionToI32(I.getOperand(0)->getType()) &&
1680       UA.isUniform(&I))
1681     Changed |= promoteUniformOpToI32(I);
1682 
1683   return Changed;
1684 }
1685 
1686 bool AMDGPUCodeGenPrepareImpl::visitSelectInst(SelectInst &I) {
1687   Value *Cond = I.getCondition();
1688   Value *TrueVal = I.getTrueValue();
1689   Value *FalseVal = I.getFalseValue();
1690   Value *CmpVal;
1691   FCmpInst::Predicate Pred;
1692 
1693   if (ST.has16BitInsts() && needsPromotionToI32(I.getType())) {
1694     if (UA.isUniform(&I))
1695       return promoteUniformOpToI32(I);
1696     return false;
1697   }
1698 
1699   // Match fract pattern with nan check.
1700   if (!match(Cond, m_FCmp(Pred, m_Value(CmpVal), m_NonNaN())))
1701     return false;
1702 
1703   FPMathOperator *FPOp = dyn_cast<FPMathOperator>(&I);
1704   if (!FPOp)
1705     return false;
1706 
1707   IRBuilder<> Builder(&I);
1708   Builder.setFastMathFlags(FPOp->getFastMathFlags());
1709 
1710   auto *IITrue = dyn_cast<IntrinsicInst>(TrueVal);
1711   auto *IIFalse = dyn_cast<IntrinsicInst>(FalseVal);
1712 
1713   Value *Fract = nullptr;
1714   if (Pred == FCmpInst::FCMP_UNO && TrueVal == CmpVal && IIFalse &&
1715       CmpVal == matchFractPat(*IIFalse)) {
1716     // isnan(x) ? x : fract(x)
1717     Fract = applyFractPat(Builder, CmpVal);
1718   } else if (Pred == FCmpInst::FCMP_ORD && FalseVal == CmpVal && IITrue &&
1719              CmpVal == matchFractPat(*IITrue)) {
1720     // !isnan(x) ? fract(x) : x
1721     Fract = applyFractPat(Builder, CmpVal);
1722   } else
1723     return false;
1724 
1725   Fract->takeName(&I);
1726   I.replaceAllUsesWith(Fract);
1727   RecursivelyDeleteTriviallyDeadInstructions(&I, TLI);
1728   return true;
1729 }
1730 
1731 static bool areInSameBB(const Value *A, const Value *B) {
1732   const auto *IA = dyn_cast<Instruction>(A);
1733   const auto *IB = dyn_cast<Instruction>(B);
1734   return IA && IB && IA->getParent() == IB->getParent();
1735 }
1736 
1737 // Helper for breaking large PHIs that returns true when an extractelement on V
1738 // is likely to be folded away by the DAG combiner.
1739 static bool isInterestingPHIIncomingValue(const Value *V) {
1740   const auto *FVT = dyn_cast<FixedVectorType>(V->getType());
1741   if (!FVT)
1742     return false;
1743 
1744   const Value *CurVal = V;
1745 
1746   // Check for insertelements, keeping track of the elements covered.
1747   BitVector EltsCovered(FVT->getNumElements());
1748   while (const auto *IE = dyn_cast<InsertElementInst>(CurVal)) {
1749     const auto *Idx = dyn_cast<ConstantInt>(IE->getOperand(2));
1750 
1751     // Non constant index/out of bounds index -> folding is unlikely.
1752     // The latter is more of a sanity check because canonical IR should just
1753     // have replaced those with poison.
1754     if (!Idx || Idx->getZExtValue() >= FVT->getNumElements())
1755       return false;
1756 
1757     const auto *VecSrc = IE->getOperand(0);
1758 
1759     // If the vector source is another instruction, it must be in the same basic
1760     // block. Otherwise, the DAGCombiner won't see the whole thing and is
1761     // unlikely to be able to do anything interesting here.
1762     if (isa<Instruction>(VecSrc) && !areInSameBB(VecSrc, IE))
1763       return false;
1764 
1765     CurVal = VecSrc;
1766     EltsCovered.set(Idx->getZExtValue());
1767 
1768     // All elements covered.
1769     if (EltsCovered.all())
1770       return true;
1771   }
1772 
1773   // We either didn't find a single insertelement, or the insertelement chain
1774   // ended before all elements were covered. Check for other interesting values.
1775 
1776   // Constants are always interesting because we can just constant fold the
1777   // extractelements.
1778   if (isa<Constant>(CurVal))
1779     return true;
1780 
1781   // shufflevector is likely to be profitable if either operand is a constant,
1782   // or if either source is in the same block.
1783   // This is because shufflevector is most often lowered as a series of
1784   // insert/extract elements anyway.
1785   if (const auto *SV = dyn_cast<ShuffleVectorInst>(CurVal)) {
1786     return isa<Constant>(SV->getOperand(1)) ||
1787            areInSameBB(SV, SV->getOperand(0)) ||
1788            areInSameBB(SV, SV->getOperand(1));
1789   }
1790 
1791   return false;
1792 }
1793 
1794 static void collectPHINodes(const PHINode &I,
1795                             SmallPtrSet<const PHINode *, 8> &SeenPHIs) {
1796   const auto [It, Inserted] = SeenPHIs.insert(&I);
1797   if (!Inserted)
1798     return;
1799 
1800   for (const Value *Inc : I.incoming_values()) {
1801     if (const auto *PhiInc = dyn_cast<PHINode>(Inc))
1802       collectPHINodes(*PhiInc, SeenPHIs);
1803   }
1804 
1805   for (const User *U : I.users()) {
1806     if (const auto *PhiU = dyn_cast<PHINode>(U))
1807       collectPHINodes(*PhiU, SeenPHIs);
1808   }
1809 }
1810 
1811 bool AMDGPUCodeGenPrepareImpl::canBreakPHINode(const PHINode &I) {
1812   // Check in the cache first.
1813   if (const auto It = BreakPhiNodesCache.find(&I);
1814       It != BreakPhiNodesCache.end())
1815     return It->second;
1816 
1817   // We consider PHI nodes as part of "chains", so given a PHI node I, we
1818   // recursively consider all its users and incoming values that are also PHI
1819   // nodes. We then make a decision about all of those PHIs at once. Either they
1820   // all get broken up, or none of them do. That way, we avoid cases where a
1821   // single PHI is/is not broken and we end up reforming/exploding a vector
1822   // multiple times, or even worse, doing it in a loop.
1823   SmallPtrSet<const PHINode *, 8> WorkList;
1824   collectPHINodes(I, WorkList);
1825 
1826 #ifndef NDEBUG
1827   // Check that none of the PHI nodes in the worklist are in the map. If some of
1828   // them are, it means we're not good enough at collecting related PHIs.
1829   for (const PHINode *WLP : WorkList) {
1830     assert(BreakPhiNodesCache.count(WLP) == 0);
1831   }
1832 #endif
1833 
1834   // To consider a PHI profitable to break, we need to see some interesting
1835   // incoming values. At least 2/3rd (rounded up) of all PHIs in the worklist
1836   // must have one to consider all PHIs breakable.
1837   //
1838   // This threshold has been determined through performance testing.
1839   //
1840   // Note that the computation below is equivalent to
1841   //
1842   //    (unsigned)ceil((K / 3.0) * 2)
1843   //
1844   // It's simply written this way to avoid mixing integral/FP arithmetic.
1845   const auto Threshold = (alignTo(WorkList.size() * 2, 3) / 3);
1846   unsigned NumBreakablePHIs = 0;
1847   bool CanBreak = false;
1848   for (const PHINode *Cur : WorkList) {
1849     // Don't break PHIs that have no interesting incoming values. That is, where
1850     // there is no clear opportunity to fold the "extractelement" instructions
1851     // we would add.
1852     //
1853     // Note: IC does not run after this pass, so we're only interested in the
1854     // foldings that the DAG combiner can do.
1855     if (any_of(Cur->incoming_values(), isInterestingPHIIncomingValue)) {
1856       if (++NumBreakablePHIs >= Threshold) {
1857         CanBreak = true;
1858         break;
1859       }
1860     }
1861   }
1862 
1863   for (const PHINode *Cur : WorkList)
1864     BreakPhiNodesCache[Cur] = CanBreak;
1865 
1866   return CanBreak;
1867 }
1868 
1869 /// Helper class for "break large PHIs" (visitPHINode).
1870 ///
1871 /// This represents a slice of a PHI's incoming value, which is made up of:
1872 ///   - The type of the slice (Ty)
1873 ///   - The index in the incoming value's vector where the slice starts (Idx)
1874 ///   - The number of elements in the slice (NumElts).
1875 /// It also keeps track of the NewPHI node inserted for this particular slice.
1876 ///
1877 /// Slice examples:
1878 ///   <4 x i64> -> Split into four i64 slices.
1879 ///     -> [i64, 0, 1], [i64, 1, 1], [i64, 2, 1], [i64, 3, 1]
1880 ///   <5 x i16> -> Split into 2 <2 x i16> slices + a i16 tail.
1881 ///     -> [<2 x i16>, 0, 2], [<2 x i16>, 2, 2], [i16, 4, 1]
1882 class VectorSlice {
1883 public:
1884   VectorSlice(Type *Ty, unsigned Idx, unsigned NumElts)
1885       : Ty(Ty), Idx(Idx), NumElts(NumElts) {}
1886 
1887   Type *Ty = nullptr;
1888   unsigned Idx = 0;
1889   unsigned NumElts = 0;
1890   PHINode *NewPHI = nullptr;
1891 
1892   /// Slice \p Inc according to the information contained within this slice.
1893   /// This is cached, so if called multiple times for the same \p BB & \p Inc
1894   /// pair, it returns the same Sliced value as well.
1895   ///
1896   /// Note this *intentionally* does not return the same value for, say,
1897   /// [%bb.0, %0] & [%bb.1, %0] as:
1898   ///   - It could cause issues with dominance (e.g. if bb.1 is seen first, then
1899   ///   the value in bb.1 may not be reachable from bb.0 if it's its
1900   ///   predecessor.)
1901   ///   - We also want to make our extract instructions as local as possible so
1902   ///   the DAG has better chances of folding them out. Duplicating them like
1903   ///   that is beneficial in that regard.
1904   ///
1905   /// This is both a minor optimization to avoid creating duplicate
1906   /// instructions, but also a requirement for correctness. It is not forbidden
1907   /// for a PHI node to have the same [BB, Val] pair multiple times. If we
1908   /// returned a new value each time, those previously identical pairs would all
1909   /// have different incoming values (from the same block) and it'd cause a "PHI
1910   /// node has multiple entries for the same basic block with different incoming
1911   /// values!" verifier error.
1912   Value *getSlicedVal(BasicBlock *BB, Value *Inc, StringRef NewValName) {
1913     Value *&Res = SlicedVals[{BB, Inc}];
1914     if (Res)
1915       return Res;
1916 
1917     IRBuilder<> B(BB->getTerminator());
1918     if (Instruction *IncInst = dyn_cast<Instruction>(Inc))
1919       B.SetCurrentDebugLocation(IncInst->getDebugLoc());
1920 
1921     if (NumElts > 1) {
1922       SmallVector<int, 4> Mask;
1923       for (unsigned K = Idx; K < (Idx + NumElts); ++K)
1924         Mask.push_back(K);
1925       Res = B.CreateShuffleVector(Inc, Mask, NewValName);
1926     } else
1927       Res = B.CreateExtractElement(Inc, Idx, NewValName);
1928 
1929     return Res;
1930   }
1931 
1932 private:
1933   SmallDenseMap<std::pair<BasicBlock *, Value *>, Value *> SlicedVals;
1934 };
1935 
1936 bool AMDGPUCodeGenPrepareImpl::visitPHINode(PHINode &I) {
1937   // Break-up fixed-vector PHIs into smaller pieces.
1938   // Default threshold is 32, so it breaks up any vector that's >32 bits into
1939   // its elements, or into 32-bit pieces (for 8/16 bit elts).
1940   //
1941   // This is only helpful for DAGISel because it doesn't handle large PHIs as
1942   // well as GlobalISel. DAGISel lowers PHIs by using CopyToReg/CopyFromReg.
1943   // With large, odd-sized PHIs we may end up needing many `build_vector`
1944   // operations with most elements being "undef". This inhibits a lot of
1945   // optimization opportunities and can result in unreasonably high register
1946   // pressure and the inevitable stack spilling.
1947   if (!BreakLargePHIs || getCGPassBuilderOption().EnableGlobalISelOption)
1948     return false;
1949 
1950   FixedVectorType *FVT = dyn_cast<FixedVectorType>(I.getType());
1951   if (!FVT || FVT->getNumElements() == 1 ||
1952       DL.getTypeSizeInBits(FVT) <= BreakLargePHIsThreshold)
1953     return false;
1954 
1955   if (!ForceBreakLargePHIs && !canBreakPHINode(I))
1956     return false;
1957 
1958   std::vector<VectorSlice> Slices;
1959 
1960   Type *EltTy = FVT->getElementType();
1961   {
1962     unsigned Idx = 0;
1963     // For 8/16 bits type, don't scalarize fully but break it up into as many
1964     // 32-bit slices as we can, and scalarize the tail.
1965     const unsigned EltSize = DL.getTypeSizeInBits(EltTy);
1966     const unsigned NumElts = FVT->getNumElements();
1967     if (EltSize == 8 || EltSize == 16) {
1968       const unsigned SubVecSize = (32 / EltSize);
1969       Type *SubVecTy = FixedVectorType::get(EltTy, SubVecSize);
1970       for (unsigned End = alignDown(NumElts, SubVecSize); Idx < End;
1971            Idx += SubVecSize)
1972         Slices.emplace_back(SubVecTy, Idx, SubVecSize);
1973     }
1974 
1975     // Scalarize all remaining elements.
1976     for (; Idx < NumElts; ++Idx)
1977       Slices.emplace_back(EltTy, Idx, 1);
1978   }
1979 
1980   assert(Slices.size() > 1);
1981 
1982   // Create one PHI per vector piece. The "VectorSlice" class takes care of
1983   // creating the necessary instruction to extract the relevant slices of each
1984   // incoming value.
1985   IRBuilder<> B(I.getParent());
1986   B.SetCurrentDebugLocation(I.getDebugLoc());
1987 
1988   unsigned IncNameSuffix = 0;
1989   for (VectorSlice &S : Slices) {
1990     // We need to reset the build on each iteration, because getSlicedVal may
1991     // have inserted something into I's BB.
1992     B.SetInsertPoint(I.getParent()->getFirstNonPHIIt());
1993     S.NewPHI = B.CreatePHI(S.Ty, I.getNumIncomingValues());
1994 
1995     for (const auto &[Idx, BB] : enumerate(I.blocks())) {
1996       S.NewPHI->addIncoming(S.getSlicedVal(BB, I.getIncomingValue(Idx),
1997                                            "largephi.extractslice" +
1998                                                std::to_string(IncNameSuffix++)),
1999                             BB);
2000     }
2001   }
2002 
2003   // And replace this PHI with a vector of all the previous PHI values.
2004   Value *Vec = PoisonValue::get(FVT);
2005   unsigned NameSuffix = 0;
2006   for (VectorSlice &S : Slices) {
2007     const auto ValName = "largephi.insertslice" + std::to_string(NameSuffix++);
2008     if (S.NumElts > 1)
2009       Vec =
2010           B.CreateInsertVector(FVT, Vec, S.NewPHI, B.getInt64(S.Idx), ValName);
2011     else
2012       Vec = B.CreateInsertElement(Vec, S.NewPHI, S.Idx, ValName);
2013   }
2014 
2015   I.replaceAllUsesWith(Vec);
2016   I.eraseFromParent();
2017   return true;
2018 }
2019 
2020 /// \param V  Value to check
2021 /// \param DL DataLayout
2022 /// \param TM TargetMachine (TODO: remove once DL contains nullptr values)
2023 /// \param AS Target Address Space
2024 /// \return true if \p V cannot be the null value of \p AS, false otherwise.
2025 static bool isPtrKnownNeverNull(const Value *V, const DataLayout &DL,
2026                                 const AMDGPUTargetMachine &TM, unsigned AS) {
2027   // Pointer cannot be null if it's a block address, GV or alloca.
2028   // NOTE: We don't support extern_weak, but if we did, we'd need to check for
2029   // it as the symbol could be null in such cases.
2030   if (isa<BlockAddress>(V) || isa<GlobalValue>(V) || isa<AllocaInst>(V))
2031     return true;
2032 
2033   // Check nonnull arguments.
2034   if (const auto *Arg = dyn_cast<Argument>(V); Arg && Arg->hasNonNullAttr())
2035     return true;
2036 
2037   // getUnderlyingObject may have looked through another addrspacecast, although
2038   // the optimizable situations most likely folded out by now.
2039   if (AS != cast<PointerType>(V->getType())->getAddressSpace())
2040     return false;
2041 
2042   // TODO: Calls that return nonnull?
2043 
2044   // For all other things, use KnownBits.
2045   // We either use 0 or all bits set to indicate null, so check whether the
2046   // value can be zero or all ones.
2047   //
2048   // TODO: Use ValueTracking's isKnownNeverNull if it becomes aware that some
2049   // address spaces have non-zero null values.
2050   auto SrcPtrKB = computeKnownBits(V, DL);
2051   const auto NullVal = TM.getNullPointerValue(AS);
2052 
2053   assert(SrcPtrKB.getBitWidth() == DL.getPointerSizeInBits(AS));
2054   assert((NullVal == 0 || NullVal == -1) &&
2055          "don't know how to check for this null value!");
2056   return NullVal ? !SrcPtrKB.getMaxValue().isAllOnes() : SrcPtrKB.isNonZero();
2057 }
2058 
2059 bool AMDGPUCodeGenPrepareImpl::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2060   // Intrinsic doesn't support vectors, also it seems that it's often difficult
2061   // to prove that a vector cannot have any nulls in it so it's unclear if it's
2062   // worth supporting.
2063   if (I.getType()->isVectorTy())
2064     return false;
2065 
2066   // Check if this can be lowered to a amdgcn.addrspacecast.nonnull.
2067   // This is only worthwhile for casts from/to priv/local to flat.
2068   const unsigned SrcAS = I.getSrcAddressSpace();
2069   const unsigned DstAS = I.getDestAddressSpace();
2070 
2071   bool CanLower = false;
2072   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
2073     CanLower = (DstAS == AMDGPUAS::LOCAL_ADDRESS ||
2074                 DstAS == AMDGPUAS::PRIVATE_ADDRESS);
2075   else if (DstAS == AMDGPUAS::FLAT_ADDRESS)
2076     CanLower = (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
2077                 SrcAS == AMDGPUAS::PRIVATE_ADDRESS);
2078   if (!CanLower)
2079     return false;
2080 
2081   SmallVector<const Value *, 4> WorkList;
2082   getUnderlyingObjects(I.getOperand(0), WorkList);
2083   if (!all_of(WorkList, [&](const Value *V) {
2084         return isPtrKnownNeverNull(V, DL, TM, SrcAS);
2085       }))
2086     return false;
2087 
2088   IRBuilder<> B(&I);
2089   auto *Intrin = B.CreateIntrinsic(
2090       I.getType(), Intrinsic::amdgcn_addrspacecast_nonnull, {I.getOperand(0)});
2091   I.replaceAllUsesWith(Intrin);
2092   I.eraseFromParent();
2093   return true;
2094 }
2095 
2096 bool AMDGPUCodeGenPrepareImpl::visitIntrinsicInst(IntrinsicInst &I) {
2097   switch (I.getIntrinsicID()) {
2098   case Intrinsic::bitreverse:
2099     return visitBitreverseIntrinsicInst(I);
2100   case Intrinsic::minnum:
2101     return visitMinNum(I);
2102   case Intrinsic::sqrt:
2103     return visitSqrt(I);
2104   default:
2105     return false;
2106   }
2107 }
2108 
2109 bool AMDGPUCodeGenPrepareImpl::visitBitreverseIntrinsicInst(IntrinsicInst &I) {
2110   bool Changed = false;
2111 
2112   if (ST.has16BitInsts() && needsPromotionToI32(I.getType()) &&
2113       UA.isUniform(&I))
2114     Changed |= promoteUniformBitreverseToI32(I);
2115 
2116   return Changed;
2117 }
2118 
2119 /// Match non-nan fract pattern.
2120 ///   minnum(fsub(x, floor(x)), nextafter(1.0, -1.0)
2121 ///
2122 /// If fract is a useful instruction for the subtarget. Does not account for the
2123 /// nan handling; the instruction has a nan check on the input value.
2124 Value *AMDGPUCodeGenPrepareImpl::matchFractPat(IntrinsicInst &I) {
2125   if (ST.hasFractBug())
2126     return nullptr;
2127 
2128   if (I.getIntrinsicID() != Intrinsic::minnum)
2129     return nullptr;
2130 
2131   Type *Ty = I.getType();
2132   if (!isLegalFloatingTy(Ty->getScalarType()))
2133     return nullptr;
2134 
2135   Value *Arg0 = I.getArgOperand(0);
2136   Value *Arg1 = I.getArgOperand(1);
2137 
2138   const APFloat *C;
2139   if (!match(Arg1, m_APFloat(C)))
2140     return nullptr;
2141 
2142   APFloat One(1.0);
2143   bool LosesInfo;
2144   One.convert(C->getSemantics(), APFloat::rmNearestTiesToEven, &LosesInfo);
2145 
2146   // Match nextafter(1.0, -1)
2147   One.next(true);
2148   if (One != *C)
2149     return nullptr;
2150 
2151   Value *FloorSrc;
2152   if (match(Arg0, m_FSub(m_Value(FloorSrc),
2153                          m_Intrinsic<Intrinsic::floor>(m_Deferred(FloorSrc)))))
2154     return FloorSrc;
2155   return nullptr;
2156 }
2157 
2158 Value *AMDGPUCodeGenPrepareImpl::applyFractPat(IRBuilder<> &Builder,
2159                                                Value *FractArg) {
2160   SmallVector<Value *, 4> FractVals;
2161   extractValues(Builder, FractVals, FractArg);
2162 
2163   SmallVector<Value *, 4> ResultVals(FractVals.size());
2164 
2165   Type *Ty = FractArg->getType()->getScalarType();
2166   for (unsigned I = 0, E = FractVals.size(); I != E; ++I) {
2167     ResultVals[I] =
2168         Builder.CreateIntrinsic(Intrinsic::amdgcn_fract, {Ty}, {FractVals[I]});
2169   }
2170 
2171   return insertValues(Builder, FractArg->getType(), ResultVals);
2172 }
2173 
2174 bool AMDGPUCodeGenPrepareImpl::visitMinNum(IntrinsicInst &I) {
2175   Value *FractArg = matchFractPat(I);
2176   if (!FractArg)
2177     return false;
2178 
2179   // Match pattern for fract intrinsic in contexts where the nan check has been
2180   // optimized out (and hope the knowledge the source can't be nan wasn't lost).
2181   if (!I.hasNoNaNs() &&
2182       !isKnownNeverNaN(FractArg, /*Depth=*/0, SimplifyQuery(DL, TLI)))
2183     return false;
2184 
2185   IRBuilder<> Builder(&I);
2186   FastMathFlags FMF = I.getFastMathFlags();
2187   FMF.setNoNaNs();
2188   Builder.setFastMathFlags(FMF);
2189 
2190   Value *Fract = applyFractPat(Builder, FractArg);
2191   Fract->takeName(&I);
2192   I.replaceAllUsesWith(Fract);
2193 
2194   RecursivelyDeleteTriviallyDeadInstructions(&I, TLI);
2195   return true;
2196 }
2197 
2198 static bool isOneOrNegOne(const Value *Val) {
2199   const APFloat *C;
2200   return match(Val, m_APFloat(C)) && C->getExactLog2Abs() == 0;
2201 }
2202 
2203 // Expand llvm.sqrt.f32 calls with !fpmath metadata in a semi-fast way.
2204 bool AMDGPUCodeGenPrepareImpl::visitSqrt(IntrinsicInst &Sqrt) {
2205   Type *Ty = Sqrt.getType()->getScalarType();
2206   if (!Ty->isFloatTy() && (!Ty->isHalfTy() || ST.has16BitInsts()))
2207     return false;
2208 
2209   const FPMathOperator *FPOp = cast<const FPMathOperator>(&Sqrt);
2210   FastMathFlags SqrtFMF = FPOp->getFastMathFlags();
2211 
2212   // We're trying to handle the fast-but-not-that-fast case only. The lowering
2213   // of fast llvm.sqrt will give the raw instruction anyway.
2214   if (SqrtFMF.approxFunc() || HasUnsafeFPMath)
2215     return false;
2216 
2217   const float ReqdAccuracy = FPOp->getFPAccuracy();
2218 
2219   // Defer correctly rounded expansion to codegen.
2220   if (ReqdAccuracy < 1.0f)
2221     return false;
2222 
2223   // FIXME: This is an ugly hack for this pass using forward iteration instead
2224   // of reverse. If it worked like a normal combiner, the rsq would form before
2225   // we saw a sqrt call.
2226   auto *FDiv =
2227       dyn_cast_or_null<FPMathOperator>(Sqrt.getUniqueUndroppableUser());
2228   if (FDiv && FDiv->getOpcode() == Instruction::FDiv &&
2229       FDiv->getFPAccuracy() >= 1.0f &&
2230       canOptimizeWithRsq(FPOp, FDiv->getFastMathFlags(), SqrtFMF) &&
2231       // TODO: We should also handle the arcp case for the fdiv with non-1 value
2232       isOneOrNegOne(FDiv->getOperand(0)))
2233     return false;
2234 
2235   Value *SrcVal = Sqrt.getOperand(0);
2236   bool CanTreatAsDAZ = canIgnoreDenormalInput(SrcVal, &Sqrt);
2237 
2238   // The raw instruction is 1 ulp, but the correction for denormal handling
2239   // brings it to 2.
2240   if (!CanTreatAsDAZ && ReqdAccuracy < 2.0f)
2241     return false;
2242 
2243   IRBuilder<> Builder(&Sqrt);
2244   SmallVector<Value *, 4> SrcVals;
2245   extractValues(Builder, SrcVals, SrcVal);
2246 
2247   SmallVector<Value *, 4> ResultVals(SrcVals.size());
2248   for (int I = 0, E = SrcVals.size(); I != E; ++I) {
2249     if (CanTreatAsDAZ)
2250       ResultVals[I] = Builder.CreateCall(getSqrtF32(), SrcVals[I]);
2251     else
2252       ResultVals[I] = emitSqrtIEEE2ULP(Builder, SrcVals[I], SqrtFMF);
2253   }
2254 
2255   Value *NewSqrt = insertValues(Builder, Sqrt.getType(), ResultVals);
2256   NewSqrt->takeName(&Sqrt);
2257   Sqrt.replaceAllUsesWith(NewSqrt);
2258   Sqrt.eraseFromParent();
2259   return true;
2260 }
2261 
2262 bool AMDGPUCodeGenPrepare::runOnFunction(Function &F) {
2263   if (skipFunction(F))
2264     return false;
2265 
2266   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
2267   if (!TPC)
2268     return false;
2269 
2270   const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>();
2271   const TargetLibraryInfo *TLI =
2272       &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2273   AssumptionCache *AC =
2274       &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2275   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
2276   const DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
2277   const UniformityInfo &UA =
2278       getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
2279   return AMDGPUCodeGenPrepareImpl(F, TM, TLI, AC, DT, UA).run();
2280 }
2281 
2282 PreservedAnalyses AMDGPUCodeGenPreparePass::run(Function &F,
2283                                                 FunctionAnalysisManager &FAM) {
2284   const AMDGPUTargetMachine &ATM = static_cast<const AMDGPUTargetMachine &>(TM);
2285   const TargetLibraryInfo *TLI = &FAM.getResult<TargetLibraryAnalysis>(F);
2286   AssumptionCache *AC = &FAM.getResult<AssumptionAnalysis>(F);
2287   const DominatorTree *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
2288   const UniformityInfo &UA = FAM.getResult<UniformityInfoAnalysis>(F);
2289   AMDGPUCodeGenPrepareImpl Impl(F, ATM, TLI, AC, DT, UA);
2290   if (!Impl.run())
2291     return PreservedAnalyses::all();
2292   PreservedAnalyses PA = PreservedAnalyses::none();
2293   if (!Impl.FlowChanged)
2294     PA.preserveSet<CFGAnalyses>();
2295   return PA;
2296 }
2297 
2298 INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE,
2299                       "AMDGPU IR optimizations", false, false)
2300 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2301 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2302 INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)
2303 INITIALIZE_PASS_END(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations",
2304                     false, false)
2305 
2306 char AMDGPUCodeGenPrepare::ID = 0;
2307 
2308 FunctionPass *llvm::createAMDGPUCodeGenPreparePass() {
2309   return new AMDGPUCodeGenPrepare();
2310 }
2311