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