xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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;
102*0fca6ea1SDimitry Andric   const AMDGPUTargetMachine *TM = nullptr;
10306c3fb27SDimitry Andric   const TargetLibraryInfo *TLInfo = nullptr;
1040b57cec5SDimitry Andric   AssumptionCache *AC = nullptr;
1055ffd83dbSDimitry Andric   DominatorTree *DT = nullptr;
10606c3fb27SDimitry Andric   UniformityInfo *UA = nullptr;
1070b57cec5SDimitry Andric   Module *Mod = nullptr;
1080b57cec5SDimitry Andric   const DataLayout *DL = nullptr;
1090b57cec5SDimitry Andric   bool HasUnsafeFPMath = false;
11006c3fb27SDimitry Andric   bool HasFP32DenormalFlush = false;
11106c3fb27SDimitry Andric   bool FlowChanged = false;
1125f757f3fSDimitry Andric   mutable Function *SqrtF32 = nullptr;
1135f757f3fSDimitry Andric   mutable Function *LdexpF32 = nullptr;
11406c3fb27SDimitry Andric 
11506c3fb27SDimitry Andric   DenseMap<const PHINode *, bool> BreakPhiNodesCache;
11606c3fb27SDimitry Andric 
1175f757f3fSDimitry Andric   Function *getSqrtF32() const {
1185f757f3fSDimitry Andric     if (SqrtF32)
1195f757f3fSDimitry Andric       return SqrtF32;
1205f757f3fSDimitry Andric 
1215f757f3fSDimitry Andric     LLVMContext &Ctx = Mod->getContext();
1225f757f3fSDimitry Andric     SqrtF32 = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_sqrt,
1235f757f3fSDimitry Andric                                         {Type::getFloatTy(Ctx)});
1245f757f3fSDimitry Andric     return SqrtF32;
1255f757f3fSDimitry Andric   }
1265f757f3fSDimitry Andric 
1275f757f3fSDimitry Andric   Function *getLdexpF32() const {
1285f757f3fSDimitry Andric     if (LdexpF32)
1295f757f3fSDimitry Andric       return LdexpF32;
1305f757f3fSDimitry Andric 
1315f757f3fSDimitry Andric     LLVMContext &Ctx = Mod->getContext();
1325f757f3fSDimitry Andric     LdexpF32 = Intrinsic::getDeclaration(
1335f757f3fSDimitry Andric         Mod, Intrinsic::ldexp, {Type::getFloatTy(Ctx), Type::getInt32Ty(Ctx)});
1345f757f3fSDimitry Andric     return LdexpF32;
1355f757f3fSDimitry Andric   }
1365f757f3fSDimitry Andric 
13706c3fb27SDimitry Andric   bool canBreakPHINode(const PHINode &I);
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   /// Copies exact/nsw/nuw flags (if any) from binary operation \p I to
1400b57cec5SDimitry Andric   /// binary operation \p V.
1410b57cec5SDimitry Andric   ///
1420b57cec5SDimitry Andric   /// \returns Binary operation \p V.
1430b57cec5SDimitry Andric   /// \returns \p T's base element bit width.
1440b57cec5SDimitry Andric   unsigned getBaseElementBitWidth(const Type *T) const;
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric   /// \returns Equivalent 32 bit integer type for given type \p T. For example,
1470b57cec5SDimitry Andric   /// if \p T is i7, then i32 is returned; if \p T is <3 x i12>, then <3 x i32>
1480b57cec5SDimitry Andric   /// is returned.
1490b57cec5SDimitry Andric   Type *getI32Ty(IRBuilder<> &B, const Type *T) const;
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric   /// \returns True if binary operation \p I is a signed binary operation, false
1520b57cec5SDimitry Andric   /// otherwise.
1530b57cec5SDimitry Andric   bool isSigned(const BinaryOperator &I) const;
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric   /// \returns True if the condition of 'select' operation \p I comes from a
1560b57cec5SDimitry Andric   /// signed 'icmp' operation, false otherwise.
1570b57cec5SDimitry Andric   bool isSigned(const SelectInst &I) const;
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   /// \returns True if type \p T needs to be promoted to 32 bit integer type,
1600b57cec5SDimitry Andric   /// false otherwise.
1610b57cec5SDimitry Andric   bool needsPromotionToI32(const Type *T) const;
1620b57cec5SDimitry Andric 
16306c3fb27SDimitry Andric   /// Return true if \p T is a legal scalar floating point type.
16406c3fb27SDimitry Andric   bool isLegalFloatingTy(const Type *T) const;
16506c3fb27SDimitry Andric 
16606c3fb27SDimitry Andric   /// Wrapper to pass all the arguments to computeKnownFPClass
16706c3fb27SDimitry Andric   KnownFPClass computeKnownFPClass(const Value *V, FPClassTest Interested,
16806c3fb27SDimitry Andric                                    const Instruction *CtxI) const {
16906c3fb27SDimitry Andric     return llvm::computeKnownFPClass(V, *DL, Interested, 0, TLInfo, AC, CtxI,
17006c3fb27SDimitry Andric                                      DT);
17106c3fb27SDimitry Andric   }
17206c3fb27SDimitry Andric 
17306c3fb27SDimitry Andric   bool canIgnoreDenormalInput(const Value *V, const Instruction *CtxI) const {
17406c3fb27SDimitry Andric     return HasFP32DenormalFlush ||
17506c3fb27SDimitry Andric            computeKnownFPClass(V, fcSubnormal, CtxI).isKnownNeverSubnormal();
17606c3fb27SDimitry Andric   }
17706c3fb27SDimitry Andric 
1780b57cec5SDimitry Andric   /// Promotes uniform binary operation \p I to equivalent 32 bit binary
1790b57cec5SDimitry Andric   /// operation.
1800b57cec5SDimitry Andric   ///
1810b57cec5SDimitry Andric   /// \details \p I's base element bit width must be greater than 1 and less
1820b57cec5SDimitry Andric   /// than or equal 16. Promotion is done by sign or zero extending operands to
1830b57cec5SDimitry Andric   /// 32 bits, replacing \p I with equivalent 32 bit binary operation, and
1840b57cec5SDimitry Andric   /// truncating the result of 32 bit binary operation back to \p I's original
1850b57cec5SDimitry Andric   /// type. Division operation is not promoted.
1860b57cec5SDimitry Andric   ///
1870b57cec5SDimitry Andric   /// \returns True if \p I is promoted to equivalent 32 bit binary operation,
1880b57cec5SDimitry Andric   /// false otherwise.
1890b57cec5SDimitry Andric   bool promoteUniformOpToI32(BinaryOperator &I) const;
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   /// Promotes uniform 'icmp' operation \p I to 32 bit 'icmp' operation.
1920b57cec5SDimitry Andric   ///
1930b57cec5SDimitry Andric   /// \details \p I's base element bit width must be greater than 1 and less
1940b57cec5SDimitry Andric   /// than or equal 16. Promotion is done by sign or zero extending operands to
1950b57cec5SDimitry Andric   /// 32 bits, and replacing \p I with 32 bit 'icmp' operation.
1960b57cec5SDimitry Andric   ///
1970b57cec5SDimitry Andric   /// \returns True.
1980b57cec5SDimitry Andric   bool promoteUniformOpToI32(ICmpInst &I) const;
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   /// Promotes uniform 'select' operation \p I to 32 bit 'select'
2010b57cec5SDimitry Andric   /// operation.
2020b57cec5SDimitry Andric   ///
2030b57cec5SDimitry Andric   /// \details \p I's base element bit width must be greater than 1 and less
2040b57cec5SDimitry Andric   /// than or equal 16. Promotion is done by sign or zero extending operands to
2050b57cec5SDimitry Andric   /// 32 bits, replacing \p I with 32 bit 'select' operation, and truncating the
2060b57cec5SDimitry Andric   /// result of 32 bit 'select' operation back to \p I's original type.
2070b57cec5SDimitry Andric   ///
2080b57cec5SDimitry Andric   /// \returns True.
2090b57cec5SDimitry Andric   bool promoteUniformOpToI32(SelectInst &I) const;
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric   /// Promotes uniform 'bitreverse' intrinsic \p I to 32 bit 'bitreverse'
2120b57cec5SDimitry Andric   /// intrinsic.
2130b57cec5SDimitry Andric   ///
2140b57cec5SDimitry Andric   /// \details \p I's base element bit width must be greater than 1 and less
2150b57cec5SDimitry Andric   /// than or equal 16. Promotion is done by zero extending the operand to 32
2160b57cec5SDimitry Andric   /// bits, replacing \p I with 32 bit 'bitreverse' intrinsic, shifting the
2170b57cec5SDimitry Andric   /// result of 32 bit 'bitreverse' intrinsic to the right with zero fill (the
2180b57cec5SDimitry Andric   /// shift amount is 32 minus \p I's base element bit width), and truncating
2190b57cec5SDimitry Andric   /// the result of the shift operation back to \p I's original type.
2200b57cec5SDimitry Andric   ///
2210b57cec5SDimitry Andric   /// \returns True.
2220b57cec5SDimitry Andric   bool promoteUniformBitreverseToI32(IntrinsicInst &I) const;
2230b57cec5SDimitry Andric 
224349cc55cSDimitry Andric   /// \returns The minimum number of bits needed to store the value of \Op as an
225349cc55cSDimitry Andric   /// unsigned integer. Truncating to this size and then zero-extending to
22604eeddc0SDimitry Andric   /// the original will not change the value.
22704eeddc0SDimitry Andric   unsigned numBitsUnsigned(Value *Op) const;
228349cc55cSDimitry Andric 
229349cc55cSDimitry Andric   /// \returns The minimum number of bits needed to store the value of \Op as a
230349cc55cSDimitry Andric   /// signed integer. Truncating to this size and then sign-extending to
23104eeddc0SDimitry Andric   /// the original size will not change the value.
23204eeddc0SDimitry Andric   unsigned numBitsSigned(Value *Op) const;
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric   /// Replace mul instructions with llvm.amdgcn.mul.u24 or llvm.amdgcn.mul.s24.
2350b57cec5SDimitry Andric   /// SelectionDAG has an issue where an and asserting the bits are known
2360b57cec5SDimitry Andric   bool replaceMulWithMul24(BinaryOperator &I) const;
2370b57cec5SDimitry Andric 
2385ffd83dbSDimitry Andric   /// Perform same function as equivalently named function in DAGCombiner. Since
2395ffd83dbSDimitry Andric   /// we expand some divisions here, we need to perform this before obscuring.
2405ffd83dbSDimitry Andric   bool foldBinOpIntoSelect(BinaryOperator &I) const;
2415ffd83dbSDimitry Andric 
2425ffd83dbSDimitry Andric   bool divHasSpecialOptimization(BinaryOperator &I,
2435ffd83dbSDimitry Andric                                  Value *Num, Value *Den) const;
2445ffd83dbSDimitry Andric   int getDivNumBits(BinaryOperator &I,
2455ffd83dbSDimitry Andric                     Value *Num, Value *Den,
2465ffd83dbSDimitry Andric                     unsigned AtLeast, bool Signed) const;
2475ffd83dbSDimitry Andric 
2480b57cec5SDimitry Andric   /// Expands 24 bit div or rem.
2490b57cec5SDimitry Andric   Value* expandDivRem24(IRBuilder<> &Builder, BinaryOperator &I,
2500b57cec5SDimitry Andric                         Value *Num, Value *Den,
2510b57cec5SDimitry Andric                         bool IsDiv, bool IsSigned) const;
2520b57cec5SDimitry Andric 
2535ffd83dbSDimitry Andric   Value *expandDivRem24Impl(IRBuilder<> &Builder, BinaryOperator &I,
2545ffd83dbSDimitry Andric                             Value *Num, Value *Den, unsigned NumBits,
2555ffd83dbSDimitry Andric                             bool IsDiv, bool IsSigned) const;
2565ffd83dbSDimitry Andric 
2570b57cec5SDimitry Andric   /// Expands 32 bit div or rem.
2580b57cec5SDimitry Andric   Value* expandDivRem32(IRBuilder<> &Builder, BinaryOperator &I,
2590b57cec5SDimitry Andric                         Value *Num, Value *Den) const;
2600b57cec5SDimitry Andric 
2615ffd83dbSDimitry Andric   Value *shrinkDivRem64(IRBuilder<> &Builder, BinaryOperator &I,
2625ffd83dbSDimitry Andric                         Value *Num, Value *Den) const;
2635ffd83dbSDimitry Andric   void expandDivRem64(BinaryOperator &I) const;
2645ffd83dbSDimitry Andric 
2650b57cec5SDimitry Andric   /// Widen a scalar load.
2660b57cec5SDimitry Andric   ///
2670b57cec5SDimitry Andric   /// \details \p Widen scalar load for uniform, small type loads from constant
2680b57cec5SDimitry Andric   //  memory / to a full 32-bits and then truncate the input to allow a scalar
2690b57cec5SDimitry Andric   //  load instead of a vector load.
2700b57cec5SDimitry Andric   //
2710b57cec5SDimitry Andric   /// \returns True.
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   bool canWidenScalarExtLoad(LoadInst &I) const;
2740b57cec5SDimitry Andric 
27506c3fb27SDimitry Andric   Value *matchFractPat(IntrinsicInst &I);
27606c3fb27SDimitry Andric   Value *applyFractPat(IRBuilder<> &Builder, Value *FractArg);
27706c3fb27SDimitry Andric 
27806c3fb27SDimitry Andric   bool canOptimizeWithRsq(const FPMathOperator *SqrtOp, FastMathFlags DivFMF,
27906c3fb27SDimitry Andric                           FastMathFlags SqrtFMF) const;
28006c3fb27SDimitry Andric 
28106c3fb27SDimitry Andric   Value *optimizeWithRsq(IRBuilder<> &Builder, Value *Num, Value *Den,
28206c3fb27SDimitry Andric                          FastMathFlags DivFMF, FastMathFlags SqrtFMF,
28306c3fb27SDimitry Andric                          const Instruction *CtxI) const;
28406c3fb27SDimitry Andric 
28506c3fb27SDimitry Andric   Value *optimizeWithRcp(IRBuilder<> &Builder, Value *Num, Value *Den,
28606c3fb27SDimitry Andric                          FastMathFlags FMF, const Instruction *CtxI) const;
28706c3fb27SDimitry Andric   Value *optimizeWithFDivFast(IRBuilder<> &Builder, Value *Num, Value *Den,
28806c3fb27SDimitry Andric                               float ReqdAccuracy) const;
28906c3fb27SDimitry Andric 
29006c3fb27SDimitry Andric   Value *visitFDivElement(IRBuilder<> &Builder, Value *Num, Value *Den,
29106c3fb27SDimitry Andric                           FastMathFlags DivFMF, FastMathFlags SqrtFMF,
29206c3fb27SDimitry Andric                           Value *RsqOp, const Instruction *FDiv,
29306c3fb27SDimitry Andric                           float ReqdAccuracy) const;
29406c3fb27SDimitry Andric 
29506c3fb27SDimitry Andric   std::pair<Value *, Value *> getFrexpResults(IRBuilder<> &Builder,
29606c3fb27SDimitry Andric                                               Value *Src) const;
29706c3fb27SDimitry Andric 
29806c3fb27SDimitry Andric   Value *emitRcpIEEE1ULP(IRBuilder<> &Builder, Value *Src,
29906c3fb27SDimitry Andric                          bool IsNegative) const;
30006c3fb27SDimitry Andric   Value *emitFrexpDiv(IRBuilder<> &Builder, Value *LHS, Value *RHS,
30106c3fb27SDimitry Andric                       FastMathFlags FMF) const;
3025f757f3fSDimitry Andric   Value *emitSqrtIEEE2ULP(IRBuilder<> &Builder, Value *Src,
3035f757f3fSDimitry Andric                           FastMathFlags FMF) const;
30406c3fb27SDimitry Andric 
3050b57cec5SDimitry Andric public:
3060b57cec5SDimitry Andric   bool visitFDiv(BinaryOperator &I);
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric   bool visitInstruction(Instruction &I) { return false; }
3090b57cec5SDimitry Andric   bool visitBinaryOperator(BinaryOperator &I);
3100b57cec5SDimitry Andric   bool visitLoadInst(LoadInst &I);
3110b57cec5SDimitry Andric   bool visitICmpInst(ICmpInst &I);
3120b57cec5SDimitry Andric   bool visitSelectInst(SelectInst &I);
31306c3fb27SDimitry Andric   bool visitPHINode(PHINode &I);
314*0fca6ea1SDimitry Andric   bool visitAddrSpaceCastInst(AddrSpaceCastInst &I);
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric   bool visitIntrinsicInst(IntrinsicInst &I);
3170b57cec5SDimitry Andric   bool visitBitreverseIntrinsicInst(IntrinsicInst &I);
31806c3fb27SDimitry Andric   bool visitMinNum(IntrinsicInst &I);
3195f757f3fSDimitry Andric   bool visitSqrt(IntrinsicInst &I);
32006c3fb27SDimitry Andric   bool run(Function &F);
32106c3fb27SDimitry Andric };
3220b57cec5SDimitry Andric 
32306c3fb27SDimitry Andric class AMDGPUCodeGenPrepare : public FunctionPass {
32406c3fb27SDimitry Andric private:
32506c3fb27SDimitry Andric   AMDGPUCodeGenPrepareImpl Impl;
3260b57cec5SDimitry Andric 
32706c3fb27SDimitry Andric public:
32806c3fb27SDimitry Andric   static char ID;
32906c3fb27SDimitry Andric   AMDGPUCodeGenPrepare() : FunctionPass(ID) {
33006c3fb27SDimitry Andric     initializeAMDGPUCodeGenPreparePass(*PassRegistry::getPassRegistry());
33106c3fb27SDimitry Andric   }
3320b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
3330b57cec5SDimitry Andric     AU.addRequired<AssumptionCacheTracker>();
33406c3fb27SDimitry Andric     AU.addRequired<UniformityInfoWrapperPass>();
33506c3fb27SDimitry Andric     AU.addRequired<TargetLibraryInfoWrapperPass>();
3365ffd83dbSDimitry Andric 
3375ffd83dbSDimitry Andric     // FIXME: Division expansion needs to preserve the dominator tree.
3385ffd83dbSDimitry Andric     if (!ExpandDiv64InIR)
3390b57cec5SDimitry Andric       AU.setPreservesAll();
3400b57cec5SDimitry Andric   }
34106c3fb27SDimitry Andric   bool runOnFunction(Function &F) override;
34206c3fb27SDimitry Andric   bool doInitialization(Module &M) override;
34306c3fb27SDimitry Andric   StringRef getPassName() const override { return "AMDGPU IR optimizations"; }
3440b57cec5SDimitry Andric };
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric } // end anonymous namespace
3470b57cec5SDimitry Andric 
34806c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::run(Function &F) {
3495f757f3fSDimitry Andric   BreakPhiNodesCache.clear();
35006c3fb27SDimitry Andric   bool MadeChange = false;
35106c3fb27SDimitry Andric 
35206c3fb27SDimitry Andric   Function::iterator NextBB;
35306c3fb27SDimitry Andric   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; FI = NextBB) {
35406c3fb27SDimitry Andric     BasicBlock *BB = &*FI;
35506c3fb27SDimitry Andric     NextBB = std::next(FI);
35606c3fb27SDimitry Andric 
35706c3fb27SDimitry Andric     BasicBlock::iterator Next;
35806c3fb27SDimitry Andric     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;
35906c3fb27SDimitry Andric          I = Next) {
36006c3fb27SDimitry Andric       Next = std::next(I);
36106c3fb27SDimitry Andric 
36206c3fb27SDimitry Andric       MadeChange |= visit(*I);
36306c3fb27SDimitry Andric 
36406c3fb27SDimitry Andric       if (Next != E) { // Control flow changed
36506c3fb27SDimitry Andric         BasicBlock *NextInstBB = Next->getParent();
36606c3fb27SDimitry Andric         if (NextInstBB != BB) {
36706c3fb27SDimitry Andric           BB = NextInstBB;
36806c3fb27SDimitry Andric           E = BB->end();
36906c3fb27SDimitry Andric           FE = F.end();
37006c3fb27SDimitry Andric         }
37106c3fb27SDimitry Andric       }
37206c3fb27SDimitry Andric     }
37306c3fb27SDimitry Andric   }
37406c3fb27SDimitry Andric   return MadeChange;
37506c3fb27SDimitry Andric }
37606c3fb27SDimitry Andric 
37706c3fb27SDimitry Andric unsigned AMDGPUCodeGenPrepareImpl::getBaseElementBitWidth(const Type *T) const {
3780b57cec5SDimitry Andric   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric   if (T->isIntegerTy())
3810b57cec5SDimitry Andric     return T->getIntegerBitWidth();
3820b57cec5SDimitry Andric   return cast<VectorType>(T)->getElementType()->getIntegerBitWidth();
3830b57cec5SDimitry Andric }
3840b57cec5SDimitry Andric 
38506c3fb27SDimitry Andric Type *AMDGPUCodeGenPrepareImpl::getI32Ty(IRBuilder<> &B, const Type *T) const {
3860b57cec5SDimitry Andric   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   if (T->isIntegerTy())
3890b57cec5SDimitry Andric     return B.getInt32Ty();
3905ffd83dbSDimitry Andric   return FixedVectorType::get(B.getInt32Ty(), cast<FixedVectorType>(T));
3910b57cec5SDimitry Andric }
3920b57cec5SDimitry Andric 
39306c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::isSigned(const BinaryOperator &I) const {
3940b57cec5SDimitry Andric   return I.getOpcode() == Instruction::AShr ||
3950b57cec5SDimitry Andric       I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::SRem;
3960b57cec5SDimitry Andric }
3970b57cec5SDimitry Andric 
39806c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::isSigned(const SelectInst &I) const {
3990b57cec5SDimitry Andric   return isa<ICmpInst>(I.getOperand(0)) ?
4000b57cec5SDimitry Andric       cast<ICmpInst>(I.getOperand(0))->isSigned() : false;
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric 
40306c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::needsPromotionToI32(const Type *T) const {
404e8d8bef9SDimitry Andric   if (!Widen16BitOps)
405e8d8bef9SDimitry Andric     return false;
406e8d8bef9SDimitry Andric 
4070b57cec5SDimitry Andric   const IntegerType *IntTy = dyn_cast<IntegerType>(T);
4080b57cec5SDimitry Andric   if (IntTy && IntTy->getBitWidth() > 1 && IntTy->getBitWidth() <= 16)
4090b57cec5SDimitry Andric     return true;
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric   if (const VectorType *VT = dyn_cast<VectorType>(T)) {
4120b57cec5SDimitry Andric     // TODO: The set of packed operations is more limited, so may want to
4130b57cec5SDimitry Andric     // promote some anyway.
4140b57cec5SDimitry Andric     if (ST->hasVOP3PInsts())
4150b57cec5SDimitry Andric       return false;
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric     return needsPromotionToI32(VT->getElementType());
4180b57cec5SDimitry Andric   }
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric   return false;
4210b57cec5SDimitry Andric }
4220b57cec5SDimitry Andric 
42306c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::isLegalFloatingTy(const Type *Ty) const {
42406c3fb27SDimitry Andric   return Ty->isFloatTy() || Ty->isDoubleTy() ||
42506c3fb27SDimitry Andric          (Ty->isHalfTy() && ST->has16BitInsts());
42606c3fb27SDimitry Andric }
42706c3fb27SDimitry Andric 
4280b57cec5SDimitry Andric // Return true if the op promoted to i32 should have nsw set.
4290b57cec5SDimitry Andric static bool promotedOpIsNSW(const Instruction &I) {
4300b57cec5SDimitry Andric   switch (I.getOpcode()) {
4310b57cec5SDimitry Andric   case Instruction::Shl:
4320b57cec5SDimitry Andric   case Instruction::Add:
4330b57cec5SDimitry Andric   case Instruction::Sub:
4340b57cec5SDimitry Andric     return true;
4350b57cec5SDimitry Andric   case Instruction::Mul:
4360b57cec5SDimitry Andric     return I.hasNoUnsignedWrap();
4370b57cec5SDimitry Andric   default:
4380b57cec5SDimitry Andric     return false;
4390b57cec5SDimitry Andric   }
4400b57cec5SDimitry Andric }
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric // Return true if the op promoted to i32 should have nuw set.
4430b57cec5SDimitry Andric static bool promotedOpIsNUW(const Instruction &I) {
4440b57cec5SDimitry Andric   switch (I.getOpcode()) {
4450b57cec5SDimitry Andric   case Instruction::Shl:
4460b57cec5SDimitry Andric   case Instruction::Add:
4470b57cec5SDimitry Andric   case Instruction::Mul:
4480b57cec5SDimitry Andric     return true;
4490b57cec5SDimitry Andric   case Instruction::Sub:
4500b57cec5SDimitry Andric     return I.hasNoUnsignedWrap();
4510b57cec5SDimitry Andric   default:
4520b57cec5SDimitry Andric     return false;
4530b57cec5SDimitry Andric   }
4540b57cec5SDimitry Andric }
4550b57cec5SDimitry Andric 
45606c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::canWidenScalarExtLoad(LoadInst &I) const {
4570b57cec5SDimitry Andric   Type *Ty = I.getType();
4580b57cec5SDimitry Andric   const DataLayout &DL = Mod->getDataLayout();
4590b57cec5SDimitry Andric   int TySize = DL.getTypeSizeInBits(Ty);
4605ffd83dbSDimitry Andric   Align Alignment = DL.getValueOrABITypeAlignment(I.getAlign(), Ty);
4610b57cec5SDimitry Andric 
46206c3fb27SDimitry Andric   return I.isSimple() && TySize < 32 && Alignment >= 4 && UA->isUniform(&I);
4630b57cec5SDimitry Andric }
4640b57cec5SDimitry Andric 
46506c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(BinaryOperator &I) const {
4660b57cec5SDimitry Andric   assert(needsPromotionToI32(I.getType()) &&
4670b57cec5SDimitry Andric          "I does not need promotion to i32");
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   if (I.getOpcode() == Instruction::SDiv ||
4700b57cec5SDimitry Andric       I.getOpcode() == Instruction::UDiv ||
4710b57cec5SDimitry Andric       I.getOpcode() == Instruction::SRem ||
4720b57cec5SDimitry Andric       I.getOpcode() == Instruction::URem)
4730b57cec5SDimitry Andric     return false;
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
4760b57cec5SDimitry Andric   Builder.SetCurrentDebugLocation(I.getDebugLoc());
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   Type *I32Ty = getI32Ty(Builder, I.getType());
4790b57cec5SDimitry Andric   Value *ExtOp0 = nullptr;
4800b57cec5SDimitry Andric   Value *ExtOp1 = nullptr;
4810b57cec5SDimitry Andric   Value *ExtRes = nullptr;
4820b57cec5SDimitry Andric   Value *TruncRes = nullptr;
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric   if (isSigned(I)) {
4850b57cec5SDimitry Andric     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
4860b57cec5SDimitry Andric     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
4870b57cec5SDimitry Andric   } else {
4880b57cec5SDimitry Andric     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
4890b57cec5SDimitry Andric     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
4900b57cec5SDimitry Andric   }
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric   ExtRes = Builder.CreateBinOp(I.getOpcode(), ExtOp0, ExtOp1);
4930b57cec5SDimitry Andric   if (Instruction *Inst = dyn_cast<Instruction>(ExtRes)) {
4940b57cec5SDimitry Andric     if (promotedOpIsNSW(cast<Instruction>(I)))
4950b57cec5SDimitry Andric       Inst->setHasNoSignedWrap();
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric     if (promotedOpIsNUW(cast<Instruction>(I)))
4980b57cec5SDimitry Andric       Inst->setHasNoUnsignedWrap();
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric     if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
5010b57cec5SDimitry Andric       Inst->setIsExact(ExactOp->isExact());
5020b57cec5SDimitry Andric   }
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric   I.replaceAllUsesWith(TruncRes);
5070b57cec5SDimitry Andric   I.eraseFromParent();
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric   return true;
5100b57cec5SDimitry Andric }
5110b57cec5SDimitry Andric 
51206c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(ICmpInst &I) const {
5130b57cec5SDimitry Andric   assert(needsPromotionToI32(I.getOperand(0)->getType()) &&
5140b57cec5SDimitry Andric          "I does not need promotion to i32");
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
5170b57cec5SDimitry Andric   Builder.SetCurrentDebugLocation(I.getDebugLoc());
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   Type *I32Ty = getI32Ty(Builder, I.getOperand(0)->getType());
5200b57cec5SDimitry Andric   Value *ExtOp0 = nullptr;
5210b57cec5SDimitry Andric   Value *ExtOp1 = nullptr;
5220b57cec5SDimitry Andric   Value *NewICmp  = nullptr;
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   if (I.isSigned()) {
5250b57cec5SDimitry Andric     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
5260b57cec5SDimitry Andric     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
5270b57cec5SDimitry Andric   } else {
5280b57cec5SDimitry Andric     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
5290b57cec5SDimitry Andric     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
5300b57cec5SDimitry Andric   }
5310b57cec5SDimitry Andric   NewICmp = Builder.CreateICmp(I.getPredicate(), ExtOp0, ExtOp1);
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric   I.replaceAllUsesWith(NewICmp);
5340b57cec5SDimitry Andric   I.eraseFromParent();
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric   return true;
5370b57cec5SDimitry Andric }
5380b57cec5SDimitry Andric 
53906c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(SelectInst &I) const {
5400b57cec5SDimitry Andric   assert(needsPromotionToI32(I.getType()) &&
5410b57cec5SDimitry Andric          "I does not need promotion to i32");
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
5440b57cec5SDimitry Andric   Builder.SetCurrentDebugLocation(I.getDebugLoc());
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric   Type *I32Ty = getI32Ty(Builder, I.getType());
5470b57cec5SDimitry Andric   Value *ExtOp1 = nullptr;
5480b57cec5SDimitry Andric   Value *ExtOp2 = nullptr;
5490b57cec5SDimitry Andric   Value *ExtRes = nullptr;
5500b57cec5SDimitry Andric   Value *TruncRes = nullptr;
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric   if (isSigned(I)) {
5530b57cec5SDimitry Andric     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
5540b57cec5SDimitry Andric     ExtOp2 = Builder.CreateSExt(I.getOperand(2), I32Ty);
5550b57cec5SDimitry Andric   } else {
5560b57cec5SDimitry Andric     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
5570b57cec5SDimitry Andric     ExtOp2 = Builder.CreateZExt(I.getOperand(2), I32Ty);
5580b57cec5SDimitry Andric   }
5590b57cec5SDimitry Andric   ExtRes = Builder.CreateSelect(I.getOperand(0), ExtOp1, ExtOp2);
5600b57cec5SDimitry Andric   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric   I.replaceAllUsesWith(TruncRes);
5630b57cec5SDimitry Andric   I.eraseFromParent();
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   return true;
5660b57cec5SDimitry Andric }
5670b57cec5SDimitry Andric 
56806c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::promoteUniformBitreverseToI32(
5690b57cec5SDimitry Andric     IntrinsicInst &I) const {
5700b57cec5SDimitry Andric   assert(I.getIntrinsicID() == Intrinsic::bitreverse &&
5710b57cec5SDimitry Andric          "I must be bitreverse intrinsic");
5720b57cec5SDimitry Andric   assert(needsPromotionToI32(I.getType()) &&
5730b57cec5SDimitry Andric          "I does not need promotion to i32");
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
5760b57cec5SDimitry Andric   Builder.SetCurrentDebugLocation(I.getDebugLoc());
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric   Type *I32Ty = getI32Ty(Builder, I.getType());
5790b57cec5SDimitry Andric   Function *I32 =
5800b57cec5SDimitry Andric       Intrinsic::getDeclaration(Mod, Intrinsic::bitreverse, { I32Ty });
5810b57cec5SDimitry Andric   Value *ExtOp = Builder.CreateZExt(I.getOperand(0), I32Ty);
5820b57cec5SDimitry Andric   Value *ExtRes = Builder.CreateCall(I32, { ExtOp });
5830b57cec5SDimitry Andric   Value *LShrOp =
5840b57cec5SDimitry Andric       Builder.CreateLShr(ExtRes, 32 - getBaseElementBitWidth(I.getType()));
5850b57cec5SDimitry Andric   Value *TruncRes =
5860b57cec5SDimitry Andric       Builder.CreateTrunc(LShrOp, I.getType());
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric   I.replaceAllUsesWith(TruncRes);
5890b57cec5SDimitry Andric   I.eraseFromParent();
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric   return true;
5920b57cec5SDimitry Andric }
5930b57cec5SDimitry Andric 
59406c3fb27SDimitry Andric unsigned AMDGPUCodeGenPrepareImpl::numBitsUnsigned(Value *Op) const {
59504eeddc0SDimitry Andric   return computeKnownBits(Op, *DL, 0, AC).countMaxActiveBits();
5960b57cec5SDimitry Andric }
5970b57cec5SDimitry Andric 
59806c3fb27SDimitry Andric unsigned AMDGPUCodeGenPrepareImpl::numBitsSigned(Value *Op) const {
59904eeddc0SDimitry Andric   return ComputeMaxSignificantBits(Op, *DL, 0, AC);
6000b57cec5SDimitry Andric }
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric static void extractValues(IRBuilder<> &Builder,
6030b57cec5SDimitry Andric                           SmallVectorImpl<Value *> &Values, Value *V) {
6045ffd83dbSDimitry Andric   auto *VT = dyn_cast<FixedVectorType>(V->getType());
6050b57cec5SDimitry Andric   if (!VT) {
6060b57cec5SDimitry Andric     Values.push_back(V);
6070b57cec5SDimitry Andric     return;
6080b57cec5SDimitry Andric   }
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric   for (int I = 0, E = VT->getNumElements(); I != E; ++I)
6110b57cec5SDimitry Andric     Values.push_back(Builder.CreateExtractElement(V, I));
6120b57cec5SDimitry Andric }
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric static Value *insertValues(IRBuilder<> &Builder,
6150b57cec5SDimitry Andric                            Type *Ty,
6160b57cec5SDimitry Andric                            SmallVectorImpl<Value *> &Values) {
617bdd1243dSDimitry Andric   if (!Ty->isVectorTy()) {
618bdd1243dSDimitry Andric     assert(Values.size() == 1);
6190b57cec5SDimitry Andric     return Values[0];
620bdd1243dSDimitry Andric   }
6210b57cec5SDimitry Andric 
622bdd1243dSDimitry Andric   Value *NewVal = PoisonValue::get(Ty);
6230b57cec5SDimitry Andric   for (int I = 0, E = Values.size(); I != E; ++I)
6240b57cec5SDimitry Andric     NewVal = Builder.CreateInsertElement(NewVal, Values[I], I);
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric   return NewVal;
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric 
62906c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::replaceMulWithMul24(BinaryOperator &I) const {
6300b57cec5SDimitry Andric   if (I.getOpcode() != Instruction::Mul)
6310b57cec5SDimitry Andric     return false;
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   Type *Ty = I.getType();
6340b57cec5SDimitry Andric   unsigned Size = Ty->getScalarSizeInBits();
6350b57cec5SDimitry Andric   if (Size <= 16 && ST->has16BitInsts())
6360b57cec5SDimitry Andric     return false;
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric   // Prefer scalar if this could be s_mul_i32
63906c3fb27SDimitry Andric   if (UA->isUniform(&I))
6400b57cec5SDimitry Andric     return false;
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   Value *LHS = I.getOperand(0);
6430b57cec5SDimitry Andric   Value *RHS = I.getOperand(1);
6440b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
6450b57cec5SDimitry Andric   Builder.SetCurrentDebugLocation(I.getDebugLoc());
6460b57cec5SDimitry Andric 
647349cc55cSDimitry Andric   unsigned LHSBits = 0, RHSBits = 0;
648349cc55cSDimitry Andric   bool IsSigned = false;
6490b57cec5SDimitry Andric 
65004eeddc0SDimitry Andric   if (ST->hasMulU24() && (LHSBits = numBitsUnsigned(LHS)) <= 24 &&
65104eeddc0SDimitry Andric       (RHSBits = numBitsUnsigned(RHS)) <= 24) {
652349cc55cSDimitry Andric     IsSigned = false;
653349cc55cSDimitry Andric 
65404eeddc0SDimitry Andric   } else if (ST->hasMulI24() && (LHSBits = numBitsSigned(LHS)) <= 24 &&
65504eeddc0SDimitry Andric              (RHSBits = numBitsSigned(RHS)) <= 24) {
656349cc55cSDimitry Andric     IsSigned = true;
657349cc55cSDimitry Andric 
6580b57cec5SDimitry Andric   } else
6590b57cec5SDimitry Andric     return false;
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   SmallVector<Value *, 4> LHSVals;
6620b57cec5SDimitry Andric   SmallVector<Value *, 4> RHSVals;
6630b57cec5SDimitry Andric   SmallVector<Value *, 4> ResultVals;
6640b57cec5SDimitry Andric   extractValues(Builder, LHSVals, LHS);
6650b57cec5SDimitry Andric   extractValues(Builder, RHSVals, RHS);
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric   IntegerType *I32Ty = Builder.getInt32Ty();
6685f757f3fSDimitry Andric   IntegerType *IntrinTy = Size > 32 ? Builder.getInt64Ty() : I32Ty;
6695f757f3fSDimitry Andric   Type *DstTy = LHSVals[0]->getType();
6705f757f3fSDimitry Andric 
6710b57cec5SDimitry Andric   for (int I = 0, E = LHSVals.size(); I != E; ++I) {
6725f757f3fSDimitry Andric     Value *LHS = IsSigned ? Builder.CreateSExtOrTrunc(LHSVals[I], I32Ty)
6735f757f3fSDimitry Andric                           : Builder.CreateZExtOrTrunc(LHSVals[I], I32Ty);
6745f757f3fSDimitry Andric     Value *RHS = IsSigned ? Builder.CreateSExtOrTrunc(RHSVals[I], I32Ty)
6755f757f3fSDimitry Andric                           : Builder.CreateZExtOrTrunc(RHSVals[I], I32Ty);
6765f757f3fSDimitry Andric     Intrinsic::ID ID =
6775f757f3fSDimitry Andric         IsSigned ? Intrinsic::amdgcn_mul_i24 : Intrinsic::amdgcn_mul_u24;
6785f757f3fSDimitry Andric     Value *Result = Builder.CreateIntrinsic(ID, {IntrinTy}, {LHS, RHS});
6795f757f3fSDimitry Andric     Result = IsSigned ? Builder.CreateSExtOrTrunc(Result, DstTy)
6805f757f3fSDimitry Andric                       : Builder.CreateZExtOrTrunc(Result, DstTy);
6815f757f3fSDimitry Andric     ResultVals.push_back(Result);
6820b57cec5SDimitry Andric   }
6830b57cec5SDimitry Andric 
6848bcb0991SDimitry Andric   Value *NewVal = insertValues(Builder, Ty, ResultVals);
6858bcb0991SDimitry Andric   NewVal->takeName(&I);
6868bcb0991SDimitry Andric   I.replaceAllUsesWith(NewVal);
6870b57cec5SDimitry Andric   I.eraseFromParent();
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric   return true;
6900b57cec5SDimitry Andric }
6910b57cec5SDimitry Andric 
6925ffd83dbSDimitry Andric // Find a select instruction, which may have been casted. This is mostly to deal
6935ffd83dbSDimitry Andric // with cases where i16 selects were promoted here to i32.
6945ffd83dbSDimitry Andric static SelectInst *findSelectThroughCast(Value *V, CastInst *&Cast) {
6955ffd83dbSDimitry Andric   Cast = nullptr;
6965ffd83dbSDimitry Andric   if (SelectInst *Sel = dyn_cast<SelectInst>(V))
6975ffd83dbSDimitry Andric     return Sel;
6980b57cec5SDimitry Andric 
6995ffd83dbSDimitry Andric   if ((Cast = dyn_cast<CastInst>(V))) {
7005ffd83dbSDimitry Andric     if (SelectInst *Sel = dyn_cast<SelectInst>(Cast->getOperand(0)))
7015ffd83dbSDimitry Andric       return Sel;
7020b57cec5SDimitry Andric   }
7030b57cec5SDimitry Andric 
7045ffd83dbSDimitry Andric   return nullptr;
7055ffd83dbSDimitry Andric }
7060b57cec5SDimitry Andric 
70706c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::foldBinOpIntoSelect(BinaryOperator &BO) const {
7085ffd83dbSDimitry Andric   // Don't do this unless the old select is going away. We want to eliminate the
7095ffd83dbSDimitry Andric   // binary operator, not replace a binop with a select.
7105ffd83dbSDimitry Andric   int SelOpNo = 0;
7115ffd83dbSDimitry Andric 
7125ffd83dbSDimitry Andric   CastInst *CastOp;
7135ffd83dbSDimitry Andric 
7145ffd83dbSDimitry Andric   // TODO: Should probably try to handle some cases with multiple
7155ffd83dbSDimitry Andric   // users. Duplicating the select may be profitable for division.
7165ffd83dbSDimitry Andric   SelectInst *Sel = findSelectThroughCast(BO.getOperand(0), CastOp);
7175ffd83dbSDimitry Andric   if (!Sel || !Sel->hasOneUse()) {
7185ffd83dbSDimitry Andric     SelOpNo = 1;
7195ffd83dbSDimitry Andric     Sel = findSelectThroughCast(BO.getOperand(1), CastOp);
7205ffd83dbSDimitry Andric   }
7215ffd83dbSDimitry Andric 
7225ffd83dbSDimitry Andric   if (!Sel || !Sel->hasOneUse())
7230b57cec5SDimitry Andric     return false;
7240b57cec5SDimitry Andric 
7255ffd83dbSDimitry Andric   Constant *CT = dyn_cast<Constant>(Sel->getTrueValue());
7265ffd83dbSDimitry Andric   Constant *CF = dyn_cast<Constant>(Sel->getFalseValue());
7275ffd83dbSDimitry Andric   Constant *CBO = dyn_cast<Constant>(BO.getOperand(SelOpNo ^ 1));
7285ffd83dbSDimitry Andric   if (!CBO || !CT || !CF)
7295ffd83dbSDimitry Andric     return false;
7305ffd83dbSDimitry Andric 
7315ffd83dbSDimitry Andric   if (CastOp) {
7325ffd83dbSDimitry Andric     if (!CastOp->hasOneUse())
7335ffd83dbSDimitry Andric       return false;
7345ffd83dbSDimitry Andric     CT = ConstantFoldCastOperand(CastOp->getOpcode(), CT, BO.getType(), *DL);
7355ffd83dbSDimitry Andric     CF = ConstantFoldCastOperand(CastOp->getOpcode(), CF, BO.getType(), *DL);
7365ffd83dbSDimitry Andric   }
7375ffd83dbSDimitry Andric 
7385ffd83dbSDimitry Andric   // TODO: Handle special 0/-1 cases DAG combine does, although we only really
7395ffd83dbSDimitry Andric   // need to handle divisions here.
7405ffd83dbSDimitry Andric   Constant *FoldedT = SelOpNo ?
7415ffd83dbSDimitry Andric     ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CT, *DL) :
7425ffd83dbSDimitry Andric     ConstantFoldBinaryOpOperands(BO.getOpcode(), CT, CBO, *DL);
743753f127fSDimitry Andric   if (!FoldedT || isa<ConstantExpr>(FoldedT))
7445ffd83dbSDimitry Andric     return false;
7455ffd83dbSDimitry Andric 
7465ffd83dbSDimitry Andric   Constant *FoldedF = SelOpNo ?
7475ffd83dbSDimitry Andric     ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CF, *DL) :
7485ffd83dbSDimitry Andric     ConstantFoldBinaryOpOperands(BO.getOpcode(), CF, CBO, *DL);
749753f127fSDimitry Andric   if (!FoldedF || isa<ConstantExpr>(FoldedF))
7505ffd83dbSDimitry Andric     return false;
7515ffd83dbSDimitry Andric 
7525ffd83dbSDimitry Andric   IRBuilder<> Builder(&BO);
7535ffd83dbSDimitry Andric   Builder.SetCurrentDebugLocation(BO.getDebugLoc());
7545ffd83dbSDimitry Andric   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&BO))
7555ffd83dbSDimitry Andric     Builder.setFastMathFlags(FPOp->getFastMathFlags());
7565ffd83dbSDimitry Andric 
7575ffd83dbSDimitry Andric   Value *NewSelect = Builder.CreateSelect(Sel->getCondition(),
7585ffd83dbSDimitry Andric                                           FoldedT, FoldedF);
7595ffd83dbSDimitry Andric   NewSelect->takeName(&BO);
7605ffd83dbSDimitry Andric   BO.replaceAllUsesWith(NewSelect);
7615ffd83dbSDimitry Andric   BO.eraseFromParent();
7625ffd83dbSDimitry Andric   if (CastOp)
7635ffd83dbSDimitry Andric     CastOp->eraseFromParent();
7645ffd83dbSDimitry Andric   Sel->eraseFromParent();
7655ffd83dbSDimitry Andric   return true;
7665ffd83dbSDimitry Andric }
7675ffd83dbSDimitry Andric 
76806c3fb27SDimitry Andric std::pair<Value *, Value *>
76906c3fb27SDimitry Andric AMDGPUCodeGenPrepareImpl::getFrexpResults(IRBuilder<> &Builder,
77006c3fb27SDimitry Andric                                           Value *Src) const {
77106c3fb27SDimitry Andric   Type *Ty = Src->getType();
77206c3fb27SDimitry Andric   Value *Frexp = Builder.CreateIntrinsic(Intrinsic::frexp,
77306c3fb27SDimitry Andric                                          {Ty, Builder.getInt32Ty()}, Src);
77406c3fb27SDimitry Andric   Value *FrexpMant = Builder.CreateExtractValue(Frexp, {0});
77506c3fb27SDimitry Andric 
77606c3fb27SDimitry Andric   // Bypass the bug workaround for the exponent result since it doesn't matter.
77706c3fb27SDimitry Andric   // TODO: Does the bug workaround even really need to consider the exponent
77806c3fb27SDimitry Andric   // result? It's unspecified by the spec.
77906c3fb27SDimitry Andric 
78006c3fb27SDimitry Andric   Value *FrexpExp =
78106c3fb27SDimitry Andric       ST->hasFractBug()
78206c3fb27SDimitry Andric           ? Builder.CreateIntrinsic(Intrinsic::amdgcn_frexp_exp,
78306c3fb27SDimitry Andric                                     {Builder.getInt32Ty(), Ty}, Src)
78406c3fb27SDimitry Andric           : Builder.CreateExtractValue(Frexp, {1});
78506c3fb27SDimitry Andric   return {FrexpMant, FrexpExp};
78606c3fb27SDimitry Andric }
78706c3fb27SDimitry Andric 
78806c3fb27SDimitry Andric /// Emit an expansion of 1.0 / Src good for 1ulp that supports denormals.
78906c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::emitRcpIEEE1ULP(IRBuilder<> &Builder,
79006c3fb27SDimitry Andric                                                  Value *Src,
79106c3fb27SDimitry Andric                                                  bool IsNegative) const {
79206c3fb27SDimitry Andric   // Same as for 1.0, but expand the sign out of the constant.
79306c3fb27SDimitry Andric   // -1.0 / x -> rcp (fneg x)
79406c3fb27SDimitry Andric   if (IsNegative)
79506c3fb27SDimitry Andric     Src = Builder.CreateFNeg(Src);
79606c3fb27SDimitry Andric 
79706c3fb27SDimitry Andric   // The rcp instruction doesn't support denormals, so scale the input
79806c3fb27SDimitry Andric   // out of the denormal range and convert at the end.
79906c3fb27SDimitry Andric   //
80006c3fb27SDimitry Andric   // Expand as 2^-n * (1.0 / (x * 2^n))
80106c3fb27SDimitry Andric 
80206c3fb27SDimitry Andric   // TODO: Skip scaling if input is known never denormal and the input
80306c3fb27SDimitry Andric   // range won't underflow to denormal. The hard part is knowing the
80406c3fb27SDimitry Andric   // result. We need a range check, the result could be denormal for
80506c3fb27SDimitry Andric   // 0x1p+126 < den <= 0x1p+127.
80606c3fb27SDimitry Andric   auto [FrexpMant, FrexpExp] = getFrexpResults(Builder, Src);
80706c3fb27SDimitry Andric   Value *ScaleFactor = Builder.CreateNeg(FrexpExp);
80806c3fb27SDimitry Andric   Value *Rcp = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, FrexpMant);
8095f757f3fSDimitry Andric   return Builder.CreateCall(getLdexpF32(), {Rcp, ScaleFactor});
81006c3fb27SDimitry Andric }
81106c3fb27SDimitry Andric 
81206c3fb27SDimitry Andric /// Emit a 2ulp expansion for fdiv by using frexp for input scaling.
81306c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::emitFrexpDiv(IRBuilder<> &Builder, Value *LHS,
81406c3fb27SDimitry Andric                                               Value *RHS,
81506c3fb27SDimitry Andric                                               FastMathFlags FMF) const {
81606c3fb27SDimitry Andric   // If we have have to work around the fract/frexp bug, we're worse off than
81706c3fb27SDimitry Andric   // using the fdiv.fast expansion. The full safe expansion is faster if we have
81806c3fb27SDimitry Andric   // fast FMA.
81906c3fb27SDimitry Andric   if (HasFP32DenormalFlush && ST->hasFractBug() && !ST->hasFastFMAF32() &&
82006c3fb27SDimitry Andric       (!FMF.noNaNs() || !FMF.noInfs()))
82106c3fb27SDimitry Andric     return nullptr;
82206c3fb27SDimitry Andric 
82306c3fb27SDimitry Andric   // We're scaling the LHS to avoid a denormal input, and scale the denominator
82406c3fb27SDimitry Andric   // to avoid large values underflowing the result.
82506c3fb27SDimitry Andric   auto [FrexpMantRHS, FrexpExpRHS] = getFrexpResults(Builder, RHS);
82606c3fb27SDimitry Andric 
82706c3fb27SDimitry Andric   Value *Rcp =
82806c3fb27SDimitry Andric       Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, FrexpMantRHS);
82906c3fb27SDimitry Andric 
83006c3fb27SDimitry Andric   auto [FrexpMantLHS, FrexpExpLHS] = getFrexpResults(Builder, LHS);
83106c3fb27SDimitry Andric   Value *Mul = Builder.CreateFMul(FrexpMantLHS, Rcp);
83206c3fb27SDimitry Andric 
83306c3fb27SDimitry Andric   // We multiplied by 2^N/2^M, so we need to multiply by 2^(N-M) to scale the
83406c3fb27SDimitry Andric   // result.
83506c3fb27SDimitry Andric   Value *ExpDiff = Builder.CreateSub(FrexpExpLHS, FrexpExpRHS);
8365f757f3fSDimitry Andric   return Builder.CreateCall(getLdexpF32(), {Mul, ExpDiff});
8375f757f3fSDimitry Andric }
8385f757f3fSDimitry Andric 
8395f757f3fSDimitry Andric /// Emit a sqrt that handles denormals and is accurate to 2ulp.
8405f757f3fSDimitry Andric Value *AMDGPUCodeGenPrepareImpl::emitSqrtIEEE2ULP(IRBuilder<> &Builder,
8415f757f3fSDimitry Andric                                                   Value *Src,
8425f757f3fSDimitry Andric                                                   FastMathFlags FMF) const {
8435f757f3fSDimitry Andric   Type *Ty = Src->getType();
8445f757f3fSDimitry Andric   APFloat SmallestNormal =
8455f757f3fSDimitry Andric       APFloat::getSmallestNormalized(Ty->getFltSemantics());
8465f757f3fSDimitry Andric   Value *NeedScale =
8475f757f3fSDimitry Andric       Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
8485f757f3fSDimitry Andric 
8495f757f3fSDimitry Andric   ConstantInt *Zero = Builder.getInt32(0);
8505f757f3fSDimitry Andric   Value *InputScaleFactor =
8515f757f3fSDimitry Andric       Builder.CreateSelect(NeedScale, Builder.getInt32(32), Zero);
8525f757f3fSDimitry Andric 
8535f757f3fSDimitry Andric   Value *Scaled = Builder.CreateCall(getLdexpF32(), {Src, InputScaleFactor});
8545f757f3fSDimitry Andric 
8555f757f3fSDimitry Andric   Value *Sqrt = Builder.CreateCall(getSqrtF32(), Scaled);
8565f757f3fSDimitry Andric 
8575f757f3fSDimitry Andric   Value *OutputScaleFactor =
8585f757f3fSDimitry Andric       Builder.CreateSelect(NeedScale, Builder.getInt32(-16), Zero);
8595f757f3fSDimitry Andric   return Builder.CreateCall(getLdexpF32(), {Sqrt, OutputScaleFactor});
86006c3fb27SDimitry Andric }
86106c3fb27SDimitry Andric 
86206c3fb27SDimitry Andric /// Emit an expansion of 1.0 / sqrt(Src) good for 1ulp that supports denormals.
86306c3fb27SDimitry Andric static Value *emitRsqIEEE1ULP(IRBuilder<> &Builder, Value *Src,
86406c3fb27SDimitry Andric                               bool IsNegative) {
86506c3fb27SDimitry Andric   // bool need_scale = x < 0x1p-126f;
86606c3fb27SDimitry Andric   // float input_scale = need_scale ? 0x1.0p+24f : 1.0f;
86706c3fb27SDimitry Andric   // float output_scale = need_scale ? 0x1.0p+12f : 1.0f;
86806c3fb27SDimitry Andric   // rsq(x * input_scale) * output_scale;
86906c3fb27SDimitry Andric 
87006c3fb27SDimitry Andric   Type *Ty = Src->getType();
87106c3fb27SDimitry Andric   APFloat SmallestNormal =
87206c3fb27SDimitry Andric       APFloat::getSmallestNormalized(Ty->getFltSemantics());
87306c3fb27SDimitry Andric   Value *NeedScale =
87406c3fb27SDimitry Andric       Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
87506c3fb27SDimitry Andric   Constant *One = ConstantFP::get(Ty, 1.0);
87606c3fb27SDimitry Andric   Constant *InputScale = ConstantFP::get(Ty, 0x1.0p+24);
87706c3fb27SDimitry Andric   Constant *OutputScale =
87806c3fb27SDimitry Andric       ConstantFP::get(Ty, IsNegative ? -0x1.0p+12 : 0x1.0p+12);
87906c3fb27SDimitry Andric 
88006c3fb27SDimitry Andric   Value *InputScaleFactor = Builder.CreateSelect(NeedScale, InputScale, One);
88106c3fb27SDimitry Andric 
88206c3fb27SDimitry Andric   Value *ScaledInput = Builder.CreateFMul(Src, InputScaleFactor);
88306c3fb27SDimitry Andric   Value *Rsq = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, ScaledInput);
88406c3fb27SDimitry Andric   Value *OutputScaleFactor = Builder.CreateSelect(
88506c3fb27SDimitry Andric       NeedScale, OutputScale, IsNegative ? ConstantFP::get(Ty, -1.0) : One);
88606c3fb27SDimitry Andric 
88706c3fb27SDimitry Andric   return Builder.CreateFMul(Rsq, OutputScaleFactor);
88806c3fb27SDimitry Andric }
88906c3fb27SDimitry Andric 
89006c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::canOptimizeWithRsq(const FPMathOperator *SqrtOp,
89106c3fb27SDimitry Andric                                                   FastMathFlags DivFMF,
89206c3fb27SDimitry Andric                                                   FastMathFlags SqrtFMF) const {
89306c3fb27SDimitry Andric   // The rsqrt contraction increases accuracy from ~2ulp to ~1ulp.
89406c3fb27SDimitry Andric   if (!DivFMF.allowContract() || !SqrtFMF.allowContract())
89506c3fb27SDimitry Andric     return false;
89606c3fb27SDimitry Andric 
89706c3fb27SDimitry Andric   // v_rsq_f32 gives 1ulp
89806c3fb27SDimitry Andric   return SqrtFMF.approxFunc() || HasUnsafeFPMath ||
89906c3fb27SDimitry Andric          SqrtOp->getFPAccuracy() >= 1.0f;
90006c3fb27SDimitry Andric }
90106c3fb27SDimitry Andric 
90206c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::optimizeWithRsq(
9035f757f3fSDimitry Andric     IRBuilder<> &Builder, Value *Num, Value *Den, const FastMathFlags DivFMF,
9045f757f3fSDimitry Andric     const FastMathFlags SqrtFMF, const Instruction *CtxI) const {
90506c3fb27SDimitry Andric   // The rsqrt contraction increases accuracy from ~2ulp to ~1ulp.
90606c3fb27SDimitry Andric   assert(DivFMF.allowContract() && SqrtFMF.allowContract());
90706c3fb27SDimitry Andric 
90806c3fb27SDimitry Andric   // rsq_f16 is accurate to 0.51 ulp.
90906c3fb27SDimitry Andric   // rsq_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
91006c3fb27SDimitry Andric   // rsq_f64 is never accurate.
91106c3fb27SDimitry Andric   const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num);
91206c3fb27SDimitry Andric   if (!CLHS)
91306c3fb27SDimitry Andric     return nullptr;
91406c3fb27SDimitry Andric 
91506c3fb27SDimitry Andric   assert(Den->getType()->isFloatTy());
91606c3fb27SDimitry Andric 
91706c3fb27SDimitry Andric   bool IsNegative = false;
91806c3fb27SDimitry Andric 
91906c3fb27SDimitry Andric   // TODO: Handle other numerator values with arcp.
92006c3fb27SDimitry Andric   if (CLHS->isExactlyValue(1.0) || (IsNegative = CLHS->isExactlyValue(-1.0))) {
92106c3fb27SDimitry Andric     // Add in the sqrt flags.
92206c3fb27SDimitry Andric     IRBuilder<>::FastMathFlagGuard Guard(Builder);
9235f757f3fSDimitry Andric     Builder.setFastMathFlags(DivFMF | SqrtFMF);
92406c3fb27SDimitry Andric 
9255f757f3fSDimitry Andric     if ((DivFMF.approxFunc() && SqrtFMF.approxFunc()) || HasUnsafeFPMath ||
92606c3fb27SDimitry Andric         canIgnoreDenormalInput(Den, CtxI)) {
92706c3fb27SDimitry Andric       Value *Result = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, Den);
92806c3fb27SDimitry Andric       // -1.0 / sqrt(x) -> fneg(rsq(x))
92906c3fb27SDimitry Andric       return IsNegative ? Builder.CreateFNeg(Result) : Result;
93006c3fb27SDimitry Andric     }
93106c3fb27SDimitry Andric 
93206c3fb27SDimitry Andric     return emitRsqIEEE1ULP(Builder, Den, IsNegative);
93306c3fb27SDimitry Andric   }
93406c3fb27SDimitry Andric 
93506c3fb27SDimitry Andric   return nullptr;
93606c3fb27SDimitry Andric }
93706c3fb27SDimitry Andric 
9385ffd83dbSDimitry Andric // Optimize fdiv with rcp:
9395ffd83dbSDimitry Andric //
9405ffd83dbSDimitry Andric // 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
9415ffd83dbSDimitry Andric //               allowed with unsafe-fp-math or afn.
9425ffd83dbSDimitry Andric //
94306c3fb27SDimitry Andric // a/b -> a*rcp(b) when arcp is allowed, and we only need provide ULP 1.0
94406c3fb27SDimitry Andric Value *
94506c3fb27SDimitry Andric AMDGPUCodeGenPrepareImpl::optimizeWithRcp(IRBuilder<> &Builder, Value *Num,
94606c3fb27SDimitry Andric                                           Value *Den, FastMathFlags FMF,
94706c3fb27SDimitry Andric                                           const Instruction *CtxI) const {
94806c3fb27SDimitry Andric   // rcp_f16 is accurate to 0.51 ulp.
94906c3fb27SDimitry Andric   // rcp_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
95006c3fb27SDimitry Andric   // rcp_f64 is never accurate.
95106c3fb27SDimitry Andric   assert(Den->getType()->isFloatTy());
9525ffd83dbSDimitry Andric 
9535ffd83dbSDimitry Andric   if (const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num)) {
95406c3fb27SDimitry Andric     bool IsNegative = false;
95506c3fb27SDimitry Andric     if (CLHS->isExactlyValue(1.0) ||
95606c3fb27SDimitry Andric         (IsNegative = CLHS->isExactlyValue(-1.0))) {
95706c3fb27SDimitry Andric       Value *Src = Den;
95806c3fb27SDimitry Andric 
95906c3fb27SDimitry Andric       if (HasFP32DenormalFlush || FMF.approxFunc()) {
96006c3fb27SDimitry Andric         // -1.0 / x -> 1.0 / fneg(x)
96106c3fb27SDimitry Andric         if (IsNegative)
96206c3fb27SDimitry Andric           Src = Builder.CreateFNeg(Src);
9635ffd83dbSDimitry Andric 
9645ffd83dbSDimitry Andric         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
9655ffd83dbSDimitry Andric         // the CI documentation has a worst case error of 1 ulp.
96606c3fb27SDimitry Andric         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK
96706c3fb27SDimitry Andric         // to use it as long as we aren't trying to use denormals.
9685ffd83dbSDimitry Andric         //
9695ffd83dbSDimitry Andric         // v_rcp_f16 and v_rsq_f16 DO support denormals.
9705ffd83dbSDimitry Andric 
9715ffd83dbSDimitry Andric         // NOTE: v_sqrt and v_rcp will be combined to v_rsq later. So we don't
9725ffd83dbSDimitry Andric         //       insert rsq intrinsic here.
9735ffd83dbSDimitry Andric 
9745ffd83dbSDimitry Andric         // 1.0 / x -> rcp(x)
97506c3fb27SDimitry Andric         return Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, Src);
9765ffd83dbSDimitry Andric       }
9775ffd83dbSDimitry Andric 
97806c3fb27SDimitry Andric       // TODO: If the input isn't denormal, and we know the input exponent isn't
97906c3fb27SDimitry Andric       // big enough to introduce a denormal we can avoid the scaling.
98006c3fb27SDimitry Andric       return emitRcpIEEE1ULP(Builder, Src, IsNegative);
9815ffd83dbSDimitry Andric     }
9825ffd83dbSDimitry Andric   }
9835ffd83dbSDimitry Andric 
98406c3fb27SDimitry Andric   if (FMF.allowReciprocal()) {
9855ffd83dbSDimitry Andric     // x / y -> x * (1.0 / y)
98606c3fb27SDimitry Andric 
98706c3fb27SDimitry Andric     // TODO: Could avoid denormal scaling and use raw rcp if we knew the output
98806c3fb27SDimitry Andric     // will never underflow.
98906c3fb27SDimitry Andric     if (HasFP32DenormalFlush || FMF.approxFunc()) {
99006c3fb27SDimitry Andric       Value *Recip = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, Den);
9915ffd83dbSDimitry Andric       return Builder.CreateFMul(Num, Recip);
9925ffd83dbSDimitry Andric     }
99306c3fb27SDimitry Andric 
99406c3fb27SDimitry Andric     Value *Recip = emitRcpIEEE1ULP(Builder, Den, false);
99506c3fb27SDimitry Andric     return Builder.CreateFMul(Num, Recip);
99606c3fb27SDimitry Andric   }
99706c3fb27SDimitry Andric 
9985ffd83dbSDimitry Andric   return nullptr;
9995ffd83dbSDimitry Andric }
10005ffd83dbSDimitry Andric 
10015ffd83dbSDimitry Andric // optimize with fdiv.fast:
10025ffd83dbSDimitry Andric //
10035ffd83dbSDimitry Andric // a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
10045ffd83dbSDimitry Andric //
10055ffd83dbSDimitry Andric // 1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
10065ffd83dbSDimitry Andric //
10075ffd83dbSDimitry Andric // NOTE: optimizeWithRcp should be tried first because rcp is the preference.
100806c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::optimizeWithFDivFast(
100906c3fb27SDimitry Andric     IRBuilder<> &Builder, Value *Num, Value *Den, float ReqdAccuracy) const {
10105ffd83dbSDimitry Andric   // fdiv.fast can achieve 2.5 ULP accuracy.
10115ffd83dbSDimitry Andric   if (ReqdAccuracy < 2.5f)
10125ffd83dbSDimitry Andric     return nullptr;
10135ffd83dbSDimitry Andric 
10145ffd83dbSDimitry Andric   // Only have fdiv.fast for f32.
101506c3fb27SDimitry Andric   assert(Den->getType()->isFloatTy());
10165ffd83dbSDimitry Andric 
10175ffd83dbSDimitry Andric   bool NumIsOne = false;
10185ffd83dbSDimitry Andric   if (const ConstantFP *CNum = dyn_cast<ConstantFP>(Num)) {
10195ffd83dbSDimitry Andric     if (CNum->isExactlyValue(+1.0) || CNum->isExactlyValue(-1.0))
10205ffd83dbSDimitry Andric       NumIsOne = true;
10215ffd83dbSDimitry Andric   }
10225ffd83dbSDimitry Andric 
10235ffd83dbSDimitry Andric   // fdiv does not support denormals. But 1.0/x is always fine to use it.
102406c3fb27SDimitry Andric   //
102506c3fb27SDimitry Andric   // TODO: This works for any value with a specific known exponent range, don't
102606c3fb27SDimitry Andric   // just limit to constant 1.
102706c3fb27SDimitry Andric   if (!HasFP32DenormalFlush && !NumIsOne)
10285ffd83dbSDimitry Andric     return nullptr;
10295ffd83dbSDimitry Andric 
103006c3fb27SDimitry Andric   return Builder.CreateIntrinsic(Intrinsic::amdgcn_fdiv_fast, {}, {Num, Den});
103106c3fb27SDimitry Andric }
103206c3fb27SDimitry Andric 
103306c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::visitFDivElement(
103406c3fb27SDimitry Andric     IRBuilder<> &Builder, Value *Num, Value *Den, FastMathFlags DivFMF,
103506c3fb27SDimitry Andric     FastMathFlags SqrtFMF, Value *RsqOp, const Instruction *FDivInst,
103606c3fb27SDimitry Andric     float ReqdDivAccuracy) const {
103706c3fb27SDimitry Andric   if (RsqOp) {
103806c3fb27SDimitry Andric     Value *Rsq =
103906c3fb27SDimitry Andric         optimizeWithRsq(Builder, Num, RsqOp, DivFMF, SqrtFMF, FDivInst);
104006c3fb27SDimitry Andric     if (Rsq)
104106c3fb27SDimitry Andric       return Rsq;
104206c3fb27SDimitry Andric   }
104306c3fb27SDimitry Andric 
104406c3fb27SDimitry Andric   Value *Rcp = optimizeWithRcp(Builder, Num, Den, DivFMF, FDivInst);
104506c3fb27SDimitry Andric   if (Rcp)
104606c3fb27SDimitry Andric     return Rcp;
104706c3fb27SDimitry Andric 
104806c3fb27SDimitry Andric   // In the basic case fdiv_fast has the same instruction count as the frexp div
104906c3fb27SDimitry Andric   // expansion. Slightly prefer fdiv_fast since it ends in an fmul that can
105006c3fb27SDimitry Andric   // potentially be fused into a user. Also, materialization of the constants
105106c3fb27SDimitry Andric   // can be reused for multiple instances.
105206c3fb27SDimitry Andric   Value *FDivFast = optimizeWithFDivFast(Builder, Num, Den, ReqdDivAccuracy);
105306c3fb27SDimitry Andric   if (FDivFast)
105406c3fb27SDimitry Andric     return FDivFast;
105506c3fb27SDimitry Andric 
105606c3fb27SDimitry Andric   return emitFrexpDiv(Builder, Num, Den, DivFMF);
10575ffd83dbSDimitry Andric }
10585ffd83dbSDimitry Andric 
10595ffd83dbSDimitry Andric // Optimizations is performed based on fpmath, fast math flags as well as
10605ffd83dbSDimitry Andric // denormals to optimize fdiv with either rcp or fdiv.fast.
10615ffd83dbSDimitry Andric //
10625ffd83dbSDimitry Andric // With rcp:
10635ffd83dbSDimitry Andric //   1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
10645ffd83dbSDimitry Andric //                 allowed with unsafe-fp-math or afn.
10655ffd83dbSDimitry Andric //
10665ffd83dbSDimitry Andric //   a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
10675ffd83dbSDimitry Andric //
10685ffd83dbSDimitry Andric // With fdiv.fast:
10695ffd83dbSDimitry Andric //   a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
10705ffd83dbSDimitry Andric //
10715ffd83dbSDimitry Andric //   1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
10725ffd83dbSDimitry Andric //
10735ffd83dbSDimitry Andric // NOTE: rcp is the preference in cases that both are legal.
107406c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitFDiv(BinaryOperator &FDiv) {
107506c3fb27SDimitry Andric   if (DisableFDivExpand)
107606c3fb27SDimitry Andric     return false;
10775ffd83dbSDimitry Andric 
10785ffd83dbSDimitry Andric   Type *Ty = FDiv.getType()->getScalarType();
107906c3fb27SDimitry Andric   if (!Ty->isFloatTy())
108006c3fb27SDimitry Andric     return false;
10815ffd83dbSDimitry Andric 
1082e8d8bef9SDimitry Andric   // The f64 rcp/rsq approximations are pretty inaccurate. We can do an
108306c3fb27SDimitry Andric   // expansion around them in codegen. f16 is good enough to always use.
10840b57cec5SDimitry Andric 
10850b57cec5SDimitry Andric   const FPMathOperator *FPOp = cast<const FPMathOperator>(&FDiv);
108606c3fb27SDimitry Andric   const FastMathFlags DivFMF = FPOp->getFastMathFlags();
10875ffd83dbSDimitry Andric   const float ReqdAccuracy = FPOp->getFPAccuracy();
10880b57cec5SDimitry Andric 
108906c3fb27SDimitry Andric   FastMathFlags SqrtFMF;
10900b57cec5SDimitry Andric 
10910b57cec5SDimitry Andric   Value *Num = FDiv.getOperand(0);
10920b57cec5SDimitry Andric   Value *Den = FDiv.getOperand(1);
10930b57cec5SDimitry Andric 
109406c3fb27SDimitry Andric   Value *RsqOp = nullptr;
109506c3fb27SDimitry Andric   auto *DenII = dyn_cast<IntrinsicInst>(Den);
109606c3fb27SDimitry Andric   if (DenII && DenII->getIntrinsicID() == Intrinsic::sqrt &&
109706c3fb27SDimitry Andric       DenII->hasOneUse()) {
109806c3fb27SDimitry Andric     const auto *SqrtOp = cast<FPMathOperator>(DenII);
109906c3fb27SDimitry Andric     SqrtFMF = SqrtOp->getFastMathFlags();
110006c3fb27SDimitry Andric     if (canOptimizeWithRsq(SqrtOp, DivFMF, SqrtFMF))
110106c3fb27SDimitry Andric       RsqOp = SqrtOp->getOperand(0);
11020b57cec5SDimitry Andric   }
11030b57cec5SDimitry Andric 
11045f757f3fSDimitry Andric   // Inaccurate rcp is allowed with unsafe-fp-math or afn.
11055f757f3fSDimitry Andric   //
11065f757f3fSDimitry Andric   // Defer to codegen to handle this.
11075f757f3fSDimitry Andric   //
11085f757f3fSDimitry Andric   // TODO: Decide on an interpretation for interactions between afn + arcp +
11095f757f3fSDimitry Andric   // !fpmath, and make it consistent between here and codegen. For now, defer
11105f757f3fSDimitry Andric   // expansion of afn to codegen. The current interpretation is so aggressive we
11115f757f3fSDimitry Andric   // don't need any pre-consideration here when we have better information. A
11125f757f3fSDimitry Andric   // more conservative interpretation could use handling here.
11135f757f3fSDimitry Andric   const bool AllowInaccurateRcp = HasUnsafeFPMath || DivFMF.approxFunc();
11145f757f3fSDimitry Andric   if (!RsqOp && AllowInaccurateRcp)
11155f757f3fSDimitry Andric     return false;
11165f757f3fSDimitry Andric 
11175f757f3fSDimitry Andric   // Defer the correct implementations to codegen.
11185f757f3fSDimitry Andric   if (ReqdAccuracy < 1.0f)
11195f757f3fSDimitry Andric     return false;
11205f757f3fSDimitry Andric 
112106c3fb27SDimitry Andric   IRBuilder<> Builder(FDiv.getParent(), std::next(FDiv.getIterator()));
112206c3fb27SDimitry Andric   Builder.setFastMathFlags(DivFMF);
112306c3fb27SDimitry Andric   Builder.SetCurrentDebugLocation(FDiv.getDebugLoc());
112406c3fb27SDimitry Andric 
112506c3fb27SDimitry Andric   SmallVector<Value *, 4> NumVals;
112606c3fb27SDimitry Andric   SmallVector<Value *, 4> DenVals;
112706c3fb27SDimitry Andric   SmallVector<Value *, 4> RsqDenVals;
112806c3fb27SDimitry Andric   extractValues(Builder, NumVals, Num);
112906c3fb27SDimitry Andric   extractValues(Builder, DenVals, Den);
113006c3fb27SDimitry Andric 
113106c3fb27SDimitry Andric   if (RsqOp)
113206c3fb27SDimitry Andric     extractValues(Builder, RsqDenVals, RsqOp);
113306c3fb27SDimitry Andric 
113406c3fb27SDimitry Andric   SmallVector<Value *, 4> ResultVals(NumVals.size());
113506c3fb27SDimitry Andric   for (int I = 0, E = NumVals.size(); I != E; ++I) {
113606c3fb27SDimitry Andric     Value *NumElt = NumVals[I];
113706c3fb27SDimitry Andric     Value *DenElt = DenVals[I];
113806c3fb27SDimitry Andric     Value *RsqDenElt = RsqOp ? RsqDenVals[I] : nullptr;
113906c3fb27SDimitry Andric 
114006c3fb27SDimitry Andric     Value *NewElt =
114106c3fb27SDimitry Andric         visitFDivElement(Builder, NumElt, DenElt, DivFMF, SqrtFMF, RsqDenElt,
114206c3fb27SDimitry Andric                          cast<Instruction>(FPOp), ReqdAccuracy);
114306c3fb27SDimitry Andric     if (!NewElt) {
114406c3fb27SDimitry Andric       // Keep the original, but scalarized.
114506c3fb27SDimitry Andric 
114606c3fb27SDimitry Andric       // This has the unfortunate side effect of sometimes scalarizing when
114706c3fb27SDimitry Andric       // we're not going to do anything.
114806c3fb27SDimitry Andric       NewElt = Builder.CreateFDiv(NumElt, DenElt);
114906c3fb27SDimitry Andric       if (auto *NewEltInst = dyn_cast<Instruction>(NewElt))
115006c3fb27SDimitry Andric         NewEltInst->copyMetadata(FDiv);
11510b57cec5SDimitry Andric     }
11520b57cec5SDimitry Andric 
115306c3fb27SDimitry Andric     ResultVals[I] = NewElt;
11540b57cec5SDimitry Andric   }
11550b57cec5SDimitry Andric 
115606c3fb27SDimitry Andric   Value *NewVal = insertValues(Builder, FDiv.getType(), ResultVals);
1157fe6060f1SDimitry Andric 
115806c3fb27SDimitry Andric   if (NewVal) {
115906c3fb27SDimitry Andric     FDiv.replaceAllUsesWith(NewVal);
116006c3fb27SDimitry Andric     NewVal->takeName(&FDiv);
116106c3fb27SDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(&FDiv, TLInfo);
116206c3fb27SDimitry Andric   }
1163fe6060f1SDimitry Andric 
1164fe6060f1SDimitry Andric   return true;
1165fe6060f1SDimitry Andric }
1166fe6060f1SDimitry Andric 
11670b57cec5SDimitry Andric static bool hasUnsafeFPMath(const Function &F) {
11680b57cec5SDimitry Andric   Attribute Attr = F.getFnAttribute("unsafe-fp-math");
1169fe6060f1SDimitry Andric   return Attr.getValueAsBool();
11700b57cec5SDimitry Andric }
11710b57cec5SDimitry Andric 
11720b57cec5SDimitry Andric static std::pair<Value*, Value*> getMul64(IRBuilder<> &Builder,
11730b57cec5SDimitry Andric                                           Value *LHS, Value *RHS) {
11740b57cec5SDimitry Andric   Type *I32Ty = Builder.getInt32Ty();
11750b57cec5SDimitry Andric   Type *I64Ty = Builder.getInt64Ty();
11760b57cec5SDimitry Andric 
11770b57cec5SDimitry Andric   Value *LHS_EXT64 = Builder.CreateZExt(LHS, I64Ty);
11780b57cec5SDimitry Andric   Value *RHS_EXT64 = Builder.CreateZExt(RHS, I64Ty);
11790b57cec5SDimitry Andric   Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64);
11800b57cec5SDimitry Andric   Value *Lo = Builder.CreateTrunc(MUL64, I32Ty);
11810b57cec5SDimitry Andric   Value *Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32));
11820b57cec5SDimitry Andric   Hi = Builder.CreateTrunc(Hi, I32Ty);
1183bdd1243dSDimitry Andric   return std::pair(Lo, Hi);
11840b57cec5SDimitry Andric }
11850b57cec5SDimitry Andric 
11860b57cec5SDimitry Andric static Value* getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS) {
11870b57cec5SDimitry Andric   return getMul64(Builder, LHS, RHS).second;
11880b57cec5SDimitry Andric }
11890b57cec5SDimitry Andric 
119081ad6265SDimitry Andric /// Figure out how many bits are really needed for this division. \p AtLeast is
11915ffd83dbSDimitry Andric /// an optimization hint to bypass the second ComputeNumSignBits call if we the
11925ffd83dbSDimitry Andric /// first one is insufficient. Returns -1 on failure.
119306c3fb27SDimitry Andric int AMDGPUCodeGenPrepareImpl::getDivNumBits(BinaryOperator &I, Value *Num,
119406c3fb27SDimitry Andric                                             Value *Den, unsigned AtLeast,
119506c3fb27SDimitry Andric                                             bool IsSigned) const {
11965ffd83dbSDimitry Andric   const DataLayout &DL = Mod->getDataLayout();
11975ffd83dbSDimitry Andric   unsigned LHSSignBits = ComputeNumSignBits(Num, DL, 0, AC, &I);
11985ffd83dbSDimitry Andric   if (LHSSignBits < AtLeast)
11995ffd83dbSDimitry Andric     return -1;
12005ffd83dbSDimitry Andric 
12015ffd83dbSDimitry Andric   unsigned RHSSignBits = ComputeNumSignBits(Den, DL, 0, AC, &I);
12025ffd83dbSDimitry Andric   if (RHSSignBits < AtLeast)
12035ffd83dbSDimitry Andric     return -1;
12045ffd83dbSDimitry Andric 
12055ffd83dbSDimitry Andric   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
12065ffd83dbSDimitry Andric   unsigned DivBits = Num->getType()->getScalarSizeInBits() - SignBits;
12075ffd83dbSDimitry Andric   if (IsSigned)
12085ffd83dbSDimitry Andric     ++DivBits;
12095ffd83dbSDimitry Andric   return DivBits;
12105ffd83dbSDimitry Andric }
12115ffd83dbSDimitry Andric 
12120b57cec5SDimitry Andric // The fractional part of a float is enough to accurately represent up to
12130b57cec5SDimitry Andric // a 24-bit signed integer.
121406c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::expandDivRem24(IRBuilder<> &Builder,
121506c3fb27SDimitry Andric                                                 BinaryOperator &I, Value *Num,
121606c3fb27SDimitry Andric                                                 Value *Den, bool IsDiv,
121706c3fb27SDimitry Andric                                                 bool IsSigned) const {
1218*0fca6ea1SDimitry Andric   unsigned SSBits = Num->getType()->getScalarSizeInBits();
1219*0fca6ea1SDimitry Andric   // If Num bits <= 24, assume 0 signbits.
1220*0fca6ea1SDimitry Andric   unsigned AtLeast = (SSBits <= 24) ? 0 : (SSBits - 24 + IsSigned);
1221*0fca6ea1SDimitry Andric   int DivBits = getDivNumBits(I, Num, Den, AtLeast, IsSigned);
12225ffd83dbSDimitry Andric   if (DivBits == -1)
12230b57cec5SDimitry Andric     return nullptr;
12245ffd83dbSDimitry Andric   return expandDivRem24Impl(Builder, I, Num, Den, DivBits, IsDiv, IsSigned);
12255ffd83dbSDimitry Andric }
12260b57cec5SDimitry Andric 
122706c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::expandDivRem24Impl(
122806c3fb27SDimitry Andric     IRBuilder<> &Builder, BinaryOperator &I, Value *Num, Value *Den,
122906c3fb27SDimitry Andric     unsigned DivBits, bool IsDiv, bool IsSigned) const {
12300b57cec5SDimitry Andric   Type *I32Ty = Builder.getInt32Ty();
12315ffd83dbSDimitry Andric   Num = Builder.CreateTrunc(Num, I32Ty);
12325ffd83dbSDimitry Andric   Den = Builder.CreateTrunc(Den, I32Ty);
12335ffd83dbSDimitry Andric 
12340b57cec5SDimitry Andric   Type *F32Ty = Builder.getFloatTy();
12350b57cec5SDimitry Andric   ConstantInt *One = Builder.getInt32(1);
12360b57cec5SDimitry Andric   Value *JQ = One;
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric   if (IsSigned) {
12390b57cec5SDimitry Andric     // char|short jq = ia ^ ib;
12400b57cec5SDimitry Andric     JQ = Builder.CreateXor(Num, Den);
12410b57cec5SDimitry Andric 
12420b57cec5SDimitry Andric     // jq = jq >> (bitsize - 2)
12430b57cec5SDimitry Andric     JQ = Builder.CreateAShr(JQ, Builder.getInt32(30));
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric     // jq = jq | 0x1
12460b57cec5SDimitry Andric     JQ = Builder.CreateOr(JQ, One);
12470b57cec5SDimitry Andric   }
12480b57cec5SDimitry Andric 
12490b57cec5SDimitry Andric   // int ia = (int)LHS;
12500b57cec5SDimitry Andric   Value *IA = Num;
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric   // int ib, (int)RHS;
12530b57cec5SDimitry Andric   Value *IB = Den;
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric   // float fa = (float)ia;
12560b57cec5SDimitry Andric   Value *FA = IsSigned ? Builder.CreateSIToFP(IA, F32Ty)
12570b57cec5SDimitry Andric                        : Builder.CreateUIToFP(IA, F32Ty);
12580b57cec5SDimitry Andric 
12590b57cec5SDimitry Andric   // float fb = (float)ib;
12600b57cec5SDimitry Andric   Value *FB = IsSigned ? Builder.CreateSIToFP(IB,F32Ty)
12610b57cec5SDimitry Andric                        : Builder.CreateUIToFP(IB,F32Ty);
12620b57cec5SDimitry Andric 
12635ffd83dbSDimitry Andric   Function *RcpDecl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp,
12645ffd83dbSDimitry Andric                                                 Builder.getFloatTy());
12655ffd83dbSDimitry Andric   Value *RCP = Builder.CreateCall(RcpDecl, { FB });
12660b57cec5SDimitry Andric   Value *FQM = Builder.CreateFMul(FA, RCP);
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric   // fq = trunc(fqm);
12690b57cec5SDimitry Andric   CallInst *FQ = Builder.CreateUnaryIntrinsic(Intrinsic::trunc, FQM);
12700b57cec5SDimitry Andric   FQ->copyFastMathFlags(Builder.getFastMathFlags());
12710b57cec5SDimitry Andric 
12720b57cec5SDimitry Andric   // float fqneg = -fq;
12730b57cec5SDimitry Andric   Value *FQNeg = Builder.CreateFNeg(FQ);
12740b57cec5SDimitry Andric 
12750b57cec5SDimitry Andric   // float fr = mad(fqneg, fb, fa);
12765ffd83dbSDimitry Andric   auto FMAD = !ST->hasMadMacF32Insts()
12775ffd83dbSDimitry Andric                   ? Intrinsic::fma
12785ffd83dbSDimitry Andric                   : (Intrinsic::ID)Intrinsic::amdgcn_fmad_ftz;
12795ffd83dbSDimitry Andric   Value *FR = Builder.CreateIntrinsic(FMAD,
12800b57cec5SDimitry Andric                                       {FQNeg->getType()}, {FQNeg, FB, FA}, FQ);
12810b57cec5SDimitry Andric 
12820b57cec5SDimitry Andric   // int iq = (int)fq;
12830b57cec5SDimitry Andric   Value *IQ = IsSigned ? Builder.CreateFPToSI(FQ, I32Ty)
12840b57cec5SDimitry Andric                        : Builder.CreateFPToUI(FQ, I32Ty);
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric   // fr = fabs(fr);
12870b57cec5SDimitry Andric   FR = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FR, FQ);
12880b57cec5SDimitry Andric 
12890b57cec5SDimitry Andric   // fb = fabs(fb);
12900b57cec5SDimitry Andric   FB = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FB, FQ);
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric   // int cv = fr >= fb;
12930b57cec5SDimitry Andric   Value *CV = Builder.CreateFCmpOGE(FR, FB);
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric   // jq = (cv ? jq : 0);
12960b57cec5SDimitry Andric   JQ = Builder.CreateSelect(CV, JQ, Builder.getInt32(0));
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric   // dst = iq + jq;
12990b57cec5SDimitry Andric   Value *Div = Builder.CreateAdd(IQ, JQ);
13000b57cec5SDimitry Andric 
13010b57cec5SDimitry Andric   Value *Res = Div;
13020b57cec5SDimitry Andric   if (!IsDiv) {
13030b57cec5SDimitry Andric     // Rem needs compensation, it's easier to recompute it
13040b57cec5SDimitry Andric     Value *Rem = Builder.CreateMul(Div, Den);
13050b57cec5SDimitry Andric     Res = Builder.CreateSub(Num, Rem);
13060b57cec5SDimitry Andric   }
13070b57cec5SDimitry Andric 
13085ffd83dbSDimitry Andric   if (DivBits != 0 && DivBits < 32) {
13095ffd83dbSDimitry Andric     // Extend in register from the number of bits this divide really is.
13100b57cec5SDimitry Andric     if (IsSigned) {
13115ffd83dbSDimitry Andric       int InRegBits = 32 - DivBits;
13125ffd83dbSDimitry Andric 
13135ffd83dbSDimitry Andric       Res = Builder.CreateShl(Res, InRegBits);
13145ffd83dbSDimitry Andric       Res = Builder.CreateAShr(Res, InRegBits);
13150b57cec5SDimitry Andric     } else {
13165ffd83dbSDimitry Andric       ConstantInt *TruncMask
13175ffd83dbSDimitry Andric         = Builder.getInt32((UINT64_C(1) << DivBits) - 1);
13180b57cec5SDimitry Andric       Res = Builder.CreateAnd(Res, TruncMask);
13190b57cec5SDimitry Andric     }
13205ffd83dbSDimitry Andric   }
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric   return Res;
13230b57cec5SDimitry Andric }
13240b57cec5SDimitry Andric 
13255ffd83dbSDimitry Andric // Try to recognize special cases the DAG will emit special, better expansions
13265ffd83dbSDimitry Andric // than the general expansion we do here.
13275ffd83dbSDimitry Andric 
13285ffd83dbSDimitry Andric // TODO: It would be better to just directly handle those optimizations here.
132906c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::divHasSpecialOptimization(BinaryOperator &I,
133006c3fb27SDimitry Andric                                                          Value *Num,
133106c3fb27SDimitry Andric                                                          Value *Den) const {
13325ffd83dbSDimitry Andric   if (Constant *C = dyn_cast<Constant>(Den)) {
13335ffd83dbSDimitry Andric     // Arbitrary constants get a better expansion as long as a wider mulhi is
13345ffd83dbSDimitry Andric     // legal.
13355ffd83dbSDimitry Andric     if (C->getType()->getScalarSizeInBits() <= 32)
13365ffd83dbSDimitry Andric       return true;
13375ffd83dbSDimitry Andric 
13385ffd83dbSDimitry Andric     // TODO: Sdiv check for not exact for some reason.
13395ffd83dbSDimitry Andric 
13405ffd83dbSDimitry Andric     // If there's no wider mulhi, there's only a better expansion for powers of
13415ffd83dbSDimitry Andric     // two.
13425ffd83dbSDimitry Andric     // TODO: Should really know for each vector element.
13435ffd83dbSDimitry Andric     if (isKnownToBeAPowerOfTwo(C, *DL, true, 0, AC, &I, DT))
13445ffd83dbSDimitry Andric       return true;
13455ffd83dbSDimitry Andric 
13465ffd83dbSDimitry Andric     return false;
13475ffd83dbSDimitry Andric   }
13485ffd83dbSDimitry Andric 
13495ffd83dbSDimitry Andric   if (BinaryOperator *BinOpDen = dyn_cast<BinaryOperator>(Den)) {
13505ffd83dbSDimitry Andric     // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
13515ffd83dbSDimitry Andric     if (BinOpDen->getOpcode() == Instruction::Shl &&
13525ffd83dbSDimitry Andric         isa<Constant>(BinOpDen->getOperand(0)) &&
13535ffd83dbSDimitry Andric         isKnownToBeAPowerOfTwo(BinOpDen->getOperand(0), *DL, true,
13545ffd83dbSDimitry Andric                                0, AC, &I, DT)) {
13555ffd83dbSDimitry Andric       return true;
13565ffd83dbSDimitry Andric     }
13575ffd83dbSDimitry Andric   }
13585ffd83dbSDimitry Andric 
13595ffd83dbSDimitry Andric   return false;
13605ffd83dbSDimitry Andric }
13615ffd83dbSDimitry Andric 
13625ffd83dbSDimitry Andric static Value *getSign32(Value *V, IRBuilder<> &Builder, const DataLayout *DL) {
13635ffd83dbSDimitry Andric   // Check whether the sign can be determined statically.
13645ffd83dbSDimitry Andric   KnownBits Known = computeKnownBits(V, *DL);
13655ffd83dbSDimitry Andric   if (Known.isNegative())
13665ffd83dbSDimitry Andric     return Constant::getAllOnesValue(V->getType());
13675ffd83dbSDimitry Andric   if (Known.isNonNegative())
13685ffd83dbSDimitry Andric     return Constant::getNullValue(V->getType());
13695ffd83dbSDimitry Andric   return Builder.CreateAShr(V, Builder.getInt32(31));
13705ffd83dbSDimitry Andric }
13715ffd83dbSDimitry Andric 
137206c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::expandDivRem32(IRBuilder<> &Builder,
13735ffd83dbSDimitry Andric                                                 BinaryOperator &I, Value *X,
13745ffd83dbSDimitry Andric                                                 Value *Y) const {
13750b57cec5SDimitry Andric   Instruction::BinaryOps Opc = I.getOpcode();
13760b57cec5SDimitry Andric   assert(Opc == Instruction::URem || Opc == Instruction::UDiv ||
13770b57cec5SDimitry Andric          Opc == Instruction::SRem || Opc == Instruction::SDiv);
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric   FastMathFlags FMF;
13800b57cec5SDimitry Andric   FMF.setFast();
13810b57cec5SDimitry Andric   Builder.setFastMathFlags(FMF);
13820b57cec5SDimitry Andric 
13835ffd83dbSDimitry Andric   if (divHasSpecialOptimization(I, X, Y))
13845ffd83dbSDimitry Andric     return nullptr;  // Keep it for later optimization.
13850b57cec5SDimitry Andric 
13860b57cec5SDimitry Andric   bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv;
13870b57cec5SDimitry Andric   bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv;
13880b57cec5SDimitry Andric 
13895ffd83dbSDimitry Andric   Type *Ty = X->getType();
13900b57cec5SDimitry Andric   Type *I32Ty = Builder.getInt32Ty();
13910b57cec5SDimitry Andric   Type *F32Ty = Builder.getFloatTy();
13920b57cec5SDimitry Andric 
1393*0fca6ea1SDimitry Andric   if (Ty->getScalarSizeInBits() != 32) {
13940b57cec5SDimitry Andric     if (IsSigned) {
1395*0fca6ea1SDimitry Andric       X = Builder.CreateSExtOrTrunc(X, I32Ty);
1396*0fca6ea1SDimitry Andric       Y = Builder.CreateSExtOrTrunc(Y, I32Ty);
13970b57cec5SDimitry Andric     } else {
1398*0fca6ea1SDimitry Andric       X = Builder.CreateZExtOrTrunc(X, I32Ty);
1399*0fca6ea1SDimitry Andric       Y = Builder.CreateZExtOrTrunc(Y, I32Ty);
14000b57cec5SDimitry Andric     }
14010b57cec5SDimitry Andric   }
14020b57cec5SDimitry Andric 
14035ffd83dbSDimitry Andric   if (Value *Res = expandDivRem24(Builder, I, X, Y, IsDiv, IsSigned)) {
14045ffd83dbSDimitry Andric     return IsSigned ? Builder.CreateSExtOrTrunc(Res, Ty) :
14055ffd83dbSDimitry Andric                       Builder.CreateZExtOrTrunc(Res, Ty);
14060b57cec5SDimitry Andric   }
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric   ConstantInt *Zero = Builder.getInt32(0);
14090b57cec5SDimitry Andric   ConstantInt *One = Builder.getInt32(1);
14100b57cec5SDimitry Andric 
14110b57cec5SDimitry Andric   Value *Sign = nullptr;
14120b57cec5SDimitry Andric   if (IsSigned) {
14135ffd83dbSDimitry Andric     Value *SignX = getSign32(X, Builder, DL);
14145ffd83dbSDimitry Andric     Value *SignY = getSign32(Y, Builder, DL);
14150b57cec5SDimitry Andric     // Remainder sign is the same as LHS
14165ffd83dbSDimitry Andric     Sign = IsDiv ? Builder.CreateXor(SignX, SignY) : SignX;
14170b57cec5SDimitry Andric 
14185ffd83dbSDimitry Andric     X = Builder.CreateAdd(X, SignX);
14195ffd83dbSDimitry Andric     Y = Builder.CreateAdd(Y, SignY);
14200b57cec5SDimitry Andric 
14215ffd83dbSDimitry Andric     X = Builder.CreateXor(X, SignX);
14225ffd83dbSDimitry Andric     Y = Builder.CreateXor(Y, SignY);
14230b57cec5SDimitry Andric   }
14240b57cec5SDimitry Andric 
14255ffd83dbSDimitry Andric   // The algorithm here is based on ideas from "Software Integer Division", Tom
14265ffd83dbSDimitry Andric   // Rodeheffer, August 2008.
14275ffd83dbSDimitry Andric   //
14285ffd83dbSDimitry Andric   // unsigned udiv(unsigned x, unsigned y) {
14295ffd83dbSDimitry Andric   //   // Initial estimate of inv(y). The constant is less than 2^32 to ensure
14305ffd83dbSDimitry Andric   //   // that this is a lower bound on inv(y), even if some of the calculations
14315ffd83dbSDimitry Andric   //   // round up.
14325ffd83dbSDimitry Andric   //   unsigned z = (unsigned)((4294967296.0 - 512.0) * v_rcp_f32((float)y));
14335ffd83dbSDimitry Andric   //
14345ffd83dbSDimitry Andric   //   // One round of UNR (Unsigned integer Newton-Raphson) to improve z.
14355ffd83dbSDimitry Andric   //   // Empirically this is guaranteed to give a "two-y" lower bound on
14365ffd83dbSDimitry Andric   //   // inv(y).
14375ffd83dbSDimitry Andric   //   z += umulh(z, -y * z);
14385ffd83dbSDimitry Andric   //
14395ffd83dbSDimitry Andric   //   // Quotient/remainder estimate.
14405ffd83dbSDimitry Andric   //   unsigned q = umulh(x, z);
14415ffd83dbSDimitry Andric   //   unsigned r = x - q * y;
14425ffd83dbSDimitry Andric   //
14435ffd83dbSDimitry Andric   //   // Two rounds of quotient/remainder refinement.
14445ffd83dbSDimitry Andric   //   if (r >= y) {
14455ffd83dbSDimitry Andric   //     ++q;
14465ffd83dbSDimitry Andric   //     r -= y;
14475ffd83dbSDimitry Andric   //   }
14485ffd83dbSDimitry Andric   //   if (r >= y) {
14495ffd83dbSDimitry Andric   //     ++q;
14505ffd83dbSDimitry Andric   //     r -= y;
14515ffd83dbSDimitry Andric   //   }
14525ffd83dbSDimitry Andric   //
14535ffd83dbSDimitry Andric   //   return q;
14545ffd83dbSDimitry Andric   // }
14550b57cec5SDimitry Andric 
14565ffd83dbSDimitry Andric   // Initial estimate of inv(y).
14575ffd83dbSDimitry Andric   Value *FloatY = Builder.CreateUIToFP(Y, F32Ty);
14585ffd83dbSDimitry Andric   Function *Rcp = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp, F32Ty);
14595ffd83dbSDimitry Andric   Value *RcpY = Builder.CreateCall(Rcp, {FloatY});
146006c3fb27SDimitry Andric   Constant *Scale = ConstantFP::get(F32Ty, llvm::bit_cast<float>(0x4F7FFFFE));
14615ffd83dbSDimitry Andric   Value *ScaledY = Builder.CreateFMul(RcpY, Scale);
14625ffd83dbSDimitry Andric   Value *Z = Builder.CreateFPToUI(ScaledY, I32Ty);
14630b57cec5SDimitry Andric 
14645ffd83dbSDimitry Andric   // One round of UNR.
14655ffd83dbSDimitry Andric   Value *NegY = Builder.CreateSub(Zero, Y);
14665ffd83dbSDimitry Andric   Value *NegYZ = Builder.CreateMul(NegY, Z);
14675ffd83dbSDimitry Andric   Z = Builder.CreateAdd(Z, getMulHu(Builder, Z, NegYZ));
14680b57cec5SDimitry Andric 
14695ffd83dbSDimitry Andric   // Quotient/remainder estimate.
14705ffd83dbSDimitry Andric   Value *Q = getMulHu(Builder, X, Z);
14715ffd83dbSDimitry Andric   Value *R = Builder.CreateSub(X, Builder.CreateMul(Q, Y));
14720b57cec5SDimitry Andric 
14735ffd83dbSDimitry Andric   // First quotient/remainder refinement.
14745ffd83dbSDimitry Andric   Value *Cond = Builder.CreateICmpUGE(R, Y);
14755ffd83dbSDimitry Andric   if (IsDiv)
14765ffd83dbSDimitry Andric     Q = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
14775ffd83dbSDimitry Andric   R = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
14780b57cec5SDimitry Andric 
14795ffd83dbSDimitry Andric   // Second quotient/remainder refinement.
14805ffd83dbSDimitry Andric   Cond = Builder.CreateICmpUGE(R, Y);
14810b57cec5SDimitry Andric   Value *Res;
14825ffd83dbSDimitry Andric   if (IsDiv)
14835ffd83dbSDimitry Andric     Res = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
14845ffd83dbSDimitry Andric   else
14855ffd83dbSDimitry Andric     Res = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric   if (IsSigned) {
14880b57cec5SDimitry Andric     Res = Builder.CreateXor(Res, Sign);
14890b57cec5SDimitry Andric     Res = Builder.CreateSub(Res, Sign);
1490*0fca6ea1SDimitry Andric     Res = Builder.CreateSExtOrTrunc(Res, Ty);
1491*0fca6ea1SDimitry Andric   } else {
1492*0fca6ea1SDimitry Andric     Res = Builder.CreateZExtOrTrunc(Res, Ty);
14930b57cec5SDimitry Andric   }
14940b57cec5SDimitry Andric   return Res;
14950b57cec5SDimitry Andric }
14960b57cec5SDimitry Andric 
149706c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::shrinkDivRem64(IRBuilder<> &Builder,
149806c3fb27SDimitry Andric                                                 BinaryOperator &I, Value *Num,
149906c3fb27SDimitry Andric                                                 Value *Den) const {
15005ffd83dbSDimitry Andric   if (!ExpandDiv64InIR && divHasSpecialOptimization(I, Num, Den))
15015ffd83dbSDimitry Andric     return nullptr;  // Keep it for later optimization.
15025ffd83dbSDimitry Andric 
15035ffd83dbSDimitry Andric   Instruction::BinaryOps Opc = I.getOpcode();
15045ffd83dbSDimitry Andric 
15055ffd83dbSDimitry Andric   bool IsDiv = Opc == Instruction::SDiv || Opc == Instruction::UDiv;
15065ffd83dbSDimitry Andric   bool IsSigned = Opc == Instruction::SDiv || Opc == Instruction::SRem;
15075ffd83dbSDimitry Andric 
15085ffd83dbSDimitry Andric   int NumDivBits = getDivNumBits(I, Num, Den, 32, IsSigned);
15095ffd83dbSDimitry Andric   if (NumDivBits == -1)
15105ffd83dbSDimitry Andric     return nullptr;
15115ffd83dbSDimitry Andric 
15125ffd83dbSDimitry Andric   Value *Narrowed = nullptr;
15135ffd83dbSDimitry Andric   if (NumDivBits <= 24) {
15145ffd83dbSDimitry Andric     Narrowed = expandDivRem24Impl(Builder, I, Num, Den, NumDivBits,
15155ffd83dbSDimitry Andric                                   IsDiv, IsSigned);
15165ffd83dbSDimitry Andric   } else if (NumDivBits <= 32) {
15175ffd83dbSDimitry Andric     Narrowed = expandDivRem32(Builder, I, Num, Den);
15185ffd83dbSDimitry Andric   }
15195ffd83dbSDimitry Andric 
15205ffd83dbSDimitry Andric   if (Narrowed) {
15215ffd83dbSDimitry Andric     return IsSigned ? Builder.CreateSExt(Narrowed, Num->getType()) :
15225ffd83dbSDimitry Andric                       Builder.CreateZExt(Narrowed, Num->getType());
15235ffd83dbSDimitry Andric   }
15245ffd83dbSDimitry Andric 
15255ffd83dbSDimitry Andric   return nullptr;
15265ffd83dbSDimitry Andric }
15275ffd83dbSDimitry Andric 
152806c3fb27SDimitry Andric void AMDGPUCodeGenPrepareImpl::expandDivRem64(BinaryOperator &I) const {
15295ffd83dbSDimitry Andric   Instruction::BinaryOps Opc = I.getOpcode();
15305ffd83dbSDimitry Andric   // Do the general expansion.
15315ffd83dbSDimitry Andric   if (Opc == Instruction::UDiv || Opc == Instruction::SDiv) {
15325ffd83dbSDimitry Andric     expandDivisionUpTo64Bits(&I);
15335ffd83dbSDimitry Andric     return;
15345ffd83dbSDimitry Andric   }
15355ffd83dbSDimitry Andric 
15365ffd83dbSDimitry Andric   if (Opc == Instruction::URem || Opc == Instruction::SRem) {
15375ffd83dbSDimitry Andric     expandRemainderUpTo64Bits(&I);
15385ffd83dbSDimitry Andric     return;
15395ffd83dbSDimitry Andric   }
15405ffd83dbSDimitry Andric 
15415ffd83dbSDimitry Andric   llvm_unreachable("not a division");
15425ffd83dbSDimitry Andric }
15435ffd83dbSDimitry Andric 
154406c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitBinaryOperator(BinaryOperator &I) {
15455ffd83dbSDimitry Andric   if (foldBinOpIntoSelect(I))
15465ffd83dbSDimitry Andric     return true;
15475ffd83dbSDimitry Andric 
15480b57cec5SDimitry Andric   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
154906c3fb27SDimitry Andric       UA->isUniform(&I) && promoteUniformOpToI32(I))
15500b57cec5SDimitry Andric     return true;
15510b57cec5SDimitry Andric 
15528bcb0991SDimitry Andric   if (UseMul24Intrin && replaceMulWithMul24(I))
15530b57cec5SDimitry Andric     return true;
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric   bool Changed = false;
15560b57cec5SDimitry Andric   Instruction::BinaryOps Opc = I.getOpcode();
15570b57cec5SDimitry Andric   Type *Ty = I.getType();
15580b57cec5SDimitry Andric   Value *NewDiv = nullptr;
15595ffd83dbSDimitry Andric   unsigned ScalarSize = Ty->getScalarSizeInBits();
15605ffd83dbSDimitry Andric 
15615ffd83dbSDimitry Andric   SmallVector<BinaryOperator *, 8> Div64ToExpand;
15625ffd83dbSDimitry Andric 
15630b57cec5SDimitry Andric   if ((Opc == Instruction::URem || Opc == Instruction::UDiv ||
15640b57cec5SDimitry Andric        Opc == Instruction::SRem || Opc == Instruction::SDiv) &&
15655ffd83dbSDimitry Andric       ScalarSize <= 64 &&
15665ffd83dbSDimitry Andric       !DisableIDivExpand) {
15670b57cec5SDimitry Andric     Value *Num = I.getOperand(0);
15680b57cec5SDimitry Andric     Value *Den = I.getOperand(1);
15690b57cec5SDimitry Andric     IRBuilder<> Builder(&I);
15700b57cec5SDimitry Andric     Builder.SetCurrentDebugLocation(I.getDebugLoc());
15710b57cec5SDimitry Andric 
15725ffd83dbSDimitry Andric     if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1573bdd1243dSDimitry Andric       NewDiv = PoisonValue::get(VT);
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric       for (unsigned N = 0, E = VT->getNumElements(); N != E; ++N) {
15760b57cec5SDimitry Andric         Value *NumEltN = Builder.CreateExtractElement(Num, N);
15770b57cec5SDimitry Andric         Value *DenEltN = Builder.CreateExtractElement(Den, N);
15785ffd83dbSDimitry Andric 
15795ffd83dbSDimitry Andric         Value *NewElt;
15805ffd83dbSDimitry Andric         if (ScalarSize <= 32) {
15815ffd83dbSDimitry Andric           NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN);
15820b57cec5SDimitry Andric           if (!NewElt)
15830b57cec5SDimitry Andric             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
15845ffd83dbSDimitry Andric         } else {
15855ffd83dbSDimitry Andric           // See if this 64-bit division can be shrunk to 32/24-bits before
15865ffd83dbSDimitry Andric           // producing the general expansion.
15875ffd83dbSDimitry Andric           NewElt = shrinkDivRem64(Builder, I, NumEltN, DenEltN);
15885ffd83dbSDimitry Andric           if (!NewElt) {
15895ffd83dbSDimitry Andric             // The general 64-bit expansion introduces control flow and doesn't
15905ffd83dbSDimitry Andric             // return the new value. Just insert a scalar copy and defer
15915ffd83dbSDimitry Andric             // expanding it.
15925ffd83dbSDimitry Andric             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
15935ffd83dbSDimitry Andric             Div64ToExpand.push_back(cast<BinaryOperator>(NewElt));
15945ffd83dbSDimitry Andric           }
15955ffd83dbSDimitry Andric         }
15965ffd83dbSDimitry Andric 
1597*0fca6ea1SDimitry Andric         if (auto *NewEltI = dyn_cast<Instruction>(NewElt))
1598*0fca6ea1SDimitry Andric           NewEltI->copyIRFlags(&I);
1599*0fca6ea1SDimitry Andric 
16000b57cec5SDimitry Andric         NewDiv = Builder.CreateInsertElement(NewDiv, NewElt, N);
16010b57cec5SDimitry Andric       }
16020b57cec5SDimitry Andric     } else {
16035ffd83dbSDimitry Andric       if (ScalarSize <= 32)
16040b57cec5SDimitry Andric         NewDiv = expandDivRem32(Builder, I, Num, Den);
16055ffd83dbSDimitry Andric       else {
16065ffd83dbSDimitry Andric         NewDiv = shrinkDivRem64(Builder, I, Num, Den);
16075ffd83dbSDimitry Andric         if (!NewDiv)
16085ffd83dbSDimitry Andric           Div64ToExpand.push_back(&I);
16095ffd83dbSDimitry Andric       }
16100b57cec5SDimitry Andric     }
16110b57cec5SDimitry Andric 
16120b57cec5SDimitry Andric     if (NewDiv) {
16130b57cec5SDimitry Andric       I.replaceAllUsesWith(NewDiv);
16140b57cec5SDimitry Andric       I.eraseFromParent();
16150b57cec5SDimitry Andric       Changed = true;
16160b57cec5SDimitry Andric     }
16170b57cec5SDimitry Andric   }
16180b57cec5SDimitry Andric 
16195ffd83dbSDimitry Andric   if (ExpandDiv64InIR) {
16205ffd83dbSDimitry Andric     // TODO: We get much worse code in specially handled constant cases.
16215ffd83dbSDimitry Andric     for (BinaryOperator *Div : Div64ToExpand) {
16225ffd83dbSDimitry Andric       expandDivRem64(*Div);
162306c3fb27SDimitry Andric       FlowChanged = true;
16245ffd83dbSDimitry Andric       Changed = true;
16255ffd83dbSDimitry Andric     }
16265ffd83dbSDimitry Andric   }
16275ffd83dbSDimitry Andric 
16280b57cec5SDimitry Andric   return Changed;
16290b57cec5SDimitry Andric }
16300b57cec5SDimitry Andric 
163106c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitLoadInst(LoadInst &I) {
16320b57cec5SDimitry Andric   if (!WidenLoads)
16330b57cec5SDimitry Andric     return false;
16340b57cec5SDimitry Andric 
16350b57cec5SDimitry Andric   if ((I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
16360b57cec5SDimitry Andric        I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
16370b57cec5SDimitry Andric       canWidenScalarExtLoad(I)) {
16380b57cec5SDimitry Andric     IRBuilder<> Builder(&I);
16390b57cec5SDimitry Andric     Builder.SetCurrentDebugLocation(I.getDebugLoc());
16400b57cec5SDimitry Andric 
16410b57cec5SDimitry Andric     Type *I32Ty = Builder.getInt32Ty();
164206c3fb27SDimitry Andric     LoadInst *WidenLoad = Builder.CreateLoad(I32Ty, I.getPointerOperand());
16430b57cec5SDimitry Andric     WidenLoad->copyMetadata(I);
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric     // If we have range metadata, we need to convert the type, and not make
16460b57cec5SDimitry Andric     // assumptions about the high bits.
16470b57cec5SDimitry Andric     if (auto *Range = WidenLoad->getMetadata(LLVMContext::MD_range)) {
16480b57cec5SDimitry Andric       ConstantInt *Lower =
16490b57cec5SDimitry Andric         mdconst::extract<ConstantInt>(Range->getOperand(0));
16500b57cec5SDimitry Andric 
1651349cc55cSDimitry Andric       if (Lower->isNullValue()) {
16520b57cec5SDimitry Andric         WidenLoad->setMetadata(LLVMContext::MD_range, nullptr);
16530b57cec5SDimitry Andric       } else {
16540b57cec5SDimitry Andric         Metadata *LowAndHigh[] = {
16550b57cec5SDimitry Andric           ConstantAsMetadata::get(ConstantInt::get(I32Ty, Lower->getValue().zext(32))),
16560b57cec5SDimitry Andric           // Don't make assumptions about the high bits.
16570b57cec5SDimitry Andric           ConstantAsMetadata::get(ConstantInt::get(I32Ty, 0))
16580b57cec5SDimitry Andric         };
16590b57cec5SDimitry Andric 
16600b57cec5SDimitry Andric         WidenLoad->setMetadata(LLVMContext::MD_range,
16610b57cec5SDimitry Andric                                MDNode::get(Mod->getContext(), LowAndHigh));
16620b57cec5SDimitry Andric       }
16630b57cec5SDimitry Andric     }
16640b57cec5SDimitry Andric 
16650b57cec5SDimitry Andric     int TySize = Mod->getDataLayout().getTypeSizeInBits(I.getType());
16660b57cec5SDimitry Andric     Type *IntNTy = Builder.getIntNTy(TySize);
16670b57cec5SDimitry Andric     Value *ValTrunc = Builder.CreateTrunc(WidenLoad, IntNTy);
16680b57cec5SDimitry Andric     Value *ValOrig = Builder.CreateBitCast(ValTrunc, I.getType());
16690b57cec5SDimitry Andric     I.replaceAllUsesWith(ValOrig);
16700b57cec5SDimitry Andric     I.eraseFromParent();
16710b57cec5SDimitry Andric     return true;
16720b57cec5SDimitry Andric   }
16730b57cec5SDimitry Andric 
16740b57cec5SDimitry Andric   return false;
16750b57cec5SDimitry Andric }
16760b57cec5SDimitry Andric 
167706c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitICmpInst(ICmpInst &I) {
16780b57cec5SDimitry Andric   bool Changed = false;
16790b57cec5SDimitry Andric 
16800b57cec5SDimitry Andric   if (ST->has16BitInsts() && needsPromotionToI32(I.getOperand(0)->getType()) &&
168106c3fb27SDimitry Andric       UA->isUniform(&I))
16820b57cec5SDimitry Andric     Changed |= promoteUniformOpToI32(I);
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric   return Changed;
16850b57cec5SDimitry Andric }
16860b57cec5SDimitry Andric 
168706c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitSelectInst(SelectInst &I) {
168806c3fb27SDimitry Andric   Value *Cond = I.getCondition();
168906c3fb27SDimitry Andric   Value *TrueVal = I.getTrueValue();
169006c3fb27SDimitry Andric   Value *FalseVal = I.getFalseValue();
169106c3fb27SDimitry Andric   Value *CmpVal;
169206c3fb27SDimitry Andric   FCmpInst::Predicate Pred;
16930b57cec5SDimitry Andric 
169406c3fb27SDimitry Andric   if (ST->has16BitInsts() && needsPromotionToI32(I.getType())) {
169506c3fb27SDimitry Andric     if (UA->isUniform(&I))
169606c3fb27SDimitry Andric       return promoteUniformOpToI32(I);
169706c3fb27SDimitry Andric     return false;
16980b57cec5SDimitry Andric   }
16990b57cec5SDimitry Andric 
170006c3fb27SDimitry Andric   // Match fract pattern with nan check.
170106c3fb27SDimitry Andric   if (!match(Cond, m_FCmp(Pred, m_Value(CmpVal), m_NonNaN())))
170206c3fb27SDimitry Andric     return false;
170306c3fb27SDimitry Andric 
170406c3fb27SDimitry Andric   FPMathOperator *FPOp = dyn_cast<FPMathOperator>(&I);
170506c3fb27SDimitry Andric   if (!FPOp)
170606c3fb27SDimitry Andric     return false;
170706c3fb27SDimitry Andric 
170806c3fb27SDimitry Andric   IRBuilder<> Builder(&I);
170906c3fb27SDimitry Andric   Builder.setFastMathFlags(FPOp->getFastMathFlags());
171006c3fb27SDimitry Andric 
171106c3fb27SDimitry Andric   auto *IITrue = dyn_cast<IntrinsicInst>(TrueVal);
171206c3fb27SDimitry Andric   auto *IIFalse = dyn_cast<IntrinsicInst>(FalseVal);
171306c3fb27SDimitry Andric 
171406c3fb27SDimitry Andric   Value *Fract = nullptr;
171506c3fb27SDimitry Andric   if (Pred == FCmpInst::FCMP_UNO && TrueVal == CmpVal && IIFalse &&
171606c3fb27SDimitry Andric       CmpVal == matchFractPat(*IIFalse)) {
171706c3fb27SDimitry Andric     // isnan(x) ? x : fract(x)
171806c3fb27SDimitry Andric     Fract = applyFractPat(Builder, CmpVal);
171906c3fb27SDimitry Andric   } else if (Pred == FCmpInst::FCMP_ORD && FalseVal == CmpVal && IITrue &&
172006c3fb27SDimitry Andric              CmpVal == matchFractPat(*IITrue)) {
172106c3fb27SDimitry Andric     // !isnan(x) ? fract(x) : x
172206c3fb27SDimitry Andric     Fract = applyFractPat(Builder, CmpVal);
172306c3fb27SDimitry Andric   } else
172406c3fb27SDimitry Andric     return false;
172506c3fb27SDimitry Andric 
172606c3fb27SDimitry Andric   Fract->takeName(&I);
172706c3fb27SDimitry Andric   I.replaceAllUsesWith(Fract);
172806c3fb27SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(&I, TLInfo);
172906c3fb27SDimitry Andric   return true;
173006c3fb27SDimitry Andric }
173106c3fb27SDimitry Andric 
173206c3fb27SDimitry Andric static bool areInSameBB(const Value *A, const Value *B) {
173306c3fb27SDimitry Andric   const auto *IA = dyn_cast<Instruction>(A);
173406c3fb27SDimitry Andric   const auto *IB = dyn_cast<Instruction>(B);
173506c3fb27SDimitry Andric   return IA && IB && IA->getParent() == IB->getParent();
173606c3fb27SDimitry Andric }
173706c3fb27SDimitry Andric 
173806c3fb27SDimitry Andric // Helper for breaking large PHIs that returns true when an extractelement on V
173906c3fb27SDimitry Andric // is likely to be folded away by the DAG combiner.
174006c3fb27SDimitry Andric static bool isInterestingPHIIncomingValue(const Value *V) {
174106c3fb27SDimitry Andric   const auto *FVT = dyn_cast<FixedVectorType>(V->getType());
174206c3fb27SDimitry Andric   if (!FVT)
174306c3fb27SDimitry Andric     return false;
174406c3fb27SDimitry Andric 
174506c3fb27SDimitry Andric   const Value *CurVal = V;
174606c3fb27SDimitry Andric 
174706c3fb27SDimitry Andric   // Check for insertelements, keeping track of the elements covered.
174806c3fb27SDimitry Andric   BitVector EltsCovered(FVT->getNumElements());
174906c3fb27SDimitry Andric   while (const auto *IE = dyn_cast<InsertElementInst>(CurVal)) {
175006c3fb27SDimitry Andric     const auto *Idx = dyn_cast<ConstantInt>(IE->getOperand(2));
175106c3fb27SDimitry Andric 
175206c3fb27SDimitry Andric     // Non constant index/out of bounds index -> folding is unlikely.
175306c3fb27SDimitry Andric     // The latter is more of a sanity check because canonical IR should just
175406c3fb27SDimitry Andric     // have replaced those with poison.
1755*0fca6ea1SDimitry Andric     if (!Idx || Idx->getZExtValue() >= FVT->getNumElements())
175606c3fb27SDimitry Andric       return false;
175706c3fb27SDimitry Andric 
175806c3fb27SDimitry Andric     const auto *VecSrc = IE->getOperand(0);
175906c3fb27SDimitry Andric 
176006c3fb27SDimitry Andric     // If the vector source is another instruction, it must be in the same basic
176106c3fb27SDimitry Andric     // block. Otherwise, the DAGCombiner won't see the whole thing and is
176206c3fb27SDimitry Andric     // unlikely to be able to do anything interesting here.
176306c3fb27SDimitry Andric     if (isa<Instruction>(VecSrc) && !areInSameBB(VecSrc, IE))
176406c3fb27SDimitry Andric       return false;
176506c3fb27SDimitry Andric 
176606c3fb27SDimitry Andric     CurVal = VecSrc;
1767*0fca6ea1SDimitry Andric     EltsCovered.set(Idx->getZExtValue());
176806c3fb27SDimitry Andric 
176906c3fb27SDimitry Andric     // All elements covered.
177006c3fb27SDimitry Andric     if (EltsCovered.all())
177106c3fb27SDimitry Andric       return true;
177206c3fb27SDimitry Andric   }
177306c3fb27SDimitry Andric 
177406c3fb27SDimitry Andric   // We either didn't find a single insertelement, or the insertelement chain
177506c3fb27SDimitry Andric   // ended before all elements were covered. Check for other interesting values.
177606c3fb27SDimitry Andric 
177706c3fb27SDimitry Andric   // Constants are always interesting because we can just constant fold the
177806c3fb27SDimitry Andric   // extractelements.
177906c3fb27SDimitry Andric   if (isa<Constant>(CurVal))
178006c3fb27SDimitry Andric     return true;
178106c3fb27SDimitry Andric 
178206c3fb27SDimitry Andric   // shufflevector is likely to be profitable if either operand is a constant,
178306c3fb27SDimitry Andric   // or if either source is in the same block.
178406c3fb27SDimitry Andric   // This is because shufflevector is most often lowered as a series of
178506c3fb27SDimitry Andric   // insert/extract elements anyway.
178606c3fb27SDimitry Andric   if (const auto *SV = dyn_cast<ShuffleVectorInst>(CurVal)) {
178706c3fb27SDimitry Andric     return isa<Constant>(SV->getOperand(1)) ||
178806c3fb27SDimitry Andric            areInSameBB(SV, SV->getOperand(0)) ||
178906c3fb27SDimitry Andric            areInSameBB(SV, SV->getOperand(1));
179006c3fb27SDimitry Andric   }
179106c3fb27SDimitry Andric 
179206c3fb27SDimitry Andric   return false;
179306c3fb27SDimitry Andric }
179406c3fb27SDimitry Andric 
17955f757f3fSDimitry Andric static void collectPHINodes(const PHINode &I,
17965f757f3fSDimitry Andric                             SmallPtrSet<const PHINode *, 8> &SeenPHIs) {
17975f757f3fSDimitry Andric   const auto [It, Inserted] = SeenPHIs.insert(&I);
17985f757f3fSDimitry Andric   if (!Inserted)
17995f757f3fSDimitry Andric     return;
18005f757f3fSDimitry Andric 
18015f757f3fSDimitry Andric   for (const Value *Inc : I.incoming_values()) {
18025f757f3fSDimitry Andric     if (const auto *PhiInc = dyn_cast<PHINode>(Inc))
18035f757f3fSDimitry Andric       collectPHINodes(*PhiInc, SeenPHIs);
18045f757f3fSDimitry Andric   }
18055f757f3fSDimitry Andric 
18065f757f3fSDimitry Andric   for (const User *U : I.users()) {
18075f757f3fSDimitry Andric     if (const auto *PhiU = dyn_cast<PHINode>(U))
18085f757f3fSDimitry Andric       collectPHINodes(*PhiU, SeenPHIs);
18095f757f3fSDimitry Andric   }
18105f757f3fSDimitry Andric }
18115f757f3fSDimitry Andric 
181206c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::canBreakPHINode(const PHINode &I) {
18135f757f3fSDimitry Andric   // Check in the cache first.
18145f757f3fSDimitry Andric   if (const auto It = BreakPhiNodesCache.find(&I);
18155f757f3fSDimitry Andric       It != BreakPhiNodesCache.end())
181606c3fb27SDimitry Andric     return It->second;
181706c3fb27SDimitry Andric 
18185f757f3fSDimitry Andric   // We consider PHI nodes as part of "chains", so given a PHI node I, we
18195f757f3fSDimitry Andric   // recursively consider all its users and incoming values that are also PHI
18205f757f3fSDimitry Andric   // nodes. We then make a decision about all of those PHIs at once. Either they
18215f757f3fSDimitry Andric   // all get broken up, or none of them do. That way, we avoid cases where a
18225f757f3fSDimitry Andric   // single PHI is/is not broken and we end up reforming/exploding a vector
18235f757f3fSDimitry Andric   // multiple times, or even worse, doing it in a loop.
18245f757f3fSDimitry Andric   SmallPtrSet<const PHINode *, 8> WorkList;
18255f757f3fSDimitry Andric   collectPHINodes(I, WorkList);
182606c3fb27SDimitry Andric 
18275f757f3fSDimitry Andric #ifndef NDEBUG
18285f757f3fSDimitry Andric   // Check that none of the PHI nodes in the worklist are in the map. If some of
18295f757f3fSDimitry Andric   // them are, it means we're not good enough at collecting related PHIs.
18305f757f3fSDimitry Andric   for (const PHINode *WLP : WorkList) {
18315f757f3fSDimitry Andric     assert(BreakPhiNodesCache.count(WLP) == 0);
18325f757f3fSDimitry Andric   }
18335f757f3fSDimitry Andric #endif
18345f757f3fSDimitry Andric 
18355f757f3fSDimitry Andric   // To consider a PHI profitable to break, we need to see some interesting
18365f757f3fSDimitry Andric   // incoming values. At least 2/3rd (rounded up) of all PHIs in the worklist
18375f757f3fSDimitry Andric   // must have one to consider all PHIs breakable.
18385f757f3fSDimitry Andric   //
18395f757f3fSDimitry Andric   // This threshold has been determined through performance testing.
18405f757f3fSDimitry Andric   //
18415f757f3fSDimitry Andric   // Note that the computation below is equivalent to
18425f757f3fSDimitry Andric   //
18435f757f3fSDimitry Andric   //    (unsigned)ceil((K / 3.0) * 2)
18445f757f3fSDimitry Andric   //
18455f757f3fSDimitry Andric   // It's simply written this way to avoid mixing integral/FP arithmetic.
18465f757f3fSDimitry Andric   const auto Threshold = (alignTo(WorkList.size() * 2, 3) / 3);
18475f757f3fSDimitry Andric   unsigned NumBreakablePHIs = 0;
18485f757f3fSDimitry Andric   bool CanBreak = false;
18495f757f3fSDimitry Andric   for (const PHINode *Cur : WorkList) {
185006c3fb27SDimitry Andric     // Don't break PHIs that have no interesting incoming values. That is, where
18515f757f3fSDimitry Andric     // there is no clear opportunity to fold the "extractelement" instructions
18525f757f3fSDimitry Andric     // we would add.
185306c3fb27SDimitry Andric     //
185406c3fb27SDimitry Andric     // Note: IC does not run after this pass, so we're only interested in the
185506c3fb27SDimitry Andric     // foldings that the DAG combiner can do.
18565f757f3fSDimitry Andric     if (any_of(Cur->incoming_values(), isInterestingPHIIncomingValue)) {
18575f757f3fSDimitry Andric       if (++NumBreakablePHIs >= Threshold) {
18585f757f3fSDimitry Andric         CanBreak = true;
18595f757f3fSDimitry Andric         break;
18605f757f3fSDimitry Andric       }
18615f757f3fSDimitry Andric     }
186206c3fb27SDimitry Andric   }
186306c3fb27SDimitry Andric 
18645f757f3fSDimitry Andric   for (const PHINode *Cur : WorkList)
18655f757f3fSDimitry Andric     BreakPhiNodesCache[Cur] = CanBreak;
186606c3fb27SDimitry Andric 
18675f757f3fSDimitry Andric   return CanBreak;
186806c3fb27SDimitry Andric }
186906c3fb27SDimitry Andric 
187006c3fb27SDimitry Andric /// Helper class for "break large PHIs" (visitPHINode).
187106c3fb27SDimitry Andric ///
187206c3fb27SDimitry Andric /// This represents a slice of a PHI's incoming value, which is made up of:
187306c3fb27SDimitry Andric ///   - The type of the slice (Ty)
187406c3fb27SDimitry Andric ///   - The index in the incoming value's vector where the slice starts (Idx)
187506c3fb27SDimitry Andric ///   - The number of elements in the slice (NumElts).
187606c3fb27SDimitry Andric /// It also keeps track of the NewPHI node inserted for this particular slice.
187706c3fb27SDimitry Andric ///
187806c3fb27SDimitry Andric /// Slice examples:
187906c3fb27SDimitry Andric ///   <4 x i64> -> Split into four i64 slices.
188006c3fb27SDimitry Andric ///     -> [i64, 0, 1], [i64, 1, 1], [i64, 2, 1], [i64, 3, 1]
188106c3fb27SDimitry Andric ///   <5 x i16> -> Split into 2 <2 x i16> slices + a i16 tail.
188206c3fb27SDimitry Andric ///     -> [<2 x i16>, 0, 2], [<2 x i16>, 2, 2], [i16, 4, 1]
188306c3fb27SDimitry Andric class VectorSlice {
188406c3fb27SDimitry Andric public:
188506c3fb27SDimitry Andric   VectorSlice(Type *Ty, unsigned Idx, unsigned NumElts)
188606c3fb27SDimitry Andric       : Ty(Ty), Idx(Idx), NumElts(NumElts) {}
188706c3fb27SDimitry Andric 
188806c3fb27SDimitry Andric   Type *Ty = nullptr;
188906c3fb27SDimitry Andric   unsigned Idx = 0;
189006c3fb27SDimitry Andric   unsigned NumElts = 0;
189106c3fb27SDimitry Andric   PHINode *NewPHI = nullptr;
189206c3fb27SDimitry Andric 
189306c3fb27SDimitry Andric   /// Slice \p Inc according to the information contained within this slice.
189406c3fb27SDimitry Andric   /// This is cached, so if called multiple times for the same \p BB & \p Inc
189506c3fb27SDimitry Andric   /// pair, it returns the same Sliced value as well.
189606c3fb27SDimitry Andric   ///
189706c3fb27SDimitry Andric   /// Note this *intentionally* does not return the same value for, say,
189806c3fb27SDimitry Andric   /// [%bb.0, %0] & [%bb.1, %0] as:
189906c3fb27SDimitry Andric   ///   - It could cause issues with dominance (e.g. if bb.1 is seen first, then
190006c3fb27SDimitry Andric   ///   the value in bb.1 may not be reachable from bb.0 if it's its
190106c3fb27SDimitry Andric   ///   predecessor.)
190206c3fb27SDimitry Andric   ///   - We also want to make our extract instructions as local as possible so
190306c3fb27SDimitry Andric   ///   the DAG has better chances of folding them out. Duplicating them like
190406c3fb27SDimitry Andric   ///   that is beneficial in that regard.
190506c3fb27SDimitry Andric   ///
190606c3fb27SDimitry Andric   /// This is both a minor optimization to avoid creating duplicate
190706c3fb27SDimitry Andric   /// instructions, but also a requirement for correctness. It is not forbidden
190806c3fb27SDimitry Andric   /// for a PHI node to have the same [BB, Val] pair multiple times. If we
190906c3fb27SDimitry Andric   /// returned a new value each time, those previously identical pairs would all
191006c3fb27SDimitry Andric   /// have different incoming values (from the same block) and it'd cause a "PHI
191106c3fb27SDimitry Andric   /// node has multiple entries for the same basic block with different incoming
191206c3fb27SDimitry Andric   /// values!" verifier error.
191306c3fb27SDimitry Andric   Value *getSlicedVal(BasicBlock *BB, Value *Inc, StringRef NewValName) {
191406c3fb27SDimitry Andric     Value *&Res = SlicedVals[{BB, Inc}];
191506c3fb27SDimitry Andric     if (Res)
191606c3fb27SDimitry Andric       return Res;
191706c3fb27SDimitry Andric 
191806c3fb27SDimitry Andric     IRBuilder<> B(BB->getTerminator());
191906c3fb27SDimitry Andric     if (Instruction *IncInst = dyn_cast<Instruction>(Inc))
192006c3fb27SDimitry Andric       B.SetCurrentDebugLocation(IncInst->getDebugLoc());
192106c3fb27SDimitry Andric 
192206c3fb27SDimitry Andric     if (NumElts > 1) {
192306c3fb27SDimitry Andric       SmallVector<int, 4> Mask;
192406c3fb27SDimitry Andric       for (unsigned K = Idx; K < (Idx + NumElts); ++K)
192506c3fb27SDimitry Andric         Mask.push_back(K);
192606c3fb27SDimitry Andric       Res = B.CreateShuffleVector(Inc, Mask, NewValName);
192706c3fb27SDimitry Andric     } else
192806c3fb27SDimitry Andric       Res = B.CreateExtractElement(Inc, Idx, NewValName);
192906c3fb27SDimitry Andric 
193006c3fb27SDimitry Andric     return Res;
193106c3fb27SDimitry Andric   }
193206c3fb27SDimitry Andric 
193306c3fb27SDimitry Andric private:
193406c3fb27SDimitry Andric   SmallDenseMap<std::pair<BasicBlock *, Value *>, Value *> SlicedVals;
193506c3fb27SDimitry Andric };
193606c3fb27SDimitry Andric 
193706c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitPHINode(PHINode &I) {
193806c3fb27SDimitry Andric   // Break-up fixed-vector PHIs into smaller pieces.
193906c3fb27SDimitry Andric   // Default threshold is 32, so it breaks up any vector that's >32 bits into
194006c3fb27SDimitry Andric   // its elements, or into 32-bit pieces (for 8/16 bit elts).
194106c3fb27SDimitry Andric   //
194206c3fb27SDimitry Andric   // This is only helpful for DAGISel because it doesn't handle large PHIs as
194306c3fb27SDimitry Andric   // well as GlobalISel. DAGISel lowers PHIs by using CopyToReg/CopyFromReg.
194406c3fb27SDimitry Andric   // With large, odd-sized PHIs we may end up needing many `build_vector`
194506c3fb27SDimitry Andric   // operations with most elements being "undef". This inhibits a lot of
194606c3fb27SDimitry Andric   // optimization opportunities and can result in unreasonably high register
194706c3fb27SDimitry Andric   // pressure and the inevitable stack spilling.
19485f757f3fSDimitry Andric   if (!BreakLargePHIs || getCGPassBuilderOption().EnableGlobalISelOption)
194906c3fb27SDimitry Andric     return false;
195006c3fb27SDimitry Andric 
195106c3fb27SDimitry Andric   FixedVectorType *FVT = dyn_cast<FixedVectorType>(I.getType());
19525f757f3fSDimitry Andric   if (!FVT || FVT->getNumElements() == 1 ||
19535f757f3fSDimitry Andric       DL->getTypeSizeInBits(FVT) <= BreakLargePHIsThreshold)
195406c3fb27SDimitry Andric     return false;
195506c3fb27SDimitry Andric 
19565f757f3fSDimitry Andric   if (!ForceBreakLargePHIs && !canBreakPHINode(I))
195706c3fb27SDimitry Andric     return false;
195806c3fb27SDimitry Andric 
195906c3fb27SDimitry Andric   std::vector<VectorSlice> Slices;
196006c3fb27SDimitry Andric 
196106c3fb27SDimitry Andric   Type *EltTy = FVT->getElementType();
196206c3fb27SDimitry Andric   {
196306c3fb27SDimitry Andric     unsigned Idx = 0;
196406c3fb27SDimitry Andric     // For 8/16 bits type, don't scalarize fully but break it up into as many
196506c3fb27SDimitry Andric     // 32-bit slices as we can, and scalarize the tail.
196606c3fb27SDimitry Andric     const unsigned EltSize = DL->getTypeSizeInBits(EltTy);
196706c3fb27SDimitry Andric     const unsigned NumElts = FVT->getNumElements();
196806c3fb27SDimitry Andric     if (EltSize == 8 || EltSize == 16) {
196906c3fb27SDimitry Andric       const unsigned SubVecSize = (32 / EltSize);
197006c3fb27SDimitry Andric       Type *SubVecTy = FixedVectorType::get(EltTy, SubVecSize);
197106c3fb27SDimitry Andric       for (unsigned End = alignDown(NumElts, SubVecSize); Idx < End;
197206c3fb27SDimitry Andric            Idx += SubVecSize)
197306c3fb27SDimitry Andric         Slices.emplace_back(SubVecTy, Idx, SubVecSize);
197406c3fb27SDimitry Andric     }
197506c3fb27SDimitry Andric 
197606c3fb27SDimitry Andric     // Scalarize all remaining elements.
197706c3fb27SDimitry Andric     for (; Idx < NumElts; ++Idx)
197806c3fb27SDimitry Andric       Slices.emplace_back(EltTy, Idx, 1);
197906c3fb27SDimitry Andric   }
198006c3fb27SDimitry Andric 
19815f757f3fSDimitry Andric   assert(Slices.size() > 1);
198206c3fb27SDimitry Andric 
198306c3fb27SDimitry Andric   // Create one PHI per vector piece. The "VectorSlice" class takes care of
198406c3fb27SDimitry Andric   // creating the necessary instruction to extract the relevant slices of each
198506c3fb27SDimitry Andric   // incoming value.
198606c3fb27SDimitry Andric   IRBuilder<> B(I.getParent());
198706c3fb27SDimitry Andric   B.SetCurrentDebugLocation(I.getDebugLoc());
198806c3fb27SDimitry Andric 
198906c3fb27SDimitry Andric   unsigned IncNameSuffix = 0;
199006c3fb27SDimitry Andric   for (VectorSlice &S : Slices) {
199106c3fb27SDimitry Andric     // We need to reset the build on each iteration, because getSlicedVal may
199206c3fb27SDimitry Andric     // have inserted something into I's BB.
1993*0fca6ea1SDimitry Andric     B.SetInsertPoint(I.getParent()->getFirstNonPHIIt());
199406c3fb27SDimitry Andric     S.NewPHI = B.CreatePHI(S.Ty, I.getNumIncomingValues());
199506c3fb27SDimitry Andric 
199606c3fb27SDimitry Andric     for (const auto &[Idx, BB] : enumerate(I.blocks())) {
199706c3fb27SDimitry Andric       S.NewPHI->addIncoming(S.getSlicedVal(BB, I.getIncomingValue(Idx),
199806c3fb27SDimitry Andric                                            "largephi.extractslice" +
199906c3fb27SDimitry Andric                                                std::to_string(IncNameSuffix++)),
200006c3fb27SDimitry Andric                             BB);
200106c3fb27SDimitry Andric     }
200206c3fb27SDimitry Andric   }
200306c3fb27SDimitry Andric 
200406c3fb27SDimitry Andric   // And replace this PHI with a vector of all the previous PHI values.
200506c3fb27SDimitry Andric   Value *Vec = PoisonValue::get(FVT);
200606c3fb27SDimitry Andric   unsigned NameSuffix = 0;
200706c3fb27SDimitry Andric   for (VectorSlice &S : Slices) {
200806c3fb27SDimitry Andric     const auto ValName = "largephi.insertslice" + std::to_string(NameSuffix++);
200906c3fb27SDimitry Andric     if (S.NumElts > 1)
201006c3fb27SDimitry Andric       Vec =
201106c3fb27SDimitry Andric           B.CreateInsertVector(FVT, Vec, S.NewPHI, B.getInt64(S.Idx), ValName);
201206c3fb27SDimitry Andric     else
201306c3fb27SDimitry Andric       Vec = B.CreateInsertElement(Vec, S.NewPHI, S.Idx, ValName);
201406c3fb27SDimitry Andric   }
201506c3fb27SDimitry Andric 
201606c3fb27SDimitry Andric   I.replaceAllUsesWith(Vec);
201706c3fb27SDimitry Andric   I.eraseFromParent();
201806c3fb27SDimitry Andric   return true;
201906c3fb27SDimitry Andric }
202006c3fb27SDimitry Andric 
2021*0fca6ea1SDimitry Andric /// \param V  Value to check
2022*0fca6ea1SDimitry Andric /// \param DL DataLayout
2023*0fca6ea1SDimitry Andric /// \param TM TargetMachine (TODO: remove once DL contains nullptr values)
2024*0fca6ea1SDimitry Andric /// \param AS Target Address Space
2025*0fca6ea1SDimitry Andric /// \return true if \p V cannot be the null value of \p AS, false otherwise.
2026*0fca6ea1SDimitry Andric static bool isPtrKnownNeverNull(const Value *V, const DataLayout &DL,
2027*0fca6ea1SDimitry Andric                                 const AMDGPUTargetMachine &TM, unsigned AS) {
2028*0fca6ea1SDimitry Andric   // Pointer cannot be null if it's a block address, GV or alloca.
2029*0fca6ea1SDimitry Andric   // NOTE: We don't support extern_weak, but if we did, we'd need to check for
2030*0fca6ea1SDimitry Andric   // it as the symbol could be null in such cases.
2031*0fca6ea1SDimitry Andric   if (isa<BlockAddress>(V) || isa<GlobalValue>(V) || isa<AllocaInst>(V))
2032*0fca6ea1SDimitry Andric     return true;
2033*0fca6ea1SDimitry Andric 
2034*0fca6ea1SDimitry Andric   // Check nonnull arguments.
2035*0fca6ea1SDimitry Andric   if (const auto *Arg = dyn_cast<Argument>(V); Arg && Arg->hasNonNullAttr())
2036*0fca6ea1SDimitry Andric     return true;
2037*0fca6ea1SDimitry Andric 
2038*0fca6ea1SDimitry Andric   // getUnderlyingObject may have looked through another addrspacecast, although
2039*0fca6ea1SDimitry Andric   // the optimizable situations most likely folded out by now.
2040*0fca6ea1SDimitry Andric   if (AS != cast<PointerType>(V->getType())->getAddressSpace())
2041*0fca6ea1SDimitry Andric     return false;
2042*0fca6ea1SDimitry Andric 
2043*0fca6ea1SDimitry Andric   // TODO: Calls that return nonnull?
2044*0fca6ea1SDimitry Andric 
2045*0fca6ea1SDimitry Andric   // For all other things, use KnownBits.
2046*0fca6ea1SDimitry Andric   // We either use 0 or all bits set to indicate null, so check whether the
2047*0fca6ea1SDimitry Andric   // value can be zero or all ones.
2048*0fca6ea1SDimitry Andric   //
2049*0fca6ea1SDimitry Andric   // TODO: Use ValueTracking's isKnownNeverNull if it becomes aware that some
2050*0fca6ea1SDimitry Andric   // address spaces have non-zero null values.
2051*0fca6ea1SDimitry Andric   auto SrcPtrKB = computeKnownBits(V, DL);
2052*0fca6ea1SDimitry Andric   const auto NullVal = TM.getNullPointerValue(AS);
2053*0fca6ea1SDimitry Andric 
2054*0fca6ea1SDimitry Andric   assert(SrcPtrKB.getBitWidth() == DL.getPointerSizeInBits(AS));
2055*0fca6ea1SDimitry Andric   assert((NullVal == 0 || NullVal == -1) &&
2056*0fca6ea1SDimitry Andric          "don't know how to check for this null value!");
2057*0fca6ea1SDimitry Andric   return NullVal ? !SrcPtrKB.getMaxValue().isAllOnes() : SrcPtrKB.isNonZero();
2058*0fca6ea1SDimitry Andric }
2059*0fca6ea1SDimitry Andric 
2060*0fca6ea1SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2061*0fca6ea1SDimitry Andric   // Intrinsic doesn't support vectors, also it seems that it's often difficult
2062*0fca6ea1SDimitry Andric   // to prove that a vector cannot have any nulls in it so it's unclear if it's
2063*0fca6ea1SDimitry Andric   // worth supporting.
2064*0fca6ea1SDimitry Andric   if (I.getType()->isVectorTy())
2065*0fca6ea1SDimitry Andric     return false;
2066*0fca6ea1SDimitry Andric 
2067*0fca6ea1SDimitry Andric   // Check if this can be lowered to a amdgcn.addrspacecast.nonnull.
2068*0fca6ea1SDimitry Andric   // This is only worthwhile for casts from/to priv/local to flat.
2069*0fca6ea1SDimitry Andric   const unsigned SrcAS = I.getSrcAddressSpace();
2070*0fca6ea1SDimitry Andric   const unsigned DstAS = I.getDestAddressSpace();
2071*0fca6ea1SDimitry Andric 
2072*0fca6ea1SDimitry Andric   bool CanLower = false;
2073*0fca6ea1SDimitry Andric   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
2074*0fca6ea1SDimitry Andric     CanLower = (DstAS == AMDGPUAS::LOCAL_ADDRESS ||
2075*0fca6ea1SDimitry Andric                 DstAS == AMDGPUAS::PRIVATE_ADDRESS);
2076*0fca6ea1SDimitry Andric   else if (DstAS == AMDGPUAS::FLAT_ADDRESS)
2077*0fca6ea1SDimitry Andric     CanLower = (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
2078*0fca6ea1SDimitry Andric                 SrcAS == AMDGPUAS::PRIVATE_ADDRESS);
2079*0fca6ea1SDimitry Andric   if (!CanLower)
2080*0fca6ea1SDimitry Andric     return false;
2081*0fca6ea1SDimitry Andric 
2082*0fca6ea1SDimitry Andric   SmallVector<const Value *, 4> WorkList;
2083*0fca6ea1SDimitry Andric   getUnderlyingObjects(I.getOperand(0), WorkList);
2084*0fca6ea1SDimitry Andric   if (!all_of(WorkList, [&](const Value *V) {
2085*0fca6ea1SDimitry Andric         return isPtrKnownNeverNull(V, *DL, *TM, SrcAS);
2086*0fca6ea1SDimitry Andric       }))
2087*0fca6ea1SDimitry Andric     return false;
2088*0fca6ea1SDimitry Andric 
2089*0fca6ea1SDimitry Andric   IRBuilder<> B(&I);
2090*0fca6ea1SDimitry Andric   auto *Intrin = B.CreateIntrinsic(
2091*0fca6ea1SDimitry Andric       I.getType(), Intrinsic::amdgcn_addrspacecast_nonnull, {I.getOperand(0)});
2092*0fca6ea1SDimitry Andric   I.replaceAllUsesWith(Intrin);
2093*0fca6ea1SDimitry Andric   I.eraseFromParent();
2094*0fca6ea1SDimitry Andric   return true;
2095*0fca6ea1SDimitry Andric }
2096*0fca6ea1SDimitry Andric 
209706c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitIntrinsicInst(IntrinsicInst &I) {
20980b57cec5SDimitry Andric   switch (I.getIntrinsicID()) {
20990b57cec5SDimitry Andric   case Intrinsic::bitreverse:
21000b57cec5SDimitry Andric     return visitBitreverseIntrinsicInst(I);
210106c3fb27SDimitry Andric   case Intrinsic::minnum:
210206c3fb27SDimitry Andric     return visitMinNum(I);
21035f757f3fSDimitry Andric   case Intrinsic::sqrt:
21045f757f3fSDimitry Andric     return visitSqrt(I);
21050b57cec5SDimitry Andric   default:
21060b57cec5SDimitry Andric     return false;
21070b57cec5SDimitry Andric   }
21080b57cec5SDimitry Andric }
21090b57cec5SDimitry Andric 
211006c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitBitreverseIntrinsicInst(IntrinsicInst &I) {
21110b57cec5SDimitry Andric   bool Changed = false;
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
211406c3fb27SDimitry Andric       UA->isUniform(&I))
21150b57cec5SDimitry Andric     Changed |= promoteUniformBitreverseToI32(I);
21160b57cec5SDimitry Andric 
21170b57cec5SDimitry Andric   return Changed;
21180b57cec5SDimitry Andric }
21190b57cec5SDimitry Andric 
212006c3fb27SDimitry Andric /// Match non-nan fract pattern.
212106c3fb27SDimitry Andric ///   minnum(fsub(x, floor(x)), nextafter(1.0, -1.0)
212206c3fb27SDimitry Andric ///
212306c3fb27SDimitry Andric /// If fract is a useful instruction for the subtarget. Does not account for the
212406c3fb27SDimitry Andric /// nan handling; the instruction has a nan check on the input value.
212506c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::matchFractPat(IntrinsicInst &I) {
212606c3fb27SDimitry Andric   if (ST->hasFractBug())
212706c3fb27SDimitry Andric     return nullptr;
212806c3fb27SDimitry Andric 
212906c3fb27SDimitry Andric   if (I.getIntrinsicID() != Intrinsic::minnum)
213006c3fb27SDimitry Andric     return nullptr;
213106c3fb27SDimitry Andric 
213206c3fb27SDimitry Andric   Type *Ty = I.getType();
213306c3fb27SDimitry Andric   if (!isLegalFloatingTy(Ty->getScalarType()))
213406c3fb27SDimitry Andric     return nullptr;
213506c3fb27SDimitry Andric 
213606c3fb27SDimitry Andric   Value *Arg0 = I.getArgOperand(0);
213706c3fb27SDimitry Andric   Value *Arg1 = I.getArgOperand(1);
213806c3fb27SDimitry Andric 
213906c3fb27SDimitry Andric   const APFloat *C;
214006c3fb27SDimitry Andric   if (!match(Arg1, m_APFloat(C)))
214106c3fb27SDimitry Andric     return nullptr;
214206c3fb27SDimitry Andric 
214306c3fb27SDimitry Andric   APFloat One(1.0);
214406c3fb27SDimitry Andric   bool LosesInfo;
214506c3fb27SDimitry Andric   One.convert(C->getSemantics(), APFloat::rmNearestTiesToEven, &LosesInfo);
214606c3fb27SDimitry Andric 
214706c3fb27SDimitry Andric   // Match nextafter(1.0, -1)
214806c3fb27SDimitry Andric   One.next(true);
214906c3fb27SDimitry Andric   if (One != *C)
215006c3fb27SDimitry Andric     return nullptr;
215106c3fb27SDimitry Andric 
215206c3fb27SDimitry Andric   Value *FloorSrc;
215306c3fb27SDimitry Andric   if (match(Arg0, m_FSub(m_Value(FloorSrc),
215406c3fb27SDimitry Andric                          m_Intrinsic<Intrinsic::floor>(m_Deferred(FloorSrc)))))
215506c3fb27SDimitry Andric     return FloorSrc;
215606c3fb27SDimitry Andric   return nullptr;
215706c3fb27SDimitry Andric }
215806c3fb27SDimitry Andric 
215906c3fb27SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::applyFractPat(IRBuilder<> &Builder,
216006c3fb27SDimitry Andric                                                Value *FractArg) {
216106c3fb27SDimitry Andric   SmallVector<Value *, 4> FractVals;
216206c3fb27SDimitry Andric   extractValues(Builder, FractVals, FractArg);
216306c3fb27SDimitry Andric 
216406c3fb27SDimitry Andric   SmallVector<Value *, 4> ResultVals(FractVals.size());
216506c3fb27SDimitry Andric 
216606c3fb27SDimitry Andric   Type *Ty = FractArg->getType()->getScalarType();
216706c3fb27SDimitry Andric   for (unsigned I = 0, E = FractVals.size(); I != E; ++I) {
216806c3fb27SDimitry Andric     ResultVals[I] =
216906c3fb27SDimitry Andric         Builder.CreateIntrinsic(Intrinsic::amdgcn_fract, {Ty}, {FractVals[I]});
217006c3fb27SDimitry Andric   }
217106c3fb27SDimitry Andric 
217206c3fb27SDimitry Andric   return insertValues(Builder, FractArg->getType(), ResultVals);
217306c3fb27SDimitry Andric }
217406c3fb27SDimitry Andric 
217506c3fb27SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitMinNum(IntrinsicInst &I) {
217606c3fb27SDimitry Andric   Value *FractArg = matchFractPat(I);
217706c3fb27SDimitry Andric   if (!FractArg)
217806c3fb27SDimitry Andric     return false;
217906c3fb27SDimitry Andric 
218006c3fb27SDimitry Andric   // Match pattern for fract intrinsic in contexts where the nan check has been
218106c3fb27SDimitry Andric   // optimized out (and hope the knowledge the source can't be nan wasn't lost).
2182*0fca6ea1SDimitry Andric   if (!I.hasNoNaNs() &&
2183*0fca6ea1SDimitry Andric       !isKnownNeverNaN(FractArg, /*Depth=*/0, SimplifyQuery(*DL, TLInfo)))
218406c3fb27SDimitry Andric     return false;
218506c3fb27SDimitry Andric 
218606c3fb27SDimitry Andric   IRBuilder<> Builder(&I);
218706c3fb27SDimitry Andric   FastMathFlags FMF = I.getFastMathFlags();
218806c3fb27SDimitry Andric   FMF.setNoNaNs();
218906c3fb27SDimitry Andric   Builder.setFastMathFlags(FMF);
219006c3fb27SDimitry Andric 
219106c3fb27SDimitry Andric   Value *Fract = applyFractPat(Builder, FractArg);
219206c3fb27SDimitry Andric   Fract->takeName(&I);
219306c3fb27SDimitry Andric   I.replaceAllUsesWith(Fract);
219406c3fb27SDimitry Andric 
219506c3fb27SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(&I, TLInfo);
219606c3fb27SDimitry Andric   return true;
219706c3fb27SDimitry Andric }
219806c3fb27SDimitry Andric 
21995f757f3fSDimitry Andric static bool isOneOrNegOne(const Value *Val) {
22005f757f3fSDimitry Andric   const APFloat *C;
22015f757f3fSDimitry Andric   return match(Val, m_APFloat(C)) && C->getExactLog2Abs() == 0;
22025f757f3fSDimitry Andric }
22035f757f3fSDimitry Andric 
22045f757f3fSDimitry Andric // Expand llvm.sqrt.f32 calls with !fpmath metadata in a semi-fast way.
22055f757f3fSDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitSqrt(IntrinsicInst &Sqrt) {
22065f757f3fSDimitry Andric   Type *Ty = Sqrt.getType()->getScalarType();
22075f757f3fSDimitry Andric   if (!Ty->isFloatTy() && (!Ty->isHalfTy() || ST->has16BitInsts()))
22085f757f3fSDimitry Andric     return false;
22095f757f3fSDimitry Andric 
22105f757f3fSDimitry Andric   const FPMathOperator *FPOp = cast<const FPMathOperator>(&Sqrt);
22115f757f3fSDimitry Andric   FastMathFlags SqrtFMF = FPOp->getFastMathFlags();
22125f757f3fSDimitry Andric 
22135f757f3fSDimitry Andric   // We're trying to handle the fast-but-not-that-fast case only. The lowering
22145f757f3fSDimitry Andric   // of fast llvm.sqrt will give the raw instruction anyway.
22155f757f3fSDimitry Andric   if (SqrtFMF.approxFunc() || HasUnsafeFPMath)
22165f757f3fSDimitry Andric     return false;
22175f757f3fSDimitry Andric 
22185f757f3fSDimitry Andric   const float ReqdAccuracy = FPOp->getFPAccuracy();
22195f757f3fSDimitry Andric 
22205f757f3fSDimitry Andric   // Defer correctly rounded expansion to codegen.
22215f757f3fSDimitry Andric   if (ReqdAccuracy < 1.0f)
22225f757f3fSDimitry Andric     return false;
22235f757f3fSDimitry Andric 
22245f757f3fSDimitry Andric   // FIXME: This is an ugly hack for this pass using forward iteration instead
22255f757f3fSDimitry Andric   // of reverse. If it worked like a normal combiner, the rsq would form before
22265f757f3fSDimitry Andric   // we saw a sqrt call.
22275f757f3fSDimitry Andric   auto *FDiv =
22285f757f3fSDimitry Andric       dyn_cast_or_null<FPMathOperator>(Sqrt.getUniqueUndroppableUser());
22295f757f3fSDimitry Andric   if (FDiv && FDiv->getOpcode() == Instruction::FDiv &&
22305f757f3fSDimitry Andric       FDiv->getFPAccuracy() >= 1.0f &&
22315f757f3fSDimitry Andric       canOptimizeWithRsq(FPOp, FDiv->getFastMathFlags(), SqrtFMF) &&
22325f757f3fSDimitry Andric       // TODO: We should also handle the arcp case for the fdiv with non-1 value
22335f757f3fSDimitry Andric       isOneOrNegOne(FDiv->getOperand(0)))
22345f757f3fSDimitry Andric     return false;
22355f757f3fSDimitry Andric 
22365f757f3fSDimitry Andric   Value *SrcVal = Sqrt.getOperand(0);
22375f757f3fSDimitry Andric   bool CanTreatAsDAZ = canIgnoreDenormalInput(SrcVal, &Sqrt);
22385f757f3fSDimitry Andric 
22395f757f3fSDimitry Andric   // The raw instruction is 1 ulp, but the correction for denormal handling
22405f757f3fSDimitry Andric   // brings it to 2.
22415f757f3fSDimitry Andric   if (!CanTreatAsDAZ && ReqdAccuracy < 2.0f)
22425f757f3fSDimitry Andric     return false;
22435f757f3fSDimitry Andric 
22445f757f3fSDimitry Andric   IRBuilder<> Builder(&Sqrt);
22455f757f3fSDimitry Andric   SmallVector<Value *, 4> SrcVals;
22465f757f3fSDimitry Andric   extractValues(Builder, SrcVals, SrcVal);
22475f757f3fSDimitry Andric 
22485f757f3fSDimitry Andric   SmallVector<Value *, 4> ResultVals(SrcVals.size());
22495f757f3fSDimitry Andric   for (int I = 0, E = SrcVals.size(); I != E; ++I) {
22505f757f3fSDimitry Andric     if (CanTreatAsDAZ)
22515f757f3fSDimitry Andric       ResultVals[I] = Builder.CreateCall(getSqrtF32(), SrcVals[I]);
22525f757f3fSDimitry Andric     else
22535f757f3fSDimitry Andric       ResultVals[I] = emitSqrtIEEE2ULP(Builder, SrcVals[I], SqrtFMF);
22545f757f3fSDimitry Andric   }
22555f757f3fSDimitry Andric 
22565f757f3fSDimitry Andric   Value *NewSqrt = insertValues(Builder, Sqrt.getType(), ResultVals);
22575f757f3fSDimitry Andric   NewSqrt->takeName(&Sqrt);
22585f757f3fSDimitry Andric   Sqrt.replaceAllUsesWith(NewSqrt);
22595f757f3fSDimitry Andric   Sqrt.eraseFromParent();
22605f757f3fSDimitry Andric   return true;
22615f757f3fSDimitry Andric }
22625f757f3fSDimitry Andric 
22630b57cec5SDimitry Andric bool AMDGPUCodeGenPrepare::doInitialization(Module &M) {
226406c3fb27SDimitry Andric   Impl.Mod = &M;
226506c3fb27SDimitry Andric   Impl.DL = &Impl.Mod->getDataLayout();
22665f757f3fSDimitry Andric   Impl.SqrtF32 = nullptr;
22675f757f3fSDimitry Andric   Impl.LdexpF32 = nullptr;
22680b57cec5SDimitry Andric   return false;
22690b57cec5SDimitry Andric }
22700b57cec5SDimitry Andric 
22710b57cec5SDimitry Andric bool AMDGPUCodeGenPrepare::runOnFunction(Function &F) {
22720b57cec5SDimitry Andric   if (skipFunction(F))
22730b57cec5SDimitry Andric     return false;
22740b57cec5SDimitry Andric 
22750b57cec5SDimitry Andric   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
22760b57cec5SDimitry Andric   if (!TPC)
22770b57cec5SDimitry Andric     return false;
22780b57cec5SDimitry Andric 
22790b57cec5SDimitry Andric   const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>();
2280*0fca6ea1SDimitry Andric   Impl.TM = &TM;
228106c3fb27SDimitry Andric   Impl.TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
228206c3fb27SDimitry Andric   Impl.ST = &TM.getSubtarget<GCNSubtarget>(F);
228306c3fb27SDimitry Andric   Impl.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
228406c3fb27SDimitry Andric   Impl.UA = &getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
22855ffd83dbSDimitry Andric   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
228606c3fb27SDimitry Andric   Impl.DT = DTWP ? &DTWP->getDomTree() : nullptr;
228706c3fb27SDimitry Andric   Impl.HasUnsafeFPMath = hasUnsafeFPMath(F);
22885f757f3fSDimitry Andric   SIModeRegisterDefaults Mode(F, *Impl.ST);
228906c3fb27SDimitry Andric   Impl.HasFP32DenormalFlush =
229006c3fb27SDimitry Andric       Mode.FP32Denormals == DenormalMode::getPreserveSign();
229106c3fb27SDimitry Andric   return Impl.run(F);
22920b57cec5SDimitry Andric }
22930b57cec5SDimitry Andric 
229406c3fb27SDimitry Andric PreservedAnalyses AMDGPUCodeGenPreparePass::run(Function &F,
229506c3fb27SDimitry Andric                                                 FunctionAnalysisManager &FAM) {
229606c3fb27SDimitry Andric   AMDGPUCodeGenPrepareImpl Impl;
229706c3fb27SDimitry Andric   Impl.Mod = F.getParent();
229806c3fb27SDimitry Andric   Impl.DL = &Impl.Mod->getDataLayout();
2299*0fca6ea1SDimitry Andric   Impl.TM = static_cast<const AMDGPUTargetMachine *>(&TM);
230006c3fb27SDimitry Andric   Impl.TLInfo = &FAM.getResult<TargetLibraryAnalysis>(F);
230106c3fb27SDimitry Andric   Impl.ST = &TM.getSubtarget<GCNSubtarget>(F);
230206c3fb27SDimitry Andric   Impl.AC = &FAM.getResult<AssumptionAnalysis>(F);
230306c3fb27SDimitry Andric   Impl.UA = &FAM.getResult<UniformityInfoAnalysis>(F);
230406c3fb27SDimitry Andric   Impl.DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
230506c3fb27SDimitry Andric   Impl.HasUnsafeFPMath = hasUnsafeFPMath(F);
23065f757f3fSDimitry Andric   SIModeRegisterDefaults Mode(F, *Impl.ST);
230706c3fb27SDimitry Andric   Impl.HasFP32DenormalFlush =
230806c3fb27SDimitry Andric       Mode.FP32Denormals == DenormalMode::getPreserveSign();
230906c3fb27SDimitry Andric   PreservedAnalyses PA = PreservedAnalyses::none();
231006c3fb27SDimitry Andric   if (!Impl.FlowChanged)
231106c3fb27SDimitry Andric     PA.preserveSet<CFGAnalyses>();
231206c3fb27SDimitry Andric   return Impl.run(F) ? PA : PreservedAnalyses::all();
23130b57cec5SDimitry Andric }
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE,
23160b57cec5SDimitry Andric                       "AMDGPU IR optimizations", false, false)
23170b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
231806c3fb27SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
231906c3fb27SDimitry Andric INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)
23200b57cec5SDimitry Andric INITIALIZE_PASS_END(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations",
23210b57cec5SDimitry Andric                     false, false)
23220b57cec5SDimitry Andric 
23230b57cec5SDimitry Andric char AMDGPUCodeGenPrepare::ID = 0;
23240b57cec5SDimitry Andric 
23250b57cec5SDimitry Andric FunctionPass *llvm::createAMDGPUCodeGenPreparePass() {
23260b57cec5SDimitry Andric   return new AMDGPUCodeGenPrepare();
23270b57cec5SDimitry Andric }
2328