1 //===- GVNHoist.cpp - Hoist scalar and load expressions -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass hoists expressions from branches to a common dominator. It uses 11 // GVN (global value numbering) to discover expressions computing the same 12 // values. The primary goals of code-hoisting are: 13 // 1. To reduce the code size. 14 // 2. In some cases reduce critical path (by exposing more ILP). 15 // 16 // Hoisting may affect the performance in some cases. To mitigate that, hoisting 17 // is disabled in the following cases. 18 // 1. Scalars across calls. 19 // 2. geps when corresponding load/store cannot be hoisted. 20 //===----------------------------------------------------------------------===// 21 22 #include "llvm/Transforms/Scalar/GVN.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/Statistic.h" 26 #include "llvm/Analysis/ValueTracking.h" 27 #include "llvm/Transforms/Scalar.h" 28 #include "llvm/Transforms/Utils/Local.h" 29 #include "llvm/Transforms/Utils/MemorySSA.h" 30 #include "llvm/Transforms/Utils/MemorySSAUpdater.h" 31 32 using namespace llvm; 33 34 #define DEBUG_TYPE "gvn-hoist" 35 36 STATISTIC(NumHoisted, "Number of instructions hoisted"); 37 STATISTIC(NumRemoved, "Number of instructions removed"); 38 STATISTIC(NumLoadsHoisted, "Number of loads hoisted"); 39 STATISTIC(NumLoadsRemoved, "Number of loads removed"); 40 STATISTIC(NumStoresHoisted, "Number of stores hoisted"); 41 STATISTIC(NumStoresRemoved, "Number of stores removed"); 42 STATISTIC(NumCallsHoisted, "Number of calls hoisted"); 43 STATISTIC(NumCallsRemoved, "Number of calls removed"); 44 45 static cl::opt<int> 46 MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1), 47 cl::desc("Max number of instructions to hoist " 48 "(default unlimited = -1)")); 49 static cl::opt<int> MaxNumberOfBBSInPath( 50 "gvn-hoist-max-bbs", cl::Hidden, cl::init(4), 51 cl::desc("Max number of basic blocks on the path between " 52 "hoisting locations (default = 4, unlimited = -1)")); 53 54 static cl::opt<int> MaxDepthInBB( 55 "gvn-hoist-max-depth", cl::Hidden, cl::init(100), 56 cl::desc("Hoist instructions from the beginning of the BB up to the " 57 "maximum specified depth (default = 100, unlimited = -1)")); 58 59 static cl::opt<int> 60 MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10), 61 cl::desc("Maximum length of dependent chains to hoist " 62 "(default = 10, unlimited = -1)")); 63 64 namespace { 65 66 // Provides a sorting function based on the execution order of two instructions. 67 struct SortByDFSIn { 68 private: 69 DenseMap<const Value *, unsigned> &DFSNumber; 70 71 public: 72 SortByDFSIn(DenseMap<const Value *, unsigned> &D) : DFSNumber(D) {} 73 74 // Returns true when A executes before B. 75 bool operator()(const Instruction *A, const Instruction *B) const { 76 // FIXME: libc++ has a std::sort() algorithm that will call the compare 77 // function on the same element. Once PR20837 is fixed and some more years 78 // pass by and all the buildbots have moved to a corrected std::sort(), 79 // enable the following assert: 80 // 81 // assert(A != B); 82 83 const BasicBlock *BA = A->getParent(); 84 const BasicBlock *BB = B->getParent(); 85 unsigned ADFS, BDFS; 86 if (BA == BB) { 87 ADFS = DFSNumber.lookup(A); 88 BDFS = DFSNumber.lookup(B); 89 } else { 90 ADFS = DFSNumber.lookup(BA); 91 BDFS = DFSNumber.lookup(BB); 92 } 93 assert(ADFS && BDFS); 94 return ADFS < BDFS; 95 } 96 }; 97 98 // A map from a pair of VNs to all the instructions with those VNs. 99 typedef DenseMap<std::pair<unsigned, unsigned>, SmallVector<Instruction *, 4>> 100 VNtoInsns; 101 // An invalid value number Used when inserting a single value number into 102 // VNtoInsns. 103 enum : unsigned { InvalidVN = ~2U }; 104 105 // Records all scalar instructions candidate for code hoisting. 106 class InsnInfo { 107 VNtoInsns VNtoScalars; 108 109 public: 110 // Inserts I and its value number in VNtoScalars. 111 void insert(Instruction *I, GVN::ValueTable &VN) { 112 // Scalar instruction. 113 unsigned V = VN.lookupOrAdd(I); 114 VNtoScalars[{V, InvalidVN}].push_back(I); 115 } 116 117 const VNtoInsns &getVNTable() const { return VNtoScalars; } 118 }; 119 120 // Records all load instructions candidate for code hoisting. 121 class LoadInfo { 122 VNtoInsns VNtoLoads; 123 124 public: 125 // Insert Load and the value number of its memory address in VNtoLoads. 126 void insert(LoadInst *Load, GVN::ValueTable &VN) { 127 if (Load->isSimple()) { 128 unsigned V = VN.lookupOrAdd(Load->getPointerOperand()); 129 VNtoLoads[{V, InvalidVN}].push_back(Load); 130 } 131 } 132 133 const VNtoInsns &getVNTable() const { return VNtoLoads; } 134 }; 135 136 // Records all store instructions candidate for code hoisting. 137 class StoreInfo { 138 VNtoInsns VNtoStores; 139 140 public: 141 // Insert the Store and a hash number of the store address and the stored 142 // value in VNtoStores. 143 void insert(StoreInst *Store, GVN::ValueTable &VN) { 144 if (!Store->isSimple()) 145 return; 146 // Hash the store address and the stored value. 147 Value *Ptr = Store->getPointerOperand(); 148 Value *Val = Store->getValueOperand(); 149 VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store); 150 } 151 152 const VNtoInsns &getVNTable() const { return VNtoStores; } 153 }; 154 155 // Records all call instructions candidate for code hoisting. 156 class CallInfo { 157 VNtoInsns VNtoCallsScalars; 158 VNtoInsns VNtoCallsLoads; 159 VNtoInsns VNtoCallsStores; 160 161 public: 162 // Insert Call and its value numbering in one of the VNtoCalls* containers. 163 void insert(CallInst *Call, GVN::ValueTable &VN) { 164 // A call that doesNotAccessMemory is handled as a Scalar, 165 // onlyReadsMemory will be handled as a Load instruction, 166 // all other calls will be handled as stores. 167 unsigned V = VN.lookupOrAdd(Call); 168 auto Entry = std::make_pair(V, InvalidVN); 169 170 if (Call->doesNotAccessMemory()) 171 VNtoCallsScalars[Entry].push_back(Call); 172 else if (Call->onlyReadsMemory()) 173 VNtoCallsLoads[Entry].push_back(Call); 174 else 175 VNtoCallsStores[Entry].push_back(Call); 176 } 177 178 const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; } 179 180 const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; } 181 182 const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; } 183 }; 184 185 typedef DenseMap<const BasicBlock *, bool> BBSideEffectsSet; 186 typedef SmallVector<Instruction *, 4> SmallVecInsn; 187 typedef SmallVectorImpl<Instruction *> SmallVecImplInsn; 188 189 static void combineKnownMetadata(Instruction *ReplInst, Instruction *I) { 190 static const unsigned KnownIDs[] = { 191 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 192 LLVMContext::MD_noalias, LLVMContext::MD_range, 193 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load, 194 LLVMContext::MD_invariant_group}; 195 combineMetadata(ReplInst, I, KnownIDs); 196 } 197 198 // This pass hoists common computations across branches sharing common 199 // dominator. The primary goal is to reduce the code size, and in some 200 // cases reduce critical path (by exposing more ILP). 201 class GVNHoist { 202 public: 203 GVNHoist(DominatorTree *DT, AliasAnalysis *AA, MemoryDependenceResults *MD, 204 MemorySSA *MSSA, bool OptForMinSize) 205 : DT(DT), AA(AA), MD(MD), MSSA(MSSA), 206 MSSAUpdater(make_unique<MemorySSAUpdater>(MSSA)), 207 OptForMinSize(OptForMinSize), HoistingGeps(OptForMinSize), 208 HoistedCtr(0) { 209 // Hoist as far as possible when optimizing for code-size. 210 if (OptForMinSize) 211 MaxNumberOfBBSInPath = -1; 212 } 213 214 bool run(Function &F) { 215 VN.setDomTree(DT); 216 VN.setAliasAnalysis(AA); 217 VN.setMemDep(MD); 218 bool Res = false; 219 // Perform DFS Numbering of instructions. 220 unsigned BBI = 0; 221 for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) { 222 DFSNumber[BB] = ++BBI; 223 unsigned I = 0; 224 for (auto &Inst : *BB) 225 DFSNumber[&Inst] = ++I; 226 } 227 228 int ChainLength = 0; 229 230 // FIXME: use lazy evaluation of VN to avoid the fix-point computation. 231 while (1) { 232 if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength) 233 return Res; 234 235 auto HoistStat = hoistExpressions(F); 236 if (HoistStat.first + HoistStat.second == 0) 237 return Res; 238 239 if (HoistStat.second > 0) 240 // To address a limitation of the current GVN, we need to rerun the 241 // hoisting after we hoisted loads or stores in order to be able to 242 // hoist all scalars dependent on the hoisted ld/st. 243 VN.clear(); 244 245 Res = true; 246 } 247 248 return Res; 249 } 250 251 private: 252 GVN::ValueTable VN; 253 DominatorTree *DT; 254 AliasAnalysis *AA; 255 MemoryDependenceResults *MD; 256 MemorySSA *MSSA; 257 std::unique_ptr<MemorySSAUpdater> MSSAUpdater; 258 const bool OptForMinSize; 259 const bool HoistingGeps; 260 DenseMap<const Value *, unsigned> DFSNumber; 261 BBSideEffectsSet BBSideEffects; 262 int HoistedCtr; 263 264 enum InsKind { Unknown, Scalar, Load, Store }; 265 266 // Return true when there are exception handling in BB. 267 bool hasEH(const BasicBlock *BB) { 268 auto It = BBSideEffects.find(BB); 269 if (It != BBSideEffects.end()) 270 return It->second; 271 272 if (BB->isEHPad() || BB->hasAddressTaken()) { 273 BBSideEffects[BB] = true; 274 return true; 275 } 276 277 if (BB->getTerminator()->mayThrow()) { 278 BBSideEffects[BB] = true; 279 return true; 280 } 281 282 BBSideEffects[BB] = false; 283 return false; 284 } 285 286 // Return true when a successor of BB dominates A. 287 bool successorDominate(const BasicBlock *BB, const BasicBlock *A) { 288 for (const BasicBlock *Succ : BB->getTerminator()->successors()) 289 if (DT->dominates(Succ, A)) 290 return true; 291 292 return false; 293 } 294 295 // Return true when all paths from HoistBB to the end of the function pass 296 // through one of the blocks in WL. 297 bool hoistingFromAllPaths(const BasicBlock *HoistBB, 298 SmallPtrSetImpl<const BasicBlock *> &WL) { 299 300 // Copy WL as the loop will remove elements from it. 301 SmallPtrSet<const BasicBlock *, 2> WorkList(WL.begin(), WL.end()); 302 303 for (auto It = df_begin(HoistBB), E = df_end(HoistBB); It != E;) { 304 // There exists a path from HoistBB to the exit of the function if we are 305 // still iterating in DF traversal and we removed all instructions from 306 // the work list. 307 if (WorkList.empty()) 308 return false; 309 310 const BasicBlock *BB = *It; 311 if (WorkList.erase(BB)) { 312 // Stop DFS traversal when BB is in the work list. 313 It.skipChildren(); 314 continue; 315 } 316 317 // Check for end of function, calls that do not return, etc. 318 if (!isGuaranteedToTransferExecutionToSuccessor(BB->getTerminator())) 319 return false; 320 321 // When reaching the back-edge of a loop, there may be a path through the 322 // loop that does not pass through B or C before exiting the loop. 323 if (successorDominate(BB, HoistBB)) 324 return false; 325 326 // Increment DFS traversal when not skipping children. 327 ++It; 328 } 329 330 return true; 331 } 332 333 /* Return true when I1 appears before I2 in the instructions of BB. */ 334 bool firstInBB(const Instruction *I1, const Instruction *I2) { 335 assert(I1->getParent() == I2->getParent()); 336 unsigned I1DFS = DFSNumber.lookup(I1); 337 unsigned I2DFS = DFSNumber.lookup(I2); 338 assert(I1DFS && I2DFS); 339 return I1DFS < I2DFS; 340 } 341 342 // Return true when there are memory uses of Def in BB. 343 bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def, 344 const BasicBlock *BB) { 345 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB); 346 if (!Acc) 347 return false; 348 349 Instruction *OldPt = Def->getMemoryInst(); 350 const BasicBlock *OldBB = OldPt->getParent(); 351 const BasicBlock *NewBB = NewPt->getParent(); 352 bool ReachedNewPt = false; 353 354 for (const MemoryAccess &MA : *Acc) 355 if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) { 356 Instruction *Insn = MU->getMemoryInst(); 357 358 // Do not check whether MU aliases Def when MU occurs after OldPt. 359 if (BB == OldBB && firstInBB(OldPt, Insn)) 360 break; 361 362 // Do not check whether MU aliases Def when MU occurs before NewPt. 363 if (BB == NewBB) { 364 if (!ReachedNewPt) { 365 if (firstInBB(Insn, NewPt)) 366 continue; 367 ReachedNewPt = true; 368 } 369 } 370 if (defClobbersUseOrDef(Def, MU, *AA)) 371 return true; 372 } 373 374 return false; 375 } 376 377 // Return true when there are exception handling or loads of memory Def 378 // between Def and NewPt. This function is only called for stores: Def is 379 // the MemoryDef of the store to be hoisted. 380 381 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and 382 // return true when the counter NBBsOnAllPaths reaces 0, except when it is 383 // initialized to -1 which is unlimited. 384 bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def, 385 int &NBBsOnAllPaths) { 386 const BasicBlock *NewBB = NewPt->getParent(); 387 const BasicBlock *OldBB = Def->getBlock(); 388 assert(DT->dominates(NewBB, OldBB) && "invalid path"); 389 assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) && 390 "def does not dominate new hoisting point"); 391 392 // Walk all basic blocks reachable in depth-first iteration on the inverse 393 // CFG from OldBB to NewBB. These blocks are all the blocks that may be 394 // executed between the execution of NewBB and OldBB. Hoisting an expression 395 // from OldBB into NewBB has to be safe on all execution paths. 396 for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) { 397 if (*I == NewBB) { 398 // Stop traversal when reaching HoistPt. 399 I.skipChildren(); 400 continue; 401 } 402 403 // Stop walk once the limit is reached. 404 if (NBBsOnAllPaths == 0) 405 return true; 406 407 // Impossible to hoist with exceptions on the path. 408 if (hasEH(*I)) 409 return true; 410 411 // Check that we do not move a store past loads. 412 if (hasMemoryUse(NewPt, Def, *I)) 413 return true; 414 415 // -1 is unlimited number of blocks on all paths. 416 if (NBBsOnAllPaths != -1) 417 --NBBsOnAllPaths; 418 419 ++I; 420 } 421 422 return false; 423 } 424 425 // Return true when there are exception handling between HoistPt and BB. 426 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and 427 // return true when the counter NBBsOnAllPaths reaches 0, except when it is 428 // initialized to -1 which is unlimited. 429 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *BB, 430 int &NBBsOnAllPaths) { 431 assert(DT->dominates(HoistPt, BB) && "Invalid path"); 432 433 // Walk all basic blocks reachable in depth-first iteration on 434 // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the 435 // blocks that may be executed between the execution of NewHoistPt and 436 // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe 437 // on all execution paths. 438 for (auto I = idf_begin(BB), E = idf_end(BB); I != E;) { 439 if (*I == HoistPt) { 440 // Stop traversal when reaching NewHoistPt. 441 I.skipChildren(); 442 continue; 443 } 444 445 // Stop walk once the limit is reached. 446 if (NBBsOnAllPaths == 0) 447 return true; 448 449 // Impossible to hoist with exceptions on the path. 450 if (hasEH(*I)) 451 return true; 452 453 // -1 is unlimited number of blocks on all paths. 454 if (NBBsOnAllPaths != -1) 455 --NBBsOnAllPaths; 456 457 ++I; 458 } 459 460 return false; 461 } 462 463 // Return true when it is safe to hoist a memory load or store U from OldPt 464 // to NewPt. 465 bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt, 466 MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths) { 467 468 // In place hoisting is safe. 469 if (NewPt == OldPt) 470 return true; 471 472 const BasicBlock *NewBB = NewPt->getParent(); 473 const BasicBlock *OldBB = OldPt->getParent(); 474 const BasicBlock *UBB = U->getBlock(); 475 476 // Check for dependences on the Memory SSA. 477 MemoryAccess *D = U->getDefiningAccess(); 478 BasicBlock *DBB = D->getBlock(); 479 if (DT->properlyDominates(NewBB, DBB)) 480 // Cannot move the load or store to NewBB above its definition in DBB. 481 return false; 482 483 if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D)) 484 if (auto *UD = dyn_cast<MemoryUseOrDef>(D)) 485 if (firstInBB(NewPt, UD->getMemoryInst())) 486 // Cannot move the load or store to NewPt above its definition in D. 487 return false; 488 489 // Check for unsafe hoistings due to side effects. 490 if (K == InsKind::Store) { 491 if (hasEHOrLoadsOnPath(NewPt, dyn_cast<MemoryDef>(U), NBBsOnAllPaths)) 492 return false; 493 } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths)) 494 return false; 495 496 if (UBB == NewBB) { 497 if (DT->properlyDominates(DBB, NewBB)) 498 return true; 499 assert(UBB == DBB); 500 assert(MSSA->locallyDominates(D, U)); 501 } 502 503 // No side effects: it is safe to hoist. 504 return true; 505 } 506 507 // Return true when it is safe to hoist scalar instructions from all blocks in 508 // WL to HoistBB. 509 bool safeToHoistScalar(const BasicBlock *HoistBB, 510 SmallPtrSetImpl<const BasicBlock *> &WL, 511 int &NBBsOnAllPaths) { 512 // Enable scalar hoisting at -Oz as it is safe to hoist scalars to a place 513 // where they are partially needed. 514 if (OptForMinSize) 515 return true; 516 517 // Check that the hoisted expression is needed on all paths. 518 if (!hoistingFromAllPaths(HoistBB, WL)) 519 return false; 520 521 for (const BasicBlock *BB : WL) 522 if (hasEHOnPath(HoistBB, BB, NBBsOnAllPaths)) 523 return false; 524 525 return true; 526 } 527 528 // Each element of a hoisting list contains the basic block where to hoist and 529 // a list of instructions to be hoisted. 530 typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo; 531 typedef SmallVector<HoistingPointInfo, 4> HoistingPointList; 532 533 // Partition InstructionsToHoist into a set of candidates which can share a 534 // common hoisting point. The partitions are collected in HPL. IsScalar is 535 // true when the instructions in InstructionsToHoist are scalars. IsLoad is 536 // true when the InstructionsToHoist are loads, false when they are stores. 537 void partitionCandidates(SmallVecImplInsn &InstructionsToHoist, 538 HoistingPointList &HPL, InsKind K) { 539 // No need to sort for two instructions. 540 if (InstructionsToHoist.size() > 2) { 541 SortByDFSIn Pred(DFSNumber); 542 std::sort(InstructionsToHoist.begin(), InstructionsToHoist.end(), Pred); 543 } 544 545 int NumBBsOnAllPaths = MaxNumberOfBBSInPath; 546 547 SmallVecImplInsn::iterator II = InstructionsToHoist.begin(); 548 SmallVecImplInsn::iterator Start = II; 549 Instruction *HoistPt = *II; 550 BasicBlock *HoistBB = HoistPt->getParent(); 551 MemoryUseOrDef *UD; 552 if (K != InsKind::Scalar) 553 UD = MSSA->getMemoryAccess(HoistPt); 554 555 for (++II; II != InstructionsToHoist.end(); ++II) { 556 Instruction *Insn = *II; 557 BasicBlock *BB = Insn->getParent(); 558 BasicBlock *NewHoistBB; 559 Instruction *NewHoistPt; 560 561 if (BB == HoistBB) { // Both are in the same Basic Block. 562 NewHoistBB = HoistBB; 563 NewHoistPt = firstInBB(Insn, HoistPt) ? Insn : HoistPt; 564 } else { 565 // If the hoisting point contains one of the instructions, 566 // then hoist there, otherwise hoist before the terminator. 567 NewHoistBB = DT->findNearestCommonDominator(HoistBB, BB); 568 if (NewHoistBB == BB) 569 NewHoistPt = Insn; 570 else if (NewHoistBB == HoistBB) 571 NewHoistPt = HoistPt; 572 else 573 NewHoistPt = NewHoistBB->getTerminator(); 574 } 575 576 SmallPtrSet<const BasicBlock *, 2> WL; 577 WL.insert(HoistBB); 578 WL.insert(BB); 579 580 if (K == InsKind::Scalar) { 581 if (safeToHoistScalar(NewHoistBB, WL, NumBBsOnAllPaths)) { 582 // Extend HoistPt to NewHoistPt. 583 HoistPt = NewHoistPt; 584 HoistBB = NewHoistBB; 585 continue; 586 } 587 } else { 588 // When NewBB already contains an instruction to be hoisted, the 589 // expression is needed on all paths. 590 // Check that the hoisted expression is needed on all paths: it is 591 // unsafe to hoist loads to a place where there may be a path not 592 // loading from the same address: for instance there may be a branch on 593 // which the address of the load may not be initialized. 594 if ((HoistBB == NewHoistBB || BB == NewHoistBB || 595 hoistingFromAllPaths(NewHoistBB, WL)) && 596 // Also check that it is safe to move the load or store from HoistPt 597 // to NewHoistPt, and from Insn to NewHoistPt. 598 safeToHoistLdSt(NewHoistPt, HoistPt, UD, K, NumBBsOnAllPaths) && 599 safeToHoistLdSt(NewHoistPt, Insn, MSSA->getMemoryAccess(Insn), 600 K, NumBBsOnAllPaths)) { 601 // Extend HoistPt to NewHoistPt. 602 HoistPt = NewHoistPt; 603 HoistBB = NewHoistBB; 604 continue; 605 } 606 } 607 608 // At this point it is not safe to extend the current hoisting to 609 // NewHoistPt: save the hoisting list so far. 610 if (std::distance(Start, II) > 1) 611 HPL.push_back({HoistBB, SmallVecInsn(Start, II)}); 612 613 // Start over from BB. 614 Start = II; 615 if (K != InsKind::Scalar) 616 UD = MSSA->getMemoryAccess(*Start); 617 HoistPt = Insn; 618 HoistBB = BB; 619 NumBBsOnAllPaths = MaxNumberOfBBSInPath; 620 } 621 622 // Save the last partition. 623 if (std::distance(Start, II) > 1) 624 HPL.push_back({HoistBB, SmallVecInsn(Start, II)}); 625 } 626 627 // Initialize HPL from Map. 628 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL, 629 InsKind K) { 630 for (const auto &Entry : Map) { 631 if (MaxHoistedThreshold != -1 && ++HoistedCtr > MaxHoistedThreshold) 632 return; 633 634 const SmallVecInsn &V = Entry.second; 635 if (V.size() < 2) 636 continue; 637 638 // Compute the insertion point and the list of expressions to be hoisted. 639 SmallVecInsn InstructionsToHoist; 640 for (auto I : V) 641 if (!hasEH(I->getParent())) 642 InstructionsToHoist.push_back(I); 643 644 if (!InstructionsToHoist.empty()) 645 partitionCandidates(InstructionsToHoist, HPL, K); 646 } 647 } 648 649 // Return true when all operands of Instr are available at insertion point 650 // HoistPt. When limiting the number of hoisted expressions, one could hoist 651 // a load without hoisting its access function. So before hoisting any 652 // expression, make sure that all its operands are available at insert point. 653 bool allOperandsAvailable(const Instruction *I, 654 const BasicBlock *HoistPt) const { 655 for (const Use &Op : I->operands()) 656 if (const auto *Inst = dyn_cast<Instruction>(&Op)) 657 if (!DT->dominates(Inst->getParent(), HoistPt)) 658 return false; 659 660 return true; 661 } 662 663 // Same as allOperandsAvailable with recursive check for GEP operands. 664 bool allGepOperandsAvailable(const Instruction *I, 665 const BasicBlock *HoistPt) const { 666 for (const Use &Op : I->operands()) 667 if (const auto *Inst = dyn_cast<Instruction>(&Op)) 668 if (!DT->dominates(Inst->getParent(), HoistPt)) { 669 if (const GetElementPtrInst *GepOp = 670 dyn_cast<GetElementPtrInst>(Inst)) { 671 if (!allGepOperandsAvailable(GepOp, HoistPt)) 672 return false; 673 // Gep is available if all operands of GepOp are available. 674 } else { 675 // Gep is not available if it has operands other than GEPs that are 676 // defined in blocks not dominating HoistPt. 677 return false; 678 } 679 } 680 return true; 681 } 682 683 // Make all operands of the GEP available. 684 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt, 685 const SmallVecInsn &InstructionsToHoist, 686 Instruction *Gep) const { 687 assert(allGepOperandsAvailable(Gep, HoistPt) && 688 "GEP operands not available"); 689 690 Instruction *ClonedGep = Gep->clone(); 691 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i) 692 if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) { 693 694 // Check whether the operand is already available. 695 if (DT->dominates(Op->getParent(), HoistPt)) 696 continue; 697 698 // As a GEP can refer to other GEPs, recursively make all the operands 699 // of this GEP available at HoistPt. 700 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op)) 701 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp); 702 } 703 704 // Copy Gep and replace its uses in Repl with ClonedGep. 705 ClonedGep->insertBefore(HoistPt->getTerminator()); 706 707 // Conservatively discard any optimization hints, they may differ on the 708 // other paths. 709 ClonedGep->dropUnknownNonDebugMetadata(); 710 711 // If we have optimization hints which agree with each other along different 712 // paths, preserve them. 713 for (const Instruction *OtherInst : InstructionsToHoist) { 714 const GetElementPtrInst *OtherGep; 715 if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst)) 716 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand()); 717 else 718 OtherGep = cast<GetElementPtrInst>( 719 cast<StoreInst>(OtherInst)->getPointerOperand()); 720 ClonedGep->andIRFlags(OtherGep); 721 } 722 723 // Replace uses of Gep with ClonedGep in Repl. 724 Repl->replaceUsesOfWith(Gep, ClonedGep); 725 } 726 727 // In the case Repl is a load or a store, we make all their GEPs 728 // available: GEPs are not hoisted by default to avoid the address 729 // computations to be hoisted without the associated load or store. 730 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt, 731 const SmallVecInsn &InstructionsToHoist) const { 732 // Check whether the GEP of a ld/st can be synthesized at HoistPt. 733 GetElementPtrInst *Gep = nullptr; 734 Instruction *Val = nullptr; 735 if (auto *Ld = dyn_cast<LoadInst>(Repl)) { 736 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand()); 737 } else if (auto *St = dyn_cast<StoreInst>(Repl)) { 738 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand()); 739 Val = dyn_cast<Instruction>(St->getValueOperand()); 740 // Check that the stored value is available. 741 if (Val) { 742 if (isa<GetElementPtrInst>(Val)) { 743 // Check whether we can compute the GEP at HoistPt. 744 if (!allGepOperandsAvailable(Val, HoistPt)) 745 return false; 746 } else if (!DT->dominates(Val->getParent(), HoistPt)) 747 return false; 748 } 749 } 750 751 // Check whether we can compute the Gep at HoistPt. 752 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt)) 753 return false; 754 755 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep); 756 757 if (Val && isa<GetElementPtrInst>(Val)) 758 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val); 759 760 return true; 761 } 762 763 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) { 764 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0; 765 for (const HoistingPointInfo &HP : HPL) { 766 // Find out whether we already have one of the instructions in HoistPt, 767 // in which case we do not have to move it. 768 BasicBlock *HoistPt = HP.first; 769 const SmallVecInsn &InstructionsToHoist = HP.second; 770 Instruction *Repl = nullptr; 771 for (Instruction *I : InstructionsToHoist) 772 if (I->getParent() == HoistPt) 773 // If there are two instructions in HoistPt to be hoisted in place: 774 // update Repl to be the first one, such that we can rename the uses 775 // of the second based on the first. 776 if (!Repl || firstInBB(I, Repl)) 777 Repl = I; 778 779 // Keep track of whether we moved the instruction so we know whether we 780 // should move the MemoryAccess. 781 bool MoveAccess = true; 782 if (Repl) { 783 // Repl is already in HoistPt: it remains in place. 784 assert(allOperandsAvailable(Repl, HoistPt) && 785 "instruction depends on operands that are not available"); 786 MoveAccess = false; 787 } else { 788 // When we do not find Repl in HoistPt, select the first in the list 789 // and move it to HoistPt. 790 Repl = InstructionsToHoist.front(); 791 792 // We can move Repl in HoistPt only when all operands are available. 793 // The order in which hoistings are done may influence the availability 794 // of operands. 795 if (!allOperandsAvailable(Repl, HoistPt)) { 796 797 // When HoistingGeps there is nothing more we can do to make the 798 // operands available: just continue. 799 if (HoistingGeps) 800 continue; 801 802 // When not HoistingGeps we need to copy the GEPs. 803 if (!makeGepOperandsAvailable(Repl, HoistPt, InstructionsToHoist)) 804 continue; 805 } 806 807 // Move the instruction at the end of HoistPt. 808 Instruction *Last = HoistPt->getTerminator(); 809 MD->removeInstruction(Repl); 810 Repl->moveBefore(Last); 811 812 DFSNumber[Repl] = DFSNumber[Last]++; 813 } 814 815 MemoryAccess *NewMemAcc = MSSA->getMemoryAccess(Repl); 816 817 if (MoveAccess) { 818 if (MemoryUseOrDef *OldMemAcc = 819 dyn_cast_or_null<MemoryUseOrDef>(NewMemAcc)) { 820 // The definition of this ld/st will not change: ld/st hoisting is 821 // legal when the ld/st is not moved past its current definition. 822 MemoryAccess *Def = OldMemAcc->getDefiningAccess(); 823 NewMemAcc = 824 MSSAUpdater->createMemoryAccessInBB(Repl, Def, HoistPt, MemorySSA::End); 825 OldMemAcc->replaceAllUsesWith(NewMemAcc); 826 MSSAUpdater->removeMemoryAccess(OldMemAcc); 827 } 828 } 829 830 if (isa<LoadInst>(Repl)) 831 ++NL; 832 else if (isa<StoreInst>(Repl)) 833 ++NS; 834 else if (isa<CallInst>(Repl)) 835 ++NC; 836 else // Scalar 837 ++NI; 838 839 // Remove and rename all other instructions. 840 for (Instruction *I : InstructionsToHoist) 841 if (I != Repl) { 842 ++NR; 843 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) { 844 ReplacementLoad->setAlignment( 845 std::min(ReplacementLoad->getAlignment(), 846 cast<LoadInst>(I)->getAlignment())); 847 ++NumLoadsRemoved; 848 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) { 849 ReplacementStore->setAlignment( 850 std::min(ReplacementStore->getAlignment(), 851 cast<StoreInst>(I)->getAlignment())); 852 ++NumStoresRemoved; 853 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) { 854 ReplacementAlloca->setAlignment( 855 std::max(ReplacementAlloca->getAlignment(), 856 cast<AllocaInst>(I)->getAlignment())); 857 } else if (isa<CallInst>(Repl)) { 858 ++NumCallsRemoved; 859 } 860 861 if (NewMemAcc) { 862 // Update the uses of the old MSSA access with NewMemAcc. 863 MemoryAccess *OldMA = MSSA->getMemoryAccess(I); 864 OldMA->replaceAllUsesWith(NewMemAcc); 865 MSSAUpdater->removeMemoryAccess(OldMA); 866 } 867 868 Repl->andIRFlags(I); 869 combineKnownMetadata(Repl, I); 870 I->replaceAllUsesWith(Repl); 871 // Also invalidate the Alias Analysis cache. 872 MD->removeInstruction(I); 873 I->eraseFromParent(); 874 } 875 876 // Remove MemorySSA phi nodes with the same arguments. 877 if (NewMemAcc) { 878 SmallPtrSet<MemoryPhi *, 4> UsePhis; 879 for (User *U : NewMemAcc->users()) 880 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U)) 881 UsePhis.insert(Phi); 882 883 for (auto *Phi : UsePhis) { 884 auto In = Phi->incoming_values(); 885 if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) { 886 Phi->replaceAllUsesWith(NewMemAcc); 887 MSSAUpdater->removeMemoryAccess(Phi); 888 } 889 } 890 } 891 } 892 893 NumHoisted += NL + NS + NC + NI; 894 NumRemoved += NR; 895 NumLoadsHoisted += NL; 896 NumStoresHoisted += NS; 897 NumCallsHoisted += NC; 898 return {NI, NL + NC + NS}; 899 } 900 901 // Hoist all expressions. Returns Number of scalars hoisted 902 // and number of non-scalars hoisted. 903 std::pair<unsigned, unsigned> hoistExpressions(Function &F) { 904 InsnInfo II; 905 LoadInfo LI; 906 StoreInfo SI; 907 CallInfo CI; 908 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) { 909 int InstructionNb = 0; 910 for (Instruction &I1 : *BB) { 911 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting 912 // deeper may increase the register pressure and compilation time. 913 if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB) 914 break; 915 916 // Do not value number terminator instructions. 917 if (isa<TerminatorInst>(&I1)) 918 break; 919 920 if (auto *Load = dyn_cast<LoadInst>(&I1)) 921 LI.insert(Load, VN); 922 else if (auto *Store = dyn_cast<StoreInst>(&I1)) 923 SI.insert(Store, VN); 924 else if (auto *Call = dyn_cast<CallInst>(&I1)) { 925 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) { 926 if (isa<DbgInfoIntrinsic>(Intr) || 927 Intr->getIntrinsicID() == Intrinsic::assume) 928 continue; 929 } 930 if (Call->mayHaveSideEffects()) { 931 if (!OptForMinSize) 932 break; 933 // We may continue hoisting across calls which write to memory. 934 if (Call->mayThrow()) 935 break; 936 } 937 938 if (Call->isConvergent()) 939 break; 940 941 CI.insert(Call, VN); 942 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1)) 943 // Do not hoist scalars past calls that may write to memory because 944 // that could result in spills later. geps are handled separately. 945 // TODO: We can relax this for targets like AArch64 as they have more 946 // registers than X86. 947 II.insert(&I1, VN); 948 } 949 } 950 951 HoistingPointList HPL; 952 computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar); 953 computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load); 954 computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store); 955 computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar); 956 computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load); 957 computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store); 958 return hoist(HPL); 959 } 960 }; 961 962 class GVNHoistLegacyPass : public FunctionPass { 963 public: 964 static char ID; 965 966 GVNHoistLegacyPass() : FunctionPass(ID) { 967 initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry()); 968 } 969 970 bool runOnFunction(Function &F) override { 971 if (skipFunction(F)) 972 return false; 973 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 974 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 975 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); 976 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); 977 978 GVNHoist G(&DT, &AA, &MD, &MSSA, F.optForMinSize()); 979 return G.run(F); 980 } 981 982 void getAnalysisUsage(AnalysisUsage &AU) const override { 983 AU.addRequired<DominatorTreeWrapperPass>(); 984 AU.addRequired<AAResultsWrapperPass>(); 985 AU.addRequired<MemoryDependenceWrapperPass>(); 986 AU.addRequired<MemorySSAWrapperPass>(); 987 AU.addPreserved<DominatorTreeWrapperPass>(); 988 AU.addPreserved<MemorySSAWrapperPass>(); 989 } 990 }; 991 } // namespace 992 993 PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) { 994 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 995 AliasAnalysis &AA = AM.getResult<AAManager>(F); 996 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F); 997 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); 998 GVNHoist G(&DT, &AA, &MD, &MSSA, F.optForMinSize()); 999 if (!G.run(F)) 1000 return PreservedAnalyses::all(); 1001 1002 PreservedAnalyses PA; 1003 PA.preserve<DominatorTreeAnalysis>(); 1004 PA.preserve<MemorySSAAnalysis>(); 1005 return PA; 1006 } 1007 1008 char GVNHoistLegacyPass::ID = 0; 1009 INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist", 1010 "Early GVN Hoisting of Expressions", false, false) 1011 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 1012 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 1013 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1014 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1015 INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist", 1016 "Early GVN Hoisting of Expressions", false, false) 1017 1018 FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); } 1019