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