10b57cec5SDimitry Andric //===-- AMDGPUCodeGenPrepare.cpp ------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// This pass does misc. AMDGPU optimizations on IR before instruction
110b57cec5SDimitry Andric /// selection.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "AMDGPU.h"
160b57cec5SDimitry Andric #include "AMDGPUTargetMachine.h"
1706c3fb27SDimitry Andric #include "SIModeRegisterDefaults.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
195ffd83dbSDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
2006c3fb27SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
2106c3fb27SDimitry Andric #include "llvm/Analysis/UniformityAnalysis.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
245ffd83dbSDimitry Andric #include "llvm/IR/Dominators.h"
2506c3fb27SDimitry Andric #include "llvm/IR/IRBuilder.h"
260b57cec5SDimitry Andric #include "llvm/IR/InstVisitor.h"
27e8d8bef9SDimitry Andric #include "llvm/IR/IntrinsicsAMDGPU.h"
2806c3fb27SDimitry Andric #include "llvm/IR/PatternMatch.h"
29480093f4SDimitry Andric #include "llvm/InitializePasses.h"
300b57cec5SDimitry Andric #include "llvm/Pass.h"
31e8d8bef9SDimitry Andric #include "llvm/Support/KnownBits.h"
325ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/IntegerDivision.h"
3306c3fb27SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric #define DEBUG_TYPE "amdgpu-codegenprepare"
360b57cec5SDimitry Andric 
370b57cec5SDimitry Andric using namespace llvm;
3806c3fb27SDimitry Andric using namespace llvm::PatternMatch;
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric namespace {
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric static cl::opt<bool> WidenLoads(
430b57cec5SDimitry Andric   "amdgpu-codegenprepare-widen-constant-loads",
440b57cec5SDimitry Andric   cl::desc("Widen sub-dword constant address space loads in AMDGPUCodeGenPrepare"),
450b57cec5SDimitry Andric   cl::ReallyHidden,
465ffd83dbSDimitry Andric   cl::init(false));
470b57cec5SDimitry Andric 
48e8d8bef9SDimitry Andric static cl::opt<bool> Widen16BitOps(
49e8d8bef9SDimitry Andric   "amdgpu-codegenprepare-widen-16-bit-ops",
50e8d8bef9SDimitry Andric   cl::desc("Widen uniform 16-bit instructions to 32-bit in AMDGPUCodeGenPrepare"),
51e8d8bef9SDimitry Andric   cl::ReallyHidden,
52e8d8bef9SDimitry Andric   cl::init(true));
53e8d8bef9SDimitry Andric 
5406c3fb27SDimitry Andric static cl::opt<bool>
555f757f3fSDimitry Andric     BreakLargePHIs("amdgpu-codegenprepare-break-large-phis",
5606c3fb27SDimitry Andric                    cl::desc("Break large PHI nodes for DAGISel"),
5706c3fb27SDimitry Andric                    cl::ReallyHidden, cl::init(true));
5806c3fb27SDimitry Andric 
5906c3fb27SDimitry Andric static cl::opt<bool>
605f757f3fSDimitry Andric     ForceBreakLargePHIs("amdgpu-codegenprepare-force-break-large-phis",
6106c3fb27SDimitry Andric                         cl::desc("For testing purposes, always break large "
6206c3fb27SDimitry Andric                                  "PHIs even if it isn't profitable."),
6306c3fb27SDimitry Andric                         cl::ReallyHidden, cl::init(false));
6406c3fb27SDimitry Andric 
655f757f3fSDimitry Andric static cl::opt<unsigned> BreakLargePHIsThreshold(
6606c3fb27SDimitry Andric     "amdgpu-codegenprepare-break-large-phis-threshold",
6706c3fb27SDimitry Andric     cl::desc("Minimum type size in bits for breaking large PHI nodes"),
6806c3fb27SDimitry Andric     cl::ReallyHidden, cl::init(32));
6906c3fb27SDimitry Andric 
708bcb0991SDimitry Andric static cl::opt<bool> UseMul24Intrin(
718bcb0991SDimitry Andric   "amdgpu-codegenprepare-mul24",
728bcb0991SDimitry Andric   cl::desc("Introduce mul24 intrinsics in AMDGPUCodeGenPrepare"),
738bcb0991SDimitry Andric   cl::ReallyHidden,
748bcb0991SDimitry Andric   cl::init(true));
758bcb0991SDimitry Andric 
765ffd83dbSDimitry Andric // Legalize 64-bit division by using the generic IR expansion.
775ffd83dbSDimitry Andric static cl::opt<bool> ExpandDiv64InIR(
785ffd83dbSDimitry Andric   "amdgpu-codegenprepare-expand-div64",
795ffd83dbSDimitry Andric   cl::desc("Expand 64-bit division in AMDGPUCodeGenPrepare"),
805ffd83dbSDimitry Andric   cl::ReallyHidden,
815ffd83dbSDimitry Andric   cl::init(false));
825ffd83dbSDimitry Andric 
835ffd83dbSDimitry Andric // Leave all division operations as they are. This supersedes ExpandDiv64InIR
845ffd83dbSDimitry Andric // and is used for testing the legalizer.
855ffd83dbSDimitry Andric static cl::opt<bool> DisableIDivExpand(
865ffd83dbSDimitry Andric   "amdgpu-codegenprepare-disable-idiv-expansion",
875ffd83dbSDimitry Andric   cl::desc("Prevent expanding integer division in AMDGPUCodeGenPrepare"),
885ffd83dbSDimitry Andric   cl::ReallyHidden,
895ffd83dbSDimitry Andric   cl::init(false));
905ffd83dbSDimitry Andric 
9106c3fb27SDimitry Andric // Disable processing of fdiv so we can better test the backend implementations.
9206c3fb27SDimitry Andric static cl::opt<bool> DisableFDivExpand(
9306c3fb27SDimitry Andric   "amdgpu-codegenprepare-disable-fdiv-expansion",
9406c3fb27SDimitry Andric   cl::desc("Prevent expanding floating point division in AMDGPUCodeGenPrepare"),
9506c3fb27SDimitry Andric   cl::ReallyHidden,
9606c3fb27SDimitry Andric   cl::init(false));
9706c3fb27SDimitry Andric 
9806c3fb27SDimitry Andric class AMDGPUCodeGenPrepareImpl
9906c3fb27SDimitry Andric     : public InstVisitor<AMDGPUCodeGenPrepareImpl, bool> {
10006c3fb27SDimitry Andric public:
1010b57cec5SDimitry Andric   const GCNSubtarget *ST = nullptr;
10206c3fb27SDimitry Andric   const TargetLibraryInfo *TLInfo = nullptr;
1030b57cec5SDimitry Andric   AssumptionCache *AC = nullptr;
1045ffd83dbSDimitry Andric   DominatorTree *DT = nullptr;
10506c3fb27SDimitry Andric   UniformityInfo *UA = nullptr;
1060b57cec5SDimitry Andric   Module *Mod = nullptr;
1070b57cec5SDimitry Andric   const DataLayout *DL = nullptr;
1080b57cec5SDimitry Andric   bool HasUnsafeFPMath = false;
10906c3fb27SDimitry Andric   bool HasFP32DenormalFlush = false;
11006c3fb27SDimitry Andric   bool FlowChanged = false;
1115f757f3fSDimitry Andric   mutable Function *SqrtF32 = nullptr;
1125f757f3fSDimitry Andric   mutable Function *LdexpF32 = nullptr;
11306c3fb27SDimitry Andric 
11406c3fb27SDimitry Andric   DenseMap<const PHINode *, bool> BreakPhiNodesCache;
11506c3fb27SDimitry Andric 
getSqrtF32() const1165f757f3fSDimitry Andric   Function *getSqrtF32() const {
1175f757f3fSDimitry Andric     if (SqrtF32)
1185f757f3fSDimitry Andric       return SqrtF32;
1195f757f3fSDimitry Andric 
1205f757f3fSDimitry Andric     LLVMContext &Ctx = Mod->getContext();
1215f757f3fSDimitry Andric     SqrtF32 = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_sqrt,
1225f757f3fSDimitry Andric                                         {Type::getFloatTy(Ctx)});
1235f757f3fSDimitry Andric     return SqrtF32;
1245f757f3fSDimitry Andric   }
1255f757f3fSDimitry Andric 
getLdexpF32() const1265f757f3fSDimitry Andric   Function *getLdexpF32() const {
1275f757f3fSDimitry Andric     if (LdexpF32)
1285f757f3fSDimitry Andric       return LdexpF32;
1295f757f3fSDimitry Andric 
1305f757f3fSDimitry Andric     LLVMContext &Ctx = Mod->getContext();
1315f757f3fSDimitry Andric     LdexpF32 = Intrinsic::getDeclaration(
1325f757f3fSDimitry Andric         Mod, Intrinsic::ldexp, {Type::getFloatTy(Ctx), Type::getInt32Ty(Ctx)});
1335f757f3fSDimitry Andric     return LdexpF32;
1345f757f3fSDimitry Andric   }
1355f757f3fSDimitry Andric 
13606c3fb27SDimitry Andric   bool canBreakPHINode(const PHINode &I);
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric   /// Copies exact/nsw/nuw flags (if any) from binary operation \p I to
1390b57cec5SDimitry Andric   /// binary operation \p V.
1400b57cec5SDimitry Andric   ///
1410b57cec5SDimitry Andric   /// \returns Binary operation \p V.
1420b57cec5SDimitry Andric   /// \returns \p T's base element bit width.
1430b57cec5SDimitry Andric   unsigned getBaseElementBitWidth(const Type *T) const;
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric   /// \returns Equivalent 32 bit integer type for given type \p T. For example,
1460b57cec5SDimitry Andric   /// if \p T is i7, then i32 is returned; if \p T is <3 x i12>, then <3 x i32>
1470b57cec5SDimitry Andric   /// is returned.
1480b57cec5SDimitry Andric   Type *getI32Ty(IRBuilder<> &B, const Type *T) const;
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   /// \returns True if binary operation \p I is a signed binary operation, false
1510b57cec5SDimitry Andric   /// otherwise.
1520b57cec5SDimitry Andric   bool isSigned(const BinaryOperator &I) const;
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   /// \returns True if the condition of 'select' operation \p I comes from a
1550b57cec5SDimitry Andric   /// signed 'icmp' operation, false otherwise.
1560b57cec5SDimitry Andric   bool isSigned(const SelectInst &I) const;
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric   /// \returns True if type \p T needs to be promoted to 32 bit integer type,
1590b57cec5SDimitry Andric   /// false otherwise.
1600b57cec5SDimitry Andric   bool needsPromotionToI32(const Type *T) const;
1610b57cec5SDimitry Andric 
16206c3fb27SDimitry Andric   /// Return true if \p T is a legal scalar floating point type.
16306c3fb27SDimitry Andric   bool isLegalFloatingTy(const Type *T) const;
16406c3fb27SDimitry Andric 
16506c3fb27SDimitry Andric   /// Wrapper to pass all the arguments to computeKnownFPClass
computeKnownFPClass(const Value * V,FPClassTest Interested,const Instruction * CtxI) const16606c3fb27SDimitry Andric   KnownFPClass computeKnownFPClass(const Value *V, FPClassTest Interested,
16706c3fb27SDimitry Andric                                    const Instruction *CtxI) const {
16806c3fb27SDimitry Andric     return llvm::computeKnownFPClass(V, *DL, Interested, 0, TLInfo, AC, CtxI,
16906c3fb27SDimitry Andric                                      DT);
17006c3fb27SDimitry Andric   }
17106c3fb27SDimitry Andric 
canIgnoreDenormalInput(const Value * V,const Instruction * CtxI) const17206c3fb27SDimitry Andric   bool canIgnoreDenormalInput(const Value *V, const Instruction *CtxI) const {
17306c3fb27SDimitry Andric     return HasFP32DenormalFlush ||
17406c3fb27SDimitry Andric            computeKnownFPClass(V, fcSubnormal, CtxI).isKnownNeverSubnormal();
17506c3fb27SDimitry Andric   }
17606c3fb27SDimitry Andric 
1770b57cec5SDimitry Andric   /// Promotes uniform binary operation \p I to equivalent 32 bit binary
1780b57cec5SDimitry Andric   /// operation.
1790b57cec5SDimitry Andric   ///
1800b57cec5SDimitry Andric   /// \details \p I's base element bit width must be greater than 1 and less
1810b57cec5SDimitry Andric   /// than or equal 16. Promotion is done by sign or zero extending operands to
1820b57cec5SDimitry Andric   /// 32 bits, replacing \p I with equivalent 32 bit binary operation, and
1830b57cec5SDimitry Andric   /// truncating the result of 32 bit binary operation back to \p I's original
1840b57cec5SDimitry Andric   /// type. Division operation is not promoted.
1850b57cec5SDimitry Andric   ///
1860b57cec5SDimitry Andric   /// \returns True if \p I is promoted to equivalent 32 bit binary operation,
1870b57cec5SDimitry Andric   /// false otherwise.
1880b57cec5SDimitry Andric   bool promoteUniformOpToI32(BinaryOperator &I) const;
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   /// Promotes uniform 'icmp' operation \p I to 32 bit 'icmp' operation.
1910b57cec5SDimitry Andric   ///
1920b57cec5SDimitry Andric   /// \details \p I's base element bit width must be greater than 1 and less
1930b57cec5SDimitry Andric   /// than or equal 16. Promotion is done by sign or zero extending operands to
1940b57cec5SDimitry Andric   /// 32 bits, and replacing \p I with 32 bit 'icmp' operation.
1950b57cec5SDimitry Andric   ///
1960b57cec5SDimitry Andric   /// \returns True.
1970b57cec5SDimitry Andric   bool promoteUniformOpToI32(ICmpInst &I) const;
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric   /// Promotes uniform 'select' operation \p I to 32 bit 'select'
2000b57cec5SDimitry Andric   /// operation.
2010b57cec5SDimitry Andric   ///
2020b57cec5SDimitry Andric   /// \details \p I's base element bit width must be greater than 1 and less
2030b57cec5SDimitry Andric   /// than or equal 16. Promotion is done by sign or zero extending operands to
2040b57cec5SDimitry Andric   /// 32 bits, replacing \p I with 32 bit 'select' operation, and truncating the
2050b57cec5SDimitry Andric   /// result of 32 bit 'select' operation back to \p I's original type.
2060b57cec5SDimitry Andric   ///
2070b57cec5SDimitry Andric   /// \returns True.
2080b57cec5SDimitry Andric   bool promoteUniformOpToI32(SelectInst &I) const;
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric   /// Promotes uniform 'bitreverse' intrinsic \p I to 32 bit 'bitreverse'
2110b57cec5SDimitry Andric   /// intrinsic.
2120b57cec5SDimitry Andric   ///
2130b57cec5SDimitry Andric   /// \details \p I's base element bit width must be greater than 1 and less
2140b57cec5SDimitry Andric   /// than or equal 16. Promotion is done by zero extending the operand to 32
2150b57cec5SDimitry Andric   /// bits, replacing \p I with 32 bit 'bitreverse' intrinsic, shifting the
2160b57cec5SDimitry Andric   /// result of 32 bit 'bitreverse' intrinsic to the right with zero fill (the
2170b57cec5SDimitry Andric   /// shift amount is 32 minus \p I's base element bit width), and truncating
2180b57cec5SDimitry Andric   /// the result of the shift operation back to \p I's original type.
2190b57cec5SDimitry Andric   ///
2200b57cec5SDimitry Andric   /// \returns True.
2210b57cec5SDimitry Andric   bool promoteUniformBitreverseToI32(IntrinsicInst &I) const;
2220b57cec5SDimitry Andric 
223349cc55cSDimitry Andric   /// \returns The minimum number of bits needed to store the value of \Op as an
224349cc55cSDimitry Andric   /// unsigned integer. Truncating to this size and then zero-extending to
22504eeddc0SDimitry Andric   /// the original will not change the value.
22604eeddc0SDimitry Andric   unsigned numBitsUnsigned(Value *Op) const;
227349cc55cSDimitry Andric 
228349cc55cSDimitry Andric   /// \returns The minimum number of bits needed to store the value of \Op as a
229349cc55cSDimitry Andric   /// signed integer. Truncating to this size and then sign-extending to
23004eeddc0SDimitry Andric   /// the original size will not change the value.
23104eeddc0SDimitry Andric   unsigned numBitsSigned(Value *Op) const;
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   /// Replace mul instructions with llvm.amdgcn.mul.u24 or llvm.amdgcn.mul.s24.
2340b57cec5SDimitry Andric   /// SelectionDAG has an issue where an and asserting the bits are known
2350b57cec5SDimitry Andric   bool replaceMulWithMul24(BinaryOperator &I) const;
2360b57cec5SDimitry Andric 
2375ffd83dbSDimitry Andric   /// Perform same function as equivalently named function in DAGCombiner. Since
2385ffd83dbSDimitry Andric   /// we expand some divisions here, we need to perform this before obscuring.
2395ffd83dbSDimitry Andric   bool foldBinOpIntoSelect(BinaryOperator &I) const;
2405ffd83dbSDimitry Andric 
2415ffd83dbSDimitry Andric   bool divHasSpecialOptimization(BinaryOperator &I,
2425ffd83dbSDimitry Andric                                  Value *Num, Value *Den) const;
2435ffd83dbSDimitry Andric   int getDivNumBits(BinaryOperator &I,
2445ffd83dbSDimitry Andric                     Value *Num, Value *Den,
2455ffd83dbSDimitry Andric                     unsigned AtLeast, bool Signed) const;
2465ffd83dbSDimitry Andric 
2470b57cec5SDimitry Andric   /// Expands 24 bit div or rem.
2480b57cec5SDimitry Andric   Value* expandDivRem24(IRBuilder<> &Builder, BinaryOperator &I,
2490b57cec5SDimitry Andric                         Value *Num, Value *Den,
2500b57cec5SDimitry Andric                         bool IsDiv, bool IsSigned) const;
2510b57cec5SDimitry Andric 
2525ffd83dbSDimitry Andric   Value *expandDivRem24Impl(IRBuilder<> &Builder, BinaryOperator &I,
2535ffd83dbSDimitry Andric                             Value *Num, Value *Den, unsigned NumBits,
2545ffd83dbSDimitry Andric                             bool IsDiv, bool IsSigned) const;
2555ffd83dbSDimitry Andric 
2560b57cec5SDimitry Andric   /// Expands 32 bit div or rem.
2570b57cec5SDimitry Andric   Value* expandDivRem32(IRBuilder<> &Builder, BinaryOperator &I,
2580b57cec5SDimitry Andric                         Value *Num, Value *Den) const;
2590b57cec5SDimitry Andric 
2605ffd83dbSDimitry Andric   Value *shrinkDivRem64(IRBuilder<> &Builder, BinaryOperator &I,
2615ffd83dbSDimitry Andric                         Value *Num, Value *Den) const;
2625ffd83dbSDimitry Andric   void expandDivRem64(BinaryOperator &I) const;
2635ffd83dbSDimitry Andric 
2640b57cec5SDimitry Andric   /// Widen a scalar load.
2650b57cec5SDimitry Andric   ///
2660b57cec5SDimitry Andric   /// \details \p Widen scalar load for uniform, small type loads from constant
2670b57cec5SDimitry Andric   //  memory / to a full 32-bits and then truncate the input to allow a scalar
2680b57cec5SDimitry Andric   //  load instead of a vector load.
2690b57cec5SDimitry Andric   //
2700b57cec5SDimitry Andric   /// \returns True.
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   bool canWidenScalarExtLoad(LoadInst &I) const;
2730b57cec5SDimitry Andric 
27406c3fb27SDimitry Andric   Value *matchFractPat(IntrinsicInst &I);
27506c3fb27SDimitry Andric   Value *applyFractPat(IRBuilder<> &Builder, Value *FractArg);
27606c3fb27SDimitry Andric 
27706c3fb27SDimitry Andric   bool canOptimizeWithRsq(const FPMathOperator *SqrtOp, FastMathFlags DivFMF,
27806c3fb27SDimitry Andric                           FastMathFlags SqrtFMF) const;
27906c3fb27SDimitry Andric 
28006c3fb27SDimitry Andric   Value *optimizeWithRsq(IRBuilder<> &Builder, Value *Num, Value *Den,
28106c3fb27SDimitry Andric                          FastMathFlags DivFMF, FastMathFlags SqrtFMF,
28206c3fb27SDimitry Andric                          const Instruction *CtxI) const;
28306c3fb27SDimitry Andric 
28406c3fb27SDimitry Andric   Value *optimizeWithRcp(IRBuilder<> &Builder, Value *Num, Value *Den,
28506c3fb27SDimitry Andric                          FastMathFlags FMF, const Instruction *CtxI) const;
28606c3fb27SDimitry Andric   Value *optimizeWithFDivFast(IRBuilder<> &Builder, Value *Num, Value *Den,
28706c3fb27SDimitry Andric                               float ReqdAccuracy) const;
28806c3fb27SDimitry Andric 
28906c3fb27SDimitry Andric   Value *visitFDivElement(IRBuilder<> &Builder, Value *Num, Value *Den,
29006c3fb27SDimitry Andric                           FastMathFlags DivFMF, FastMathFlags SqrtFMF,
29106c3fb27SDimitry Andric                           Value *RsqOp, const Instruction *FDiv,
29206c3fb27SDimitry Andric                           float ReqdAccuracy) const;
29306c3fb27SDimitry Andric 
29406c3fb27SDimitry Andric   std::pair<Value *, Value *> getFrexpResults(IRBuilder<> &Builder,
29506c3fb27SDimitry Andric                                               Value *Src) const;
29606c3fb27SDimitry Andric 
29706c3fb27SDimitry Andric   Value *emitRcpIEEE1ULP(IRBuilder<> &Builder, Value *Src,
29806c3fb27SDimitry Andric                          bool IsNegative) const;
29906c3fb27SDimitry Andric   Value *emitFrexpDiv(IRBuilder<> &Builder, Value *LHS, Value *RHS,
30006c3fb27SDimitry Andric                       FastMathFlags FMF) const;
3015f757f3fSDimitry Andric   Value *emitSqrtIEEE2ULP(IRBuilder<> &Builder, Value *Src,
3025f757f3fSDimitry Andric                           FastMathFlags FMF) const;
30306c3fb27SDimitry Andric 
3040b57cec5SDimitry Andric public:
3050b57cec5SDimitry Andric   bool visitFDiv(BinaryOperator &I);
3060b57cec5SDimitry Andric 
visitInstruction(Instruction & I)3070b57cec5SDimitry Andric   bool visitInstruction(Instruction &I) { return false; }
3080b57cec5SDimitry Andric   bool visitBinaryOperator(BinaryOperator &I);
3090b57cec5SDimitry Andric   bool visitLoadInst(LoadInst &I);
3100b57cec5SDimitry Andric   bool visitICmpInst(ICmpInst &I);
3110b57cec5SDimitry Andric   bool visitSelectInst(SelectInst &I);
31206c3fb27SDimitry Andric   bool visitPHINode(PHINode &I);
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   bool visitIntrinsicInst(IntrinsicInst &I);
3150b57cec5SDimitry Andric   bool visitBitreverseIntrinsicInst(IntrinsicInst &I);
31606c3fb27SDimitry Andric   bool visitMinNum(IntrinsicInst &I);
3175f757f3fSDimitry Andric   bool visitSqrt(IntrinsicInst &I);
31806c3fb27SDimitry Andric   bool run(Function &F);
31906c3fb27SDimitry Andric };
3200b57cec5SDimitry Andric 
32106c3fb27SDimitry Andric class AMDGPUCodeGenPrepare : public FunctionPass {
32206c3fb27SDimitry Andric private:
32306c3fb27SDimitry Andric   AMDGPUCodeGenPrepareImpl Impl;
3240b57cec5SDimitry Andric 
32506c3fb27SDimitry Andric public:
32606c3fb27SDimitry Andric   static char ID;
AMDGPUCodeGenPrepare()32706c3fb27SDimitry Andric   AMDGPUCodeGenPrepare() : FunctionPass(ID) {
32806c3fb27SDimitry Andric     initializeAMDGPUCodeGenPreparePass(*PassRegistry::getPassRegistry());
32906c3fb27SDimitry Andric   }
getAnalysisUsage(AnalysisUsage & AU) const3300b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
3310b57cec5SDimitry Andric     AU.addRequired<AssumptionCacheTracker>();
33206c3fb27SDimitry Andric     AU.addRequired<UniformityInfoWrapperPass>();
33306c3fb27SDimitry Andric     AU.addRequired<TargetLibraryInfoWrapperPass>();
3345ffd83dbSDimitry Andric 
3355ffd83dbSDimitry Andric     // FIXME: Division expansion needs to preserve the dominator tree.
3365ffd83dbSDimitry Andric     if (!ExpandDiv64InIR)
3370b57cec5SDimitry Andric       AU.setPreservesAll();
3380b57cec5SDimitry Andric   }
33906c3fb27SDimitry Andric   bool runOnFunction(Function &F) override;
34006c3fb27SDimitry Andric   bool doInitialization(Module &M) override;
getPassName() const34106c3fb27SDimitry Andric   StringRef getPassName() const override { return "AMDGPU IR optimizations"; }
3420b57cec5SDimitry Andric };
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric } // end anonymous namespace
3450b57cec5SDimitry Andric 
run(Function & F)34606c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::run(Function &F) {
3475f757f3fSDimitry Andric   BreakPhiNodesCache.clear();
34806c3fb27SDimitry Andric   bool MadeChange = false;
34906c3fb27SDimitry Andric 
35006c3fb27SDimitry Andric   Function::iterator NextBB;
35106c3fb27SDimitry Andric   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; FI = NextBB) {
35206c3fb27SDimitry Andric     BasicBlock *BB = &*FI;
35306c3fb27SDimitry Andric     NextBB = std::next(FI);
35406c3fb27SDimitry Andric 
35506c3fb27SDimitry Andric     BasicBlock::iterator Next;
35606c3fb27SDimitry Andric     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;
35706c3fb27SDimitry Andric          I = Next) {
35806c3fb27SDimitry Andric       Next = std::next(I);
35906c3fb27SDimitry Andric 
36006c3fb27SDimitry Andric       MadeChange |= visit(*I);
36106c3fb27SDimitry Andric 
36206c3fb27SDimitry Andric       if (Next != E) { // Control flow changed
36306c3fb27SDimitry Andric         BasicBlock *NextInstBB = Next->getParent();
36406c3fb27SDimitry Andric         if (NextInstBB != BB) {
36506c3fb27SDimitry Andric           BB = NextInstBB;
36606c3fb27SDimitry Andric           E = BB->end();
36706c3fb27SDimitry Andric           FE = F.end();
36806c3fb27SDimitry Andric         }
36906c3fb27SDimitry Andric       }
37006c3fb27SDimitry Andric     }
37106c3fb27SDimitry Andric   }
37206c3fb27SDimitry Andric   return MadeChange;
37306c3fb27SDimitry Andric }
37406c3fb27SDimitry Andric 
getBaseElementBitWidth(const Type * T) const37506c3fb27SDimitry Andric unsigned AMDGPUCodeGenPrepareImpl::getBaseElementBitWidth(const Type *T) const {
3760b57cec5SDimitry Andric   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   if (T->isIntegerTy())
3790b57cec5SDimitry Andric     return T->getIntegerBitWidth();
3800b57cec5SDimitry Andric   return cast<VectorType>(T)->getElementType()->getIntegerBitWidth();
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric 
getI32Ty(IRBuilder<> & B,const Type * T) const38306c3fb27SDimitry Andric Type *AMDGPUCodeGenPrepareImpl::getI32Ty(IRBuilder<> &B, const Type *T) const {
3840b57cec5SDimitry Andric   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric   if (T->isIntegerTy())
3870b57cec5SDimitry Andric     return B.getInt32Ty();
3885ffd83dbSDimitry Andric   return FixedVectorType::get(B.getInt32Ty(), cast<FixedVectorType>(T));
3890b57cec5SDimitry Andric }
3900b57cec5SDimitry Andric 
isSigned(const BinaryOperator & I) const39106c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::isSigned(const BinaryOperator &I) const {
3920b57cec5SDimitry Andric   return I.getOpcode() == Instruction::AShr ||
3930b57cec5SDimitry Andric       I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::SRem;
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric 
isSigned(const SelectInst & I) const39606c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::isSigned(const SelectInst &I) const {
3970b57cec5SDimitry Andric   return isa<ICmpInst>(I.getOperand(0)) ?
3980b57cec5SDimitry Andric       cast<ICmpInst>(I.getOperand(0))->isSigned() : false;
3990b57cec5SDimitry Andric }
4000b57cec5SDimitry Andric 
needsPromotionToI32(const Type * T) const40106c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::needsPromotionToI32(const Type *T) const {
402e8d8bef9SDimitry Andric   if (!Widen16BitOps)
403e8d8bef9SDimitry Andric     return false;
404e8d8bef9SDimitry Andric 
4050b57cec5SDimitry Andric   const IntegerType *IntTy = dyn_cast<IntegerType>(T);
4060b57cec5SDimitry Andric   if (IntTy && IntTy->getBitWidth() > 1 && IntTy->getBitWidth() <= 16)
4070b57cec5SDimitry Andric     return true;
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   if (const VectorType *VT = dyn_cast<VectorType>(T)) {
4100b57cec5SDimitry Andric     // TODO: The set of packed operations is more limited, so may want to
4110b57cec5SDimitry Andric     // promote some anyway.
4120b57cec5SDimitry Andric     if (ST->hasVOP3PInsts())
4130b57cec5SDimitry Andric       return false;
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric     return needsPromotionToI32(VT->getElementType());
4160b57cec5SDimitry Andric   }
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   return false;
4190b57cec5SDimitry Andric }
4200b57cec5SDimitry Andric 
isLegalFloatingTy(const Type * Ty) const42106c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::isLegalFloatingTy(const Type *Ty) const {
42206c3fb27SDimitry Andric   return Ty->isFloatTy() || Ty->isDoubleTy() ||
42306c3fb27SDimitry Andric          (Ty->isHalfTy() && ST->has16BitInsts());
42406c3fb27SDimitry Andric }
42506c3fb27SDimitry Andric 
4260b57cec5SDimitry Andric // Return true if the op promoted to i32 should have nsw set.
promotedOpIsNSW(const Instruction & I)4270b57cec5SDimitry Andric static bool promotedOpIsNSW(const Instruction &I) {
4280b57cec5SDimitry Andric   switch (I.getOpcode()) {
4290b57cec5SDimitry Andric   case Instruction::Shl:
4300b57cec5SDimitry Andric   case Instruction::Add:
4310b57cec5SDimitry Andric   case Instruction::Sub:
4320b57cec5SDimitry Andric     return true;
4330b57cec5SDimitry Andric   case Instruction::Mul:
4340b57cec5SDimitry Andric     return I.hasNoUnsignedWrap();
4350b57cec5SDimitry Andric   default:
4360b57cec5SDimitry Andric     return false;
4370b57cec5SDimitry Andric   }
4380b57cec5SDimitry Andric }
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric // Return true if the op promoted to i32 should have nuw set.
promotedOpIsNUW(const Instruction & I)4410b57cec5SDimitry Andric static bool promotedOpIsNUW(const Instruction &I) {
4420b57cec5SDimitry Andric   switch (I.getOpcode()) {
4430b57cec5SDimitry Andric   case Instruction::Shl:
4440b57cec5SDimitry Andric   case Instruction::Add:
4450b57cec5SDimitry Andric   case Instruction::Mul:
4460b57cec5SDimitry Andric     return true;
4470b57cec5SDimitry Andric   case Instruction::Sub:
4480b57cec5SDimitry Andric     return I.hasNoUnsignedWrap();
4490b57cec5SDimitry Andric   default:
4500b57cec5SDimitry Andric     return false;
4510b57cec5SDimitry Andric   }
4520b57cec5SDimitry Andric }
4530b57cec5SDimitry Andric 
canWidenScalarExtLoad(LoadInst & I) const45406c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::canWidenScalarExtLoad(LoadInst &I) const {
4550b57cec5SDimitry Andric   Type *Ty = I.getType();
4560b57cec5SDimitry Andric   const DataLayout &DL = Mod->getDataLayout();
4570b57cec5SDimitry Andric   int TySize = DL.getTypeSizeInBits(Ty);
4585ffd83dbSDimitry Andric   Align Alignment = DL.getValueOrABITypeAlignment(I.getAlign(), Ty);
4590b57cec5SDimitry Andric 
46006c3fb27SDimitry Andric   return I.isSimple() && TySize < 32 && Alignment >= 4 && UA->isUniform(&I);
4610b57cec5SDimitry Andric }
4620b57cec5SDimitry Andric 
promoteUniformOpToI32(BinaryOperator & I) const46306c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(BinaryOperator &I) const {
4640b57cec5SDimitry Andric   assert(needsPromotionToI32(I.getType()) &&
4650b57cec5SDimitry Andric          "I does not need promotion to i32");
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric   if (I.getOpcode() == Instruction::SDiv ||
4680b57cec5SDimitry Andric       I.getOpcode() == Instruction::UDiv ||
4690b57cec5SDimitry Andric       I.getOpcode() == Instruction::SRem ||
4700b57cec5SDimitry Andric       I.getOpcode() == Instruction::URem)
4710b57cec5SDimitry Andric     return false;
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
4740b57cec5SDimitry Andric   Builder.SetCurrentDebugLocation(I.getDebugLoc());
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric   Type *I32Ty = getI32Ty(Builder, I.getType());
4770b57cec5SDimitry Andric   Value *ExtOp0 = nullptr;
4780b57cec5SDimitry Andric   Value *ExtOp1 = nullptr;
4790b57cec5SDimitry Andric   Value *ExtRes = nullptr;
4800b57cec5SDimitry Andric   Value *TruncRes = nullptr;
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric   if (isSigned(I)) {
4830b57cec5SDimitry Andric     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
4840b57cec5SDimitry Andric     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
4850b57cec5SDimitry Andric   } else {
4860b57cec5SDimitry Andric     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
4870b57cec5SDimitry Andric     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
4880b57cec5SDimitry Andric   }
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric   ExtRes = Builder.CreateBinOp(I.getOpcode(), ExtOp0, ExtOp1);
4910b57cec5SDimitry Andric   if (Instruction *Inst = dyn_cast<Instruction>(ExtRes)) {
4920b57cec5SDimitry Andric     if (promotedOpIsNSW(cast<Instruction>(I)))
4930b57cec5SDimitry Andric       Inst->setHasNoSignedWrap();
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric     if (promotedOpIsNUW(cast<Instruction>(I)))
4960b57cec5SDimitry Andric       Inst->setHasNoUnsignedWrap();
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric     if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
4990b57cec5SDimitry Andric       Inst->setIsExact(ExactOp->isExact());
5000b57cec5SDimitry Andric   }
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric   I.replaceAllUsesWith(TruncRes);
5050b57cec5SDimitry Andric   I.eraseFromParent();
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric   return true;
5080b57cec5SDimitry Andric }
5090b57cec5SDimitry Andric 
promoteUniformOpToI32(ICmpInst & I) const51006c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(ICmpInst &I) const {
5110b57cec5SDimitry Andric   assert(needsPromotionToI32(I.getOperand(0)->getType()) &&
5120b57cec5SDimitry Andric          "I does not need promotion to i32");
5130b57cec5SDimitry Andric 
5140b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
5150b57cec5SDimitry Andric   Builder.SetCurrentDebugLocation(I.getDebugLoc());
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   Type *I32Ty = getI32Ty(Builder, I.getOperand(0)->getType());
5180b57cec5SDimitry Andric   Value *ExtOp0 = nullptr;
5190b57cec5SDimitry Andric   Value *ExtOp1 = nullptr;
5200b57cec5SDimitry Andric   Value *NewICmp  = nullptr;
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric   if (I.isSigned()) {
5230b57cec5SDimitry Andric     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
5240b57cec5SDimitry Andric     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
5250b57cec5SDimitry Andric   } else {
5260b57cec5SDimitry Andric     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
5270b57cec5SDimitry Andric     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
5280b57cec5SDimitry Andric   }
5290b57cec5SDimitry Andric   NewICmp = Builder.CreateICmp(I.getPredicate(), ExtOp0, ExtOp1);
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   I.replaceAllUsesWith(NewICmp);
5320b57cec5SDimitry Andric   I.eraseFromParent();
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   return true;
5350b57cec5SDimitry Andric }
5360b57cec5SDimitry Andric 
promoteUniformOpToI32(SelectInst & I) const53706c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(SelectInst &I) const {
5380b57cec5SDimitry Andric   assert(needsPromotionToI32(I.getType()) &&
5390b57cec5SDimitry Andric          "I does not need promotion to i32");
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
5420b57cec5SDimitry Andric   Builder.SetCurrentDebugLocation(I.getDebugLoc());
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric   Type *I32Ty = getI32Ty(Builder, I.getType());
5450b57cec5SDimitry Andric   Value *ExtOp1 = nullptr;
5460b57cec5SDimitry Andric   Value *ExtOp2 = nullptr;
5470b57cec5SDimitry Andric   Value *ExtRes = nullptr;
5480b57cec5SDimitry Andric   Value *TruncRes = nullptr;
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric   if (isSigned(I)) {
5510b57cec5SDimitry Andric     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
5520b57cec5SDimitry Andric     ExtOp2 = Builder.CreateSExt(I.getOperand(2), I32Ty);
5530b57cec5SDimitry Andric   } else {
5540b57cec5SDimitry Andric     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
5550b57cec5SDimitry Andric     ExtOp2 = Builder.CreateZExt(I.getOperand(2), I32Ty);
5560b57cec5SDimitry Andric   }
5570b57cec5SDimitry Andric   ExtRes = Builder.CreateSelect(I.getOperand(0), ExtOp1, ExtOp2);
5580b57cec5SDimitry Andric   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric   I.replaceAllUsesWith(TruncRes);
5610b57cec5SDimitry Andric   I.eraseFromParent();
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric   return true;
5640b57cec5SDimitry Andric }
5650b57cec5SDimitry Andric 
promoteUniformBitreverseToI32(IntrinsicInst & I) const56606c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::promoteUniformBitreverseToI32(
5670b57cec5SDimitry Andric     IntrinsicInst &I) const {
5680b57cec5SDimitry Andric   assert(I.getIntrinsicID() == Intrinsic::bitreverse &&
5690b57cec5SDimitry Andric          "I must be bitreverse intrinsic");
5700b57cec5SDimitry Andric   assert(needsPromotionToI32(I.getType()) &&
5710b57cec5SDimitry Andric          "I does not need promotion to i32");
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
5740b57cec5SDimitry Andric   Builder.SetCurrentDebugLocation(I.getDebugLoc());
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric   Type *I32Ty = getI32Ty(Builder, I.getType());
5770b57cec5SDimitry Andric   Function *I32 =
5780b57cec5SDimitry Andric       Intrinsic::getDeclaration(Mod, Intrinsic::bitreverse, { I32Ty });
5790b57cec5SDimitry Andric   Value *ExtOp = Builder.CreateZExt(I.getOperand(0), I32Ty);
5800b57cec5SDimitry Andric   Value *ExtRes = Builder.CreateCall(I32, { ExtOp });
5810b57cec5SDimitry Andric   Value *LShrOp =
5820b57cec5SDimitry Andric       Builder.CreateLShr(ExtRes, 32 - getBaseElementBitWidth(I.getType()));
5830b57cec5SDimitry Andric   Value *TruncRes =
5840b57cec5SDimitry Andric       Builder.CreateTrunc(LShrOp, I.getType());
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric   I.replaceAllUsesWith(TruncRes);
5870b57cec5SDimitry Andric   I.eraseFromParent();
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   return true;
5900b57cec5SDimitry Andric }
5910b57cec5SDimitry Andric 
numBitsUnsigned(Value * Op) const59206c3fb27SDimitry Andric unsigned AMDGPUCodeGenPrepareImpl::numBitsUnsigned(Value *Op) const {
59304eeddc0SDimitry Andric   return computeKnownBits(Op, *DL, 0, AC).countMaxActiveBits();
5940b57cec5SDimitry Andric }
5950b57cec5SDimitry Andric 
numBitsSigned(Value * Op) const59606c3fb27SDimitry Andric unsigned AMDGPUCodeGenPrepareImpl::numBitsSigned(Value *Op) const {
59704eeddc0SDimitry Andric   return ComputeMaxSignificantBits(Op, *DL, 0, AC);
5980b57cec5SDimitry Andric }
5990b57cec5SDimitry Andric 
extractValues(IRBuilder<> & Builder,SmallVectorImpl<Value * > & Values,Value * V)6000b57cec5SDimitry Andric static void extractValues(IRBuilder<> &Builder,
6010b57cec5SDimitry Andric                           SmallVectorImpl<Value *> &Values, Value *V) {
6025ffd83dbSDimitry Andric   auto *VT = dyn_cast<FixedVectorType>(V->getType());
6030b57cec5SDimitry Andric   if (!VT) {
6040b57cec5SDimitry Andric     Values.push_back(V);
6050b57cec5SDimitry Andric     return;
6060b57cec5SDimitry Andric   }
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   for (int I = 0, E = VT->getNumElements(); I != E; ++I)
6090b57cec5SDimitry Andric     Values.push_back(Builder.CreateExtractElement(V, I));
6100b57cec5SDimitry Andric }
6110b57cec5SDimitry Andric 
insertValues(IRBuilder<> & Builder,Type * Ty,SmallVectorImpl<Value * > & Values)6120b57cec5SDimitry Andric static Value *insertValues(IRBuilder<> &Builder,
6130b57cec5SDimitry Andric                            Type *Ty,
6140b57cec5SDimitry Andric                            SmallVectorImpl<Value *> &Values) {
615bdd1243dSDimitry Andric   if (!Ty->isVectorTy()) {
616bdd1243dSDimitry Andric     assert(Values.size() == 1);
6170b57cec5SDimitry Andric     return Values[0];
618bdd1243dSDimitry Andric   }
6190b57cec5SDimitry Andric 
620bdd1243dSDimitry Andric   Value *NewVal = PoisonValue::get(Ty);
6210b57cec5SDimitry Andric   for (int I = 0, E = Values.size(); I != E; ++I)
6220b57cec5SDimitry Andric     NewVal = Builder.CreateInsertElement(NewVal, Values[I], I);
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric   return NewVal;
6250b57cec5SDimitry Andric }
6260b57cec5SDimitry Andric 
replaceMulWithMul24(BinaryOperator & I) const62706c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::replaceMulWithMul24(BinaryOperator &I) const {
6280b57cec5SDimitry Andric   if (I.getOpcode() != Instruction::Mul)
6290b57cec5SDimitry Andric     return false;
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric   Type *Ty = I.getType();
6320b57cec5SDimitry Andric   unsigned Size = Ty->getScalarSizeInBits();
6330b57cec5SDimitry Andric   if (Size <= 16 && ST->has16BitInsts())
6340b57cec5SDimitry Andric     return false;
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric   // Prefer scalar if this could be s_mul_i32
63706c3fb27SDimitry Andric   if (UA->isUniform(&I))
6380b57cec5SDimitry Andric     return false;
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   Value *LHS = I.getOperand(0);
6410b57cec5SDimitry Andric   Value *RHS = I.getOperand(1);
6420b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
6430b57cec5SDimitry Andric   Builder.SetCurrentDebugLocation(I.getDebugLoc());
6440b57cec5SDimitry Andric 
645349cc55cSDimitry Andric   unsigned LHSBits = 0, RHSBits = 0;
646349cc55cSDimitry Andric   bool IsSigned = false;
6470b57cec5SDimitry Andric 
64804eeddc0SDimitry Andric   if (ST->hasMulU24() && (LHSBits = numBitsUnsigned(LHS)) <= 24 &&
64904eeddc0SDimitry Andric       (RHSBits = numBitsUnsigned(RHS)) <= 24) {
650349cc55cSDimitry Andric     IsSigned = false;
651349cc55cSDimitry Andric 
65204eeddc0SDimitry Andric   } else if (ST->hasMulI24() && (LHSBits = numBitsSigned(LHS)) <= 24 &&
65304eeddc0SDimitry Andric              (RHSBits = numBitsSigned(RHS)) <= 24) {
654349cc55cSDimitry Andric     IsSigned = true;
655349cc55cSDimitry Andric 
6560b57cec5SDimitry Andric   } else
6570b57cec5SDimitry Andric     return false;
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric   SmallVector<Value *, 4> LHSVals;
6600b57cec5SDimitry Andric   SmallVector<Value *, 4> RHSVals;
6610b57cec5SDimitry Andric   SmallVector<Value *, 4> ResultVals;
6620b57cec5SDimitry Andric   extractValues(Builder, LHSVals, LHS);
6630b57cec5SDimitry Andric   extractValues(Builder, RHSVals, RHS);
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   IntegerType *I32Ty = Builder.getInt32Ty();
6665f757f3fSDimitry Andric   IntegerType *IntrinTy = Size > 32 ? Builder.getInt64Ty() : I32Ty;
6675f757f3fSDimitry Andric   Type *DstTy = LHSVals[0]->getType();
6685f757f3fSDimitry Andric 
6690b57cec5SDimitry Andric   for (int I = 0, E = LHSVals.size(); I != E; ++I) {
6705f757f3fSDimitry Andric     Value *LHS = IsSigned ? Builder.CreateSExtOrTrunc(LHSVals[I], I32Ty)
6715f757f3fSDimitry Andric                           : Builder.CreateZExtOrTrunc(LHSVals[I], I32Ty);
6725f757f3fSDimitry Andric     Value *RHS = IsSigned ? Builder.CreateSExtOrTrunc(RHSVals[I], I32Ty)
6735f757f3fSDimitry Andric                           : Builder.CreateZExtOrTrunc(RHSVals[I], I32Ty);
6745f757f3fSDimitry Andric     Intrinsic::ID ID =
6755f757f3fSDimitry Andric         IsSigned ? Intrinsic::amdgcn_mul_i24 : Intrinsic::amdgcn_mul_u24;
6765f757f3fSDimitry Andric     Value *Result = Builder.CreateIntrinsic(ID, {IntrinTy}, {LHS, RHS});
6775f757f3fSDimitry Andric     Result = IsSigned ? Builder.CreateSExtOrTrunc(Result, DstTy)
6785f757f3fSDimitry Andric                       : Builder.CreateZExtOrTrunc(Result, DstTy);
6795f757f3fSDimitry Andric     ResultVals.push_back(Result);
6800b57cec5SDimitry Andric   }
6810b57cec5SDimitry Andric 
6828bcb0991SDimitry Andric   Value *NewVal = insertValues(Builder, Ty, ResultVals);
6838bcb0991SDimitry Andric   NewVal->takeName(&I);
6848bcb0991SDimitry Andric   I.replaceAllUsesWith(NewVal);
6850b57cec5SDimitry Andric   I.eraseFromParent();
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric   return true;
6880b57cec5SDimitry Andric }
6890b57cec5SDimitry Andric 
6905ffd83dbSDimitry Andric // Find a select instruction, which may have been casted. This is mostly to deal
6915ffd83dbSDimitry Andric // with cases where i16 selects were promoted here to i32.
findSelectThroughCast(Value * V,CastInst * & Cast)6925ffd83dbSDimitry Andric static SelectInst *findSelectThroughCast(Value *V, CastInst *&Cast) {
6935ffd83dbSDimitry Andric   Cast = nullptr;
6945ffd83dbSDimitry Andric   if (SelectInst *Sel = dyn_cast<SelectInst>(V))
6955ffd83dbSDimitry Andric     return Sel;
6960b57cec5SDimitry Andric 
6975ffd83dbSDimitry Andric   if ((Cast = dyn_cast<CastInst>(V))) {
6985ffd83dbSDimitry Andric     if (SelectInst *Sel = dyn_cast<SelectInst>(Cast->getOperand(0)))
6995ffd83dbSDimitry Andric       return Sel;
7000b57cec5SDimitry Andric   }
7010b57cec5SDimitry Andric 
7025ffd83dbSDimitry Andric   return nullptr;
7035ffd83dbSDimitry Andric }
7040b57cec5SDimitry Andric 
foldBinOpIntoSelect(BinaryOperator & BO) const70506c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::foldBinOpIntoSelect(BinaryOperator &BO) const {
7065ffd83dbSDimitry Andric   // Don't do this unless the old select is going away. We want to eliminate the
7075ffd83dbSDimitry Andric   // binary operator, not replace a binop with a select.
7085ffd83dbSDimitry Andric   int SelOpNo = 0;
7095ffd83dbSDimitry Andric 
7105ffd83dbSDimitry Andric   CastInst *CastOp;
7115ffd83dbSDimitry Andric 
7125ffd83dbSDimitry Andric   // TODO: Should probably try to handle some cases with multiple
7135ffd83dbSDimitry Andric   // users. Duplicating the select may be profitable for division.
7145ffd83dbSDimitry Andric   SelectInst *Sel = findSelectThroughCast(BO.getOperand(0), CastOp);
7155ffd83dbSDimitry Andric   if (!Sel || !Sel->hasOneUse()) {
7165ffd83dbSDimitry Andric     SelOpNo = 1;
7175ffd83dbSDimitry Andric     Sel = findSelectThroughCast(BO.getOperand(1), CastOp);
7185ffd83dbSDimitry Andric   }
7195ffd83dbSDimitry Andric 
7205ffd83dbSDimitry Andric   if (!Sel || !Sel->hasOneUse())
7210b57cec5SDimitry Andric     return false;
7220b57cec5SDimitry Andric 
7235ffd83dbSDimitry Andric   Constant *CT = dyn_cast<Constant>(Sel->getTrueValue());
7245ffd83dbSDimitry Andric   Constant *CF = dyn_cast<Constant>(Sel->getFalseValue());
7255ffd83dbSDimitry Andric   Constant *CBO = dyn_cast<Constant>(BO.getOperand(SelOpNo ^ 1));
7265ffd83dbSDimitry Andric   if (!CBO || !CT || !CF)
7275ffd83dbSDimitry Andric     return false;
7285ffd83dbSDimitry Andric 
7295ffd83dbSDimitry Andric   if (CastOp) {
7305ffd83dbSDimitry Andric     if (!CastOp->hasOneUse())
7315ffd83dbSDimitry Andric       return false;
7325ffd83dbSDimitry Andric     CT = ConstantFoldCastOperand(CastOp->getOpcode(), CT, BO.getType(), *DL);
7335ffd83dbSDimitry Andric     CF = ConstantFoldCastOperand(CastOp->getOpcode(), CF, BO.getType(), *DL);
7345ffd83dbSDimitry Andric   }
7355ffd83dbSDimitry Andric 
7365ffd83dbSDimitry Andric   // TODO: Handle special 0/-1 cases DAG combine does, although we only really
7375ffd83dbSDimitry Andric   // need to handle divisions here.
7385ffd83dbSDimitry Andric   Constant *FoldedT = SelOpNo ?
7395ffd83dbSDimitry Andric     ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CT, *DL) :
7405ffd83dbSDimitry Andric     ConstantFoldBinaryOpOperands(BO.getOpcode(), CT, CBO, *DL);
741753f127fSDimitry Andric   if (!FoldedT || isa<ConstantExpr>(FoldedT))
7425ffd83dbSDimitry Andric     return false;
7435ffd83dbSDimitry Andric 
7445ffd83dbSDimitry Andric   Constant *FoldedF = SelOpNo ?
7455ffd83dbSDimitry Andric     ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CF, *DL) :
7465ffd83dbSDimitry Andric     ConstantFoldBinaryOpOperands(BO.getOpcode(), CF, CBO, *DL);
747753f127fSDimitry Andric   if (!FoldedF || isa<ConstantExpr>(FoldedF))
7485ffd83dbSDimitry Andric     return false;
7495ffd83dbSDimitry Andric 
7505ffd83dbSDimitry Andric   IRBuilder<> Builder(&BO);
7515ffd83dbSDimitry Andric   Builder.SetCurrentDebugLocation(BO.getDebugLoc());
7525ffd83dbSDimitry Andric   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&BO))
7535ffd83dbSDimitry Andric     Builder.setFastMathFlags(FPOp->getFastMathFlags());
7545ffd83dbSDimitry Andric 
7555ffd83dbSDimitry Andric   Value *NewSelect = Builder.CreateSelect(Sel->getCondition(),
7565ffd83dbSDimitry Andric                                           FoldedT, FoldedF);
7575ffd83dbSDimitry Andric   NewSelect->takeName(&BO);
7585ffd83dbSDimitry Andric   BO.replaceAllUsesWith(NewSelect);
7595ffd83dbSDimitry Andric   BO.eraseFromParent();
7605ffd83dbSDimitry Andric   if (CastOp)
7615ffd83dbSDimitry Andric     CastOp->eraseFromParent();
7625ffd83dbSDimitry Andric   Sel->eraseFromParent();
7635ffd83dbSDimitry Andric   return true;
7645ffd83dbSDimitry Andric }
7655ffd83dbSDimitry Andric 
76606c3fb27SDimitry Andric std::pair<Value *, Value *>
getFrexpResults(IRBuilder<> & Builder,Value * Src) const76706c3fb27SDimitry Andric AMDGPUCodeGenPrepareImpl::getFrexpResults(IRBuilder<> &Builder,
76806c3fb27SDimitry Andric                                           Value *Src) const {
76906c3fb27SDimitry Andric   Type *Ty = Src->getType();
77006c3fb27SDimitry Andric   Value *Frexp = Builder.CreateIntrinsic(Intrinsic::frexp,
77106c3fb27SDimitry Andric                                          {Ty, Builder.getInt32Ty()}, Src);
77206c3fb27SDimitry Andric   Value *FrexpMant = Builder.CreateExtractValue(Frexp, {0});
77306c3fb27SDimitry Andric 
77406c3fb27SDimitry Andric   // Bypass the bug workaround for the exponent result since it doesn't matter.
77506c3fb27SDimitry Andric   // TODO: Does the bug workaround even really need to consider the exponent
77606c3fb27SDimitry Andric   // result? It's unspecified by the spec.
77706c3fb27SDimitry Andric 
77806c3fb27SDimitry Andric   Value *FrexpExp =
77906c3fb27SDimitry Andric       ST->hasFractBug()
78006c3fb27SDimitry Andric           ? Builder.CreateIntrinsic(Intrinsic::amdgcn_frexp_exp,
78106c3fb27SDimitry Andric                                     {Builder.getInt32Ty(), Ty}, Src)
78206c3fb27SDimitry Andric           : Builder.CreateExtractValue(Frexp, {1});
78306c3fb27SDimitry Andric   return {FrexpMant, FrexpExp};
78406c3fb27SDimitry Andric }
78506c3fb27SDimitry Andric 
78606c3fb27SDimitry Andric /// Emit an expansion of 1.0 / Src good for 1ulp that supports denormals.
emitRcpIEEE1ULP(IRBuilder<> & Builder,Value * Src,bool IsNegative) const78706c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::emitRcpIEEE1ULP(IRBuilder<> &Builder,
78806c3fb27SDimitry Andric                                                  Value *Src,
78906c3fb27SDimitry Andric                                                  bool IsNegative) const {
79006c3fb27SDimitry Andric   // Same as for 1.0, but expand the sign out of the constant.
79106c3fb27SDimitry Andric   // -1.0 / x -> rcp (fneg x)
79206c3fb27SDimitry Andric   if (IsNegative)
79306c3fb27SDimitry Andric     Src = Builder.CreateFNeg(Src);
79406c3fb27SDimitry Andric 
79506c3fb27SDimitry Andric   // The rcp instruction doesn't support denormals, so scale the input
79606c3fb27SDimitry Andric   // out of the denormal range and convert at the end.
79706c3fb27SDimitry Andric   //
79806c3fb27SDimitry Andric   // Expand as 2^-n * (1.0 / (x * 2^n))
79906c3fb27SDimitry Andric 
80006c3fb27SDimitry Andric   // TODO: Skip scaling if input is known never denormal and the input
80106c3fb27SDimitry Andric   // range won't underflow to denormal. The hard part is knowing the
80206c3fb27SDimitry Andric   // result. We need a range check, the result could be denormal for
80306c3fb27SDimitry Andric   // 0x1p+126 < den <= 0x1p+127.
80406c3fb27SDimitry Andric   auto [FrexpMant, FrexpExp] = getFrexpResults(Builder, Src);
80506c3fb27SDimitry Andric   Value *ScaleFactor = Builder.CreateNeg(FrexpExp);
80606c3fb27SDimitry Andric   Value *Rcp = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, FrexpMant);
8075f757f3fSDimitry Andric   return Builder.CreateCall(getLdexpF32(), {Rcp, ScaleFactor});
80806c3fb27SDimitry Andric }
80906c3fb27SDimitry Andric 
81006c3fb27SDimitry Andric /// Emit a 2ulp expansion for fdiv by using frexp for input scaling.
emitFrexpDiv(IRBuilder<> & Builder,Value * LHS,Value * RHS,FastMathFlags FMF) const81106c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::emitFrexpDiv(IRBuilder<> &Builder, Value *LHS,
81206c3fb27SDimitry Andric                                               Value *RHS,
81306c3fb27SDimitry Andric                                               FastMathFlags FMF) const {
81406c3fb27SDimitry Andric   // If we have have to work around the fract/frexp bug, we're worse off than
81506c3fb27SDimitry Andric   // using the fdiv.fast expansion. The full safe expansion is faster if we have
81606c3fb27SDimitry Andric   // fast FMA.
81706c3fb27SDimitry Andric   if (HasFP32DenormalFlush && ST->hasFractBug() && !ST->hasFastFMAF32() &&
81806c3fb27SDimitry Andric       (!FMF.noNaNs() || !FMF.noInfs()))
81906c3fb27SDimitry Andric     return nullptr;
82006c3fb27SDimitry Andric 
82106c3fb27SDimitry Andric   // We're scaling the LHS to avoid a denormal input, and scale the denominator
82206c3fb27SDimitry Andric   // to avoid large values underflowing the result.
82306c3fb27SDimitry Andric   auto [FrexpMantRHS, FrexpExpRHS] = getFrexpResults(Builder, RHS);
82406c3fb27SDimitry Andric 
82506c3fb27SDimitry Andric   Value *Rcp =
82606c3fb27SDimitry Andric       Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, FrexpMantRHS);
82706c3fb27SDimitry Andric 
82806c3fb27SDimitry Andric   auto [FrexpMantLHS, FrexpExpLHS] = getFrexpResults(Builder, LHS);
82906c3fb27SDimitry Andric   Value *Mul = Builder.CreateFMul(FrexpMantLHS, Rcp);
83006c3fb27SDimitry Andric 
83106c3fb27SDimitry Andric   // We multiplied by 2^N/2^M, so we need to multiply by 2^(N-M) to scale the
83206c3fb27SDimitry Andric   // result.
83306c3fb27SDimitry Andric   Value *ExpDiff = Builder.CreateSub(FrexpExpLHS, FrexpExpRHS);
8345f757f3fSDimitry Andric   return Builder.CreateCall(getLdexpF32(), {Mul, ExpDiff});
8355f757f3fSDimitry Andric }
8365f757f3fSDimitry Andric 
8375f757f3fSDimitry Andric /// Emit a sqrt that handles denormals and is accurate to 2ulp.
emitSqrtIEEE2ULP(IRBuilder<> & Builder,Value * Src,FastMathFlags FMF) const8385f757f3fSDimitry Andric Value *AMDGPUCodeGenPrepareImpl::emitSqrtIEEE2ULP(IRBuilder<> &Builder,
8395f757f3fSDimitry Andric                                                   Value *Src,
8405f757f3fSDimitry Andric                                                   FastMathFlags FMF) const {
8415f757f3fSDimitry Andric   Type *Ty = Src->getType();
8425f757f3fSDimitry Andric   APFloat SmallestNormal =
8435f757f3fSDimitry Andric       APFloat::getSmallestNormalized(Ty->getFltSemantics());
8445f757f3fSDimitry Andric   Value *NeedScale =
8455f757f3fSDimitry Andric       Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
8465f757f3fSDimitry Andric 
8475f757f3fSDimitry Andric   ConstantInt *Zero = Builder.getInt32(0);
8485f757f3fSDimitry Andric   Value *InputScaleFactor =
8495f757f3fSDimitry Andric       Builder.CreateSelect(NeedScale, Builder.getInt32(32), Zero);
8505f757f3fSDimitry Andric 
8515f757f3fSDimitry Andric   Value *Scaled = Builder.CreateCall(getLdexpF32(), {Src, InputScaleFactor});
8525f757f3fSDimitry Andric 
8535f757f3fSDimitry Andric   Value *Sqrt = Builder.CreateCall(getSqrtF32(), Scaled);
8545f757f3fSDimitry Andric 
8555f757f3fSDimitry Andric   Value *OutputScaleFactor =
8565f757f3fSDimitry Andric       Builder.CreateSelect(NeedScale, Builder.getInt32(-16), Zero);
8575f757f3fSDimitry Andric   return Builder.CreateCall(getLdexpF32(), {Sqrt, OutputScaleFactor});
85806c3fb27SDimitry Andric }
85906c3fb27SDimitry Andric 
86006c3fb27SDimitry Andric /// Emit an expansion of 1.0 / sqrt(Src) good for 1ulp that supports denormals.
emitRsqIEEE1ULP(IRBuilder<> & Builder,Value * Src,bool IsNegative)86106c3fb27SDimitry Andric static Value *emitRsqIEEE1ULP(IRBuilder<> &Builder, Value *Src,
86206c3fb27SDimitry Andric                               bool IsNegative) {
86306c3fb27SDimitry Andric   // bool need_scale = x < 0x1p-126f;
86406c3fb27SDimitry Andric   // float input_scale = need_scale ? 0x1.0p+24f : 1.0f;
86506c3fb27SDimitry Andric   // float output_scale = need_scale ? 0x1.0p+12f : 1.0f;
86606c3fb27SDimitry Andric   // rsq(x * input_scale) * output_scale;
86706c3fb27SDimitry Andric 
86806c3fb27SDimitry Andric   Type *Ty = Src->getType();
86906c3fb27SDimitry Andric   APFloat SmallestNormal =
87006c3fb27SDimitry Andric       APFloat::getSmallestNormalized(Ty->getFltSemantics());
87106c3fb27SDimitry Andric   Value *NeedScale =
87206c3fb27SDimitry Andric       Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
87306c3fb27SDimitry Andric   Constant *One = ConstantFP::get(Ty, 1.0);
87406c3fb27SDimitry Andric   Constant *InputScale = ConstantFP::get(Ty, 0x1.0p+24);
87506c3fb27SDimitry Andric   Constant *OutputScale =
87606c3fb27SDimitry Andric       ConstantFP::get(Ty, IsNegative ? -0x1.0p+12 : 0x1.0p+12);
87706c3fb27SDimitry Andric 
87806c3fb27SDimitry Andric   Value *InputScaleFactor = Builder.CreateSelect(NeedScale, InputScale, One);
87906c3fb27SDimitry Andric 
88006c3fb27SDimitry Andric   Value *ScaledInput = Builder.CreateFMul(Src, InputScaleFactor);
88106c3fb27SDimitry Andric   Value *Rsq = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, ScaledInput);
88206c3fb27SDimitry Andric   Value *OutputScaleFactor = Builder.CreateSelect(
88306c3fb27SDimitry Andric       NeedScale, OutputScale, IsNegative ? ConstantFP::get(Ty, -1.0) : One);
88406c3fb27SDimitry Andric 
88506c3fb27SDimitry Andric   return Builder.CreateFMul(Rsq, OutputScaleFactor);
88606c3fb27SDimitry Andric }
88706c3fb27SDimitry Andric 
canOptimizeWithRsq(const FPMathOperator * SqrtOp,FastMathFlags DivFMF,FastMathFlags SqrtFMF) const88806c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::canOptimizeWithRsq(const FPMathOperator *SqrtOp,
88906c3fb27SDimitry Andric                                                   FastMathFlags DivFMF,
89006c3fb27SDimitry Andric                                                   FastMathFlags SqrtFMF) const {
89106c3fb27SDimitry Andric   // The rsqrt contraction increases accuracy from ~2ulp to ~1ulp.
89206c3fb27SDimitry Andric   if (!DivFMF.allowContract() || !SqrtFMF.allowContract())
89306c3fb27SDimitry Andric     return false;
89406c3fb27SDimitry Andric 
89506c3fb27SDimitry Andric   // v_rsq_f32 gives 1ulp
89606c3fb27SDimitry Andric   return SqrtFMF.approxFunc() || HasUnsafeFPMath ||
89706c3fb27SDimitry Andric          SqrtOp->getFPAccuracy() >= 1.0f;
89806c3fb27SDimitry Andric }
89906c3fb27SDimitry Andric 
optimizeWithRsq(IRBuilder<> & Builder,Value * Num,Value * Den,const FastMathFlags DivFMF,const FastMathFlags SqrtFMF,const Instruction * CtxI) const90006c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::optimizeWithRsq(
9015f757f3fSDimitry Andric     IRBuilder<> &Builder, Value *Num, Value *Den, const FastMathFlags DivFMF,
9025f757f3fSDimitry Andric     const FastMathFlags SqrtFMF, const Instruction *CtxI) const {
90306c3fb27SDimitry Andric   // The rsqrt contraction increases accuracy from ~2ulp to ~1ulp.
90406c3fb27SDimitry Andric   assert(DivFMF.allowContract() && SqrtFMF.allowContract());
90506c3fb27SDimitry Andric 
90606c3fb27SDimitry Andric   // rsq_f16 is accurate to 0.51 ulp.
90706c3fb27SDimitry Andric   // rsq_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
90806c3fb27SDimitry Andric   // rsq_f64 is never accurate.
90906c3fb27SDimitry Andric   const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num);
91006c3fb27SDimitry Andric   if (!CLHS)
91106c3fb27SDimitry Andric     return nullptr;
91206c3fb27SDimitry Andric 
91306c3fb27SDimitry Andric   assert(Den->getType()->isFloatTy());
91406c3fb27SDimitry Andric 
91506c3fb27SDimitry Andric   bool IsNegative = false;
91606c3fb27SDimitry Andric 
91706c3fb27SDimitry Andric   // TODO: Handle other numerator values with arcp.
91806c3fb27SDimitry Andric   if (CLHS->isExactlyValue(1.0) || (IsNegative = CLHS->isExactlyValue(-1.0))) {
91906c3fb27SDimitry Andric     // Add in the sqrt flags.
92006c3fb27SDimitry Andric     IRBuilder<>::FastMathFlagGuard Guard(Builder);
9215f757f3fSDimitry Andric     Builder.setFastMathFlags(DivFMF | SqrtFMF);
92206c3fb27SDimitry Andric 
9235f757f3fSDimitry Andric     if ((DivFMF.approxFunc() && SqrtFMF.approxFunc()) || HasUnsafeFPMath ||
92406c3fb27SDimitry Andric         canIgnoreDenormalInput(Den, CtxI)) {
92506c3fb27SDimitry Andric       Value *Result = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, Den);
92606c3fb27SDimitry Andric       // -1.0 / sqrt(x) -> fneg(rsq(x))
92706c3fb27SDimitry Andric       return IsNegative ? Builder.CreateFNeg(Result) : Result;
92806c3fb27SDimitry Andric     }
92906c3fb27SDimitry Andric 
93006c3fb27SDimitry Andric     return emitRsqIEEE1ULP(Builder, Den, IsNegative);
93106c3fb27SDimitry Andric   }
93206c3fb27SDimitry Andric 
93306c3fb27SDimitry Andric   return nullptr;
93406c3fb27SDimitry Andric }
93506c3fb27SDimitry Andric 
9365ffd83dbSDimitry Andric // Optimize fdiv with rcp:
9375ffd83dbSDimitry Andric //
9385ffd83dbSDimitry Andric // 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
9395ffd83dbSDimitry Andric //               allowed with unsafe-fp-math or afn.
9405ffd83dbSDimitry Andric //
94106c3fb27SDimitry Andric // a/b -> a*rcp(b) when arcp is allowed, and we only need provide ULP 1.0
94206c3fb27SDimitry Andric Value *
optimizeWithRcp(IRBuilder<> & Builder,Value * Num,Value * Den,FastMathFlags FMF,const Instruction * CtxI) const94306c3fb27SDimitry Andric AMDGPUCodeGenPrepareImpl::optimizeWithRcp(IRBuilder<> &Builder, Value *Num,
94406c3fb27SDimitry Andric                                           Value *Den, FastMathFlags FMF,
94506c3fb27SDimitry Andric                                           const Instruction *CtxI) const {
94606c3fb27SDimitry Andric   // rcp_f16 is accurate to 0.51 ulp.
94706c3fb27SDimitry Andric   // rcp_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
94806c3fb27SDimitry Andric   // rcp_f64 is never accurate.
94906c3fb27SDimitry Andric   assert(Den->getType()->isFloatTy());
9505ffd83dbSDimitry Andric 
9515ffd83dbSDimitry Andric   if (const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num)) {
95206c3fb27SDimitry Andric     bool IsNegative = false;
95306c3fb27SDimitry Andric     if (CLHS->isExactlyValue(1.0) ||
95406c3fb27SDimitry Andric         (IsNegative = CLHS->isExactlyValue(-1.0))) {
95506c3fb27SDimitry Andric       Value *Src = Den;
95606c3fb27SDimitry Andric 
95706c3fb27SDimitry Andric       if (HasFP32DenormalFlush || FMF.approxFunc()) {
95806c3fb27SDimitry Andric         // -1.0 / x -> 1.0 / fneg(x)
95906c3fb27SDimitry Andric         if (IsNegative)
96006c3fb27SDimitry Andric           Src = Builder.CreateFNeg(Src);
9615ffd83dbSDimitry Andric 
9625ffd83dbSDimitry Andric         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
9635ffd83dbSDimitry Andric         // the CI documentation has a worst case error of 1 ulp.
96406c3fb27SDimitry Andric         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK
96506c3fb27SDimitry Andric         // to use it as long as we aren't trying to use denormals.
9665ffd83dbSDimitry Andric         //
9675ffd83dbSDimitry Andric         // v_rcp_f16 and v_rsq_f16 DO support denormals.
9685ffd83dbSDimitry Andric 
9695ffd83dbSDimitry Andric         // NOTE: v_sqrt and v_rcp will be combined to v_rsq later. So we don't
9705ffd83dbSDimitry Andric         //       insert rsq intrinsic here.
9715ffd83dbSDimitry Andric 
9725ffd83dbSDimitry Andric         // 1.0 / x -> rcp(x)
97306c3fb27SDimitry Andric         return Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, Src);
9745ffd83dbSDimitry Andric       }
9755ffd83dbSDimitry Andric 
97606c3fb27SDimitry Andric       // TODO: If the input isn't denormal, and we know the input exponent isn't
97706c3fb27SDimitry Andric       // big enough to introduce a denormal we can avoid the scaling.
97806c3fb27SDimitry Andric       return emitRcpIEEE1ULP(Builder, Src, IsNegative);
9795ffd83dbSDimitry Andric     }
9805ffd83dbSDimitry Andric   }
9815ffd83dbSDimitry Andric 
98206c3fb27SDimitry Andric   if (FMF.allowReciprocal()) {
9835ffd83dbSDimitry Andric     // x / y -> x * (1.0 / y)
98406c3fb27SDimitry Andric 
98506c3fb27SDimitry Andric     // TODO: Could avoid denormal scaling and use raw rcp if we knew the output
98606c3fb27SDimitry Andric     // will never underflow.
98706c3fb27SDimitry Andric     if (HasFP32DenormalFlush || FMF.approxFunc()) {
98806c3fb27SDimitry Andric       Value *Recip = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, Den);
9895ffd83dbSDimitry Andric       return Builder.CreateFMul(Num, Recip);
9905ffd83dbSDimitry Andric     }
99106c3fb27SDimitry Andric 
99206c3fb27SDimitry Andric     Value *Recip = emitRcpIEEE1ULP(Builder, Den, false);
99306c3fb27SDimitry Andric     return Builder.CreateFMul(Num, Recip);
99406c3fb27SDimitry Andric   }
99506c3fb27SDimitry Andric 
9965ffd83dbSDimitry Andric   return nullptr;
9975ffd83dbSDimitry Andric }
9985ffd83dbSDimitry Andric 
9995ffd83dbSDimitry Andric // optimize with fdiv.fast:
10005ffd83dbSDimitry Andric //
10015ffd83dbSDimitry Andric // a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
10025ffd83dbSDimitry Andric //
10035ffd83dbSDimitry Andric // 1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
10045ffd83dbSDimitry Andric //
10055ffd83dbSDimitry Andric // NOTE: optimizeWithRcp should be tried first because rcp is the preference.
optimizeWithFDivFast(IRBuilder<> & Builder,Value * Num,Value * Den,float ReqdAccuracy) const100606c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::optimizeWithFDivFast(
100706c3fb27SDimitry Andric     IRBuilder<> &Builder, Value *Num, Value *Den, float ReqdAccuracy) const {
10085ffd83dbSDimitry Andric   // fdiv.fast can achieve 2.5 ULP accuracy.
10095ffd83dbSDimitry Andric   if (ReqdAccuracy < 2.5f)
10105ffd83dbSDimitry Andric     return nullptr;
10115ffd83dbSDimitry Andric 
10125ffd83dbSDimitry Andric   // Only have fdiv.fast for f32.
101306c3fb27SDimitry Andric   assert(Den->getType()->isFloatTy());
10145ffd83dbSDimitry Andric 
10155ffd83dbSDimitry Andric   bool NumIsOne = false;
10165ffd83dbSDimitry Andric   if (const ConstantFP *CNum = dyn_cast<ConstantFP>(Num)) {
10175ffd83dbSDimitry Andric     if (CNum->isExactlyValue(+1.0) || CNum->isExactlyValue(-1.0))
10185ffd83dbSDimitry Andric       NumIsOne = true;
10195ffd83dbSDimitry Andric   }
10205ffd83dbSDimitry Andric 
10215ffd83dbSDimitry Andric   // fdiv does not support denormals. But 1.0/x is always fine to use it.
102206c3fb27SDimitry Andric   //
102306c3fb27SDimitry Andric   // TODO: This works for any value with a specific known exponent range, don't
102406c3fb27SDimitry Andric   // just limit to constant 1.
102506c3fb27SDimitry Andric   if (!HasFP32DenormalFlush && !NumIsOne)
10265ffd83dbSDimitry Andric     return nullptr;
10275ffd83dbSDimitry Andric 
102806c3fb27SDimitry Andric   return Builder.CreateIntrinsic(Intrinsic::amdgcn_fdiv_fast, {}, {Num, Den});
102906c3fb27SDimitry Andric }
103006c3fb27SDimitry Andric 
visitFDivElement(IRBuilder<> & Builder,Value * Num,Value * Den,FastMathFlags DivFMF,FastMathFlags SqrtFMF,Value * RsqOp,const Instruction * FDivInst,float ReqdDivAccuracy) const103106c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::visitFDivElement(
103206c3fb27SDimitry Andric     IRBuilder<> &Builder, Value *Num, Value *Den, FastMathFlags DivFMF,
103306c3fb27SDimitry Andric     FastMathFlags SqrtFMF, Value *RsqOp, const Instruction *FDivInst,
103406c3fb27SDimitry Andric     float ReqdDivAccuracy) const {
103506c3fb27SDimitry Andric   if (RsqOp) {
103606c3fb27SDimitry Andric     Value *Rsq =
103706c3fb27SDimitry Andric         optimizeWithRsq(Builder, Num, RsqOp, DivFMF, SqrtFMF, FDivInst);
103806c3fb27SDimitry Andric     if (Rsq)
103906c3fb27SDimitry Andric       return Rsq;
104006c3fb27SDimitry Andric   }
104106c3fb27SDimitry Andric 
104206c3fb27SDimitry Andric   Value *Rcp = optimizeWithRcp(Builder, Num, Den, DivFMF, FDivInst);
104306c3fb27SDimitry Andric   if (Rcp)
104406c3fb27SDimitry Andric     return Rcp;
104506c3fb27SDimitry Andric 
104606c3fb27SDimitry Andric   // In the basic case fdiv_fast has the same instruction count as the frexp div
104706c3fb27SDimitry Andric   // expansion. Slightly prefer fdiv_fast since it ends in an fmul that can
104806c3fb27SDimitry Andric   // potentially be fused into a user. Also, materialization of the constants
104906c3fb27SDimitry Andric   // can be reused for multiple instances.
105006c3fb27SDimitry Andric   Value *FDivFast = optimizeWithFDivFast(Builder, Num, Den, ReqdDivAccuracy);
105106c3fb27SDimitry Andric   if (FDivFast)
105206c3fb27SDimitry Andric     return FDivFast;
105306c3fb27SDimitry Andric 
105406c3fb27SDimitry Andric   return emitFrexpDiv(Builder, Num, Den, DivFMF);
10555ffd83dbSDimitry Andric }
10565ffd83dbSDimitry Andric 
10575ffd83dbSDimitry Andric // Optimizations is performed based on fpmath, fast math flags as well as
10585ffd83dbSDimitry Andric // denormals to optimize fdiv with either rcp or fdiv.fast.
10595ffd83dbSDimitry Andric //
10605ffd83dbSDimitry Andric // With rcp:
10615ffd83dbSDimitry Andric //   1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
10625ffd83dbSDimitry Andric //                 allowed with unsafe-fp-math or afn.
10635ffd83dbSDimitry Andric //
10645ffd83dbSDimitry Andric //   a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
10655ffd83dbSDimitry Andric //
10665ffd83dbSDimitry Andric // With fdiv.fast:
10675ffd83dbSDimitry Andric //   a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
10685ffd83dbSDimitry Andric //
10695ffd83dbSDimitry Andric //   1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
10705ffd83dbSDimitry Andric //
10715ffd83dbSDimitry Andric // NOTE: rcp is the preference in cases that both are legal.
visitFDiv(BinaryOperator & FDiv)107206c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitFDiv(BinaryOperator &FDiv) {
107306c3fb27SDimitry Andric   if (DisableFDivExpand)
107406c3fb27SDimitry Andric     return false;
10755ffd83dbSDimitry Andric 
10765ffd83dbSDimitry Andric   Type *Ty = FDiv.getType()->getScalarType();
107706c3fb27SDimitry Andric   if (!Ty->isFloatTy())
107806c3fb27SDimitry Andric     return false;
10795ffd83dbSDimitry Andric 
1080e8d8bef9SDimitry Andric   // The f64 rcp/rsq approximations are pretty inaccurate. We can do an
108106c3fb27SDimitry Andric   // expansion around them in codegen. f16 is good enough to always use.
10820b57cec5SDimitry Andric 
10830b57cec5SDimitry Andric   const FPMathOperator *FPOp = cast<const FPMathOperator>(&FDiv);
108406c3fb27SDimitry Andric   const FastMathFlags DivFMF = FPOp->getFastMathFlags();
10855ffd83dbSDimitry Andric   const float ReqdAccuracy = FPOp->getFPAccuracy();
10860b57cec5SDimitry Andric 
108706c3fb27SDimitry Andric   FastMathFlags SqrtFMF;
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric   Value *Num = FDiv.getOperand(0);
10900b57cec5SDimitry Andric   Value *Den = FDiv.getOperand(1);
10910b57cec5SDimitry Andric 
109206c3fb27SDimitry Andric   Value *RsqOp = nullptr;
109306c3fb27SDimitry Andric   auto *DenII = dyn_cast<IntrinsicInst>(Den);
109406c3fb27SDimitry Andric   if (DenII && DenII->getIntrinsicID() == Intrinsic::sqrt &&
109506c3fb27SDimitry Andric       DenII->hasOneUse()) {
109606c3fb27SDimitry Andric     const auto *SqrtOp = cast<FPMathOperator>(DenII);
109706c3fb27SDimitry Andric     SqrtFMF = SqrtOp->getFastMathFlags();
109806c3fb27SDimitry Andric     if (canOptimizeWithRsq(SqrtOp, DivFMF, SqrtFMF))
109906c3fb27SDimitry Andric       RsqOp = SqrtOp->getOperand(0);
11000b57cec5SDimitry Andric   }
11010b57cec5SDimitry Andric 
11025f757f3fSDimitry Andric   // Inaccurate rcp is allowed with unsafe-fp-math or afn.
11035f757f3fSDimitry Andric   //
11045f757f3fSDimitry Andric   // Defer to codegen to handle this.
11055f757f3fSDimitry Andric   //
11065f757f3fSDimitry Andric   // TODO: Decide on an interpretation for interactions between afn + arcp +
11075f757f3fSDimitry Andric   // !fpmath, and make it consistent between here and codegen. For now, defer
11085f757f3fSDimitry Andric   // expansion of afn to codegen. The current interpretation is so aggressive we
11095f757f3fSDimitry Andric   // don't need any pre-consideration here when we have better information. A
11105f757f3fSDimitry Andric   // more conservative interpretation could use handling here.
11115f757f3fSDimitry Andric   const bool AllowInaccurateRcp = HasUnsafeFPMath || DivFMF.approxFunc();
11125f757f3fSDimitry Andric   if (!RsqOp && AllowInaccurateRcp)
11135f757f3fSDimitry Andric     return false;
11145f757f3fSDimitry Andric 
11155f757f3fSDimitry Andric   // Defer the correct implementations to codegen.
11165f757f3fSDimitry Andric   if (ReqdAccuracy < 1.0f)
11175f757f3fSDimitry Andric     return false;
11185f757f3fSDimitry Andric 
111906c3fb27SDimitry Andric   IRBuilder<> Builder(FDiv.getParent(), std::next(FDiv.getIterator()));
112006c3fb27SDimitry Andric   Builder.setFastMathFlags(DivFMF);
112106c3fb27SDimitry Andric   Builder.SetCurrentDebugLocation(FDiv.getDebugLoc());
112206c3fb27SDimitry Andric 
112306c3fb27SDimitry Andric   SmallVector<Value *, 4> NumVals;
112406c3fb27SDimitry Andric   SmallVector<Value *, 4> DenVals;
112506c3fb27SDimitry Andric   SmallVector<Value *, 4> RsqDenVals;
112606c3fb27SDimitry Andric   extractValues(Builder, NumVals, Num);
112706c3fb27SDimitry Andric   extractValues(Builder, DenVals, Den);
112806c3fb27SDimitry Andric 
112906c3fb27SDimitry Andric   if (RsqOp)
113006c3fb27SDimitry Andric     extractValues(Builder, RsqDenVals, RsqOp);
113106c3fb27SDimitry Andric 
113206c3fb27SDimitry Andric   SmallVector<Value *, 4> ResultVals(NumVals.size());
113306c3fb27SDimitry Andric   for (int I = 0, E = NumVals.size(); I != E; ++I) {
113406c3fb27SDimitry Andric     Value *NumElt = NumVals[I];
113506c3fb27SDimitry Andric     Value *DenElt = DenVals[I];
113606c3fb27SDimitry Andric     Value *RsqDenElt = RsqOp ? RsqDenVals[I] : nullptr;
113706c3fb27SDimitry Andric 
113806c3fb27SDimitry Andric     Value *NewElt =
113906c3fb27SDimitry Andric         visitFDivElement(Builder, NumElt, DenElt, DivFMF, SqrtFMF, RsqDenElt,
114006c3fb27SDimitry Andric                          cast<Instruction>(FPOp), ReqdAccuracy);
114106c3fb27SDimitry Andric     if (!NewElt) {
114206c3fb27SDimitry Andric       // Keep the original, but scalarized.
114306c3fb27SDimitry Andric 
114406c3fb27SDimitry Andric       // This has the unfortunate side effect of sometimes scalarizing when
114506c3fb27SDimitry Andric       // we're not going to do anything.
114606c3fb27SDimitry Andric       NewElt = Builder.CreateFDiv(NumElt, DenElt);
114706c3fb27SDimitry Andric       if (auto *NewEltInst = dyn_cast<Instruction>(NewElt))
114806c3fb27SDimitry Andric         NewEltInst->copyMetadata(FDiv);
11490b57cec5SDimitry Andric     }
11500b57cec5SDimitry Andric 
115106c3fb27SDimitry Andric     ResultVals[I] = NewElt;
11520b57cec5SDimitry Andric   }
11530b57cec5SDimitry Andric 
115406c3fb27SDimitry Andric   Value *NewVal = insertValues(Builder, FDiv.getType(), ResultVals);
1155fe6060f1SDimitry Andric 
115606c3fb27SDimitry Andric   if (NewVal) {
115706c3fb27SDimitry Andric     FDiv.replaceAllUsesWith(NewVal);
115806c3fb27SDimitry Andric     NewVal->takeName(&FDiv);
115906c3fb27SDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(&FDiv, TLInfo);
116006c3fb27SDimitry Andric   }
1161fe6060f1SDimitry Andric 
1162fe6060f1SDimitry Andric   return true;
1163fe6060f1SDimitry Andric }
1164fe6060f1SDimitry Andric 
hasUnsafeFPMath(const Function & F)11650b57cec5SDimitry Andric static bool hasUnsafeFPMath(const Function &F) {
11660b57cec5SDimitry Andric   Attribute Attr = F.getFnAttribute("unsafe-fp-math");
1167fe6060f1SDimitry Andric   return Attr.getValueAsBool();
11680b57cec5SDimitry Andric }
11690b57cec5SDimitry Andric 
getMul64(IRBuilder<> & Builder,Value * LHS,Value * RHS)11700b57cec5SDimitry Andric static std::pair<Value*, Value*> getMul64(IRBuilder<> &Builder,
11710b57cec5SDimitry Andric                                           Value *LHS, Value *RHS) {
11720b57cec5SDimitry Andric   Type *I32Ty = Builder.getInt32Ty();
11730b57cec5SDimitry Andric   Type *I64Ty = Builder.getInt64Ty();
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric   Value *LHS_EXT64 = Builder.CreateZExt(LHS, I64Ty);
11760b57cec5SDimitry Andric   Value *RHS_EXT64 = Builder.CreateZExt(RHS, I64Ty);
11770b57cec5SDimitry Andric   Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64);
11780b57cec5SDimitry Andric   Value *Lo = Builder.CreateTrunc(MUL64, I32Ty);
11790b57cec5SDimitry Andric   Value *Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32));
11800b57cec5SDimitry Andric   Hi = Builder.CreateTrunc(Hi, I32Ty);
1181bdd1243dSDimitry Andric   return std::pair(Lo, Hi);
11820b57cec5SDimitry Andric }
11830b57cec5SDimitry Andric 
getMulHu(IRBuilder<> & Builder,Value * LHS,Value * RHS)11840b57cec5SDimitry Andric static Value* getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS) {
11850b57cec5SDimitry Andric   return getMul64(Builder, LHS, RHS).second;
11860b57cec5SDimitry Andric }
11870b57cec5SDimitry Andric 
118881ad6265SDimitry Andric /// Figure out how many bits are really needed for this division. \p AtLeast is
11895ffd83dbSDimitry Andric /// an optimization hint to bypass the second ComputeNumSignBits call if we the
11905ffd83dbSDimitry Andric /// first one is insufficient. Returns -1 on failure.
getDivNumBits(BinaryOperator & I,Value * Num,Value * Den,unsigned AtLeast,bool IsSigned) const119106c3fb27SDimitry Andric int AMDGPUCodeGenPrepareImpl::getDivNumBits(BinaryOperator &I, Value *Num,
119206c3fb27SDimitry Andric                                             Value *Den, unsigned AtLeast,
119306c3fb27SDimitry Andric                                             bool IsSigned) const {
11945ffd83dbSDimitry Andric   const DataLayout &DL = Mod->getDataLayout();
11955ffd83dbSDimitry Andric   unsigned LHSSignBits = ComputeNumSignBits(Num, DL, 0, AC, &I);
11965ffd83dbSDimitry Andric   if (LHSSignBits < AtLeast)
11975ffd83dbSDimitry Andric     return -1;
11985ffd83dbSDimitry Andric 
11995ffd83dbSDimitry Andric   unsigned RHSSignBits = ComputeNumSignBits(Den, DL, 0, AC, &I);
12005ffd83dbSDimitry Andric   if (RHSSignBits < AtLeast)
12015ffd83dbSDimitry Andric     return -1;
12025ffd83dbSDimitry Andric 
12035ffd83dbSDimitry Andric   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
12045ffd83dbSDimitry Andric   unsigned DivBits = Num->getType()->getScalarSizeInBits() - SignBits;
12055ffd83dbSDimitry Andric   if (IsSigned)
12065ffd83dbSDimitry Andric     ++DivBits;
12075ffd83dbSDimitry Andric   return DivBits;
12085ffd83dbSDimitry Andric }
12095ffd83dbSDimitry Andric 
12100b57cec5SDimitry Andric // The fractional part of a float is enough to accurately represent up to
12110b57cec5SDimitry Andric // a 24-bit signed integer.
expandDivRem24(IRBuilder<> & Builder,BinaryOperator & I,Value * Num,Value * Den,bool IsDiv,bool IsSigned) const121206c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::expandDivRem24(IRBuilder<> &Builder,
121306c3fb27SDimitry Andric                                                 BinaryOperator &I, Value *Num,
121406c3fb27SDimitry Andric                                                 Value *Den, bool IsDiv,
121506c3fb27SDimitry Andric                                                 bool IsSigned) const {
12165ffd83dbSDimitry Andric   int DivBits = getDivNumBits(I, Num, Den, 9, IsSigned);
12175ffd83dbSDimitry Andric   if (DivBits == -1)
12180b57cec5SDimitry Andric     return nullptr;
12195ffd83dbSDimitry Andric   return expandDivRem24Impl(Builder, I, Num, Den, DivBits, IsDiv, IsSigned);
12205ffd83dbSDimitry Andric }
12210b57cec5SDimitry Andric 
expandDivRem24Impl(IRBuilder<> & Builder,BinaryOperator & I,Value * Num,Value * Den,unsigned DivBits,bool IsDiv,bool IsSigned) const122206c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::expandDivRem24Impl(
122306c3fb27SDimitry Andric     IRBuilder<> &Builder, BinaryOperator &I, Value *Num, Value *Den,
122406c3fb27SDimitry Andric     unsigned DivBits, bool IsDiv, bool IsSigned) const {
12250b57cec5SDimitry Andric   Type *I32Ty = Builder.getInt32Ty();
12265ffd83dbSDimitry Andric   Num = Builder.CreateTrunc(Num, I32Ty);
12275ffd83dbSDimitry Andric   Den = Builder.CreateTrunc(Den, I32Ty);
12285ffd83dbSDimitry Andric 
12290b57cec5SDimitry Andric   Type *F32Ty = Builder.getFloatTy();
12300b57cec5SDimitry Andric   ConstantInt *One = Builder.getInt32(1);
12310b57cec5SDimitry Andric   Value *JQ = One;
12320b57cec5SDimitry Andric 
12330b57cec5SDimitry Andric   if (IsSigned) {
12340b57cec5SDimitry Andric     // char|short jq = ia ^ ib;
12350b57cec5SDimitry Andric     JQ = Builder.CreateXor(Num, Den);
12360b57cec5SDimitry Andric 
12370b57cec5SDimitry Andric     // jq = jq >> (bitsize - 2)
12380b57cec5SDimitry Andric     JQ = Builder.CreateAShr(JQ, Builder.getInt32(30));
12390b57cec5SDimitry Andric 
12400b57cec5SDimitry Andric     // jq = jq | 0x1
12410b57cec5SDimitry Andric     JQ = Builder.CreateOr(JQ, One);
12420b57cec5SDimitry Andric   }
12430b57cec5SDimitry Andric 
12440b57cec5SDimitry Andric   // int ia = (int)LHS;
12450b57cec5SDimitry Andric   Value *IA = Num;
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric   // int ib, (int)RHS;
12480b57cec5SDimitry Andric   Value *IB = Den;
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric   // float fa = (float)ia;
12510b57cec5SDimitry Andric   Value *FA = IsSigned ? Builder.CreateSIToFP(IA, F32Ty)
12520b57cec5SDimitry Andric                        : Builder.CreateUIToFP(IA, F32Ty);
12530b57cec5SDimitry Andric 
12540b57cec5SDimitry Andric   // float fb = (float)ib;
12550b57cec5SDimitry Andric   Value *FB = IsSigned ? Builder.CreateSIToFP(IB,F32Ty)
12560b57cec5SDimitry Andric                        : Builder.CreateUIToFP(IB,F32Ty);
12570b57cec5SDimitry Andric 
12585ffd83dbSDimitry Andric   Function *RcpDecl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp,
12595ffd83dbSDimitry Andric                                                 Builder.getFloatTy());
12605ffd83dbSDimitry Andric   Value *RCP = Builder.CreateCall(RcpDecl, { FB });
12610b57cec5SDimitry Andric   Value *FQM = Builder.CreateFMul(FA, RCP);
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric   // fq = trunc(fqm);
12640b57cec5SDimitry Andric   CallInst *FQ = Builder.CreateUnaryIntrinsic(Intrinsic::trunc, FQM);
12650b57cec5SDimitry Andric   FQ->copyFastMathFlags(Builder.getFastMathFlags());
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric   // float fqneg = -fq;
12680b57cec5SDimitry Andric   Value *FQNeg = Builder.CreateFNeg(FQ);
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric   // float fr = mad(fqneg, fb, fa);
12715ffd83dbSDimitry Andric   auto FMAD = !ST->hasMadMacF32Insts()
12725ffd83dbSDimitry Andric                   ? Intrinsic::fma
12735ffd83dbSDimitry Andric                   : (Intrinsic::ID)Intrinsic::amdgcn_fmad_ftz;
12745ffd83dbSDimitry Andric   Value *FR = Builder.CreateIntrinsic(FMAD,
12750b57cec5SDimitry Andric                                       {FQNeg->getType()}, {FQNeg, FB, FA}, FQ);
12760b57cec5SDimitry Andric 
12770b57cec5SDimitry Andric   // int iq = (int)fq;
12780b57cec5SDimitry Andric   Value *IQ = IsSigned ? Builder.CreateFPToSI(FQ, I32Ty)
12790b57cec5SDimitry Andric                        : Builder.CreateFPToUI(FQ, I32Ty);
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric   // fr = fabs(fr);
12820b57cec5SDimitry Andric   FR = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FR, FQ);
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric   // fb = fabs(fb);
12850b57cec5SDimitry Andric   FB = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FB, FQ);
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric   // int cv = fr >= fb;
12880b57cec5SDimitry Andric   Value *CV = Builder.CreateFCmpOGE(FR, FB);
12890b57cec5SDimitry Andric 
12900b57cec5SDimitry Andric   // jq = (cv ? jq : 0);
12910b57cec5SDimitry Andric   JQ = Builder.CreateSelect(CV, JQ, Builder.getInt32(0));
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric   // dst = iq + jq;
12940b57cec5SDimitry Andric   Value *Div = Builder.CreateAdd(IQ, JQ);
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric   Value *Res = Div;
12970b57cec5SDimitry Andric   if (!IsDiv) {
12980b57cec5SDimitry Andric     // Rem needs compensation, it's easier to recompute it
12990b57cec5SDimitry Andric     Value *Rem = Builder.CreateMul(Div, Den);
13000b57cec5SDimitry Andric     Res = Builder.CreateSub(Num, Rem);
13010b57cec5SDimitry Andric   }
13020b57cec5SDimitry Andric 
13035ffd83dbSDimitry Andric   if (DivBits != 0 && DivBits < 32) {
13045ffd83dbSDimitry Andric     // Extend in register from the number of bits this divide really is.
13050b57cec5SDimitry Andric     if (IsSigned) {
13065ffd83dbSDimitry Andric       int InRegBits = 32 - DivBits;
13075ffd83dbSDimitry Andric 
13085ffd83dbSDimitry Andric       Res = Builder.CreateShl(Res, InRegBits);
13095ffd83dbSDimitry Andric       Res = Builder.CreateAShr(Res, InRegBits);
13100b57cec5SDimitry Andric     } else {
13115ffd83dbSDimitry Andric       ConstantInt *TruncMask
13125ffd83dbSDimitry Andric         = Builder.getInt32((UINT64_C(1) << DivBits) - 1);
13130b57cec5SDimitry Andric       Res = Builder.CreateAnd(Res, TruncMask);
13140b57cec5SDimitry Andric     }
13155ffd83dbSDimitry Andric   }
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric   return Res;
13180b57cec5SDimitry Andric }
13190b57cec5SDimitry Andric 
13205ffd83dbSDimitry Andric // Try to recognize special cases the DAG will emit special, better expansions
13215ffd83dbSDimitry Andric // than the general expansion we do here.
13225ffd83dbSDimitry Andric 
13235ffd83dbSDimitry Andric // TODO: It would be better to just directly handle those optimizations here.
divHasSpecialOptimization(BinaryOperator & I,Value * Num,Value * Den) const132406c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::divHasSpecialOptimization(BinaryOperator &I,
132506c3fb27SDimitry Andric                                                          Value *Num,
132606c3fb27SDimitry Andric                                                          Value *Den) const {
13275ffd83dbSDimitry Andric   if (Constant *C = dyn_cast<Constant>(Den)) {
13285ffd83dbSDimitry Andric     // Arbitrary constants get a better expansion as long as a wider mulhi is
13295ffd83dbSDimitry Andric     // legal.
13305ffd83dbSDimitry Andric     if (C->getType()->getScalarSizeInBits() <= 32)
13315ffd83dbSDimitry Andric       return true;
13325ffd83dbSDimitry Andric 
13335ffd83dbSDimitry Andric     // TODO: Sdiv check for not exact for some reason.
13345ffd83dbSDimitry Andric 
13355ffd83dbSDimitry Andric     // If there's no wider mulhi, there's only a better expansion for powers of
13365ffd83dbSDimitry Andric     // two.
13375ffd83dbSDimitry Andric     // TODO: Should really know for each vector element.
13385ffd83dbSDimitry Andric     if (isKnownToBeAPowerOfTwo(C, *DL, true, 0, AC, &I, DT))
13395ffd83dbSDimitry Andric       return true;
13405ffd83dbSDimitry Andric 
13415ffd83dbSDimitry Andric     return false;
13425ffd83dbSDimitry Andric   }
13435ffd83dbSDimitry Andric 
13445ffd83dbSDimitry Andric   if (BinaryOperator *BinOpDen = dyn_cast<BinaryOperator>(Den)) {
13455ffd83dbSDimitry Andric     // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
13465ffd83dbSDimitry Andric     if (BinOpDen->getOpcode() == Instruction::Shl &&
13475ffd83dbSDimitry Andric         isa<Constant>(BinOpDen->getOperand(0)) &&
13485ffd83dbSDimitry Andric         isKnownToBeAPowerOfTwo(BinOpDen->getOperand(0), *DL, true,
13495ffd83dbSDimitry Andric                                0, AC, &I, DT)) {
13505ffd83dbSDimitry Andric       return true;
13515ffd83dbSDimitry Andric     }
13525ffd83dbSDimitry Andric   }
13535ffd83dbSDimitry Andric 
13545ffd83dbSDimitry Andric   return false;
13555ffd83dbSDimitry Andric }
13565ffd83dbSDimitry Andric 
getSign32(Value * V,IRBuilder<> & Builder,const DataLayout * DL)13575ffd83dbSDimitry Andric static Value *getSign32(Value *V, IRBuilder<> &Builder, const DataLayout *DL) {
13585ffd83dbSDimitry Andric   // Check whether the sign can be determined statically.
13595ffd83dbSDimitry Andric   KnownBits Known = computeKnownBits(V, *DL);
13605ffd83dbSDimitry Andric   if (Known.isNegative())
13615ffd83dbSDimitry Andric     return Constant::getAllOnesValue(V->getType());
13625ffd83dbSDimitry Andric   if (Known.isNonNegative())
13635ffd83dbSDimitry Andric     return Constant::getNullValue(V->getType());
13645ffd83dbSDimitry Andric   return Builder.CreateAShr(V, Builder.getInt32(31));
13655ffd83dbSDimitry Andric }
13665ffd83dbSDimitry Andric 
expandDivRem32(IRBuilder<> & Builder,BinaryOperator & I,Value * X,Value * Y) const136706c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::expandDivRem32(IRBuilder<> &Builder,
13685ffd83dbSDimitry Andric                                                 BinaryOperator &I, Value *X,
13695ffd83dbSDimitry Andric                                                 Value *Y) const {
13700b57cec5SDimitry Andric   Instruction::BinaryOps Opc = I.getOpcode();
13710b57cec5SDimitry Andric   assert(Opc == Instruction::URem || Opc == Instruction::UDiv ||
13720b57cec5SDimitry Andric          Opc == Instruction::SRem || Opc == Instruction::SDiv);
13730b57cec5SDimitry Andric 
13740b57cec5SDimitry Andric   FastMathFlags FMF;
13750b57cec5SDimitry Andric   FMF.setFast();
13760b57cec5SDimitry Andric   Builder.setFastMathFlags(FMF);
13770b57cec5SDimitry Andric 
13785ffd83dbSDimitry Andric   if (divHasSpecialOptimization(I, X, Y))
13795ffd83dbSDimitry Andric     return nullptr;  // Keep it for later optimization.
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric   bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv;
13820b57cec5SDimitry Andric   bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv;
13830b57cec5SDimitry Andric 
13845ffd83dbSDimitry Andric   Type *Ty = X->getType();
13850b57cec5SDimitry Andric   Type *I32Ty = Builder.getInt32Ty();
13860b57cec5SDimitry Andric   Type *F32Ty = Builder.getFloatTy();
13870b57cec5SDimitry Andric 
13880b57cec5SDimitry Andric   if (Ty->getScalarSizeInBits() < 32) {
13890b57cec5SDimitry Andric     if (IsSigned) {
13905ffd83dbSDimitry Andric       X = Builder.CreateSExt(X, I32Ty);
13915ffd83dbSDimitry Andric       Y = Builder.CreateSExt(Y, I32Ty);
13920b57cec5SDimitry Andric     } else {
13935ffd83dbSDimitry Andric       X = Builder.CreateZExt(X, I32Ty);
13945ffd83dbSDimitry Andric       Y = Builder.CreateZExt(Y, I32Ty);
13950b57cec5SDimitry Andric     }
13960b57cec5SDimitry Andric   }
13970b57cec5SDimitry Andric 
13985ffd83dbSDimitry Andric   if (Value *Res = expandDivRem24(Builder, I, X, Y, IsDiv, IsSigned)) {
13995ffd83dbSDimitry Andric     return IsSigned ? Builder.CreateSExtOrTrunc(Res, Ty) :
14005ffd83dbSDimitry Andric                       Builder.CreateZExtOrTrunc(Res, Ty);
14010b57cec5SDimitry Andric   }
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   ConstantInt *Zero = Builder.getInt32(0);
14040b57cec5SDimitry Andric   ConstantInt *One = Builder.getInt32(1);
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric   Value *Sign = nullptr;
14070b57cec5SDimitry Andric   if (IsSigned) {
14085ffd83dbSDimitry Andric     Value *SignX = getSign32(X, Builder, DL);
14095ffd83dbSDimitry Andric     Value *SignY = getSign32(Y, Builder, DL);
14100b57cec5SDimitry Andric     // Remainder sign is the same as LHS
14115ffd83dbSDimitry Andric     Sign = IsDiv ? Builder.CreateXor(SignX, SignY) : SignX;
14120b57cec5SDimitry Andric 
14135ffd83dbSDimitry Andric     X = Builder.CreateAdd(X, SignX);
14145ffd83dbSDimitry Andric     Y = Builder.CreateAdd(Y, SignY);
14150b57cec5SDimitry Andric 
14165ffd83dbSDimitry Andric     X = Builder.CreateXor(X, SignX);
14175ffd83dbSDimitry Andric     Y = Builder.CreateXor(Y, SignY);
14180b57cec5SDimitry Andric   }
14190b57cec5SDimitry Andric 
14205ffd83dbSDimitry Andric   // The algorithm here is based on ideas from "Software Integer Division", Tom
14215ffd83dbSDimitry Andric   // Rodeheffer, August 2008.
14225ffd83dbSDimitry Andric   //
14235ffd83dbSDimitry Andric   // unsigned udiv(unsigned x, unsigned y) {
14245ffd83dbSDimitry Andric   //   // Initial estimate of inv(y). The constant is less than 2^32 to ensure
14255ffd83dbSDimitry Andric   //   // that this is a lower bound on inv(y), even if some of the calculations
14265ffd83dbSDimitry Andric   //   // round up.
14275ffd83dbSDimitry Andric   //   unsigned z = (unsigned)((4294967296.0 - 512.0) * v_rcp_f32((float)y));
14285ffd83dbSDimitry Andric   //
14295ffd83dbSDimitry Andric   //   // One round of UNR (Unsigned integer Newton-Raphson) to improve z.
14305ffd83dbSDimitry Andric   //   // Empirically this is guaranteed to give a "two-y" lower bound on
14315ffd83dbSDimitry Andric   //   // inv(y).
14325ffd83dbSDimitry Andric   //   z += umulh(z, -y * z);
14335ffd83dbSDimitry Andric   //
14345ffd83dbSDimitry Andric   //   // Quotient/remainder estimate.
14355ffd83dbSDimitry Andric   //   unsigned q = umulh(x, z);
14365ffd83dbSDimitry Andric   //   unsigned r = x - q * y;
14375ffd83dbSDimitry Andric   //
14385ffd83dbSDimitry Andric   //   // Two rounds of quotient/remainder refinement.
14395ffd83dbSDimitry Andric   //   if (r >= y) {
14405ffd83dbSDimitry Andric   //     ++q;
14415ffd83dbSDimitry Andric   //     r -= y;
14425ffd83dbSDimitry Andric   //   }
14435ffd83dbSDimitry Andric   //   if (r >= y) {
14445ffd83dbSDimitry Andric   //     ++q;
14455ffd83dbSDimitry Andric   //     r -= y;
14465ffd83dbSDimitry Andric   //   }
14475ffd83dbSDimitry Andric   //
14485ffd83dbSDimitry Andric   //   return q;
14495ffd83dbSDimitry Andric   // }
14500b57cec5SDimitry Andric 
14515ffd83dbSDimitry Andric   // Initial estimate of inv(y).
14525ffd83dbSDimitry Andric   Value *FloatY = Builder.CreateUIToFP(Y, F32Ty);
14535ffd83dbSDimitry Andric   Function *Rcp = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp, F32Ty);
14545ffd83dbSDimitry Andric   Value *RcpY = Builder.CreateCall(Rcp, {FloatY});
145506c3fb27SDimitry Andric   Constant *Scale = ConstantFP::get(F32Ty, llvm::bit_cast<float>(0x4F7FFFFE));
14565ffd83dbSDimitry Andric   Value *ScaledY = Builder.CreateFMul(RcpY, Scale);
14575ffd83dbSDimitry Andric   Value *Z = Builder.CreateFPToUI(ScaledY, I32Ty);
14580b57cec5SDimitry Andric 
14595ffd83dbSDimitry Andric   // One round of UNR.
14605ffd83dbSDimitry Andric   Value *NegY = Builder.CreateSub(Zero, Y);
14615ffd83dbSDimitry Andric   Value *NegYZ = Builder.CreateMul(NegY, Z);
14625ffd83dbSDimitry Andric   Z = Builder.CreateAdd(Z, getMulHu(Builder, Z, NegYZ));
14630b57cec5SDimitry Andric 
14645ffd83dbSDimitry Andric   // Quotient/remainder estimate.
14655ffd83dbSDimitry Andric   Value *Q = getMulHu(Builder, X, Z);
14665ffd83dbSDimitry Andric   Value *R = Builder.CreateSub(X, Builder.CreateMul(Q, Y));
14670b57cec5SDimitry Andric 
14685ffd83dbSDimitry Andric   // First quotient/remainder refinement.
14695ffd83dbSDimitry Andric   Value *Cond = Builder.CreateICmpUGE(R, Y);
14705ffd83dbSDimitry Andric   if (IsDiv)
14715ffd83dbSDimitry Andric     Q = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
14725ffd83dbSDimitry Andric   R = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
14730b57cec5SDimitry Andric 
14745ffd83dbSDimitry Andric   // Second quotient/remainder refinement.
14755ffd83dbSDimitry Andric   Cond = Builder.CreateICmpUGE(R, Y);
14760b57cec5SDimitry Andric   Value *Res;
14775ffd83dbSDimitry Andric   if (IsDiv)
14785ffd83dbSDimitry Andric     Res = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
14795ffd83dbSDimitry Andric   else
14805ffd83dbSDimitry Andric     Res = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
14810b57cec5SDimitry Andric 
14820b57cec5SDimitry Andric   if (IsSigned) {
14830b57cec5SDimitry Andric     Res = Builder.CreateXor(Res, Sign);
14840b57cec5SDimitry Andric     Res = Builder.CreateSub(Res, Sign);
14850b57cec5SDimitry Andric   }
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric   Res = Builder.CreateTrunc(Res, Ty);
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric   return Res;
14900b57cec5SDimitry Andric }
14910b57cec5SDimitry Andric 
shrinkDivRem64(IRBuilder<> & Builder,BinaryOperator & I,Value * Num,Value * Den) const149206c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::shrinkDivRem64(IRBuilder<> &Builder,
149306c3fb27SDimitry Andric                                                 BinaryOperator &I, Value *Num,
149406c3fb27SDimitry Andric                                                 Value *Den) const {
14955ffd83dbSDimitry Andric   if (!ExpandDiv64InIR && divHasSpecialOptimization(I, Num, Den))
14965ffd83dbSDimitry Andric     return nullptr;  // Keep it for later optimization.
14975ffd83dbSDimitry Andric 
14985ffd83dbSDimitry Andric   Instruction::BinaryOps Opc = I.getOpcode();
14995ffd83dbSDimitry Andric 
15005ffd83dbSDimitry Andric   bool IsDiv = Opc == Instruction::SDiv || Opc == Instruction::UDiv;
15015ffd83dbSDimitry Andric   bool IsSigned = Opc == Instruction::SDiv || Opc == Instruction::SRem;
15025ffd83dbSDimitry Andric 
15035ffd83dbSDimitry Andric   int NumDivBits = getDivNumBits(I, Num, Den, 32, IsSigned);
15045ffd83dbSDimitry Andric   if (NumDivBits == -1)
15055ffd83dbSDimitry Andric     return nullptr;
15065ffd83dbSDimitry Andric 
15075ffd83dbSDimitry Andric   Value *Narrowed = nullptr;
15085ffd83dbSDimitry Andric   if (NumDivBits <= 24) {
15095ffd83dbSDimitry Andric     Narrowed = expandDivRem24Impl(Builder, I, Num, Den, NumDivBits,
15105ffd83dbSDimitry Andric                                   IsDiv, IsSigned);
15115ffd83dbSDimitry Andric   } else if (NumDivBits <= 32) {
15125ffd83dbSDimitry Andric     Narrowed = expandDivRem32(Builder, I, Num, Den);
15135ffd83dbSDimitry Andric   }
15145ffd83dbSDimitry Andric 
15155ffd83dbSDimitry Andric   if (Narrowed) {
15165ffd83dbSDimitry Andric     return IsSigned ? Builder.CreateSExt(Narrowed, Num->getType()) :
15175ffd83dbSDimitry Andric                       Builder.CreateZExt(Narrowed, Num->getType());
15185ffd83dbSDimitry Andric   }
15195ffd83dbSDimitry Andric 
15205ffd83dbSDimitry Andric   return nullptr;
15215ffd83dbSDimitry Andric }
15225ffd83dbSDimitry Andric 
expandDivRem64(BinaryOperator & I) const152306c3fb27SDimitry Andric void AMDGPUCodeGenPrepareImpl::expandDivRem64(BinaryOperator &I) const {
15245ffd83dbSDimitry Andric   Instruction::BinaryOps Opc = I.getOpcode();
15255ffd83dbSDimitry Andric   // Do the general expansion.
15265ffd83dbSDimitry Andric   if (Opc == Instruction::UDiv || Opc == Instruction::SDiv) {
15275ffd83dbSDimitry Andric     expandDivisionUpTo64Bits(&I);
15285ffd83dbSDimitry Andric     return;
15295ffd83dbSDimitry Andric   }
15305ffd83dbSDimitry Andric 
15315ffd83dbSDimitry Andric   if (Opc == Instruction::URem || Opc == Instruction::SRem) {
15325ffd83dbSDimitry Andric     expandRemainderUpTo64Bits(&I);
15335ffd83dbSDimitry Andric     return;
15345ffd83dbSDimitry Andric   }
15355ffd83dbSDimitry Andric 
15365ffd83dbSDimitry Andric   llvm_unreachable("not a division");
15375ffd83dbSDimitry Andric }
15385ffd83dbSDimitry Andric 
visitBinaryOperator(BinaryOperator & I)153906c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitBinaryOperator(BinaryOperator &I) {
15405ffd83dbSDimitry Andric   if (foldBinOpIntoSelect(I))
15415ffd83dbSDimitry Andric     return true;
15425ffd83dbSDimitry Andric 
15430b57cec5SDimitry Andric   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
154406c3fb27SDimitry Andric       UA->isUniform(&I) && promoteUniformOpToI32(I))
15450b57cec5SDimitry Andric     return true;
15460b57cec5SDimitry Andric 
15478bcb0991SDimitry Andric   if (UseMul24Intrin && replaceMulWithMul24(I))
15480b57cec5SDimitry Andric     return true;
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric   bool Changed = false;
15510b57cec5SDimitry Andric   Instruction::BinaryOps Opc = I.getOpcode();
15520b57cec5SDimitry Andric   Type *Ty = I.getType();
15530b57cec5SDimitry Andric   Value *NewDiv = nullptr;
15545ffd83dbSDimitry Andric   unsigned ScalarSize = Ty->getScalarSizeInBits();
15555ffd83dbSDimitry Andric 
15565ffd83dbSDimitry Andric   SmallVector<BinaryOperator *, 8> Div64ToExpand;
15575ffd83dbSDimitry Andric 
15580b57cec5SDimitry Andric   if ((Opc == Instruction::URem || Opc == Instruction::UDiv ||
15590b57cec5SDimitry Andric        Opc == Instruction::SRem || Opc == Instruction::SDiv) &&
15605ffd83dbSDimitry Andric       ScalarSize <= 64 &&
15615ffd83dbSDimitry Andric       !DisableIDivExpand) {
15620b57cec5SDimitry Andric     Value *Num = I.getOperand(0);
15630b57cec5SDimitry Andric     Value *Den = I.getOperand(1);
15640b57cec5SDimitry Andric     IRBuilder<> Builder(&I);
15650b57cec5SDimitry Andric     Builder.SetCurrentDebugLocation(I.getDebugLoc());
15660b57cec5SDimitry Andric 
15675ffd83dbSDimitry Andric     if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1568bdd1243dSDimitry Andric       NewDiv = PoisonValue::get(VT);
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric       for (unsigned N = 0, E = VT->getNumElements(); N != E; ++N) {
15710b57cec5SDimitry Andric         Value *NumEltN = Builder.CreateExtractElement(Num, N);
15720b57cec5SDimitry Andric         Value *DenEltN = Builder.CreateExtractElement(Den, N);
15735ffd83dbSDimitry Andric 
15745ffd83dbSDimitry Andric         Value *NewElt;
15755ffd83dbSDimitry Andric         if (ScalarSize <= 32) {
15765ffd83dbSDimitry Andric           NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN);
15770b57cec5SDimitry Andric           if (!NewElt)
15780b57cec5SDimitry Andric             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
15795ffd83dbSDimitry Andric         } else {
15805ffd83dbSDimitry Andric           // See if this 64-bit division can be shrunk to 32/24-bits before
15815ffd83dbSDimitry Andric           // producing the general expansion.
15825ffd83dbSDimitry Andric           NewElt = shrinkDivRem64(Builder, I, NumEltN, DenEltN);
15835ffd83dbSDimitry Andric           if (!NewElt) {
15845ffd83dbSDimitry Andric             // The general 64-bit expansion introduces control flow and doesn't
15855ffd83dbSDimitry Andric             // return the new value. Just insert a scalar copy and defer
15865ffd83dbSDimitry Andric             // expanding it.
15875ffd83dbSDimitry Andric             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
15885ffd83dbSDimitry Andric             Div64ToExpand.push_back(cast<BinaryOperator>(NewElt));
15895ffd83dbSDimitry Andric           }
15905ffd83dbSDimitry Andric         }
15915ffd83dbSDimitry Andric 
15920b57cec5SDimitry Andric         NewDiv = Builder.CreateInsertElement(NewDiv, NewElt, N);
15930b57cec5SDimitry Andric       }
15940b57cec5SDimitry Andric     } else {
15955ffd83dbSDimitry Andric       if (ScalarSize <= 32)
15960b57cec5SDimitry Andric         NewDiv = expandDivRem32(Builder, I, Num, Den);
15975ffd83dbSDimitry Andric       else {
15985ffd83dbSDimitry Andric         NewDiv = shrinkDivRem64(Builder, I, Num, Den);
15995ffd83dbSDimitry Andric         if (!NewDiv)
16005ffd83dbSDimitry Andric           Div64ToExpand.push_back(&I);
16015ffd83dbSDimitry Andric       }
16020b57cec5SDimitry Andric     }
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric     if (NewDiv) {
16050b57cec5SDimitry Andric       I.replaceAllUsesWith(NewDiv);
16060b57cec5SDimitry Andric       I.eraseFromParent();
16070b57cec5SDimitry Andric       Changed = true;
16080b57cec5SDimitry Andric     }
16090b57cec5SDimitry Andric   }
16100b57cec5SDimitry Andric 
16115ffd83dbSDimitry Andric   if (ExpandDiv64InIR) {
16125ffd83dbSDimitry Andric     // TODO: We get much worse code in specially handled constant cases.
16135ffd83dbSDimitry Andric     for (BinaryOperator *Div : Div64ToExpand) {
16145ffd83dbSDimitry Andric       expandDivRem64(*Div);
161506c3fb27SDimitry Andric       FlowChanged = true;
16165ffd83dbSDimitry Andric       Changed = true;
16175ffd83dbSDimitry Andric     }
16185ffd83dbSDimitry Andric   }
16195ffd83dbSDimitry Andric 
16200b57cec5SDimitry Andric   return Changed;
16210b57cec5SDimitry Andric }
16220b57cec5SDimitry Andric 
visitLoadInst(LoadInst & I)162306c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitLoadInst(LoadInst &I) {
16240b57cec5SDimitry Andric   if (!WidenLoads)
16250b57cec5SDimitry Andric     return false;
16260b57cec5SDimitry Andric 
16270b57cec5SDimitry Andric   if ((I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
16280b57cec5SDimitry Andric        I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
16290b57cec5SDimitry Andric       canWidenScalarExtLoad(I)) {
16300b57cec5SDimitry Andric     IRBuilder<> Builder(&I);
16310b57cec5SDimitry Andric     Builder.SetCurrentDebugLocation(I.getDebugLoc());
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric     Type *I32Ty = Builder.getInt32Ty();
163406c3fb27SDimitry Andric     LoadInst *WidenLoad = Builder.CreateLoad(I32Ty, I.getPointerOperand());
16350b57cec5SDimitry Andric     WidenLoad->copyMetadata(I);
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric     // If we have range metadata, we need to convert the type, and not make
16380b57cec5SDimitry Andric     // assumptions about the high bits.
16390b57cec5SDimitry Andric     if (auto *Range = WidenLoad->getMetadata(LLVMContext::MD_range)) {
16400b57cec5SDimitry Andric       ConstantInt *Lower =
16410b57cec5SDimitry Andric         mdconst::extract<ConstantInt>(Range->getOperand(0));
16420b57cec5SDimitry Andric 
1643349cc55cSDimitry Andric       if (Lower->isNullValue()) {
16440b57cec5SDimitry Andric         WidenLoad->setMetadata(LLVMContext::MD_range, nullptr);
16450b57cec5SDimitry Andric       } else {
16460b57cec5SDimitry Andric         Metadata *LowAndHigh[] = {
16470b57cec5SDimitry Andric           ConstantAsMetadata::get(ConstantInt::get(I32Ty, Lower->getValue().zext(32))),
16480b57cec5SDimitry Andric           // Don't make assumptions about the high bits.
16490b57cec5SDimitry Andric           ConstantAsMetadata::get(ConstantInt::get(I32Ty, 0))
16500b57cec5SDimitry Andric         };
16510b57cec5SDimitry Andric 
16520b57cec5SDimitry Andric         WidenLoad->setMetadata(LLVMContext::MD_range,
16530b57cec5SDimitry Andric                                MDNode::get(Mod->getContext(), LowAndHigh));
16540b57cec5SDimitry Andric       }
16550b57cec5SDimitry Andric     }
16560b57cec5SDimitry Andric 
16570b57cec5SDimitry Andric     int TySize = Mod->getDataLayout().getTypeSizeInBits(I.getType());
16580b57cec5SDimitry Andric     Type *IntNTy = Builder.getIntNTy(TySize);
16590b57cec5SDimitry Andric     Value *ValTrunc = Builder.CreateTrunc(WidenLoad, IntNTy);
16600b57cec5SDimitry Andric     Value *ValOrig = Builder.CreateBitCast(ValTrunc, I.getType());
16610b57cec5SDimitry Andric     I.replaceAllUsesWith(ValOrig);
16620b57cec5SDimitry Andric     I.eraseFromParent();
16630b57cec5SDimitry Andric     return true;
16640b57cec5SDimitry Andric   }
16650b57cec5SDimitry Andric 
16660b57cec5SDimitry Andric   return false;
16670b57cec5SDimitry Andric }
16680b57cec5SDimitry Andric 
visitICmpInst(ICmpInst & I)166906c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitICmpInst(ICmpInst &I) {
16700b57cec5SDimitry Andric   bool Changed = false;
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric   if (ST->has16BitInsts() && needsPromotionToI32(I.getOperand(0)->getType()) &&
167306c3fb27SDimitry Andric       UA->isUniform(&I))
16740b57cec5SDimitry Andric     Changed |= promoteUniformOpToI32(I);
16750b57cec5SDimitry Andric 
16760b57cec5SDimitry Andric   return Changed;
16770b57cec5SDimitry Andric }
16780b57cec5SDimitry Andric 
visitSelectInst(SelectInst & I)167906c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitSelectInst(SelectInst &I) {
168006c3fb27SDimitry Andric   Value *Cond = I.getCondition();
168106c3fb27SDimitry Andric   Value *TrueVal = I.getTrueValue();
168206c3fb27SDimitry Andric   Value *FalseVal = I.getFalseValue();
168306c3fb27SDimitry Andric   Value *CmpVal;
168406c3fb27SDimitry Andric   FCmpInst::Predicate Pred;
16850b57cec5SDimitry Andric 
168606c3fb27SDimitry Andric   if (ST->has16BitInsts() && needsPromotionToI32(I.getType())) {
168706c3fb27SDimitry Andric     if (UA->isUniform(&I))
168806c3fb27SDimitry Andric       return promoteUniformOpToI32(I);
168906c3fb27SDimitry Andric     return false;
16900b57cec5SDimitry Andric   }
16910b57cec5SDimitry Andric 
169206c3fb27SDimitry Andric   // Match fract pattern with nan check.
169306c3fb27SDimitry Andric   if (!match(Cond, m_FCmp(Pred, m_Value(CmpVal), m_NonNaN())))
169406c3fb27SDimitry Andric     return false;
169506c3fb27SDimitry Andric 
169606c3fb27SDimitry Andric   FPMathOperator *FPOp = dyn_cast<FPMathOperator>(&I);
169706c3fb27SDimitry Andric   if (!FPOp)
169806c3fb27SDimitry Andric     return false;
169906c3fb27SDimitry Andric 
170006c3fb27SDimitry Andric   IRBuilder<> Builder(&I);
170106c3fb27SDimitry Andric   Builder.setFastMathFlags(FPOp->getFastMathFlags());
170206c3fb27SDimitry Andric 
170306c3fb27SDimitry Andric   auto *IITrue = dyn_cast<IntrinsicInst>(TrueVal);
170406c3fb27SDimitry Andric   auto *IIFalse = dyn_cast<IntrinsicInst>(FalseVal);
170506c3fb27SDimitry Andric 
170606c3fb27SDimitry Andric   Value *Fract = nullptr;
170706c3fb27SDimitry Andric   if (Pred == FCmpInst::FCMP_UNO && TrueVal == CmpVal && IIFalse &&
170806c3fb27SDimitry Andric       CmpVal == matchFractPat(*IIFalse)) {
170906c3fb27SDimitry Andric     // isnan(x) ? x : fract(x)
171006c3fb27SDimitry Andric     Fract = applyFractPat(Builder, CmpVal);
171106c3fb27SDimitry Andric   } else if (Pred == FCmpInst::FCMP_ORD && FalseVal == CmpVal && IITrue &&
171206c3fb27SDimitry Andric              CmpVal == matchFractPat(*IITrue)) {
171306c3fb27SDimitry Andric     // !isnan(x) ? fract(x) : x
171406c3fb27SDimitry Andric     Fract = applyFractPat(Builder, CmpVal);
171506c3fb27SDimitry Andric   } else
171606c3fb27SDimitry Andric     return false;
171706c3fb27SDimitry Andric 
171806c3fb27SDimitry Andric   Fract->takeName(&I);
171906c3fb27SDimitry Andric   I.replaceAllUsesWith(Fract);
172006c3fb27SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(&I, TLInfo);
172106c3fb27SDimitry Andric   return true;
172206c3fb27SDimitry Andric }
172306c3fb27SDimitry Andric 
areInSameBB(const Value * A,const Value * B)172406c3fb27SDimitry Andric static bool areInSameBB(const Value *A, const Value *B) {
172506c3fb27SDimitry Andric   const auto *IA = dyn_cast<Instruction>(A);
172606c3fb27SDimitry Andric   const auto *IB = dyn_cast<Instruction>(B);
172706c3fb27SDimitry Andric   return IA && IB && IA->getParent() == IB->getParent();
172806c3fb27SDimitry Andric }
172906c3fb27SDimitry Andric 
173006c3fb27SDimitry Andric // Helper for breaking large PHIs that returns true when an extractelement on V
173106c3fb27SDimitry Andric // is likely to be folded away by the DAG combiner.
isInterestingPHIIncomingValue(const Value * V)173206c3fb27SDimitry Andric static bool isInterestingPHIIncomingValue(const Value *V) {
173306c3fb27SDimitry Andric   const auto *FVT = dyn_cast<FixedVectorType>(V->getType());
173406c3fb27SDimitry Andric   if (!FVT)
173506c3fb27SDimitry Andric     return false;
173606c3fb27SDimitry Andric 
173706c3fb27SDimitry Andric   const Value *CurVal = V;
173806c3fb27SDimitry Andric 
173906c3fb27SDimitry Andric   // Check for insertelements, keeping track of the elements covered.
174006c3fb27SDimitry Andric   BitVector EltsCovered(FVT->getNumElements());
174106c3fb27SDimitry Andric   while (const auto *IE = dyn_cast<InsertElementInst>(CurVal)) {
174206c3fb27SDimitry Andric     const auto *Idx = dyn_cast<ConstantInt>(IE->getOperand(2));
174306c3fb27SDimitry Andric 
174406c3fb27SDimitry Andric     // Non constant index/out of bounds index -> folding is unlikely.
174506c3fb27SDimitry Andric     // The latter is more of a sanity check because canonical IR should just
174606c3fb27SDimitry Andric     // have replaced those with poison.
174706c3fb27SDimitry Andric     if (!Idx || Idx->getSExtValue() >= FVT->getNumElements())
174806c3fb27SDimitry Andric       return false;
174906c3fb27SDimitry Andric 
175006c3fb27SDimitry Andric     const auto *VecSrc = IE->getOperand(0);
175106c3fb27SDimitry Andric 
175206c3fb27SDimitry Andric     // If the vector source is another instruction, it must be in the same basic
175306c3fb27SDimitry Andric     // block. Otherwise, the DAGCombiner won't see the whole thing and is
175406c3fb27SDimitry Andric     // unlikely to be able to do anything interesting here.
175506c3fb27SDimitry Andric     if (isa<Instruction>(VecSrc) && !areInSameBB(VecSrc, IE))
175606c3fb27SDimitry Andric       return false;
175706c3fb27SDimitry Andric 
175806c3fb27SDimitry Andric     CurVal = VecSrc;
175906c3fb27SDimitry Andric     EltsCovered.set(Idx->getSExtValue());
176006c3fb27SDimitry Andric 
176106c3fb27SDimitry Andric     // All elements covered.
176206c3fb27SDimitry Andric     if (EltsCovered.all())
176306c3fb27SDimitry Andric       return true;
176406c3fb27SDimitry Andric   }
176506c3fb27SDimitry Andric 
176606c3fb27SDimitry Andric   // We either didn't find a single insertelement, or the insertelement chain
176706c3fb27SDimitry Andric   // ended before all elements were covered. Check for other interesting values.
176806c3fb27SDimitry Andric 
176906c3fb27SDimitry Andric   // Constants are always interesting because we can just constant fold the
177006c3fb27SDimitry Andric   // extractelements.
177106c3fb27SDimitry Andric   if (isa<Constant>(CurVal))
177206c3fb27SDimitry Andric     return true;
177306c3fb27SDimitry Andric 
177406c3fb27SDimitry Andric   // shufflevector is likely to be profitable if either operand is a constant,
177506c3fb27SDimitry Andric   // or if either source is in the same block.
177606c3fb27SDimitry Andric   // This is because shufflevector is most often lowered as a series of
177706c3fb27SDimitry Andric   // insert/extract elements anyway.
177806c3fb27SDimitry Andric   if (const auto *SV = dyn_cast<ShuffleVectorInst>(CurVal)) {
177906c3fb27SDimitry Andric     return isa<Constant>(SV->getOperand(1)) ||
178006c3fb27SDimitry Andric            areInSameBB(SV, SV->getOperand(0)) ||
178106c3fb27SDimitry Andric            areInSameBB(SV, SV->getOperand(1));
178206c3fb27SDimitry Andric   }
178306c3fb27SDimitry Andric 
178406c3fb27SDimitry Andric   return false;
178506c3fb27SDimitry Andric }
178606c3fb27SDimitry Andric 
collectPHINodes(const PHINode & I,SmallPtrSet<const PHINode *,8> & SeenPHIs)17875f757f3fSDimitry Andric static void collectPHINodes(const PHINode &I,
17885f757f3fSDimitry Andric                             SmallPtrSet<const PHINode *, 8> &SeenPHIs) {
17895f757f3fSDimitry Andric   const auto [It, Inserted] = SeenPHIs.insert(&I);
17905f757f3fSDimitry Andric   if (!Inserted)
17915f757f3fSDimitry Andric     return;
17925f757f3fSDimitry Andric 
17935f757f3fSDimitry Andric   for (const Value *Inc : I.incoming_values()) {
17945f757f3fSDimitry Andric     if (const auto *PhiInc = dyn_cast<PHINode>(Inc))
17955f757f3fSDimitry Andric       collectPHINodes(*PhiInc, SeenPHIs);
17965f757f3fSDimitry Andric   }
17975f757f3fSDimitry Andric 
17985f757f3fSDimitry Andric   for (const User *U : I.users()) {
17995f757f3fSDimitry Andric     if (const auto *PhiU = dyn_cast<PHINode>(U))
18005f757f3fSDimitry Andric       collectPHINodes(*PhiU, SeenPHIs);
18015f757f3fSDimitry Andric   }
18025f757f3fSDimitry Andric }
18035f757f3fSDimitry Andric 
canBreakPHINode(const PHINode & I)180406c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::canBreakPHINode(const PHINode &I) {
18055f757f3fSDimitry Andric   // Check in the cache first.
18065f757f3fSDimitry Andric   if (const auto It = BreakPhiNodesCache.find(&I);
18075f757f3fSDimitry Andric       It != BreakPhiNodesCache.end())
180806c3fb27SDimitry Andric     return It->second;
180906c3fb27SDimitry Andric 
18105f757f3fSDimitry Andric   // We consider PHI nodes as part of "chains", so given a PHI node I, we
18115f757f3fSDimitry Andric   // recursively consider all its users and incoming values that are also PHI
18125f757f3fSDimitry Andric   // nodes. We then make a decision about all of those PHIs at once. Either they
18135f757f3fSDimitry Andric   // all get broken up, or none of them do. That way, we avoid cases where a
18145f757f3fSDimitry Andric   // single PHI is/is not broken and we end up reforming/exploding a vector
18155f757f3fSDimitry Andric   // multiple times, or even worse, doing it in a loop.
18165f757f3fSDimitry Andric   SmallPtrSet<const PHINode *, 8> WorkList;
18175f757f3fSDimitry Andric   collectPHINodes(I, WorkList);
181806c3fb27SDimitry Andric 
18195f757f3fSDimitry Andric #ifndef NDEBUG
18205f757f3fSDimitry Andric   // Check that none of the PHI nodes in the worklist are in the map. If some of
18215f757f3fSDimitry Andric   // them are, it means we're not good enough at collecting related PHIs.
18225f757f3fSDimitry Andric   for (const PHINode *WLP : WorkList) {
18235f757f3fSDimitry Andric     assert(BreakPhiNodesCache.count(WLP) == 0);
18245f757f3fSDimitry Andric   }
18255f757f3fSDimitry Andric #endif
18265f757f3fSDimitry Andric 
18275f757f3fSDimitry Andric   // To consider a PHI profitable to break, we need to see some interesting
18285f757f3fSDimitry Andric   // incoming values. At least 2/3rd (rounded up) of all PHIs in the worklist
18295f757f3fSDimitry Andric   // must have one to consider all PHIs breakable.
18305f757f3fSDimitry Andric   //
18315f757f3fSDimitry Andric   // This threshold has been determined through performance testing.
18325f757f3fSDimitry Andric   //
18335f757f3fSDimitry Andric   // Note that the computation below is equivalent to
18345f757f3fSDimitry Andric   //
18355f757f3fSDimitry Andric   //    (unsigned)ceil((K / 3.0) * 2)
18365f757f3fSDimitry Andric   //
18375f757f3fSDimitry Andric   // It's simply written this way to avoid mixing integral/FP arithmetic.
18385f757f3fSDimitry Andric   const auto Threshold = (alignTo(WorkList.size() * 2, 3) / 3);
18395f757f3fSDimitry Andric   unsigned NumBreakablePHIs = 0;
18405f757f3fSDimitry Andric   bool CanBreak = false;
18415f757f3fSDimitry Andric   for (const PHINode *Cur : WorkList) {
184206c3fb27SDimitry Andric     // Don't break PHIs that have no interesting incoming values. That is, where
18435f757f3fSDimitry Andric     // there is no clear opportunity to fold the "extractelement" instructions
18445f757f3fSDimitry Andric     // we would add.
184506c3fb27SDimitry Andric     //
184606c3fb27SDimitry Andric     // Note: IC does not run after this pass, so we're only interested in the
184706c3fb27SDimitry Andric     // foldings that the DAG combiner can do.
18485f757f3fSDimitry Andric     if (any_of(Cur->incoming_values(), isInterestingPHIIncomingValue)) {
18495f757f3fSDimitry Andric       if (++NumBreakablePHIs >= Threshold) {
18505f757f3fSDimitry Andric         CanBreak = true;
18515f757f3fSDimitry Andric         break;
18525f757f3fSDimitry Andric       }
18535f757f3fSDimitry Andric     }
185406c3fb27SDimitry Andric   }
185506c3fb27SDimitry Andric 
18565f757f3fSDimitry Andric   for (const PHINode *Cur : WorkList)
18575f757f3fSDimitry Andric     BreakPhiNodesCache[Cur] = CanBreak;
185806c3fb27SDimitry Andric 
18595f757f3fSDimitry Andric   return CanBreak;
186006c3fb27SDimitry Andric }
186106c3fb27SDimitry Andric 
186206c3fb27SDimitry Andric /// Helper class for "break large PHIs" (visitPHINode).
186306c3fb27SDimitry Andric ///
186406c3fb27SDimitry Andric /// This represents a slice of a PHI's incoming value, which is made up of:
186506c3fb27SDimitry Andric ///   - The type of the slice (Ty)
186606c3fb27SDimitry Andric ///   - The index in the incoming value's vector where the slice starts (Idx)
186706c3fb27SDimitry Andric ///   - The number of elements in the slice (NumElts).
186806c3fb27SDimitry Andric /// It also keeps track of the NewPHI node inserted for this particular slice.
186906c3fb27SDimitry Andric ///
187006c3fb27SDimitry Andric /// Slice examples:
187106c3fb27SDimitry Andric ///   <4 x i64> -> Split into four i64 slices.
187206c3fb27SDimitry Andric ///     -> [i64, 0, 1], [i64, 1, 1], [i64, 2, 1], [i64, 3, 1]
187306c3fb27SDimitry Andric ///   <5 x i16> -> Split into 2 <2 x i16> slices + a i16 tail.
187406c3fb27SDimitry Andric ///     -> [<2 x i16>, 0, 2], [<2 x i16>, 2, 2], [i16, 4, 1]
187506c3fb27SDimitry Andric class VectorSlice {
187606c3fb27SDimitry Andric public:
VectorSlice(Type * Ty,unsigned Idx,unsigned NumElts)187706c3fb27SDimitry Andric   VectorSlice(Type *Ty, unsigned Idx, unsigned NumElts)
187806c3fb27SDimitry Andric       : Ty(Ty), Idx(Idx), NumElts(NumElts) {}
187906c3fb27SDimitry Andric 
188006c3fb27SDimitry Andric   Type *Ty = nullptr;
188106c3fb27SDimitry Andric   unsigned Idx = 0;
188206c3fb27SDimitry Andric   unsigned NumElts = 0;
188306c3fb27SDimitry Andric   PHINode *NewPHI = nullptr;
188406c3fb27SDimitry Andric 
188506c3fb27SDimitry Andric   /// Slice \p Inc according to the information contained within this slice.
188606c3fb27SDimitry Andric   /// This is cached, so if called multiple times for the same \p BB & \p Inc
188706c3fb27SDimitry Andric   /// pair, it returns the same Sliced value as well.
188806c3fb27SDimitry Andric   ///
188906c3fb27SDimitry Andric   /// Note this *intentionally* does not return the same value for, say,
189006c3fb27SDimitry Andric   /// [%bb.0, %0] & [%bb.1, %0] as:
189106c3fb27SDimitry Andric   ///   - It could cause issues with dominance (e.g. if bb.1 is seen first, then
189206c3fb27SDimitry Andric   ///   the value in bb.1 may not be reachable from bb.0 if it's its
189306c3fb27SDimitry Andric   ///   predecessor.)
189406c3fb27SDimitry Andric   ///   - We also want to make our extract instructions as local as possible so
189506c3fb27SDimitry Andric   ///   the DAG has better chances of folding them out. Duplicating them like
189606c3fb27SDimitry Andric   ///   that is beneficial in that regard.
189706c3fb27SDimitry Andric   ///
189806c3fb27SDimitry Andric   /// This is both a minor optimization to avoid creating duplicate
189906c3fb27SDimitry Andric   /// instructions, but also a requirement for correctness. It is not forbidden
190006c3fb27SDimitry Andric   /// for a PHI node to have the same [BB, Val] pair multiple times. If we
190106c3fb27SDimitry Andric   /// returned a new value each time, those previously identical pairs would all
190206c3fb27SDimitry Andric   /// have different incoming values (from the same block) and it'd cause a "PHI
190306c3fb27SDimitry Andric   /// node has multiple entries for the same basic block with different incoming
190406c3fb27SDimitry Andric   /// values!" verifier error.
getSlicedVal(BasicBlock * BB,Value * Inc,StringRef NewValName)190506c3fb27SDimitry Andric   Value *getSlicedVal(BasicBlock *BB, Value *Inc, StringRef NewValName) {
190606c3fb27SDimitry Andric     Value *&Res = SlicedVals[{BB, Inc}];
190706c3fb27SDimitry Andric     if (Res)
190806c3fb27SDimitry Andric       return Res;
190906c3fb27SDimitry Andric 
191006c3fb27SDimitry Andric     IRBuilder<> B(BB->getTerminator());
191106c3fb27SDimitry Andric     if (Instruction *IncInst = dyn_cast<Instruction>(Inc))
191206c3fb27SDimitry Andric       B.SetCurrentDebugLocation(IncInst->getDebugLoc());
191306c3fb27SDimitry Andric 
191406c3fb27SDimitry Andric     if (NumElts > 1) {
191506c3fb27SDimitry Andric       SmallVector<int, 4> Mask;
191606c3fb27SDimitry Andric       for (unsigned K = Idx; K < (Idx + NumElts); ++K)
191706c3fb27SDimitry Andric         Mask.push_back(K);
191806c3fb27SDimitry Andric       Res = B.CreateShuffleVector(Inc, Mask, NewValName);
191906c3fb27SDimitry Andric     } else
192006c3fb27SDimitry Andric       Res = B.CreateExtractElement(Inc, Idx, NewValName);
192106c3fb27SDimitry Andric 
192206c3fb27SDimitry Andric     return Res;
192306c3fb27SDimitry Andric   }
192406c3fb27SDimitry Andric 
192506c3fb27SDimitry Andric private:
192606c3fb27SDimitry Andric   SmallDenseMap<std::pair<BasicBlock *, Value *>, Value *> SlicedVals;
192706c3fb27SDimitry Andric };
192806c3fb27SDimitry Andric 
visitPHINode(PHINode & I)192906c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitPHINode(PHINode &I) {
193006c3fb27SDimitry Andric   // Break-up fixed-vector PHIs into smaller pieces.
193106c3fb27SDimitry Andric   // Default threshold is 32, so it breaks up any vector that's >32 bits into
193206c3fb27SDimitry Andric   // its elements, or into 32-bit pieces (for 8/16 bit elts).
193306c3fb27SDimitry Andric   //
193406c3fb27SDimitry Andric   // This is only helpful for DAGISel because it doesn't handle large PHIs as
193506c3fb27SDimitry Andric   // well as GlobalISel. DAGISel lowers PHIs by using CopyToReg/CopyFromReg.
193606c3fb27SDimitry Andric   // With large, odd-sized PHIs we may end up needing many `build_vector`
193706c3fb27SDimitry Andric   // operations with most elements being "undef". This inhibits a lot of
193806c3fb27SDimitry Andric   // optimization opportunities and can result in unreasonably high register
193906c3fb27SDimitry Andric   // pressure and the inevitable stack spilling.
19405f757f3fSDimitry Andric   if (!BreakLargePHIs || getCGPassBuilderOption().EnableGlobalISelOption)
194106c3fb27SDimitry Andric     return false;
194206c3fb27SDimitry Andric 
194306c3fb27SDimitry Andric   FixedVectorType *FVT = dyn_cast<FixedVectorType>(I.getType());
19445f757f3fSDimitry Andric   if (!FVT || FVT->getNumElements() == 1 ||
19455f757f3fSDimitry Andric       DL->getTypeSizeInBits(FVT) <= BreakLargePHIsThreshold)
194606c3fb27SDimitry Andric     return false;
194706c3fb27SDimitry Andric 
19485f757f3fSDimitry Andric   if (!ForceBreakLargePHIs && !canBreakPHINode(I))
194906c3fb27SDimitry Andric     return false;
195006c3fb27SDimitry Andric 
195106c3fb27SDimitry Andric   std::vector<VectorSlice> Slices;
195206c3fb27SDimitry Andric 
195306c3fb27SDimitry Andric   Type *EltTy = FVT->getElementType();
195406c3fb27SDimitry Andric   {
195506c3fb27SDimitry Andric     unsigned Idx = 0;
195606c3fb27SDimitry Andric     // For 8/16 bits type, don't scalarize fully but break it up into as many
195706c3fb27SDimitry Andric     // 32-bit slices as we can, and scalarize the tail.
195806c3fb27SDimitry Andric     const unsigned EltSize = DL->getTypeSizeInBits(EltTy);
195906c3fb27SDimitry Andric     const unsigned NumElts = FVT->getNumElements();
196006c3fb27SDimitry Andric     if (EltSize == 8 || EltSize == 16) {
196106c3fb27SDimitry Andric       const unsigned SubVecSize = (32 / EltSize);
196206c3fb27SDimitry Andric       Type *SubVecTy = FixedVectorType::get(EltTy, SubVecSize);
196306c3fb27SDimitry Andric       for (unsigned End = alignDown(NumElts, SubVecSize); Idx < End;
196406c3fb27SDimitry Andric            Idx += SubVecSize)
196506c3fb27SDimitry Andric         Slices.emplace_back(SubVecTy, Idx, SubVecSize);
196606c3fb27SDimitry Andric     }
196706c3fb27SDimitry Andric 
196806c3fb27SDimitry Andric     // Scalarize all remaining elements.
196906c3fb27SDimitry Andric     for (; Idx < NumElts; ++Idx)
197006c3fb27SDimitry Andric       Slices.emplace_back(EltTy, Idx, 1);
197106c3fb27SDimitry Andric   }
197206c3fb27SDimitry Andric 
19735f757f3fSDimitry Andric   assert(Slices.size() > 1);
197406c3fb27SDimitry Andric 
197506c3fb27SDimitry Andric   // Create one PHI per vector piece. The "VectorSlice" class takes care of
197606c3fb27SDimitry Andric   // creating the necessary instruction to extract the relevant slices of each
197706c3fb27SDimitry Andric   // incoming value.
197806c3fb27SDimitry Andric   IRBuilder<> B(I.getParent());
197906c3fb27SDimitry Andric   B.SetCurrentDebugLocation(I.getDebugLoc());
198006c3fb27SDimitry Andric 
198106c3fb27SDimitry Andric   unsigned IncNameSuffix = 0;
198206c3fb27SDimitry Andric   for (VectorSlice &S : Slices) {
198306c3fb27SDimitry Andric     // We need to reset the build on each iteration, because getSlicedVal may
198406c3fb27SDimitry Andric     // have inserted something into I's BB.
198506c3fb27SDimitry Andric     B.SetInsertPoint(I.getParent()->getFirstNonPHI());
198606c3fb27SDimitry Andric     S.NewPHI = B.CreatePHI(S.Ty, I.getNumIncomingValues());
198706c3fb27SDimitry Andric 
198806c3fb27SDimitry Andric     for (const auto &[Idx, BB] : enumerate(I.blocks())) {
198906c3fb27SDimitry Andric       S.NewPHI->addIncoming(S.getSlicedVal(BB, I.getIncomingValue(Idx),
199006c3fb27SDimitry Andric                                            "largephi.extractslice" +
199106c3fb27SDimitry Andric                                                std::to_string(IncNameSuffix++)),
199206c3fb27SDimitry Andric                             BB);
199306c3fb27SDimitry Andric     }
199406c3fb27SDimitry Andric   }
199506c3fb27SDimitry Andric 
199606c3fb27SDimitry Andric   // And replace this PHI with a vector of all the previous PHI values.
199706c3fb27SDimitry Andric   Value *Vec = PoisonValue::get(FVT);
199806c3fb27SDimitry Andric   unsigned NameSuffix = 0;
199906c3fb27SDimitry Andric   for (VectorSlice &S : Slices) {
200006c3fb27SDimitry Andric     const auto ValName = "largephi.insertslice" + std::to_string(NameSuffix++);
200106c3fb27SDimitry Andric     if (S.NumElts > 1)
200206c3fb27SDimitry Andric       Vec =
200306c3fb27SDimitry Andric           B.CreateInsertVector(FVT, Vec, S.NewPHI, B.getInt64(S.Idx), ValName);
200406c3fb27SDimitry Andric     else
200506c3fb27SDimitry Andric       Vec = B.CreateInsertElement(Vec, S.NewPHI, S.Idx, ValName);
200606c3fb27SDimitry Andric   }
200706c3fb27SDimitry Andric 
200806c3fb27SDimitry Andric   I.replaceAllUsesWith(Vec);
200906c3fb27SDimitry Andric   I.eraseFromParent();
201006c3fb27SDimitry Andric   return true;
201106c3fb27SDimitry Andric }
201206c3fb27SDimitry Andric 
visitIntrinsicInst(IntrinsicInst & I)201306c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitIntrinsicInst(IntrinsicInst &I) {
20140b57cec5SDimitry Andric   switch (I.getIntrinsicID()) {
20150b57cec5SDimitry Andric   case Intrinsic::bitreverse:
20160b57cec5SDimitry Andric     return visitBitreverseIntrinsicInst(I);
201706c3fb27SDimitry Andric   case Intrinsic::minnum:
201806c3fb27SDimitry Andric     return visitMinNum(I);
20195f757f3fSDimitry Andric   case Intrinsic::sqrt:
20205f757f3fSDimitry Andric     return visitSqrt(I);
20210b57cec5SDimitry Andric   default:
20220b57cec5SDimitry Andric     return false;
20230b57cec5SDimitry Andric   }
20240b57cec5SDimitry Andric }
20250b57cec5SDimitry Andric 
visitBitreverseIntrinsicInst(IntrinsicInst & I)202606c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitBitreverseIntrinsicInst(IntrinsicInst &I) {
20270b57cec5SDimitry Andric   bool Changed = false;
20280b57cec5SDimitry Andric 
20290b57cec5SDimitry Andric   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
203006c3fb27SDimitry Andric       UA->isUniform(&I))
20310b57cec5SDimitry Andric     Changed |= promoteUniformBitreverseToI32(I);
20320b57cec5SDimitry Andric 
20330b57cec5SDimitry Andric   return Changed;
20340b57cec5SDimitry Andric }
20350b57cec5SDimitry Andric 
203606c3fb27SDimitry Andric /// Match non-nan fract pattern.
203706c3fb27SDimitry Andric ///   minnum(fsub(x, floor(x)), nextafter(1.0, -1.0)
203806c3fb27SDimitry Andric ///
203906c3fb27SDimitry Andric /// If fract is a useful instruction for the subtarget. Does not account for the
204006c3fb27SDimitry Andric /// nan handling; the instruction has a nan check on the input value.
matchFractPat(IntrinsicInst & I)204106c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::matchFractPat(IntrinsicInst &I) {
204206c3fb27SDimitry Andric   if (ST->hasFractBug())
204306c3fb27SDimitry Andric     return nullptr;
204406c3fb27SDimitry Andric 
204506c3fb27SDimitry Andric   if (I.getIntrinsicID() != Intrinsic::minnum)
204606c3fb27SDimitry Andric     return nullptr;
204706c3fb27SDimitry Andric 
204806c3fb27SDimitry Andric   Type *Ty = I.getType();
204906c3fb27SDimitry Andric   if (!isLegalFloatingTy(Ty->getScalarType()))
205006c3fb27SDimitry Andric     return nullptr;
205106c3fb27SDimitry Andric 
205206c3fb27SDimitry Andric   Value *Arg0 = I.getArgOperand(0);
205306c3fb27SDimitry Andric   Value *Arg1 = I.getArgOperand(1);
205406c3fb27SDimitry Andric 
205506c3fb27SDimitry Andric   const APFloat *C;
205606c3fb27SDimitry Andric   if (!match(Arg1, m_APFloat(C)))
205706c3fb27SDimitry Andric     return nullptr;
205806c3fb27SDimitry Andric 
205906c3fb27SDimitry Andric   APFloat One(1.0);
206006c3fb27SDimitry Andric   bool LosesInfo;
206106c3fb27SDimitry Andric   One.convert(C->getSemantics(), APFloat::rmNearestTiesToEven, &LosesInfo);
206206c3fb27SDimitry Andric 
206306c3fb27SDimitry Andric   // Match nextafter(1.0, -1)
206406c3fb27SDimitry Andric   One.next(true);
206506c3fb27SDimitry Andric   if (One != *C)
206606c3fb27SDimitry Andric     return nullptr;
206706c3fb27SDimitry Andric 
206806c3fb27SDimitry Andric   Value *FloorSrc;
206906c3fb27SDimitry Andric   if (match(Arg0, m_FSub(m_Value(FloorSrc),
207006c3fb27SDimitry Andric                          m_Intrinsic<Intrinsic::floor>(m_Deferred(FloorSrc)))))
207106c3fb27SDimitry Andric     return FloorSrc;
207206c3fb27SDimitry Andric   return nullptr;
207306c3fb27SDimitry Andric }
207406c3fb27SDimitry Andric 
applyFractPat(IRBuilder<> & Builder,Value * FractArg)207506c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::applyFractPat(IRBuilder<> &Builder,
207606c3fb27SDimitry Andric                                                Value *FractArg) {
207706c3fb27SDimitry Andric   SmallVector<Value *, 4> FractVals;
207806c3fb27SDimitry Andric   extractValues(Builder, FractVals, FractArg);
207906c3fb27SDimitry Andric 
208006c3fb27SDimitry Andric   SmallVector<Value *, 4> ResultVals(FractVals.size());
208106c3fb27SDimitry Andric 
208206c3fb27SDimitry Andric   Type *Ty = FractArg->getType()->getScalarType();
208306c3fb27SDimitry Andric   for (unsigned I = 0, E = FractVals.size(); I != E; ++I) {
208406c3fb27SDimitry Andric     ResultVals[I] =
208506c3fb27SDimitry Andric         Builder.CreateIntrinsic(Intrinsic::amdgcn_fract, {Ty}, {FractVals[I]});
208606c3fb27SDimitry Andric   }
208706c3fb27SDimitry Andric 
208806c3fb27SDimitry Andric   return insertValues(Builder, FractArg->getType(), ResultVals);
208906c3fb27SDimitry Andric }
209006c3fb27SDimitry Andric 
visitMinNum(IntrinsicInst & I)209106c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitMinNum(IntrinsicInst &I) {
209206c3fb27SDimitry Andric   Value *FractArg = matchFractPat(I);
209306c3fb27SDimitry Andric   if (!FractArg)
209406c3fb27SDimitry Andric     return false;
209506c3fb27SDimitry Andric 
209606c3fb27SDimitry Andric   // Match pattern for fract intrinsic in contexts where the nan check has been
209706c3fb27SDimitry Andric   // optimized out (and hope the knowledge the source can't be nan wasn't lost).
209806c3fb27SDimitry Andric   if (!I.hasNoNaNs() && !isKnownNeverNaN(FractArg, *DL, TLInfo))
209906c3fb27SDimitry Andric     return false;
210006c3fb27SDimitry Andric 
210106c3fb27SDimitry Andric   IRBuilder<> Builder(&I);
210206c3fb27SDimitry Andric   FastMathFlags FMF = I.getFastMathFlags();
210306c3fb27SDimitry Andric   FMF.setNoNaNs();
210406c3fb27SDimitry Andric   Builder.setFastMathFlags(FMF);
210506c3fb27SDimitry Andric 
210606c3fb27SDimitry Andric   Value *Fract = applyFractPat(Builder, FractArg);
210706c3fb27SDimitry Andric   Fract->takeName(&I);
210806c3fb27SDimitry Andric   I.replaceAllUsesWith(Fract);
210906c3fb27SDimitry Andric 
211006c3fb27SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(&I, TLInfo);
211106c3fb27SDimitry Andric   return true;
211206c3fb27SDimitry Andric }
211306c3fb27SDimitry Andric 
isOneOrNegOne(const Value * Val)21145f757f3fSDimitry Andric static bool isOneOrNegOne(const Value *Val) {
21155f757f3fSDimitry Andric   const APFloat *C;
21165f757f3fSDimitry Andric   return match(Val, m_APFloat(C)) && C->getExactLog2Abs() == 0;
21175f757f3fSDimitry Andric }
21185f757f3fSDimitry Andric 
21195f757f3fSDimitry Andric // Expand llvm.sqrt.f32 calls with !fpmath metadata in a semi-fast way.
visitSqrt(IntrinsicInst & Sqrt)21205f757f3fSDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitSqrt(IntrinsicInst &Sqrt) {
21215f757f3fSDimitry Andric   Type *Ty = Sqrt.getType()->getScalarType();
21225f757f3fSDimitry Andric   if (!Ty->isFloatTy() && (!Ty->isHalfTy() || ST->has16BitInsts()))
21235f757f3fSDimitry Andric     return false;
21245f757f3fSDimitry Andric 
21255f757f3fSDimitry Andric   const FPMathOperator *FPOp = cast<const FPMathOperator>(&Sqrt);
21265f757f3fSDimitry Andric   FastMathFlags SqrtFMF = FPOp->getFastMathFlags();
21275f757f3fSDimitry Andric 
21285f757f3fSDimitry Andric   // We're trying to handle the fast-but-not-that-fast case only. The lowering
21295f757f3fSDimitry Andric   // of fast llvm.sqrt will give the raw instruction anyway.
21305f757f3fSDimitry Andric   if (SqrtFMF.approxFunc() || HasUnsafeFPMath)
21315f757f3fSDimitry Andric     return false;
21325f757f3fSDimitry Andric 
21335f757f3fSDimitry Andric   const float ReqdAccuracy = FPOp->getFPAccuracy();
21345f757f3fSDimitry Andric 
21355f757f3fSDimitry Andric   // Defer correctly rounded expansion to codegen.
21365f757f3fSDimitry Andric   if (ReqdAccuracy < 1.0f)
21375f757f3fSDimitry Andric     return false;
21385f757f3fSDimitry Andric 
21395f757f3fSDimitry Andric   // FIXME: This is an ugly hack for this pass using forward iteration instead
21405f757f3fSDimitry Andric   // of reverse. If it worked like a normal combiner, the rsq would form before
21415f757f3fSDimitry Andric   // we saw a sqrt call.
21425f757f3fSDimitry Andric   auto *FDiv =
21435f757f3fSDimitry Andric       dyn_cast_or_null<FPMathOperator>(Sqrt.getUniqueUndroppableUser());
21445f757f3fSDimitry Andric   if (FDiv && FDiv->getOpcode() == Instruction::FDiv &&
21455f757f3fSDimitry Andric       FDiv->getFPAccuracy() >= 1.0f &&
21465f757f3fSDimitry Andric       canOptimizeWithRsq(FPOp, FDiv->getFastMathFlags(), SqrtFMF) &&
21475f757f3fSDimitry Andric       // TODO: We should also handle the arcp case for the fdiv with non-1 value
21485f757f3fSDimitry Andric       isOneOrNegOne(FDiv->getOperand(0)))
21495f757f3fSDimitry Andric     return false;
21505f757f3fSDimitry Andric 
21515f757f3fSDimitry Andric   Value *SrcVal = Sqrt.getOperand(0);
21525f757f3fSDimitry Andric   bool CanTreatAsDAZ = canIgnoreDenormalInput(SrcVal, &Sqrt);
21535f757f3fSDimitry Andric 
21545f757f3fSDimitry Andric   // The raw instruction is 1 ulp, but the correction for denormal handling
21555f757f3fSDimitry Andric   // brings it to 2.
21565f757f3fSDimitry Andric   if (!CanTreatAsDAZ && ReqdAccuracy < 2.0f)
21575f757f3fSDimitry Andric     return false;
21585f757f3fSDimitry Andric 
21595f757f3fSDimitry Andric   IRBuilder<> Builder(&Sqrt);
21605f757f3fSDimitry Andric   SmallVector<Value *, 4> SrcVals;
21615f757f3fSDimitry Andric   extractValues(Builder, SrcVals, SrcVal);
21625f757f3fSDimitry Andric 
21635f757f3fSDimitry Andric   SmallVector<Value *, 4> ResultVals(SrcVals.size());
21645f757f3fSDimitry Andric   for (int I = 0, E = SrcVals.size(); I != E; ++I) {
21655f757f3fSDimitry Andric     if (CanTreatAsDAZ)
21665f757f3fSDimitry Andric       ResultVals[I] = Builder.CreateCall(getSqrtF32(), SrcVals[I]);
21675f757f3fSDimitry Andric     else
21685f757f3fSDimitry Andric       ResultVals[I] = emitSqrtIEEE2ULP(Builder, SrcVals[I], SqrtFMF);
21695f757f3fSDimitry Andric   }
21705f757f3fSDimitry Andric 
21715f757f3fSDimitry Andric   Value *NewSqrt = insertValues(Builder, Sqrt.getType(), ResultVals);
21725f757f3fSDimitry Andric   NewSqrt->takeName(&Sqrt);
21735f757f3fSDimitry Andric   Sqrt.replaceAllUsesWith(NewSqrt);
21745f757f3fSDimitry Andric   Sqrt.eraseFromParent();
21755f757f3fSDimitry Andric   return true;
21765f757f3fSDimitry Andric }
21775f757f3fSDimitry Andric 
doInitialization(Module & M)21780b57cec5SDimitry Andric bool AMDGPUCodeGenPrepare::doInitialization(Module &M) {
217906c3fb27SDimitry Andric   Impl.Mod = &M;
218006c3fb27SDimitry Andric   Impl.DL = &Impl.Mod->getDataLayout();
21815f757f3fSDimitry Andric   Impl.SqrtF32 = nullptr;
21825f757f3fSDimitry Andric   Impl.LdexpF32 = nullptr;
21830b57cec5SDimitry Andric   return false;
21840b57cec5SDimitry Andric }
21850b57cec5SDimitry Andric 
runOnFunction(Function & F)21860b57cec5SDimitry Andric bool AMDGPUCodeGenPrepare::runOnFunction(Function &F) {
21870b57cec5SDimitry Andric   if (skipFunction(F))
21880b57cec5SDimitry Andric     return false;
21890b57cec5SDimitry Andric 
21900b57cec5SDimitry Andric   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
21910b57cec5SDimitry Andric   if (!TPC)
21920b57cec5SDimitry Andric     return false;
21930b57cec5SDimitry Andric 
21940b57cec5SDimitry Andric   const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>();
219506c3fb27SDimitry Andric   Impl.TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
219606c3fb27SDimitry Andric   Impl.ST = &TM.getSubtarget<GCNSubtarget>(F);
219706c3fb27SDimitry Andric   Impl.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
219806c3fb27SDimitry Andric   Impl.UA = &getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
21995ffd83dbSDimitry Andric   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
220006c3fb27SDimitry Andric   Impl.DT = DTWP ? &DTWP->getDomTree() : nullptr;
220106c3fb27SDimitry Andric   Impl.HasUnsafeFPMath = hasUnsafeFPMath(F);
22025f757f3fSDimitry Andric   SIModeRegisterDefaults Mode(F, *Impl.ST);
220306c3fb27SDimitry Andric   Impl.HasFP32DenormalFlush =
220406c3fb27SDimitry Andric       Mode.FP32Denormals == DenormalMode::getPreserveSign();
220506c3fb27SDimitry Andric   return Impl.run(F);
22060b57cec5SDimitry Andric }
22070b57cec5SDimitry Andric 
run(Function & F,FunctionAnalysisManager & FAM)220806c3fb27SDimitry Andric PreservedAnalyses AMDGPUCodeGenPreparePass::run(Function &F,
220906c3fb27SDimitry Andric                                                 FunctionAnalysisManager &FAM) {
221006c3fb27SDimitry Andric   AMDGPUCodeGenPrepareImpl Impl;
221106c3fb27SDimitry Andric   Impl.Mod = F.getParent();
221206c3fb27SDimitry Andric   Impl.DL = &Impl.Mod->getDataLayout();
221306c3fb27SDimitry Andric   Impl.TLInfo = &FAM.getResult<TargetLibraryAnalysis>(F);
221406c3fb27SDimitry Andric   Impl.ST = &TM.getSubtarget<GCNSubtarget>(F);
221506c3fb27SDimitry Andric   Impl.AC = &FAM.getResult<AssumptionAnalysis>(F);
221606c3fb27SDimitry Andric   Impl.UA = &FAM.getResult<UniformityInfoAnalysis>(F);
221706c3fb27SDimitry Andric   Impl.DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
221806c3fb27SDimitry Andric   Impl.HasUnsafeFPMath = hasUnsafeFPMath(F);
22195f757f3fSDimitry Andric   SIModeRegisterDefaults Mode(F, *Impl.ST);
222006c3fb27SDimitry Andric   Impl.HasFP32DenormalFlush =
222106c3fb27SDimitry Andric       Mode.FP32Denormals == DenormalMode::getPreserveSign();
222206c3fb27SDimitry Andric   PreservedAnalyses PA = PreservedAnalyses::none();
222306c3fb27SDimitry Andric   if (!Impl.FlowChanged)
222406c3fb27SDimitry Andric     PA.preserveSet<CFGAnalyses>();
222506c3fb27SDimitry Andric   return Impl.run(F) ? PA : PreservedAnalyses::all();
22260b57cec5SDimitry Andric }
22270b57cec5SDimitry Andric 
22280b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE,
22290b57cec5SDimitry Andric                       "AMDGPU IR optimizations", false, false)
22300b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
223106c3fb27SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
223206c3fb27SDimitry Andric INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)
22330b57cec5SDimitry Andric INITIALIZE_PASS_END(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations",
22340b57cec5SDimitry Andric                     false, false)
22350b57cec5SDimitry Andric 
22360b57cec5SDimitry Andric char AMDGPUCodeGenPrepare::ID = 0;
22370b57cec5SDimitry Andric 
createAMDGPUCodeGenPreparePass()22380b57cec5SDimitry Andric FunctionPass *llvm::createAMDGPUCodeGenPreparePass() {
22390b57cec5SDimitry Andric   return new AMDGPUCodeGenPrepare();
22400b57cec5SDimitry Andric }
2241