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