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