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