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