1 //===- MergedLoadStoreMotion.cpp - merge and hoist/sink load/stores -------===// 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 //! \file 11 //! \brief This pass performs merges of loads and stores on both sides of a 12 // diamond (hammock). It hoists the loads and sinks the stores. 13 // 14 // The algorithm iteratively hoists two loads to the same address out of a 15 // diamond (hammock) and merges them into a single load in the header. Similar 16 // it sinks and merges two stores to the tail block (footer). The algorithm 17 // iterates over the instructions of one side of the diamond and attempts to 18 // find a matching load/store on the other side. It hoists / sinks when it 19 // thinks it safe to do so. This optimization helps with eg. hiding load 20 // latencies, triggering if-conversion, and reducing static code size. 21 // 22 //===----------------------------------------------------------------------===// 23 // 24 // 25 // Example: 26 // Diamond shaped code before merge: 27 // 28 // header: 29 // br %cond, label %if.then, label %if.else 30 // + + 31 // + + 32 // + + 33 // if.then: if.else: 34 // %lt = load %addr_l %le = load %addr_l 35 // <use %lt> <use %le> 36 // <...> <...> 37 // store %st, %addr_s store %se, %addr_s 38 // br label %if.end br label %if.end 39 // + + 40 // + + 41 // + + 42 // if.end ("footer"): 43 // <...> 44 // 45 // Diamond shaped code after merge: 46 // 47 // header: 48 // %l = load %addr_l 49 // br %cond, label %if.then, label %if.else 50 // + + 51 // + + 52 // + + 53 // if.then: if.else: 54 // <use %l> <use %l> 55 // <...> <...> 56 // br label %if.end br label %if.end 57 // + + 58 // + + 59 // + + 60 // if.end ("footer"): 61 // %s.sink = phi [%st, if.then], [%se, if.else] 62 // <...> 63 // store %s.sink, %addr_s 64 // <...> 65 // 66 // 67 //===----------------------- TODO -----------------------------------------===// 68 // 69 // 1) Generalize to regions other than diamonds 70 // 2) Be more aggressive merging memory operations 71 // Note that both changes require register pressure control 72 // 73 //===----------------------------------------------------------------------===// 74 75 #include "llvm/Transforms/Scalar.h" 76 #include "llvm/ADT/SetVector.h" 77 #include "llvm/ADT/SmallPtrSet.h" 78 #include "llvm/ADT/Statistic.h" 79 #include "llvm/Analysis/AliasAnalysis.h" 80 #include "llvm/Analysis/CFG.h" 81 #include "llvm/Analysis/Loads.h" 82 #include "llvm/Analysis/MemoryBuiltins.h" 83 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 84 #include "llvm/IR/Metadata.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/Support/Allocator.h" 87 #include "llvm/Support/CommandLine.h" 88 #include "llvm/Support/Debug.h" 89 #include "llvm/Target/TargetLibraryInfo.h" 90 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 91 #include "llvm/Transforms/Utils/SSAUpdater.h" 92 #include <vector> 93 using namespace llvm; 94 95 #define DEBUG_TYPE "mldst-motion" 96 97 //===----------------------------------------------------------------------===// 98 // MergedLoadStoreMotion Pass 99 //===----------------------------------------------------------------------===// 100 101 namespace { 102 class MergedLoadStoreMotion : public FunctionPass { 103 AliasAnalysis *AA; 104 MemoryDependenceAnalysis *MD; 105 106 public: 107 static char ID; // Pass identification, replacement for typeid 108 explicit MergedLoadStoreMotion(void) 109 : FunctionPass(ID), MD(nullptr), MagicCompileTimeControl(250) { 110 initializeMergedLoadStoreMotionPass(*PassRegistry::getPassRegistry()); 111 } 112 113 bool runOnFunction(Function &F) override; 114 115 private: 116 // This transformation requires dominator postdominator info 117 void getAnalysisUsage(AnalysisUsage &AU) const override { 118 AU.addRequired<TargetLibraryInfo>(); 119 AU.addRequired<MemoryDependenceAnalysis>(); 120 AU.addRequired<AliasAnalysis>(); 121 AU.addPreserved<AliasAnalysis>(); 122 } 123 124 // Helper routines 125 126 /// 127 /// \brief Remove instruction from parent and update memory dependence 128 /// analysis. 129 /// 130 void removeInstruction(Instruction *Inst); 131 BasicBlock *getDiamondTail(BasicBlock *BB); 132 bool isDiamondHead(BasicBlock *BB); 133 // Routines for hoisting loads 134 bool isLoadHoistBarrierInRange(const Instruction& Start, 135 const Instruction& End, 136 LoadInst* LI); 137 LoadInst *canHoistFromBlock(BasicBlock *BB, LoadInst *LI); 138 void hoistInstruction(BasicBlock *BB, Instruction *HoistCand, 139 Instruction *ElseInst); 140 bool isSafeToHoist(Instruction *I) const; 141 bool hoistLoad(BasicBlock *BB, LoadInst *HoistCand, LoadInst *ElseInst); 142 bool mergeLoads(BasicBlock *BB); 143 // Routines for sinking stores 144 StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI); 145 PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1); 146 bool isStoreSinkBarrier(Instruction *Inst); 147 bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst); 148 bool mergeStores(BasicBlock *BB); 149 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity, 150 // where Size0 and Size1 are the #instructions on the two sides of 151 // the diamond. The constant chosen here is arbitrary. Compiler Time 152 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl. 153 const int MagicCompileTimeControl; 154 }; 155 156 char MergedLoadStoreMotion::ID = 0; 157 } 158 159 /// 160 /// \brief createMergedLoadStoreMotionPass - The public interface to this file. 161 /// 162 FunctionPass *llvm::createMergedLoadStoreMotionPass() { 163 return new MergedLoadStoreMotion(); 164 } 165 166 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotion, "mldst-motion", 167 "MergedLoadStoreMotion", false, false) 168 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis) 169 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo) 170 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 171 INITIALIZE_PASS_END(MergedLoadStoreMotion, "mldst-motion", 172 "MergedLoadStoreMotion", false, false) 173 174 /// 175 /// \brief Remove instruction from parent and update memory dependence analysis. 176 /// 177 void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) { 178 // Notify the memory dependence analysis. 179 if (MD) { 180 MD->removeInstruction(Inst); 181 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) 182 MD->invalidateCachedPointerInfo(LI->getPointerOperand()); 183 if (Inst->getType()->getScalarType()->isPointerTy()) { 184 MD->invalidateCachedPointerInfo(Inst); 185 } 186 } 187 Inst->eraseFromParent(); 188 } 189 190 /// 191 /// \brief Return tail block of a diamond. 192 /// 193 BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) { 194 assert(isDiamondHead(BB) && "Basic block is not head of a diamond"); 195 BranchInst *BI = (BranchInst *)(BB->getTerminator()); 196 BasicBlock *Succ0 = BI->getSuccessor(0); 197 BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0); 198 return Tail; 199 } 200 201 /// 202 /// \brief True when BB is the head of a diamond (hammock) 203 /// 204 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) { 205 if (!BB) 206 return false; 207 if (!isa<BranchInst>(BB->getTerminator())) 208 return false; 209 if (BB->getTerminator()->getNumSuccessors() != 2) 210 return false; 211 212 BranchInst *BI = (BranchInst *)(BB->getTerminator()); 213 BasicBlock *Succ0 = BI->getSuccessor(0); 214 BasicBlock *Succ1 = BI->getSuccessor(1); 215 216 if (!Succ0->getSinglePredecessor() || 217 Succ0->getTerminator()->getNumSuccessors() != 1) 218 return false; 219 if (!Succ1->getSinglePredecessor() || 220 Succ1->getTerminator()->getNumSuccessors() != 1) 221 return false; 222 223 BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0); 224 // Ignore triangles. 225 if (Succ1->getTerminator()->getSuccessor(0) != Tail) 226 return false; 227 return true; 228 } 229 230 /// 231 /// \brief True when instruction is a hoist barrier for a load 232 /// 233 /// Whenever an instruction could possibly modify the value 234 /// being loaded or protect against the load from happening 235 /// it is considered a hoist barrier. 236 /// 237 238 bool MergedLoadStoreMotion::isLoadHoistBarrierInRange(const Instruction& Start, 239 const Instruction& End, 240 LoadInst* LI) { 241 AliasAnalysis::Location Loc = AA->getLocation(LI); 242 return AA->canInstructionRangeModify(Start, End, Loc); 243 } 244 245 /// 246 /// \brief Decide if a load can be hoisted 247 /// 248 /// When there is a load in \p BB to the same address as \p LI 249 /// and it can be hoisted from \p BB, return that load. 250 /// Otherwise return Null. 251 /// 252 LoadInst *MergedLoadStoreMotion::canHoistFromBlock(BasicBlock *BB1, 253 LoadInst *Load0) { 254 255 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE; 256 ++BBI) { 257 Instruction *Inst = BBI; 258 259 // Only merge and hoist loads when their result in used only in BB 260 if (!isa<LoadInst>(Inst) || Inst->isUsedOutsideOfBlock(BB1)) 261 continue; 262 263 LoadInst *Load1 = dyn_cast<LoadInst>(Inst); 264 BasicBlock *BB0 = Load0->getParent(); 265 266 AliasAnalysis::Location Loc0 = AA->getLocation(Load0); 267 AliasAnalysis::Location Loc1 = AA->getLocation(Load1); 268 if (AA->isMustAlias(Loc0, Loc1) && Load0->isSameOperationAs(Load1) && 269 !isLoadHoistBarrierInRange(BB1->front(), *Load1, Load1) && 270 !isLoadHoistBarrierInRange(BB0->front(), *Load0, Load0)) { 271 return Load1; 272 } 273 } 274 return nullptr; 275 } 276 277 /// 278 /// \brief Merge two equivalent instructions \p HoistCand and \p ElseInst into 279 /// \p BB 280 /// 281 /// BB is the head of a diamond 282 /// 283 void MergedLoadStoreMotion::hoistInstruction(BasicBlock *BB, 284 Instruction *HoistCand, 285 Instruction *ElseInst) { 286 DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump(); 287 dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n"; 288 dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n"); 289 // Hoist the instruction. 290 assert(HoistCand->getParent() != BB); 291 292 // Intersect optional metadata. 293 HoistCand->intersectOptionalDataWith(ElseInst); 294 HoistCand->dropUnknownMetadata(); 295 296 // Prepend point for instruction insert 297 Instruction *HoistPt = BB->getTerminator(); 298 299 // Merged instruction 300 Instruction *HoistedInst = HoistCand->clone(); 301 302 // Notify AA of the new value. 303 if (isa<LoadInst>(HoistCand)) 304 AA->copyValue(HoistCand, HoistedInst); 305 306 // Hoist instruction. 307 HoistedInst->insertBefore(HoistPt); 308 309 HoistCand->replaceAllUsesWith(HoistedInst); 310 removeInstruction(HoistCand); 311 // Replace the else block instruction. 312 ElseInst->replaceAllUsesWith(HoistedInst); 313 removeInstruction(ElseInst); 314 } 315 316 /// 317 /// \brief Return true if no operand of \p I is defined in I's parent block 318 /// 319 bool MergedLoadStoreMotion::isSafeToHoist(Instruction *I) const { 320 BasicBlock *Parent = I->getParent(); 321 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 322 Instruction *Instr = dyn_cast<Instruction>(I->getOperand(i)); 323 if (Instr && Instr->getParent() == Parent) 324 return false; 325 } 326 return true; 327 } 328 329 /// 330 /// \brief Merge two equivalent loads and GEPs and hoist into diamond head 331 /// 332 bool MergedLoadStoreMotion::hoistLoad(BasicBlock *BB, LoadInst *L0, 333 LoadInst *L1) { 334 // Only one definition? 335 Instruction *A0 = dyn_cast<Instruction>(L0->getPointerOperand()); 336 Instruction *A1 = dyn_cast<Instruction>(L1->getPointerOperand()); 337 if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) && 338 A0->hasOneUse() && (A0->getParent() == L0->getParent()) && 339 A1->hasOneUse() && (A1->getParent() == L1->getParent()) && 340 isa<GetElementPtrInst>(A0)) { 341 DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump(); 342 dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n"; 343 dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n"); 344 hoistInstruction(BB, A0, A1); 345 hoistInstruction(BB, L0, L1); 346 return true; 347 } else 348 return false; 349 } 350 351 /// 352 /// \brief Try to hoist two loads to same address into diamond header 353 /// 354 /// Starting from a diamond head block, iterate over the instructions in one 355 /// successor block and try to match a load in the second successor. 356 /// 357 bool MergedLoadStoreMotion::mergeLoads(BasicBlock *BB) { 358 bool MergedLoads = false; 359 assert(isDiamondHead(BB)); 360 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); 361 BasicBlock *Succ0 = BI->getSuccessor(0); 362 BasicBlock *Succ1 = BI->getSuccessor(1); 363 // #Instructions in Succ1 for Compile Time Control 364 int Size1 = Succ1->size(); 365 int NLoads = 0; 366 for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end(); 367 BBI != BBE;) { 368 369 Instruction *I = BBI; 370 ++BBI; 371 372 // Only move non-simple (atomic, volatile) loads. 373 LoadInst *L0 = dyn_cast<LoadInst>(I); 374 if (!L0 || !L0->isSimple() || L0->isUsedOutsideOfBlock(Succ0)) 375 continue; 376 377 ++NLoads; 378 if (NLoads * Size1 >= MagicCompileTimeControl) 379 break; 380 if (LoadInst *L1 = canHoistFromBlock(Succ1, L0)) { 381 bool Res = hoistLoad(BB, L0, L1); 382 MergedLoads |= Res; 383 // Don't attempt to hoist above loads that had not been hoisted. 384 if (!Res) 385 break; 386 } 387 } 388 return MergedLoads; 389 } 390 391 /// 392 /// \brief True when instruction is sink barrier for a store 393 /// 394 bool MergedLoadStoreMotion::isStoreSinkBarrier(Instruction *Inst) { 395 // FIXME: Conservatively let a load instruction block the store. 396 // Use alias analysis instead. 397 if (isa<LoadInst>(Inst)) 398 return true; 399 if (isa<CallInst>(Inst)) 400 return true; 401 if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst)) 402 return true; 403 // Note: mayHaveSideEffects covers all instructions that could 404 // trigger a change to state. Eg. in-flight stores have to be executed 405 // before ordered loads or fences, calls could invoke functions that store 406 // data to memory etc. 407 if (!isa<StoreInst>(Inst) && Inst->mayHaveSideEffects()) { 408 return true; 409 } 410 DEBUG(dbgs() << "No Sink Barrier\n"); 411 return false; 412 } 413 414 /// 415 /// \brief Check if \p BB contains a store to the same address as \p SI 416 /// 417 /// \return The store in \p when it is safe to sink. Otherwise return Null. 418 /// 419 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB, 420 StoreInst *SI) { 421 StoreInst *I = 0; 422 DEBUG(dbgs() << "can Sink? : "; SI->dump(); dbgs() << "\n"); 423 for (BasicBlock::reverse_iterator RBI = BB->rbegin(), RBE = BB->rend(); 424 RBI != RBE; ++RBI) { 425 Instruction *Inst = &*RBI; 426 427 // Only move loads if they are used in the block. 428 if (isStoreSinkBarrier(Inst)) 429 break; 430 if (isa<StoreInst>(Inst)) { 431 AliasAnalysis::Location LocSI = AA->getLocation(SI); 432 AliasAnalysis::Location LocInst = AA->getLocation((StoreInst *)Inst); 433 if (AA->isMustAlias(LocSI, LocInst)) { 434 I = (StoreInst *)Inst; 435 break; 436 } 437 } 438 } 439 return I; 440 } 441 442 /// 443 /// \brief Create a PHI node in BB for the operands of S0 and S1 444 /// 445 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0, 446 StoreInst *S1) { 447 // Create a phi if the values mismatch. 448 PHINode *NewPN = 0; 449 Value *Opd1 = S0->getValueOperand(); 450 Value *Opd2 = S1->getValueOperand(); 451 if (Opd1 != Opd2) { 452 NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink", 453 BB->begin()); 454 NewPN->addIncoming(Opd1, S0->getParent()); 455 NewPN->addIncoming(Opd2, S1->getParent()); 456 if (NewPN->getType()->getScalarType()->isPointerTy()) { 457 // Notify AA of the new value. 458 AA->copyValue(Opd1, NewPN); 459 AA->copyValue(Opd2, NewPN); 460 // AA needs to be informed when a PHI-use of the pointer value is added 461 for (unsigned I = 0, E = NewPN->getNumIncomingValues(); I != E; ++I) { 462 unsigned J = PHINode::getOperandNumForIncomingValue(I); 463 AA->addEscapingUse(NewPN->getOperandUse(J)); 464 } 465 if (MD) 466 MD->invalidateCachedPointerInfo(NewPN); 467 } 468 } 469 return NewPN; 470 } 471 472 /// 473 /// \brief Merge two stores to same address and sink into \p BB 474 /// 475 /// Also sinks GEP instruction computing the store address 476 /// 477 bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0, 478 StoreInst *S1) { 479 // Only one definition? 480 Instruction *A0 = dyn_cast<Instruction>(S0->getPointerOperand()); 481 Instruction *A1 = dyn_cast<Instruction>(S1->getPointerOperand()); 482 if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() && 483 (A0->getParent() == S0->getParent()) && A1->hasOneUse() && 484 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) { 485 DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump(); 486 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n"; 487 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n"); 488 // Hoist the instruction. 489 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt(); 490 // Intersect optional metadata. 491 S0->intersectOptionalDataWith(S1); 492 S0->dropUnknownMetadata(); 493 494 // Create the new store to be inserted at the join point. 495 StoreInst *SNew = (StoreInst *)(S0->clone()); 496 Instruction *ANew = A0->clone(); 497 AA->copyValue(S0, SNew); 498 SNew->insertBefore(InsertPt); 499 ANew->insertBefore(SNew); 500 501 assert(S0->getParent() == A0->getParent()); 502 assert(S1->getParent() == A1->getParent()); 503 504 PHINode *NewPN = getPHIOperand(BB, S0, S1); 505 // New PHI operand? Use it. 506 if (NewPN) 507 SNew->setOperand(0, NewPN); 508 removeInstruction(S0); 509 removeInstruction(S1); 510 A0->replaceAllUsesWith(ANew); 511 removeInstruction(A0); 512 A1->replaceAllUsesWith(ANew); 513 removeInstruction(A1); 514 return true; 515 } 516 return false; 517 } 518 519 /// 520 /// \brief True when two stores are equivalent and can sink into the footer 521 /// 522 /// Starting from a diamond tail block, iterate over the instructions in one 523 /// predecessor block and try to match a store in the second predecessor. 524 /// 525 bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) { 526 527 bool MergedStores = false; 528 assert(T && "Footer of a diamond cannot be empty"); 529 530 pred_iterator PI = pred_begin(T), E = pred_end(T); 531 assert(PI != E); 532 BasicBlock *Pred0 = *PI; 533 ++PI; 534 BasicBlock *Pred1 = *PI; 535 ++PI; 536 // tail block of a diamond/hammock? 537 if (Pred0 == Pred1) 538 return false; // No. 539 if (PI != E) 540 return false; // No. More than 2 predecessors. 541 542 // #Instructions in Succ1 for Compile Time Control 543 int Size1 = Pred1->size(); 544 int NStores = 0; 545 546 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend(); 547 RBI != RBE;) { 548 549 Instruction *I = &*RBI; 550 ++RBI; 551 if (isStoreSinkBarrier(I)) 552 break; 553 // Sink move non-simple (atomic, volatile) stores 554 if (!isa<StoreInst>(I)) 555 continue; 556 StoreInst *S0 = (StoreInst *)I; 557 if (!S0->isSimple()) 558 continue; 559 560 ++NStores; 561 if (NStores * Size1 >= MagicCompileTimeControl) 562 break; 563 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) { 564 bool Res = sinkStore(T, S0, S1); 565 MergedStores |= Res; 566 // Don't attempt to sink below stores that had to stick around 567 // But after removal of a store and some of its feeding 568 // instruction search again from the beginning since the iterator 569 // is likely stale at this point. 570 if (!Res) 571 break; 572 else { 573 RBI = Pred0->rbegin(); 574 RBE = Pred0->rend(); 575 DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump()); 576 } 577 } 578 } 579 return MergedStores; 580 } 581 /// 582 /// \brief Run the transformation for each function 583 /// 584 bool MergedLoadStoreMotion::runOnFunction(Function &F) { 585 MD = &getAnalysis<MemoryDependenceAnalysis>(); 586 AA = &getAnalysis<AliasAnalysis>(); 587 588 bool Changed = false; 589 DEBUG(dbgs() << "Instruction Merger\n"); 590 591 // Merge unconditional branches, allowing PRE to catch more 592 // optimization opportunities. 593 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) { 594 BasicBlock *BB = FI++; 595 596 // Hoist equivalent loads and sink stores 597 // outside diamonds when possible 598 if (isDiamondHead(BB)) { 599 Changed |= mergeLoads(BB); 600 Changed |= mergeStores(getDiamondTail(BB)); 601 } 602 } 603 return Changed; 604 } 605