1 //===-- AMDGPUCodeGenPrepare.cpp ------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This pass does misc. AMDGPU optimizations on IR before instruction
11 /// selection.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPU.h"
16 #include "AMDGPUSubtarget.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "llvm/ADT/FloatingPointMode.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
23 #include "llvm/Analysis/Loads.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/InstVisitor.h"
35 #include "llvm/IR/InstrTypes.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Intrinsics.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/IR/Operator.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/IR/Value.h"
44 #include "llvm/InitializePasses.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Transforms/Utils/IntegerDivision.h"
48 #include <cassert>
49 #include <iterator>
50 
51 #define DEBUG_TYPE "amdgpu-codegenprepare"
52 
53 using namespace llvm;
54 
55 namespace {
56 
57 static cl::opt<bool> WidenLoads(
58   "amdgpu-codegenprepare-widen-constant-loads",
59   cl::desc("Widen sub-dword constant address space loads in AMDGPUCodeGenPrepare"),
60   cl::ReallyHidden,
61   cl::init(false));
62 
63 static cl::opt<bool> Widen16BitOps(
64   "amdgpu-codegenprepare-widen-16-bit-ops",
65   cl::desc("Widen uniform 16-bit instructions to 32-bit in AMDGPUCodeGenPrepare"),
66   cl::ReallyHidden,
67   cl::init(true));
68 
69 static cl::opt<bool> UseMul24Intrin(
70   "amdgpu-codegenprepare-mul24",
71   cl::desc("Introduce mul24 intrinsics in AMDGPUCodeGenPrepare"),
72   cl::ReallyHidden,
73   cl::init(true));
74 
75 // Legalize 64-bit division by using the generic IR expansion.
76 static cl::opt<bool> ExpandDiv64InIR(
77   "amdgpu-codegenprepare-expand-div64",
78   cl::desc("Expand 64-bit division in AMDGPUCodeGenPrepare"),
79   cl::ReallyHidden,
80   cl::init(false));
81 
82 // Leave all division operations as they are. This supersedes ExpandDiv64InIR
83 // and is used for testing the legalizer.
84 static cl::opt<bool> DisableIDivExpand(
85   "amdgpu-codegenprepare-disable-idiv-expansion",
86   cl::desc("Prevent expanding integer division in AMDGPUCodeGenPrepare"),
87   cl::ReallyHidden,
88   cl::init(false));
89 
90 class AMDGPUCodeGenPrepare : public FunctionPass,
91                              public InstVisitor<AMDGPUCodeGenPrepare, bool> {
92   const GCNSubtarget *ST = nullptr;
93   AssumptionCache *AC = nullptr;
94   DominatorTree *DT = nullptr;
95   LegacyDivergenceAnalysis *DA = nullptr;
96   Module *Mod = nullptr;
97   const DataLayout *DL = nullptr;
98   bool HasUnsafeFPMath = false;
99   bool HasFP32Denormals = false;
100 
101   /// Copies exact/nsw/nuw flags (if any) from binary operation \p I to
102   /// binary operation \p V.
103   ///
104   /// \returns Binary operation \p V.
105   /// \returns \p T's base element bit width.
106   unsigned getBaseElementBitWidth(const Type *T) const;
107 
108   /// \returns Equivalent 32 bit integer type for given type \p T. For example,
109   /// if \p T is i7, then i32 is returned; if \p T is <3 x i12>, then <3 x i32>
110   /// is returned.
111   Type *getI32Ty(IRBuilder<> &B, const Type *T) const;
112 
113   /// \returns True if binary operation \p I is a signed binary operation, false
114   /// otherwise.
115   bool isSigned(const BinaryOperator &I) const;
116 
117   /// \returns True if the condition of 'select' operation \p I comes from a
118   /// signed 'icmp' operation, false otherwise.
119   bool isSigned(const SelectInst &I) const;
120 
121   /// \returns True if type \p T needs to be promoted to 32 bit integer type,
122   /// false otherwise.
123   bool needsPromotionToI32(const Type *T) const;
124 
125   /// Promotes uniform binary operation \p I to equivalent 32 bit binary
126   /// operation.
127   ///
128   /// \details \p I's base element bit width must be greater than 1 and less
129   /// than or equal 16. Promotion is done by sign or zero extending operands to
130   /// 32 bits, replacing \p I with equivalent 32 bit binary operation, and
131   /// truncating the result of 32 bit binary operation back to \p I's original
132   /// type. Division operation is not promoted.
133   ///
134   /// \returns True if \p I is promoted to equivalent 32 bit binary operation,
135   /// false otherwise.
136   bool promoteUniformOpToI32(BinaryOperator &I) const;
137 
138   /// Promotes uniform 'icmp' operation \p I to 32 bit 'icmp' operation.
139   ///
140   /// \details \p I's base element bit width must be greater than 1 and less
141   /// than or equal 16. Promotion is done by sign or zero extending operands to
142   /// 32 bits, and replacing \p I with 32 bit 'icmp' operation.
143   ///
144   /// \returns True.
145   bool promoteUniformOpToI32(ICmpInst &I) const;
146 
147   /// Promotes uniform 'select' operation \p I to 32 bit 'select'
148   /// operation.
149   ///
150   /// \details \p I's base element bit width must be greater than 1 and less
151   /// than or equal 16. Promotion is done by sign or zero extending operands to
152   /// 32 bits, replacing \p I with 32 bit 'select' operation, and truncating the
153   /// result of 32 bit 'select' operation back to \p I's original type.
154   ///
155   /// \returns True.
156   bool promoteUniformOpToI32(SelectInst &I) const;
157 
158   /// Promotes uniform 'bitreverse' intrinsic \p I to 32 bit 'bitreverse'
159   /// intrinsic.
160   ///
161   /// \details \p I's base element bit width must be greater than 1 and less
162   /// than or equal 16. Promotion is done by zero extending the operand to 32
163   /// bits, replacing \p I with 32 bit 'bitreverse' intrinsic, shifting the
164   /// result of 32 bit 'bitreverse' intrinsic to the right with zero fill (the
165   /// shift amount is 32 minus \p I's base element bit width), and truncating
166   /// the result of the shift operation back to \p I's original type.
167   ///
168   /// \returns True.
169   bool promoteUniformBitreverseToI32(IntrinsicInst &I) const;
170 
171 
172   unsigned numBitsUnsigned(Value *Op, unsigned ScalarSize) const;
173   unsigned numBitsSigned(Value *Op, unsigned ScalarSize) const;
174   bool isI24(Value *V, unsigned ScalarSize) const;
175   bool isU24(Value *V, unsigned ScalarSize) const;
176 
177   /// Replace mul instructions with llvm.amdgcn.mul.u24 or llvm.amdgcn.mul.s24.
178   /// SelectionDAG has an issue where an and asserting the bits are known
179   bool replaceMulWithMul24(BinaryOperator &I) const;
180 
181   /// Perform same function as equivalently named function in DAGCombiner. Since
182   /// we expand some divisions here, we need to perform this before obscuring.
183   bool foldBinOpIntoSelect(BinaryOperator &I) const;
184 
185   bool divHasSpecialOptimization(BinaryOperator &I,
186                                  Value *Num, Value *Den) const;
187   int getDivNumBits(BinaryOperator &I,
188                     Value *Num, Value *Den,
189                     unsigned AtLeast, bool Signed) const;
190 
191   /// Expands 24 bit div or rem.
192   Value* expandDivRem24(IRBuilder<> &Builder, BinaryOperator &I,
193                         Value *Num, Value *Den,
194                         bool IsDiv, bool IsSigned) const;
195 
196   Value *expandDivRem24Impl(IRBuilder<> &Builder, BinaryOperator &I,
197                             Value *Num, Value *Den, unsigned NumBits,
198                             bool IsDiv, bool IsSigned) const;
199 
200   /// Expands 32 bit div or rem.
201   Value* expandDivRem32(IRBuilder<> &Builder, BinaryOperator &I,
202                         Value *Num, Value *Den) const;
203 
204   Value *shrinkDivRem64(IRBuilder<> &Builder, BinaryOperator &I,
205                         Value *Num, Value *Den) const;
206   void expandDivRem64(BinaryOperator &I) const;
207 
208   /// Widen a scalar load.
209   ///
210   /// \details \p Widen scalar load for uniform, small type loads from constant
211   //  memory / to a full 32-bits and then truncate the input to allow a scalar
212   //  load instead of a vector load.
213   //
214   /// \returns True.
215 
216   bool canWidenScalarExtLoad(LoadInst &I) const;
217 
218 public:
219   static char ID;
220 
221   AMDGPUCodeGenPrepare() : FunctionPass(ID) {}
222 
223   bool visitFDiv(BinaryOperator &I);
224 
225   bool visitInstruction(Instruction &I) { return false; }
226   bool visitBinaryOperator(BinaryOperator &I);
227   bool visitLoadInst(LoadInst &I);
228   bool visitICmpInst(ICmpInst &I);
229   bool visitSelectInst(SelectInst &I);
230 
231   bool visitIntrinsicInst(IntrinsicInst &I);
232   bool visitBitreverseIntrinsicInst(IntrinsicInst &I);
233 
234   bool doInitialization(Module &M) override;
235   bool runOnFunction(Function &F) override;
236 
237   StringRef getPassName() const override { return "AMDGPU IR optimizations"; }
238 
239   void getAnalysisUsage(AnalysisUsage &AU) const override {
240     AU.addRequired<AssumptionCacheTracker>();
241     AU.addRequired<LegacyDivergenceAnalysis>();
242 
243     // FIXME: Division expansion needs to preserve the dominator tree.
244     if (!ExpandDiv64InIR)
245       AU.setPreservesAll();
246  }
247 };
248 
249 } // end anonymous namespace
250 
251 unsigned AMDGPUCodeGenPrepare::getBaseElementBitWidth(const Type *T) const {
252   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
253 
254   if (T->isIntegerTy())
255     return T->getIntegerBitWidth();
256   return cast<VectorType>(T)->getElementType()->getIntegerBitWidth();
257 }
258 
259 Type *AMDGPUCodeGenPrepare::getI32Ty(IRBuilder<> &B, const Type *T) const {
260   assert(needsPromotionToI32(T) && "T does not need promotion to i32");
261 
262   if (T->isIntegerTy())
263     return B.getInt32Ty();
264   return FixedVectorType::get(B.getInt32Ty(), cast<FixedVectorType>(T));
265 }
266 
267 bool AMDGPUCodeGenPrepare::isSigned(const BinaryOperator &I) const {
268   return I.getOpcode() == Instruction::AShr ||
269       I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::SRem;
270 }
271 
272 bool AMDGPUCodeGenPrepare::isSigned(const SelectInst &I) const {
273   return isa<ICmpInst>(I.getOperand(0)) ?
274       cast<ICmpInst>(I.getOperand(0))->isSigned() : false;
275 }
276 
277 bool AMDGPUCodeGenPrepare::needsPromotionToI32(const Type *T) const {
278   if (!Widen16BitOps)
279     return false;
280 
281   const IntegerType *IntTy = dyn_cast<IntegerType>(T);
282   if (IntTy && IntTy->getBitWidth() > 1 && IntTy->getBitWidth() <= 16)
283     return true;
284 
285   if (const VectorType *VT = dyn_cast<VectorType>(T)) {
286     // TODO: The set of packed operations is more limited, so may want to
287     // promote some anyway.
288     if (ST->hasVOP3PInsts())
289       return false;
290 
291     return needsPromotionToI32(VT->getElementType());
292   }
293 
294   return false;
295 }
296 
297 // Return true if the op promoted to i32 should have nsw set.
298 static bool promotedOpIsNSW(const Instruction &I) {
299   switch (I.getOpcode()) {
300   case Instruction::Shl:
301   case Instruction::Add:
302   case Instruction::Sub:
303     return true;
304   case Instruction::Mul:
305     return I.hasNoUnsignedWrap();
306   default:
307     return false;
308   }
309 }
310 
311 // Return true if the op promoted to i32 should have nuw set.
312 static bool promotedOpIsNUW(const Instruction &I) {
313   switch (I.getOpcode()) {
314   case Instruction::Shl:
315   case Instruction::Add:
316   case Instruction::Mul:
317     return true;
318   case Instruction::Sub:
319     return I.hasNoUnsignedWrap();
320   default:
321     return false;
322   }
323 }
324 
325 bool AMDGPUCodeGenPrepare::canWidenScalarExtLoad(LoadInst &I) const {
326   Type *Ty = I.getType();
327   const DataLayout &DL = Mod->getDataLayout();
328   int TySize = DL.getTypeSizeInBits(Ty);
329   Align Alignment = DL.getValueOrABITypeAlignment(I.getAlign(), Ty);
330 
331   return I.isSimple() && TySize < 32 && Alignment >= 4 && DA->isUniform(&I);
332 }
333 
334 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(BinaryOperator &I) const {
335   assert(needsPromotionToI32(I.getType()) &&
336          "I does not need promotion to i32");
337 
338   if (I.getOpcode() == Instruction::SDiv ||
339       I.getOpcode() == Instruction::UDiv ||
340       I.getOpcode() == Instruction::SRem ||
341       I.getOpcode() == Instruction::URem)
342     return false;
343 
344   IRBuilder<> Builder(&I);
345   Builder.SetCurrentDebugLocation(I.getDebugLoc());
346 
347   Type *I32Ty = getI32Ty(Builder, I.getType());
348   Value *ExtOp0 = nullptr;
349   Value *ExtOp1 = nullptr;
350   Value *ExtRes = nullptr;
351   Value *TruncRes = nullptr;
352 
353   if (isSigned(I)) {
354     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
355     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
356   } else {
357     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
358     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
359   }
360 
361   ExtRes = Builder.CreateBinOp(I.getOpcode(), ExtOp0, ExtOp1);
362   if (Instruction *Inst = dyn_cast<Instruction>(ExtRes)) {
363     if (promotedOpIsNSW(cast<Instruction>(I)))
364       Inst->setHasNoSignedWrap();
365 
366     if (promotedOpIsNUW(cast<Instruction>(I)))
367       Inst->setHasNoUnsignedWrap();
368 
369     if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
370       Inst->setIsExact(ExactOp->isExact());
371   }
372 
373   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
374 
375   I.replaceAllUsesWith(TruncRes);
376   I.eraseFromParent();
377 
378   return true;
379 }
380 
381 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(ICmpInst &I) const {
382   assert(needsPromotionToI32(I.getOperand(0)->getType()) &&
383          "I does not need promotion to i32");
384 
385   IRBuilder<> Builder(&I);
386   Builder.SetCurrentDebugLocation(I.getDebugLoc());
387 
388   Type *I32Ty = getI32Ty(Builder, I.getOperand(0)->getType());
389   Value *ExtOp0 = nullptr;
390   Value *ExtOp1 = nullptr;
391   Value *NewICmp  = nullptr;
392 
393   if (I.isSigned()) {
394     ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
395     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
396   } else {
397     ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
398     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
399   }
400   NewICmp = Builder.CreateICmp(I.getPredicate(), ExtOp0, ExtOp1);
401 
402   I.replaceAllUsesWith(NewICmp);
403   I.eraseFromParent();
404 
405   return true;
406 }
407 
408 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(SelectInst &I) const {
409   assert(needsPromotionToI32(I.getType()) &&
410          "I does not need promotion to i32");
411 
412   IRBuilder<> Builder(&I);
413   Builder.SetCurrentDebugLocation(I.getDebugLoc());
414 
415   Type *I32Ty = getI32Ty(Builder, I.getType());
416   Value *ExtOp1 = nullptr;
417   Value *ExtOp2 = nullptr;
418   Value *ExtRes = nullptr;
419   Value *TruncRes = nullptr;
420 
421   if (isSigned(I)) {
422     ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
423     ExtOp2 = Builder.CreateSExt(I.getOperand(2), I32Ty);
424   } else {
425     ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
426     ExtOp2 = Builder.CreateZExt(I.getOperand(2), I32Ty);
427   }
428   ExtRes = Builder.CreateSelect(I.getOperand(0), ExtOp1, ExtOp2);
429   TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
430 
431   I.replaceAllUsesWith(TruncRes);
432   I.eraseFromParent();
433 
434   return true;
435 }
436 
437 bool AMDGPUCodeGenPrepare::promoteUniformBitreverseToI32(
438     IntrinsicInst &I) const {
439   assert(I.getIntrinsicID() == Intrinsic::bitreverse &&
440          "I must be bitreverse intrinsic");
441   assert(needsPromotionToI32(I.getType()) &&
442          "I does not need promotion to i32");
443 
444   IRBuilder<> Builder(&I);
445   Builder.SetCurrentDebugLocation(I.getDebugLoc());
446 
447   Type *I32Ty = getI32Ty(Builder, I.getType());
448   Function *I32 =
449       Intrinsic::getDeclaration(Mod, Intrinsic::bitreverse, { I32Ty });
450   Value *ExtOp = Builder.CreateZExt(I.getOperand(0), I32Ty);
451   Value *ExtRes = Builder.CreateCall(I32, { ExtOp });
452   Value *LShrOp =
453       Builder.CreateLShr(ExtRes, 32 - getBaseElementBitWidth(I.getType()));
454   Value *TruncRes =
455       Builder.CreateTrunc(LShrOp, I.getType());
456 
457   I.replaceAllUsesWith(TruncRes);
458   I.eraseFromParent();
459 
460   return true;
461 }
462 
463 unsigned AMDGPUCodeGenPrepare::numBitsUnsigned(Value *Op,
464                                                unsigned ScalarSize) const {
465   KnownBits Known = computeKnownBits(Op, *DL, 0, AC);
466   return ScalarSize - Known.countMinLeadingZeros();
467 }
468 
469 unsigned AMDGPUCodeGenPrepare::numBitsSigned(Value *Op,
470                                              unsigned ScalarSize) const {
471   // In order for this to be a signed 24-bit value, bit 23, must
472   // be a sign bit.
473   return ScalarSize - ComputeNumSignBits(Op, *DL, 0, AC);
474 }
475 
476 bool AMDGPUCodeGenPrepare::isI24(Value *V, unsigned ScalarSize) const {
477   return ScalarSize >= 24 && // Types less than 24-bit should be treated
478                                      // as unsigned 24-bit values.
479     numBitsSigned(V, ScalarSize) < 24;
480 }
481 
482 bool AMDGPUCodeGenPrepare::isU24(Value *V, unsigned ScalarSize) const {
483   return numBitsUnsigned(V, ScalarSize) <= 24;
484 }
485 
486 static void extractValues(IRBuilder<> &Builder,
487                           SmallVectorImpl<Value *> &Values, Value *V) {
488   auto *VT = dyn_cast<FixedVectorType>(V->getType());
489   if (!VT) {
490     Values.push_back(V);
491     return;
492   }
493 
494   for (int I = 0, E = VT->getNumElements(); I != E; ++I)
495     Values.push_back(Builder.CreateExtractElement(V, I));
496 }
497 
498 static Value *insertValues(IRBuilder<> &Builder,
499                            Type *Ty,
500                            SmallVectorImpl<Value *> &Values) {
501   if (Values.size() == 1)
502     return Values[0];
503 
504   Value *NewVal = UndefValue::get(Ty);
505   for (int I = 0, E = Values.size(); I != E; ++I)
506     NewVal = Builder.CreateInsertElement(NewVal, Values[I], I);
507 
508   return NewVal;
509 }
510 
511 bool AMDGPUCodeGenPrepare::replaceMulWithMul24(BinaryOperator &I) const {
512   if (I.getOpcode() != Instruction::Mul)
513     return false;
514 
515   Type *Ty = I.getType();
516   unsigned Size = Ty->getScalarSizeInBits();
517   if (Size <= 16 && ST->has16BitInsts())
518     return false;
519 
520   // Prefer scalar if this could be s_mul_i32
521   if (DA->isUniform(&I))
522     return false;
523 
524   Value *LHS = I.getOperand(0);
525   Value *RHS = I.getOperand(1);
526   IRBuilder<> Builder(&I);
527   Builder.SetCurrentDebugLocation(I.getDebugLoc());
528 
529   Intrinsic::ID IntrID = Intrinsic::not_intrinsic;
530 
531   // TODO: Should this try to match mulhi24?
532   if (ST->hasMulU24() && isU24(LHS, Size) && isU24(RHS, Size)) {
533     IntrID = Intrinsic::amdgcn_mul_u24;
534   } else if (ST->hasMulI24() && isI24(LHS, Size) && isI24(RHS, Size)) {
535     IntrID = Intrinsic::amdgcn_mul_i24;
536   } else
537     return false;
538 
539   SmallVector<Value *, 4> LHSVals;
540   SmallVector<Value *, 4> RHSVals;
541   SmallVector<Value *, 4> ResultVals;
542   extractValues(Builder, LHSVals, LHS);
543   extractValues(Builder, RHSVals, RHS);
544 
545 
546   IntegerType *I32Ty = Builder.getInt32Ty();
547   FunctionCallee Intrin = Intrinsic::getDeclaration(Mod, IntrID);
548   for (int I = 0, E = LHSVals.size(); I != E; ++I) {
549     Value *LHS, *RHS;
550     if (IntrID == Intrinsic::amdgcn_mul_u24) {
551       LHS = Builder.CreateZExtOrTrunc(LHSVals[I], I32Ty);
552       RHS = Builder.CreateZExtOrTrunc(RHSVals[I], I32Ty);
553     } else {
554       LHS = Builder.CreateSExtOrTrunc(LHSVals[I], I32Ty);
555       RHS = Builder.CreateSExtOrTrunc(RHSVals[I], I32Ty);
556     }
557 
558     Value *Result = Builder.CreateCall(Intrin, {LHS, RHS});
559 
560     if (IntrID == Intrinsic::amdgcn_mul_u24) {
561       ResultVals.push_back(Builder.CreateZExtOrTrunc(Result,
562                                                      LHSVals[I]->getType()));
563     } else {
564       ResultVals.push_back(Builder.CreateSExtOrTrunc(Result,
565                                                      LHSVals[I]->getType()));
566     }
567   }
568 
569   Value *NewVal = insertValues(Builder, Ty, ResultVals);
570   NewVal->takeName(&I);
571   I.replaceAllUsesWith(NewVal);
572   I.eraseFromParent();
573 
574   return true;
575 }
576 
577 // Find a select instruction, which may have been casted. This is mostly to deal
578 // with cases where i16 selects were promoted here to i32.
579 static SelectInst *findSelectThroughCast(Value *V, CastInst *&Cast) {
580   Cast = nullptr;
581   if (SelectInst *Sel = dyn_cast<SelectInst>(V))
582     return Sel;
583 
584   if ((Cast = dyn_cast<CastInst>(V))) {
585     if (SelectInst *Sel = dyn_cast<SelectInst>(Cast->getOperand(0)))
586       return Sel;
587   }
588 
589   return nullptr;
590 }
591 
592 bool AMDGPUCodeGenPrepare::foldBinOpIntoSelect(BinaryOperator &BO) const {
593   // Don't do this unless the old select is going away. We want to eliminate the
594   // binary operator, not replace a binop with a select.
595   int SelOpNo = 0;
596 
597   CastInst *CastOp;
598 
599   // TODO: Should probably try to handle some cases with multiple
600   // users. Duplicating the select may be profitable for division.
601   SelectInst *Sel = findSelectThroughCast(BO.getOperand(0), CastOp);
602   if (!Sel || !Sel->hasOneUse()) {
603     SelOpNo = 1;
604     Sel = findSelectThroughCast(BO.getOperand(1), CastOp);
605   }
606 
607   if (!Sel || !Sel->hasOneUse())
608     return false;
609 
610   Constant *CT = dyn_cast<Constant>(Sel->getTrueValue());
611   Constant *CF = dyn_cast<Constant>(Sel->getFalseValue());
612   Constant *CBO = dyn_cast<Constant>(BO.getOperand(SelOpNo ^ 1));
613   if (!CBO || !CT || !CF)
614     return false;
615 
616   if (CastOp) {
617     if (!CastOp->hasOneUse())
618       return false;
619     CT = ConstantFoldCastOperand(CastOp->getOpcode(), CT, BO.getType(), *DL);
620     CF = ConstantFoldCastOperand(CastOp->getOpcode(), CF, BO.getType(), *DL);
621   }
622 
623   // TODO: Handle special 0/-1 cases DAG combine does, although we only really
624   // need to handle divisions here.
625   Constant *FoldedT = SelOpNo ?
626     ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CT, *DL) :
627     ConstantFoldBinaryOpOperands(BO.getOpcode(), CT, CBO, *DL);
628   if (isa<ConstantExpr>(FoldedT))
629     return false;
630 
631   Constant *FoldedF = SelOpNo ?
632     ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CF, *DL) :
633     ConstantFoldBinaryOpOperands(BO.getOpcode(), CF, CBO, *DL);
634   if (isa<ConstantExpr>(FoldedF))
635     return false;
636 
637   IRBuilder<> Builder(&BO);
638   Builder.SetCurrentDebugLocation(BO.getDebugLoc());
639   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&BO))
640     Builder.setFastMathFlags(FPOp->getFastMathFlags());
641 
642   Value *NewSelect = Builder.CreateSelect(Sel->getCondition(),
643                                           FoldedT, FoldedF);
644   NewSelect->takeName(&BO);
645   BO.replaceAllUsesWith(NewSelect);
646   BO.eraseFromParent();
647   if (CastOp)
648     CastOp->eraseFromParent();
649   Sel->eraseFromParent();
650   return true;
651 }
652 
653 // Optimize fdiv with rcp:
654 //
655 // 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
656 //               allowed with unsafe-fp-math or afn.
657 //
658 // a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
659 static Value *optimizeWithRcp(Value *Num, Value *Den, bool AllowInaccurateRcp,
660                               bool RcpIsAccurate, IRBuilder<> &Builder,
661                               Module *Mod) {
662 
663   if (!AllowInaccurateRcp && !RcpIsAccurate)
664     return nullptr;
665 
666   Type *Ty = Den->getType();
667   if (const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num)) {
668     if (AllowInaccurateRcp || RcpIsAccurate) {
669       if (CLHS->isExactlyValue(1.0)) {
670         Function *Decl = Intrinsic::getDeclaration(
671           Mod, Intrinsic::amdgcn_rcp, Ty);
672 
673         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
674         // the CI documentation has a worst case error of 1 ulp.
675         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
676         // use it as long as we aren't trying to use denormals.
677         //
678         // v_rcp_f16 and v_rsq_f16 DO support denormals.
679 
680         // NOTE: v_sqrt and v_rcp will be combined to v_rsq later. So we don't
681         //       insert rsq intrinsic here.
682 
683         // 1.0 / x -> rcp(x)
684         return Builder.CreateCall(Decl, { Den });
685       }
686 
687        // Same as for 1.0, but expand the sign out of the constant.
688       if (CLHS->isExactlyValue(-1.0)) {
689         Function *Decl = Intrinsic::getDeclaration(
690           Mod, Intrinsic::amdgcn_rcp, Ty);
691 
692          // -1.0 / x -> rcp (fneg x)
693          Value *FNeg = Builder.CreateFNeg(Den);
694          return Builder.CreateCall(Decl, { FNeg });
695        }
696     }
697   }
698 
699   if (AllowInaccurateRcp) {
700     Function *Decl = Intrinsic::getDeclaration(
701       Mod, Intrinsic::amdgcn_rcp, Ty);
702 
703     // Turn into multiply by the reciprocal.
704     // x / y -> x * (1.0 / y)
705     Value *Recip = Builder.CreateCall(Decl, { Den });
706     return Builder.CreateFMul(Num, Recip);
707   }
708   return nullptr;
709 }
710 
711 // optimize with fdiv.fast:
712 //
713 // a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
714 //
715 // 1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
716 //
717 // NOTE: optimizeWithRcp should be tried first because rcp is the preference.
718 static Value *optimizeWithFDivFast(Value *Num, Value *Den, float ReqdAccuracy,
719                                    bool HasDenormals, IRBuilder<> &Builder,
720                                    Module *Mod) {
721   // fdiv.fast can achieve 2.5 ULP accuracy.
722   if (ReqdAccuracy < 2.5f)
723     return nullptr;
724 
725   // Only have fdiv.fast for f32.
726   Type *Ty = Den->getType();
727   if (!Ty->isFloatTy())
728     return nullptr;
729 
730   bool NumIsOne = false;
731   if (const ConstantFP *CNum = dyn_cast<ConstantFP>(Num)) {
732     if (CNum->isExactlyValue(+1.0) || CNum->isExactlyValue(-1.0))
733       NumIsOne = true;
734   }
735 
736   // fdiv does not support denormals. But 1.0/x is always fine to use it.
737   if (HasDenormals && !NumIsOne)
738     return nullptr;
739 
740   Function *Decl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_fdiv_fast);
741   return Builder.CreateCall(Decl, { Num, Den });
742 }
743 
744 // Optimizations is performed based on fpmath, fast math flags as well as
745 // denormals to optimize fdiv with either rcp or fdiv.fast.
746 //
747 // With rcp:
748 //   1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
749 //                 allowed with unsafe-fp-math or afn.
750 //
751 //   a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
752 //
753 // With fdiv.fast:
754 //   a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
755 //
756 //   1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
757 //
758 // NOTE: rcp is the preference in cases that both are legal.
759 bool AMDGPUCodeGenPrepare::visitFDiv(BinaryOperator &FDiv) {
760 
761   Type *Ty = FDiv.getType()->getScalarType();
762 
763   // No intrinsic for fdiv16 if target does not support f16.
764   if (Ty->isHalfTy() && !ST->has16BitInsts())
765     return false;
766 
767   const FPMathOperator *FPOp = cast<const FPMathOperator>(&FDiv);
768   const float ReqdAccuracy =  FPOp->getFPAccuracy();
769 
770   // Inaccurate rcp is allowed with unsafe-fp-math or afn.
771   FastMathFlags FMF = FPOp->getFastMathFlags();
772   const bool AllowInaccurateRcp = HasUnsafeFPMath || FMF.approxFunc();
773 
774   // rcp_f16 is accurate for !fpmath >= 1.0ulp.
775   // rcp_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
776   // rcp_f64 is never accurate.
777   const bool RcpIsAccurate = (Ty->isHalfTy() && ReqdAccuracy >= 1.0f) ||
778             (Ty->isFloatTy() && !HasFP32Denormals && ReqdAccuracy >= 1.0f);
779 
780   IRBuilder<> Builder(FDiv.getParent(), std::next(FDiv.getIterator()));
781   Builder.setFastMathFlags(FMF);
782   Builder.SetCurrentDebugLocation(FDiv.getDebugLoc());
783 
784   Value *Num = FDiv.getOperand(0);
785   Value *Den = FDiv.getOperand(1);
786 
787   Value *NewFDiv = nullptr;
788   if (auto *VT = dyn_cast<FixedVectorType>(FDiv.getType())) {
789     NewFDiv = UndefValue::get(VT);
790 
791     // FIXME: Doesn't do the right thing for cases where the vector is partially
792     // constant. This works when the scalarizer pass is run first.
793     for (unsigned I = 0, E = VT->getNumElements(); I != E; ++I) {
794       Value *NumEltI = Builder.CreateExtractElement(Num, I);
795       Value *DenEltI = Builder.CreateExtractElement(Den, I);
796       // Try rcp first.
797       Value *NewElt = optimizeWithRcp(NumEltI, DenEltI, AllowInaccurateRcp,
798                                       RcpIsAccurate, Builder, Mod);
799       if (!NewElt) // Try fdiv.fast.
800         NewElt = optimizeWithFDivFast(NumEltI, DenEltI, ReqdAccuracy,
801                                       HasFP32Denormals, Builder, Mod);
802       if (!NewElt) // Keep the original.
803         NewElt = Builder.CreateFDiv(NumEltI, DenEltI);
804 
805       NewFDiv = Builder.CreateInsertElement(NewFDiv, NewElt, I);
806     }
807   } else { // Scalar FDiv.
808     // Try rcp first.
809     NewFDiv = optimizeWithRcp(Num, Den, AllowInaccurateRcp, RcpIsAccurate,
810                               Builder, Mod);
811     if (!NewFDiv) { // Try fdiv.fast.
812       NewFDiv = optimizeWithFDivFast(Num, Den, ReqdAccuracy, HasFP32Denormals,
813                                      Builder, Mod);
814     }
815   }
816 
817   if (NewFDiv) {
818     FDiv.replaceAllUsesWith(NewFDiv);
819     NewFDiv->takeName(&FDiv);
820     FDiv.eraseFromParent();
821   }
822 
823   return !!NewFDiv;
824 }
825 
826 static bool hasUnsafeFPMath(const Function &F) {
827   Attribute Attr = F.getFnAttribute("unsafe-fp-math");
828   return Attr.getValueAsString() == "true";
829 }
830 
831 static std::pair<Value*, Value*> getMul64(IRBuilder<> &Builder,
832                                           Value *LHS, Value *RHS) {
833   Type *I32Ty = Builder.getInt32Ty();
834   Type *I64Ty = Builder.getInt64Ty();
835 
836   Value *LHS_EXT64 = Builder.CreateZExt(LHS, I64Ty);
837   Value *RHS_EXT64 = Builder.CreateZExt(RHS, I64Ty);
838   Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64);
839   Value *Lo = Builder.CreateTrunc(MUL64, I32Ty);
840   Value *Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32));
841   Hi = Builder.CreateTrunc(Hi, I32Ty);
842   return std::make_pair(Lo, Hi);
843 }
844 
845 static Value* getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS) {
846   return getMul64(Builder, LHS, RHS).second;
847 }
848 
849 /// Figure out how many bits are really needed for this ddivision. \p AtLeast is
850 /// an optimization hint to bypass the second ComputeNumSignBits call if we the
851 /// first one is insufficient. Returns -1 on failure.
852 int AMDGPUCodeGenPrepare::getDivNumBits(BinaryOperator &I,
853                                         Value *Num, Value *Den,
854                                         unsigned AtLeast, bool IsSigned) const {
855   const DataLayout &DL = Mod->getDataLayout();
856   unsigned LHSSignBits = ComputeNumSignBits(Num, DL, 0, AC, &I);
857   if (LHSSignBits < AtLeast)
858     return -1;
859 
860   unsigned RHSSignBits = ComputeNumSignBits(Den, DL, 0, AC, &I);
861   if (RHSSignBits < AtLeast)
862     return -1;
863 
864   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
865   unsigned DivBits = Num->getType()->getScalarSizeInBits() - SignBits;
866   if (IsSigned)
867     ++DivBits;
868   return DivBits;
869 }
870 
871 // The fractional part of a float is enough to accurately represent up to
872 // a 24-bit signed integer.
873 Value *AMDGPUCodeGenPrepare::expandDivRem24(IRBuilder<> &Builder,
874                                             BinaryOperator &I,
875                                             Value *Num, Value *Den,
876                                             bool IsDiv, bool IsSigned) const {
877   int DivBits = getDivNumBits(I, Num, Den, 9, IsSigned);
878   if (DivBits == -1)
879     return nullptr;
880   return expandDivRem24Impl(Builder, I, Num, Den, DivBits, IsDiv, IsSigned);
881 }
882 
883 Value *AMDGPUCodeGenPrepare::expandDivRem24Impl(IRBuilder<> &Builder,
884                                                 BinaryOperator &I,
885                                                 Value *Num, Value *Den,
886                                                 unsigned DivBits,
887                                                 bool IsDiv, bool IsSigned) const {
888   Type *I32Ty = Builder.getInt32Ty();
889   Num = Builder.CreateTrunc(Num, I32Ty);
890   Den = Builder.CreateTrunc(Den, I32Ty);
891 
892   Type *F32Ty = Builder.getFloatTy();
893   ConstantInt *One = Builder.getInt32(1);
894   Value *JQ = One;
895 
896   if (IsSigned) {
897     // char|short jq = ia ^ ib;
898     JQ = Builder.CreateXor(Num, Den);
899 
900     // jq = jq >> (bitsize - 2)
901     JQ = Builder.CreateAShr(JQ, Builder.getInt32(30));
902 
903     // jq = jq | 0x1
904     JQ = Builder.CreateOr(JQ, One);
905   }
906 
907   // int ia = (int)LHS;
908   Value *IA = Num;
909 
910   // int ib, (int)RHS;
911   Value *IB = Den;
912 
913   // float fa = (float)ia;
914   Value *FA = IsSigned ? Builder.CreateSIToFP(IA, F32Ty)
915                        : Builder.CreateUIToFP(IA, F32Ty);
916 
917   // float fb = (float)ib;
918   Value *FB = IsSigned ? Builder.CreateSIToFP(IB,F32Ty)
919                        : Builder.CreateUIToFP(IB,F32Ty);
920 
921   Function *RcpDecl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp,
922                                                 Builder.getFloatTy());
923   Value *RCP = Builder.CreateCall(RcpDecl, { FB });
924   Value *FQM = Builder.CreateFMul(FA, RCP);
925 
926   // fq = trunc(fqm);
927   CallInst *FQ = Builder.CreateUnaryIntrinsic(Intrinsic::trunc, FQM);
928   FQ->copyFastMathFlags(Builder.getFastMathFlags());
929 
930   // float fqneg = -fq;
931   Value *FQNeg = Builder.CreateFNeg(FQ);
932 
933   // float fr = mad(fqneg, fb, fa);
934   auto FMAD = !ST->hasMadMacF32Insts()
935                   ? Intrinsic::fma
936                   : (Intrinsic::ID)Intrinsic::amdgcn_fmad_ftz;
937   Value *FR = Builder.CreateIntrinsic(FMAD,
938                                       {FQNeg->getType()}, {FQNeg, FB, FA}, FQ);
939 
940   // int iq = (int)fq;
941   Value *IQ = IsSigned ? Builder.CreateFPToSI(FQ, I32Ty)
942                        : Builder.CreateFPToUI(FQ, I32Ty);
943 
944   // fr = fabs(fr);
945   FR = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FR, FQ);
946 
947   // fb = fabs(fb);
948   FB = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FB, FQ);
949 
950   // int cv = fr >= fb;
951   Value *CV = Builder.CreateFCmpOGE(FR, FB);
952 
953   // jq = (cv ? jq : 0);
954   JQ = Builder.CreateSelect(CV, JQ, Builder.getInt32(0));
955 
956   // dst = iq + jq;
957   Value *Div = Builder.CreateAdd(IQ, JQ);
958 
959   Value *Res = Div;
960   if (!IsDiv) {
961     // Rem needs compensation, it's easier to recompute it
962     Value *Rem = Builder.CreateMul(Div, Den);
963     Res = Builder.CreateSub(Num, Rem);
964   }
965 
966   if (DivBits != 0 && DivBits < 32) {
967     // Extend in register from the number of bits this divide really is.
968     if (IsSigned) {
969       int InRegBits = 32 - DivBits;
970 
971       Res = Builder.CreateShl(Res, InRegBits);
972       Res = Builder.CreateAShr(Res, InRegBits);
973     } else {
974       ConstantInt *TruncMask
975         = Builder.getInt32((UINT64_C(1) << DivBits) - 1);
976       Res = Builder.CreateAnd(Res, TruncMask);
977     }
978   }
979 
980   return Res;
981 }
982 
983 // Try to recognize special cases the DAG will emit special, better expansions
984 // than the general expansion we do here.
985 
986 // TODO: It would be better to just directly handle those optimizations here.
987 bool AMDGPUCodeGenPrepare::divHasSpecialOptimization(
988   BinaryOperator &I, Value *Num, Value *Den) const {
989   if (Constant *C = dyn_cast<Constant>(Den)) {
990     // Arbitrary constants get a better expansion as long as a wider mulhi is
991     // legal.
992     if (C->getType()->getScalarSizeInBits() <= 32)
993       return true;
994 
995     // TODO: Sdiv check for not exact for some reason.
996 
997     // If there's no wider mulhi, there's only a better expansion for powers of
998     // two.
999     // TODO: Should really know for each vector element.
1000     if (isKnownToBeAPowerOfTwo(C, *DL, true, 0, AC, &I, DT))
1001       return true;
1002 
1003     return false;
1004   }
1005 
1006   if (BinaryOperator *BinOpDen = dyn_cast<BinaryOperator>(Den)) {
1007     // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1008     if (BinOpDen->getOpcode() == Instruction::Shl &&
1009         isa<Constant>(BinOpDen->getOperand(0)) &&
1010         isKnownToBeAPowerOfTwo(BinOpDen->getOperand(0), *DL, true,
1011                                0, AC, &I, DT)) {
1012       return true;
1013     }
1014   }
1015 
1016   return false;
1017 }
1018 
1019 static Value *getSign32(Value *V, IRBuilder<> &Builder, const DataLayout *DL) {
1020   // Check whether the sign can be determined statically.
1021   KnownBits Known = computeKnownBits(V, *DL);
1022   if (Known.isNegative())
1023     return Constant::getAllOnesValue(V->getType());
1024   if (Known.isNonNegative())
1025     return Constant::getNullValue(V->getType());
1026   return Builder.CreateAShr(V, Builder.getInt32(31));
1027 }
1028 
1029 Value *AMDGPUCodeGenPrepare::expandDivRem32(IRBuilder<> &Builder,
1030                                             BinaryOperator &I, Value *X,
1031                                             Value *Y) const {
1032   Instruction::BinaryOps Opc = I.getOpcode();
1033   assert(Opc == Instruction::URem || Opc == Instruction::UDiv ||
1034          Opc == Instruction::SRem || Opc == Instruction::SDiv);
1035 
1036   FastMathFlags FMF;
1037   FMF.setFast();
1038   Builder.setFastMathFlags(FMF);
1039 
1040   if (divHasSpecialOptimization(I, X, Y))
1041     return nullptr;  // Keep it for later optimization.
1042 
1043   bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv;
1044   bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv;
1045 
1046   Type *Ty = X->getType();
1047   Type *I32Ty = Builder.getInt32Ty();
1048   Type *F32Ty = Builder.getFloatTy();
1049 
1050   if (Ty->getScalarSizeInBits() < 32) {
1051     if (IsSigned) {
1052       X = Builder.CreateSExt(X, I32Ty);
1053       Y = Builder.CreateSExt(Y, I32Ty);
1054     } else {
1055       X = Builder.CreateZExt(X, I32Ty);
1056       Y = Builder.CreateZExt(Y, I32Ty);
1057     }
1058   }
1059 
1060   if (Value *Res = expandDivRem24(Builder, I, X, Y, IsDiv, IsSigned)) {
1061     return IsSigned ? Builder.CreateSExtOrTrunc(Res, Ty) :
1062                       Builder.CreateZExtOrTrunc(Res, Ty);
1063   }
1064 
1065   ConstantInt *Zero = Builder.getInt32(0);
1066   ConstantInt *One = Builder.getInt32(1);
1067 
1068   Value *Sign = nullptr;
1069   if (IsSigned) {
1070     Value *SignX = getSign32(X, Builder, DL);
1071     Value *SignY = getSign32(Y, Builder, DL);
1072     // Remainder sign is the same as LHS
1073     Sign = IsDiv ? Builder.CreateXor(SignX, SignY) : SignX;
1074 
1075     X = Builder.CreateAdd(X, SignX);
1076     Y = Builder.CreateAdd(Y, SignY);
1077 
1078     X = Builder.CreateXor(X, SignX);
1079     Y = Builder.CreateXor(Y, SignY);
1080   }
1081 
1082   // The algorithm here is based on ideas from "Software Integer Division", Tom
1083   // Rodeheffer, August 2008.
1084   //
1085   // unsigned udiv(unsigned x, unsigned y) {
1086   //   // Initial estimate of inv(y). The constant is less than 2^32 to ensure
1087   //   // that this is a lower bound on inv(y), even if some of the calculations
1088   //   // round up.
1089   //   unsigned z = (unsigned)((4294967296.0 - 512.0) * v_rcp_f32((float)y));
1090   //
1091   //   // One round of UNR (Unsigned integer Newton-Raphson) to improve z.
1092   //   // Empirically this is guaranteed to give a "two-y" lower bound on
1093   //   // inv(y).
1094   //   z += umulh(z, -y * z);
1095   //
1096   //   // Quotient/remainder estimate.
1097   //   unsigned q = umulh(x, z);
1098   //   unsigned r = x - q * y;
1099   //
1100   //   // Two rounds of quotient/remainder refinement.
1101   //   if (r >= y) {
1102   //     ++q;
1103   //     r -= y;
1104   //   }
1105   //   if (r >= y) {
1106   //     ++q;
1107   //     r -= y;
1108   //   }
1109   //
1110   //   return q;
1111   // }
1112 
1113   // Initial estimate of inv(y).
1114   Value *FloatY = Builder.CreateUIToFP(Y, F32Ty);
1115   Function *Rcp = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp, F32Ty);
1116   Value *RcpY = Builder.CreateCall(Rcp, {FloatY});
1117   Constant *Scale = ConstantFP::get(F32Ty, BitsToFloat(0x4F7FFFFE));
1118   Value *ScaledY = Builder.CreateFMul(RcpY, Scale);
1119   Value *Z = Builder.CreateFPToUI(ScaledY, I32Ty);
1120 
1121   // One round of UNR.
1122   Value *NegY = Builder.CreateSub(Zero, Y);
1123   Value *NegYZ = Builder.CreateMul(NegY, Z);
1124   Z = Builder.CreateAdd(Z, getMulHu(Builder, Z, NegYZ));
1125 
1126   // Quotient/remainder estimate.
1127   Value *Q = getMulHu(Builder, X, Z);
1128   Value *R = Builder.CreateSub(X, Builder.CreateMul(Q, Y));
1129 
1130   // First quotient/remainder refinement.
1131   Value *Cond = Builder.CreateICmpUGE(R, Y);
1132   if (IsDiv)
1133     Q = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
1134   R = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
1135 
1136   // Second quotient/remainder refinement.
1137   Cond = Builder.CreateICmpUGE(R, Y);
1138   Value *Res;
1139   if (IsDiv)
1140     Res = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
1141   else
1142     Res = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
1143 
1144   if (IsSigned) {
1145     Res = Builder.CreateXor(Res, Sign);
1146     Res = Builder.CreateSub(Res, Sign);
1147   }
1148 
1149   Res = Builder.CreateTrunc(Res, Ty);
1150 
1151   return Res;
1152 }
1153 
1154 Value *AMDGPUCodeGenPrepare::shrinkDivRem64(IRBuilder<> &Builder,
1155                                             BinaryOperator &I,
1156                                             Value *Num, Value *Den) const {
1157   if (!ExpandDiv64InIR && divHasSpecialOptimization(I, Num, Den))
1158     return nullptr;  // Keep it for later optimization.
1159 
1160   Instruction::BinaryOps Opc = I.getOpcode();
1161 
1162   bool IsDiv = Opc == Instruction::SDiv || Opc == Instruction::UDiv;
1163   bool IsSigned = Opc == Instruction::SDiv || Opc == Instruction::SRem;
1164 
1165   int NumDivBits = getDivNumBits(I, Num, Den, 32, IsSigned);
1166   if (NumDivBits == -1)
1167     return nullptr;
1168 
1169   Value *Narrowed = nullptr;
1170   if (NumDivBits <= 24) {
1171     Narrowed = expandDivRem24Impl(Builder, I, Num, Den, NumDivBits,
1172                                   IsDiv, IsSigned);
1173   } else if (NumDivBits <= 32) {
1174     Narrowed = expandDivRem32(Builder, I, Num, Den);
1175   }
1176 
1177   if (Narrowed) {
1178     return IsSigned ? Builder.CreateSExt(Narrowed, Num->getType()) :
1179                       Builder.CreateZExt(Narrowed, Num->getType());
1180   }
1181 
1182   return nullptr;
1183 }
1184 
1185 void AMDGPUCodeGenPrepare::expandDivRem64(BinaryOperator &I) const {
1186   Instruction::BinaryOps Opc = I.getOpcode();
1187   // Do the general expansion.
1188   if (Opc == Instruction::UDiv || Opc == Instruction::SDiv) {
1189     expandDivisionUpTo64Bits(&I);
1190     return;
1191   }
1192 
1193   if (Opc == Instruction::URem || Opc == Instruction::SRem) {
1194     expandRemainderUpTo64Bits(&I);
1195     return;
1196   }
1197 
1198   llvm_unreachable("not a division");
1199 }
1200 
1201 bool AMDGPUCodeGenPrepare::visitBinaryOperator(BinaryOperator &I) {
1202   if (foldBinOpIntoSelect(I))
1203     return true;
1204 
1205   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1206       DA->isUniform(&I) && promoteUniformOpToI32(I))
1207     return true;
1208 
1209   if (UseMul24Intrin && replaceMulWithMul24(I))
1210     return true;
1211 
1212   bool Changed = false;
1213   Instruction::BinaryOps Opc = I.getOpcode();
1214   Type *Ty = I.getType();
1215   Value *NewDiv = nullptr;
1216   unsigned ScalarSize = Ty->getScalarSizeInBits();
1217 
1218   SmallVector<BinaryOperator *, 8> Div64ToExpand;
1219 
1220   if ((Opc == Instruction::URem || Opc == Instruction::UDiv ||
1221        Opc == Instruction::SRem || Opc == Instruction::SDiv) &&
1222       ScalarSize <= 64 &&
1223       !DisableIDivExpand) {
1224     Value *Num = I.getOperand(0);
1225     Value *Den = I.getOperand(1);
1226     IRBuilder<> Builder(&I);
1227     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1228 
1229     if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1230       NewDiv = UndefValue::get(VT);
1231 
1232       for (unsigned N = 0, E = VT->getNumElements(); N != E; ++N) {
1233         Value *NumEltN = Builder.CreateExtractElement(Num, N);
1234         Value *DenEltN = Builder.CreateExtractElement(Den, N);
1235 
1236         Value *NewElt;
1237         if (ScalarSize <= 32) {
1238           NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN);
1239           if (!NewElt)
1240             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1241         } else {
1242           // See if this 64-bit division can be shrunk to 32/24-bits before
1243           // producing the general expansion.
1244           NewElt = shrinkDivRem64(Builder, I, NumEltN, DenEltN);
1245           if (!NewElt) {
1246             // The general 64-bit expansion introduces control flow and doesn't
1247             // return the new value. Just insert a scalar copy and defer
1248             // expanding it.
1249             NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1250             Div64ToExpand.push_back(cast<BinaryOperator>(NewElt));
1251           }
1252         }
1253 
1254         NewDiv = Builder.CreateInsertElement(NewDiv, NewElt, N);
1255       }
1256     } else {
1257       if (ScalarSize <= 32)
1258         NewDiv = expandDivRem32(Builder, I, Num, Den);
1259       else {
1260         NewDiv = shrinkDivRem64(Builder, I, Num, Den);
1261         if (!NewDiv)
1262           Div64ToExpand.push_back(&I);
1263       }
1264     }
1265 
1266     if (NewDiv) {
1267       I.replaceAllUsesWith(NewDiv);
1268       I.eraseFromParent();
1269       Changed = true;
1270     }
1271   }
1272 
1273   if (ExpandDiv64InIR) {
1274     // TODO: We get much worse code in specially handled constant cases.
1275     for (BinaryOperator *Div : Div64ToExpand) {
1276       expandDivRem64(*Div);
1277       Changed = true;
1278     }
1279   }
1280 
1281   return Changed;
1282 }
1283 
1284 bool AMDGPUCodeGenPrepare::visitLoadInst(LoadInst &I) {
1285   if (!WidenLoads)
1286     return false;
1287 
1288   if ((I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
1289        I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
1290       canWidenScalarExtLoad(I)) {
1291     IRBuilder<> Builder(&I);
1292     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1293 
1294     Type *I32Ty = Builder.getInt32Ty();
1295     Type *PT = PointerType::get(I32Ty, I.getPointerAddressSpace());
1296     Value *BitCast= Builder.CreateBitCast(I.getPointerOperand(), PT);
1297     LoadInst *WidenLoad = Builder.CreateLoad(I32Ty, BitCast);
1298     WidenLoad->copyMetadata(I);
1299 
1300     // If we have range metadata, we need to convert the type, and not make
1301     // assumptions about the high bits.
1302     if (auto *Range = WidenLoad->getMetadata(LLVMContext::MD_range)) {
1303       ConstantInt *Lower =
1304         mdconst::extract<ConstantInt>(Range->getOperand(0));
1305 
1306       if (Lower->getValue().isNullValue()) {
1307         WidenLoad->setMetadata(LLVMContext::MD_range, nullptr);
1308       } else {
1309         Metadata *LowAndHigh[] = {
1310           ConstantAsMetadata::get(ConstantInt::get(I32Ty, Lower->getValue().zext(32))),
1311           // Don't make assumptions about the high bits.
1312           ConstantAsMetadata::get(ConstantInt::get(I32Ty, 0))
1313         };
1314 
1315         WidenLoad->setMetadata(LLVMContext::MD_range,
1316                                MDNode::get(Mod->getContext(), LowAndHigh));
1317       }
1318     }
1319 
1320     int TySize = Mod->getDataLayout().getTypeSizeInBits(I.getType());
1321     Type *IntNTy = Builder.getIntNTy(TySize);
1322     Value *ValTrunc = Builder.CreateTrunc(WidenLoad, IntNTy);
1323     Value *ValOrig = Builder.CreateBitCast(ValTrunc, I.getType());
1324     I.replaceAllUsesWith(ValOrig);
1325     I.eraseFromParent();
1326     return true;
1327   }
1328 
1329   return false;
1330 }
1331 
1332 bool AMDGPUCodeGenPrepare::visitICmpInst(ICmpInst &I) {
1333   bool Changed = false;
1334 
1335   if (ST->has16BitInsts() && needsPromotionToI32(I.getOperand(0)->getType()) &&
1336       DA->isUniform(&I))
1337     Changed |= promoteUniformOpToI32(I);
1338 
1339   return Changed;
1340 }
1341 
1342 bool AMDGPUCodeGenPrepare::visitSelectInst(SelectInst &I) {
1343   bool Changed = false;
1344 
1345   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1346       DA->isUniform(&I))
1347     Changed |= promoteUniformOpToI32(I);
1348 
1349   return Changed;
1350 }
1351 
1352 bool AMDGPUCodeGenPrepare::visitIntrinsicInst(IntrinsicInst &I) {
1353   switch (I.getIntrinsicID()) {
1354   case Intrinsic::bitreverse:
1355     return visitBitreverseIntrinsicInst(I);
1356   default:
1357     return false;
1358   }
1359 }
1360 
1361 bool AMDGPUCodeGenPrepare::visitBitreverseIntrinsicInst(IntrinsicInst &I) {
1362   bool Changed = false;
1363 
1364   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1365       DA->isUniform(&I))
1366     Changed |= promoteUniformBitreverseToI32(I);
1367 
1368   return Changed;
1369 }
1370 
1371 bool AMDGPUCodeGenPrepare::doInitialization(Module &M) {
1372   Mod = &M;
1373   DL = &Mod->getDataLayout();
1374   return false;
1375 }
1376 
1377 bool AMDGPUCodeGenPrepare::runOnFunction(Function &F) {
1378   if (skipFunction(F))
1379     return false;
1380 
1381   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
1382   if (!TPC)
1383     return false;
1384 
1385   const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>();
1386   ST = &TM.getSubtarget<GCNSubtarget>(F);
1387   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1388   DA = &getAnalysis<LegacyDivergenceAnalysis>();
1389 
1390   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1391   DT = DTWP ? &DTWP->getDomTree() : nullptr;
1392 
1393   HasUnsafeFPMath = hasUnsafeFPMath(F);
1394 
1395   AMDGPU::SIModeRegisterDefaults Mode(F);
1396   HasFP32Denormals = Mode.allFP32Denormals();
1397 
1398   bool MadeChange = false;
1399 
1400   Function::iterator NextBB;
1401   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; FI = NextBB) {
1402     BasicBlock *BB = &*FI;
1403     NextBB = std::next(FI);
1404 
1405     BasicBlock::iterator Next;
1406     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; I = Next) {
1407       Next = std::next(I);
1408 
1409       MadeChange |= visit(*I);
1410 
1411       if (Next != E) { // Control flow changed
1412         BasicBlock *NextInstBB = Next->getParent();
1413         if (NextInstBB != BB) {
1414           BB = NextInstBB;
1415           E = BB->end();
1416           FE = F.end();
1417         }
1418       }
1419     }
1420   }
1421 
1422   return MadeChange;
1423 }
1424 
1425 INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE,
1426                       "AMDGPU IR optimizations", false, false)
1427 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1428 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
1429 INITIALIZE_PASS_END(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations",
1430                     false, false)
1431 
1432 char AMDGPUCodeGenPrepare::ID = 0;
1433 
1434 FunctionPass *llvm::createAMDGPUCodeGenPreparePass() {
1435   return new AMDGPUCodeGenPrepare();
1436 }
1437