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