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