xref: /llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp (revision 92c62582fc546c56b73f78402291337a24acf54e)
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 // Optimize fdiv with rcp:
610 //
611 // 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
612 //               allowed with unsafe-fp-math or afn.
613 //
614 // a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
615 static Value *optimizeWithRcp(Value *Num, Value *Den, bool AllowInaccurateRcp,
616                               bool RcpIsAccurate, IRBuilder<> Builder,
617                               Module *Mod) {
618 
619   if (!AllowInaccurateRcp && !RcpIsAccurate)
620     return nullptr;
621 
622   Type *Ty = Den->getType();
623   if (const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num)) {
624     if (AllowInaccurateRcp || RcpIsAccurate) {
625       if (CLHS->isExactlyValue(1.0)) {
626         Function *Decl = Intrinsic::getDeclaration(
627           Mod, Intrinsic::amdgcn_rcp, Ty);
628 
629         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
630         // the CI documentation has a worst case error of 1 ulp.
631         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
632         // use it as long as we aren't trying to use denormals.
633         //
634         // v_rcp_f16 and v_rsq_f16 DO support denormals.
635 
636         // NOTE: v_sqrt and v_rcp will be combined to v_rsq later. So we don't
637         //       insert rsq intrinsic here.
638 
639         // 1.0 / x -> rcp(x)
640         return Builder.CreateCall(Decl, { Den });
641       }
642 
643        // Same as for 1.0, but expand the sign out of the constant.
644       if (CLHS->isExactlyValue(-1.0)) {
645         Function *Decl = Intrinsic::getDeclaration(
646           Mod, Intrinsic::amdgcn_rcp, Ty);
647 
648          // -1.0 / x -> rcp (fneg x)
649          Value *FNeg = Builder.CreateFNeg(Den);
650          return Builder.CreateCall(Decl, { FNeg });
651        }
652     }
653   }
654 
655   if (AllowInaccurateRcp) {
656     Function *Decl = Intrinsic::getDeclaration(
657       Mod, Intrinsic::amdgcn_rcp, Ty);
658 
659     // Turn into multiply by the reciprocal.
660     // x / y -> x * (1.0 / y)
661     Value *Recip = Builder.CreateCall(Decl, { Den });
662     return Builder.CreateFMul(Num, Recip);
663   }
664   return nullptr;
665 }
666 
667 // optimize with fdiv.fast:
668 //
669 // a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
670 //
671 // 1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
672 //
673 // NOTE: optimizeWithRcp should be tried first because rcp is the preference.
674 static Value *optimizeWithFDivFast(Value *Num, Value *Den, float ReqdAccuracy,
675                                    bool HasDenormals, IRBuilder<> Builder,
676                                    Module *Mod) {
677   // fdiv.fast can achieve 2.5 ULP accuracy.
678   if (ReqdAccuracy < 2.5f)
679     return nullptr;
680 
681   // Only have fdiv.fast for f32.
682   Type *Ty = Den->getType();
683   if (!Ty->isFloatTy())
684     return nullptr;
685 
686   bool NumIsOne = false;
687   if (const ConstantFP *CNum = dyn_cast<ConstantFP>(Num)) {
688     if (CNum->isExactlyValue(+1.0) || CNum->isExactlyValue(-1.0))
689       NumIsOne = true;
690   }
691 
692   // fdiv does not support denormals. But 1.0/x is always fine to use it.
693   if (HasDenormals && !NumIsOne)
694     return nullptr;
695 
696   Function *Decl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_fdiv_fast);
697   return Builder.CreateCall(Decl, { Num, Den });
698 }
699 
700 // Optimizations is performed based on fpmath, fast math flags as well as
701 // denormals to optimize fdiv with either rcp or fdiv.fast.
702 //
703 // With rcp:
704 //   1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
705 //                 allowed with unsafe-fp-math or afn.
706 //
707 //   a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
708 //
709 // With fdiv.fast:
710 //   a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
711 //
712 //   1/x -> fdiv.fast(1,x)  when !fpmath >= 2.5ulp.
713 //
714 // NOTE: rcp is the preference in cases that both are legal.
715 bool AMDGPUCodeGenPrepare::visitFDiv(BinaryOperator &FDiv) {
716 
717   Type *Ty = FDiv.getType()->getScalarType();
718 
719   // No intrinsic for fdiv16 if target does not support f16.
720   if (Ty->isHalfTy() && !ST->has16BitInsts())
721     return false;
722 
723   const FPMathOperator *FPOp = cast<const FPMathOperator>(&FDiv);
724   const float ReqdAccuracy =  FPOp->getFPAccuracy();
725 
726   // Inaccurate rcp is allowed with unsafe-fp-math or afn.
727   FastMathFlags FMF = FPOp->getFastMathFlags();
728   const bool AllowInaccurateRcp = HasUnsafeFPMath || FMF.approxFunc();
729 
730   // rcp_f16 is accurate for !fpmath >= 1.0ulp.
731   // rcp_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
732   // rcp_f64 is never accurate.
733   const bool RcpIsAccurate = (Ty->isHalfTy() && ReqdAccuracy >= 1.0f) ||
734             (Ty->isFloatTy() && !HasFP32Denormals && ReqdAccuracy >= 1.0f);
735 
736   IRBuilder<> Builder(FDiv.getParent(), std::next(FDiv.getIterator()));
737   Builder.setFastMathFlags(FMF);
738   Builder.SetCurrentDebugLocation(FDiv.getDebugLoc());
739 
740   Value *Num = FDiv.getOperand(0);
741   Value *Den = FDiv.getOperand(1);
742 
743   Value *NewFDiv = nullptr;
744   if (VectorType *VT = dyn_cast<VectorType>(FDiv.getType())) {
745     NewFDiv = UndefValue::get(VT);
746 
747     // FIXME: Doesn't do the right thing for cases where the vector is partially
748     // constant. This works when the scalarizer pass is run first.
749     for (unsigned I = 0, E = VT->getNumElements(); I != E; ++I) {
750       Value *NumEltI = Builder.CreateExtractElement(Num, I);
751       Value *DenEltI = Builder.CreateExtractElement(Den, I);
752       // Try rcp first.
753       Value *NewElt = optimizeWithRcp(NumEltI, DenEltI, AllowInaccurateRcp,
754                                       RcpIsAccurate, Builder, Mod);
755       if (!NewElt) // Try fdiv.fast.
756         NewElt = optimizeWithFDivFast(NumEltI, DenEltI, ReqdAccuracy,
757                                       HasFP32Denormals, Builder, Mod);
758       if (!NewElt) // Keep the original.
759         NewElt = Builder.CreateFDiv(NumEltI, DenEltI);
760 
761       NewFDiv = Builder.CreateInsertElement(NewFDiv, NewElt, I);
762     }
763   } else { // Scalar FDiv.
764     // Try rcp first.
765     NewFDiv = optimizeWithRcp(Num, Den, AllowInaccurateRcp, RcpIsAccurate,
766                               Builder, Mod);
767     if (!NewFDiv) { // Try fdiv.fast.
768       NewFDiv = optimizeWithFDivFast(Num, Den, ReqdAccuracy, HasFP32Denormals,
769                                      Builder, Mod);
770     }
771   }
772 
773   if (NewFDiv) {
774     FDiv.replaceAllUsesWith(NewFDiv);
775     NewFDiv->takeName(&FDiv);
776     FDiv.eraseFromParent();
777   }
778 
779   return !!NewFDiv;
780 }
781 
782 static bool hasUnsafeFPMath(const Function &F) {
783   Attribute Attr = F.getFnAttribute("unsafe-fp-math");
784   return Attr.getValueAsString() == "true";
785 }
786 
787 static std::pair<Value*, Value*> getMul64(IRBuilder<> &Builder,
788                                           Value *LHS, Value *RHS) {
789   Type *I32Ty = Builder.getInt32Ty();
790   Type *I64Ty = Builder.getInt64Ty();
791 
792   Value *LHS_EXT64 = Builder.CreateZExt(LHS, I64Ty);
793   Value *RHS_EXT64 = Builder.CreateZExt(RHS, I64Ty);
794   Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64);
795   Value *Lo = Builder.CreateTrunc(MUL64, I32Ty);
796   Value *Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32));
797   Hi = Builder.CreateTrunc(Hi, I32Ty);
798   return std::make_pair(Lo, Hi);
799 }
800 
801 static Value* getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS) {
802   return getMul64(Builder, LHS, RHS).second;
803 }
804 
805 // The fractional part of a float is enough to accurately represent up to
806 // a 24-bit signed integer.
807 Value* AMDGPUCodeGenPrepare::expandDivRem24(IRBuilder<> &Builder,
808                                             BinaryOperator &I,
809                                             Value *Num, Value *Den,
810                                             bool IsDiv, bool IsSigned) const {
811   assert(Num->getType()->isIntegerTy(32));
812 
813   const DataLayout &DL = Mod->getDataLayout();
814   unsigned LHSSignBits = ComputeNumSignBits(Num, DL, 0, AC, &I);
815   if (LHSSignBits < 9)
816     return nullptr;
817 
818   unsigned RHSSignBits = ComputeNumSignBits(Den, DL, 0, AC, &I);
819   if (RHSSignBits < 9)
820     return nullptr;
821 
822 
823   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
824   unsigned DivBits = 32 - SignBits;
825   if (IsSigned)
826     ++DivBits;
827 
828   Type *I32Ty = Builder.getInt32Ty();
829   Type *F32Ty = Builder.getFloatTy();
830   ConstantInt *One = Builder.getInt32(1);
831   Value *JQ = One;
832 
833   if (IsSigned) {
834     // char|short jq = ia ^ ib;
835     JQ = Builder.CreateXor(Num, Den);
836 
837     // jq = jq >> (bitsize - 2)
838     JQ = Builder.CreateAShr(JQ, Builder.getInt32(30));
839 
840     // jq = jq | 0x1
841     JQ = Builder.CreateOr(JQ, One);
842   }
843 
844   // int ia = (int)LHS;
845   Value *IA = Num;
846 
847   // int ib, (int)RHS;
848   Value *IB = Den;
849 
850   // float fa = (float)ia;
851   Value *FA = IsSigned ? Builder.CreateSIToFP(IA, F32Ty)
852                        : Builder.CreateUIToFP(IA, F32Ty);
853 
854   // float fb = (float)ib;
855   Value *FB = IsSigned ? Builder.CreateSIToFP(IB,F32Ty)
856                        : Builder.CreateUIToFP(IB,F32Ty);
857 
858   Function *RcpDecl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp,
859                                                 Builder.getFloatTy());
860   Value *RCP = Builder.CreateCall(RcpDecl, { FB });
861   Value *FQM = Builder.CreateFMul(FA, RCP);
862 
863   // fq = trunc(fqm);
864   CallInst *FQ = Builder.CreateUnaryIntrinsic(Intrinsic::trunc, FQM);
865   FQ->copyFastMathFlags(Builder.getFastMathFlags());
866 
867   // float fqneg = -fq;
868   Value *FQNeg = Builder.CreateFNeg(FQ);
869 
870   // float fr = mad(fqneg, fb, fa);
871   Value *FR = Builder.CreateIntrinsic(Intrinsic::amdgcn_fmad_ftz,
872                                       {FQNeg->getType()}, {FQNeg, FB, FA}, FQ);
873 
874   // int iq = (int)fq;
875   Value *IQ = IsSigned ? Builder.CreateFPToSI(FQ, I32Ty)
876                        : Builder.CreateFPToUI(FQ, I32Ty);
877 
878   // fr = fabs(fr);
879   FR = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FR, FQ);
880 
881   // fb = fabs(fb);
882   FB = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FB, FQ);
883 
884   // int cv = fr >= fb;
885   Value *CV = Builder.CreateFCmpOGE(FR, FB);
886 
887   // jq = (cv ? jq : 0);
888   JQ = Builder.CreateSelect(CV, JQ, Builder.getInt32(0));
889 
890   // dst = iq + jq;
891   Value *Div = Builder.CreateAdd(IQ, JQ);
892 
893   Value *Res = Div;
894   if (!IsDiv) {
895     // Rem needs compensation, it's easier to recompute it
896     Value *Rem = Builder.CreateMul(Div, Den);
897     Res = Builder.CreateSub(Num, Rem);
898   }
899 
900   // Extend in register from the number of bits this divide really is.
901   if (IsSigned) {
902     Res = Builder.CreateShl(Res, 32 - DivBits);
903     Res = Builder.CreateAShr(Res, 32 - DivBits);
904   } else {
905     ConstantInt *TruncMask = Builder.getInt32((UINT64_C(1) << DivBits) - 1);
906     Res = Builder.CreateAnd(Res, TruncMask);
907   }
908 
909   return Res;
910 }
911 
912 Value* AMDGPUCodeGenPrepare::expandDivRem32(IRBuilder<> &Builder,
913                                             BinaryOperator &I,
914                                             Value *Num, Value *Den) const {
915   Instruction::BinaryOps Opc = I.getOpcode();
916   assert(Opc == Instruction::URem || Opc == Instruction::UDiv ||
917          Opc == Instruction::SRem || Opc == Instruction::SDiv);
918 
919   FastMathFlags FMF;
920   FMF.setFast();
921   Builder.setFastMathFlags(FMF);
922 
923   if (isa<Constant>(Den))
924     return nullptr; // Keep it for optimization
925 
926   bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv;
927   bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv;
928 
929   Type *Ty = Num->getType();
930   Type *I32Ty = Builder.getInt32Ty();
931   Type *F32Ty = Builder.getFloatTy();
932 
933   if (Ty->getScalarSizeInBits() < 32) {
934     if (IsSigned) {
935       Num = Builder.CreateSExt(Num, I32Ty);
936       Den = Builder.CreateSExt(Den, I32Ty);
937     } else {
938       Num = Builder.CreateZExt(Num, I32Ty);
939       Den = Builder.CreateZExt(Den, I32Ty);
940     }
941   }
942 
943   if (Value *Res = expandDivRem24(Builder, I, Num, Den, IsDiv, IsSigned)) {
944     Res = Builder.CreateTrunc(Res, Ty);
945     return Res;
946   }
947 
948   ConstantInt *Zero = Builder.getInt32(0);
949   ConstantInt *One = Builder.getInt32(1);
950   ConstantInt *MinusOne = Builder.getInt32(~0);
951 
952   Value *Sign = nullptr;
953   if (IsSigned) {
954     ConstantInt *K31 = Builder.getInt32(31);
955     Value *LHSign = Builder.CreateAShr(Num, K31);
956     Value *RHSign = Builder.CreateAShr(Den, K31);
957     // Remainder sign is the same as LHS
958     Sign = IsDiv ? Builder.CreateXor(LHSign, RHSign) : LHSign;
959 
960     Num = Builder.CreateAdd(Num, LHSign);
961     Den = Builder.CreateAdd(Den, RHSign);
962 
963     Num = Builder.CreateXor(Num, LHSign);
964     Den = Builder.CreateXor(Den, RHSign);
965   }
966 
967   // RCP =  URECIP(Den) = 2^32 / Den + e
968   // e is rounding error.
969   Value *DEN_F32 = Builder.CreateUIToFP(Den, F32Ty);
970 
971   Function *RcpDecl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp,
972                                                 Builder.getFloatTy());
973   Value *RCP_F32 = Builder.CreateCall(RcpDecl, { DEN_F32 });
974   Constant *UINT_MAX_PLUS_1 = ConstantFP::get(F32Ty, BitsToFloat(0x4f800000));
975   Value *RCP_SCALE = Builder.CreateFMul(RCP_F32, UINT_MAX_PLUS_1);
976   Value *RCP = Builder.CreateFPToUI(RCP_SCALE, I32Ty);
977 
978   // RCP_LO, RCP_HI = mul(RCP, Den) */
979   Value *RCP_LO, *RCP_HI;
980   std::tie(RCP_LO, RCP_HI) = getMul64(Builder, RCP, Den);
981 
982   // NEG_RCP_LO = -RCP_LO
983   Value *NEG_RCP_LO = Builder.CreateNeg(RCP_LO);
984 
985   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
986   Value *RCP_HI_0_CC = Builder.CreateICmpEQ(RCP_HI, Zero);
987   Value *ABS_RCP_LO = Builder.CreateSelect(RCP_HI_0_CC, NEG_RCP_LO, RCP_LO);
988 
989   // Calculate the rounding error from the URECIP instruction
990   // E = mulhu(ABS_RCP_LO, RCP)
991   Value *E = getMulHu(Builder, ABS_RCP_LO, RCP);
992 
993   // RCP_A_E = RCP + E
994   Value *RCP_A_E = Builder.CreateAdd(RCP, E);
995 
996   // RCP_S_E = RCP - E
997   Value *RCP_S_E = Builder.CreateSub(RCP, E);
998 
999   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1000   Value *Tmp0 = Builder.CreateSelect(RCP_HI_0_CC, RCP_A_E, RCP_S_E);
1001 
1002   // Quotient = mulhu(Tmp0, Num)
1003   Value *Quotient = getMulHu(Builder, Tmp0, Num);
1004 
1005   // Num_S_Remainder = Quotient * Den
1006   Value *Num_S_Remainder = Builder.CreateMul(Quotient, Den);
1007 
1008   // Remainder = Num - Num_S_Remainder
1009   Value *Remainder = Builder.CreateSub(Num, Num_S_Remainder);
1010 
1011   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1012   Value *Rem_GE_Den_CC = Builder.CreateICmpUGE(Remainder, Den);
1013   Value *Remainder_GE_Den = Builder.CreateSelect(Rem_GE_Den_CC, MinusOne, Zero);
1014 
1015   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1016   Value *Num_GE_Num_S_Rem_CC = Builder.CreateICmpUGE(Num, Num_S_Remainder);
1017   Value *Remainder_GE_Zero = Builder.CreateSelect(Num_GE_Num_S_Rem_CC,
1018                                                   MinusOne, Zero);
1019 
1020   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1021   Value *Tmp1 = Builder.CreateAnd(Remainder_GE_Den, Remainder_GE_Zero);
1022   Value *Tmp1_0_CC = Builder.CreateICmpEQ(Tmp1, Zero);
1023 
1024   Value *Res;
1025   if (IsDiv) {
1026     // Quotient_A_One = Quotient + 1
1027     Value *Quotient_A_One = Builder.CreateAdd(Quotient, One);
1028 
1029     // Quotient_S_One = Quotient - 1
1030     Value *Quotient_S_One = Builder.CreateSub(Quotient, One);
1031 
1032     // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1033     Value *Div = Builder.CreateSelect(Tmp1_0_CC, Quotient, Quotient_A_One);
1034 
1035     // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1036     Res = Builder.CreateSelect(Num_GE_Num_S_Rem_CC, Div, Quotient_S_One);
1037   } else {
1038     // Remainder_S_Den = Remainder - Den
1039     Value *Remainder_S_Den = Builder.CreateSub(Remainder, Den);
1040 
1041     // Remainder_A_Den = Remainder + Den
1042     Value *Remainder_A_Den = Builder.CreateAdd(Remainder, Den);
1043 
1044     // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1045     Value *Rem = Builder.CreateSelect(Tmp1_0_CC, Remainder, Remainder_S_Den);
1046 
1047     // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1048     Res = Builder.CreateSelect(Num_GE_Num_S_Rem_CC, Rem, Remainder_A_Den);
1049   }
1050 
1051   if (IsSigned) {
1052     Res = Builder.CreateXor(Res, Sign);
1053     Res = Builder.CreateSub(Res, Sign);
1054   }
1055 
1056   Res = Builder.CreateTrunc(Res, Ty);
1057 
1058   return Res;
1059 }
1060 
1061 bool AMDGPUCodeGenPrepare::visitBinaryOperator(BinaryOperator &I) {
1062   if (foldBinOpIntoSelect(I))
1063     return true;
1064 
1065   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1066       DA->isUniform(&I) && promoteUniformOpToI32(I))
1067     return true;
1068 
1069   if (UseMul24Intrin && replaceMulWithMul24(I))
1070     return true;
1071 
1072   bool Changed = false;
1073   Instruction::BinaryOps Opc = I.getOpcode();
1074   Type *Ty = I.getType();
1075   Value *NewDiv = nullptr;
1076   if ((Opc == Instruction::URem || Opc == Instruction::UDiv ||
1077        Opc == Instruction::SRem || Opc == Instruction::SDiv) &&
1078       Ty->getScalarSizeInBits() <= 32) {
1079     Value *Num = I.getOperand(0);
1080     Value *Den = I.getOperand(1);
1081     IRBuilder<> Builder(&I);
1082     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1083 
1084     if (VectorType *VT = dyn_cast<VectorType>(Ty)) {
1085       NewDiv = UndefValue::get(VT);
1086 
1087       for (unsigned N = 0, E = VT->getNumElements(); N != E; ++N) {
1088         Value *NumEltN = Builder.CreateExtractElement(Num, N);
1089         Value *DenEltN = Builder.CreateExtractElement(Den, N);
1090         Value *NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN);
1091         if (!NewElt)
1092           NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1093         NewDiv = Builder.CreateInsertElement(NewDiv, NewElt, N);
1094       }
1095     } else {
1096       NewDiv = expandDivRem32(Builder, I, Num, Den);
1097     }
1098 
1099     if (NewDiv) {
1100       I.replaceAllUsesWith(NewDiv);
1101       I.eraseFromParent();
1102       Changed = true;
1103     }
1104   }
1105 
1106   return Changed;
1107 }
1108 
1109 bool AMDGPUCodeGenPrepare::visitLoadInst(LoadInst &I) {
1110   if (!WidenLoads)
1111     return false;
1112 
1113   if ((I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
1114        I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
1115       canWidenScalarExtLoad(I)) {
1116     IRBuilder<> Builder(&I);
1117     Builder.SetCurrentDebugLocation(I.getDebugLoc());
1118 
1119     Type *I32Ty = Builder.getInt32Ty();
1120     Type *PT = PointerType::get(I32Ty, I.getPointerAddressSpace());
1121     Value *BitCast= Builder.CreateBitCast(I.getPointerOperand(), PT);
1122     LoadInst *WidenLoad = Builder.CreateLoad(I32Ty, BitCast);
1123     WidenLoad->copyMetadata(I);
1124 
1125     // If we have range metadata, we need to convert the type, and not make
1126     // assumptions about the high bits.
1127     if (auto *Range = WidenLoad->getMetadata(LLVMContext::MD_range)) {
1128       ConstantInt *Lower =
1129         mdconst::extract<ConstantInt>(Range->getOperand(0));
1130 
1131       if (Lower->getValue().isNullValue()) {
1132         WidenLoad->setMetadata(LLVMContext::MD_range, nullptr);
1133       } else {
1134         Metadata *LowAndHigh[] = {
1135           ConstantAsMetadata::get(ConstantInt::get(I32Ty, Lower->getValue().zext(32))),
1136           // Don't make assumptions about the high bits.
1137           ConstantAsMetadata::get(ConstantInt::get(I32Ty, 0))
1138         };
1139 
1140         WidenLoad->setMetadata(LLVMContext::MD_range,
1141                                MDNode::get(Mod->getContext(), LowAndHigh));
1142       }
1143     }
1144 
1145     int TySize = Mod->getDataLayout().getTypeSizeInBits(I.getType());
1146     Type *IntNTy = Builder.getIntNTy(TySize);
1147     Value *ValTrunc = Builder.CreateTrunc(WidenLoad, IntNTy);
1148     Value *ValOrig = Builder.CreateBitCast(ValTrunc, I.getType());
1149     I.replaceAllUsesWith(ValOrig);
1150     I.eraseFromParent();
1151     return true;
1152   }
1153 
1154   return false;
1155 }
1156 
1157 bool AMDGPUCodeGenPrepare::visitICmpInst(ICmpInst &I) {
1158   bool Changed = false;
1159 
1160   if (ST->has16BitInsts() && needsPromotionToI32(I.getOperand(0)->getType()) &&
1161       DA->isUniform(&I))
1162     Changed |= promoteUniformOpToI32(I);
1163 
1164   return Changed;
1165 }
1166 
1167 bool AMDGPUCodeGenPrepare::visitSelectInst(SelectInst &I) {
1168   bool Changed = false;
1169 
1170   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1171       DA->isUniform(&I))
1172     Changed |= promoteUniformOpToI32(I);
1173 
1174   return Changed;
1175 }
1176 
1177 bool AMDGPUCodeGenPrepare::visitIntrinsicInst(IntrinsicInst &I) {
1178   switch (I.getIntrinsicID()) {
1179   case Intrinsic::bitreverse:
1180     return visitBitreverseIntrinsicInst(I);
1181   default:
1182     return false;
1183   }
1184 }
1185 
1186 bool AMDGPUCodeGenPrepare::visitBitreverseIntrinsicInst(IntrinsicInst &I) {
1187   bool Changed = false;
1188 
1189   if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1190       DA->isUniform(&I))
1191     Changed |= promoteUniformBitreverseToI32(I);
1192 
1193   return Changed;
1194 }
1195 
1196 bool AMDGPUCodeGenPrepare::doInitialization(Module &M) {
1197   Mod = &M;
1198   DL = &Mod->getDataLayout();
1199   return false;
1200 }
1201 
1202 bool AMDGPUCodeGenPrepare::runOnFunction(Function &F) {
1203   if (skipFunction(F))
1204     return false;
1205 
1206   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
1207   if (!TPC)
1208     return false;
1209 
1210   const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>();
1211   ST = &TM.getSubtarget<GCNSubtarget>(F);
1212   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1213   DA = &getAnalysis<LegacyDivergenceAnalysis>();
1214   HasUnsafeFPMath = hasUnsafeFPMath(F);
1215   HasFP32Denormals = ST->hasFP32Denormals(F);
1216 
1217   bool MadeChange = false;
1218 
1219   for (BasicBlock &BB : F) {
1220     BasicBlock::iterator Next;
1221     for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; I = Next) {
1222       Next = std::next(I);
1223       MadeChange |= visit(*I);
1224     }
1225   }
1226 
1227   return MadeChange;
1228 }
1229 
1230 INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE,
1231                       "AMDGPU IR optimizations", false, false)
1232 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1233 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
1234 INITIALIZE_PASS_END(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations",
1235                     false, false)
1236 
1237 char AMDGPUCodeGenPrepare::ID = 0;
1238 
1239 FunctionPass *llvm::createAMDGPUCodeGenPreparePass() {
1240   return new AMDGPUCodeGenPrepare();
1241 }
1242