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 // NOTE: This code no longer performs load hoisting, it is subsumed by GVNHoist. 23 // 24 //===----------------------------------------------------------------------===// 25 // 26 // 27 // Example: 28 // Diamond shaped code before merge: 29 // 30 // header: 31 // br %cond, label %if.then, label %if.else 32 // + + 33 // + + 34 // + + 35 // if.then: if.else: 36 // %lt = load %addr_l %le = load %addr_l 37 // <use %lt> <use %le> 38 // <...> <...> 39 // store %st, %addr_s store %se, %addr_s 40 // br label %if.end br label %if.end 41 // + + 42 // + + 43 // + + 44 // if.end ("footer"): 45 // <...> 46 // 47 // Diamond shaped code after merge: 48 // 49 // header: 50 // %l = load %addr_l 51 // br %cond, label %if.then, label %if.else 52 // + + 53 // + + 54 // + + 55 // if.then: if.else: 56 // <use %l> <use %l> 57 // <...> <...> 58 // br label %if.end br label %if.end 59 // + + 60 // + + 61 // + + 62 // if.end ("footer"): 63 // %s.sink = phi [%st, if.then], [%se, if.else] 64 // <...> 65 // store %s.sink, %addr_s 66 // <...> 67 // 68 // 69 //===----------------------- TODO -----------------------------------------===// 70 // 71 // 1) Generalize to regions other than diamonds 72 // 2) Be more aggressive merging memory operations 73 // Note that both changes require register pressure control 74 // 75 //===----------------------------------------------------------------------===// 76 77 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h" 78 #include "llvm/ADT/Statistic.h" 79 #include "llvm/Analysis/AliasAnalysis.h" 80 #include "llvm/Analysis/CFG.h" 81 #include "llvm/Analysis/GlobalsModRef.h" 82 #include "llvm/Analysis/Loads.h" 83 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 84 #include "llvm/Analysis/ValueTracking.h" 85 #include "llvm/IR/Metadata.h" 86 #include "llvm/Support/Debug.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include "llvm/Transforms/Scalar.h" 89 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 90 91 using namespace llvm; 92 93 #define DEBUG_TYPE "mldst-motion" 94 95 namespace { 96 //===----------------------------------------------------------------------===// 97 // MergedLoadStoreMotion Pass 98 //===----------------------------------------------------------------------===// 99 class MergedLoadStoreMotion { 100 MemoryDependenceResults *MD = nullptr; 101 AliasAnalysis *AA = nullptr; 102 103 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity, 104 // where Size0 and Size1 are the #instructions on the two sides of 105 // the diamond. The constant chosen here is arbitrary. Compiler Time 106 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl. 107 const int MagicCompileTimeControl = 250; 108 109 public: 110 bool run(Function &F, MemoryDependenceResults *MD, AliasAnalysis &AA); 111 112 private: 113 /// 114 /// \brief Remove instruction from parent and update memory dependence 115 /// analysis. 116 /// 117 void removeInstruction(Instruction *Inst); 118 BasicBlock *getDiamondTail(BasicBlock *BB); 119 bool isDiamondHead(BasicBlock *BB); 120 // Routines for sinking stores 121 StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI); 122 PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1); 123 bool isStoreSinkBarrierInRange(const Instruction &Start, 124 const Instruction &End, MemoryLocation Loc); 125 bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst); 126 bool mergeStores(BasicBlock *BB); 127 }; 128 } // end anonymous namespace 129 130 /// 131 /// \brief Remove instruction from parent and update memory dependence analysis. 132 /// 133 void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) { 134 // Notify the memory dependence analysis. 135 if (MD) { 136 MD->removeInstruction(Inst); 137 if (auto *LI = dyn_cast<LoadInst>(Inst)) 138 MD->invalidateCachedPointerInfo(LI->getPointerOperand()); 139 if (Inst->getType()->isPtrOrPtrVectorTy()) { 140 MD->invalidateCachedPointerInfo(Inst); 141 } 142 } 143 Inst->eraseFromParent(); 144 } 145 146 /// 147 /// \brief Return tail block of a diamond. 148 /// 149 BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) { 150 assert(isDiamondHead(BB) && "Basic block is not head of a diamond"); 151 return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor(); 152 } 153 154 /// 155 /// \brief True when BB is the head of a diamond (hammock) 156 /// 157 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) { 158 if (!BB) 159 return false; 160 auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 161 if (!BI || !BI->isConditional()) 162 return false; 163 164 BasicBlock *Succ0 = BI->getSuccessor(0); 165 BasicBlock *Succ1 = BI->getSuccessor(1); 166 167 if (!Succ0->getSinglePredecessor()) 168 return false; 169 if (!Succ1->getSinglePredecessor()) 170 return false; 171 172 BasicBlock *Succ0Succ = Succ0->getSingleSuccessor(); 173 BasicBlock *Succ1Succ = Succ1->getSingleSuccessor(); 174 // Ignore triangles. 175 if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ) 176 return false; 177 return true; 178 } 179 180 181 /// 182 /// \brief True when instruction is a sink barrier for a store 183 /// located in Loc 184 /// 185 /// Whenever an instruction could possibly read or modify the 186 /// value being stored or protect against the store from 187 /// happening it is considered a sink barrier. 188 /// 189 bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start, 190 const Instruction &End, 191 MemoryLocation Loc) { 192 for (const Instruction &Inst : 193 make_range(Start.getIterator(), End.getIterator())) 194 if (Inst.mayThrow()) 195 return true; 196 return AA->canInstructionRangeModRef(Start, End, Loc, ModRefInfo::ModRef); 197 } 198 199 /// 200 /// \brief Check if \p BB contains a store to the same address as \p SI 201 /// 202 /// \return The store in \p when it is safe to sink. Otherwise return Null. 203 /// 204 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1, 205 StoreInst *Store0) { 206 DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n"); 207 BasicBlock *BB0 = Store0->getParent(); 208 for (Instruction &Inst : reverse(*BB1)) { 209 auto *Store1 = dyn_cast<StoreInst>(&Inst); 210 if (!Store1) 211 continue; 212 213 MemoryLocation Loc0 = MemoryLocation::get(Store0); 214 MemoryLocation Loc1 = MemoryLocation::get(Store1); 215 if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) && 216 !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1) && 217 !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0)) { 218 return Store1; 219 } 220 } 221 return nullptr; 222 } 223 224 /// 225 /// \brief Create a PHI node in BB for the operands of S0 and S1 226 /// 227 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0, 228 StoreInst *S1) { 229 // Create a phi if the values mismatch. 230 Value *Opd1 = S0->getValueOperand(); 231 Value *Opd2 = S1->getValueOperand(); 232 if (Opd1 == Opd2) 233 return nullptr; 234 235 auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink", 236 &BB->front()); 237 NewPN->addIncoming(Opd1, S0->getParent()); 238 NewPN->addIncoming(Opd2, S1->getParent()); 239 if (MD && NewPN->getType()->isPtrOrPtrVectorTy()) 240 MD->invalidateCachedPointerInfo(NewPN); 241 return NewPN; 242 } 243 244 /// 245 /// \brief Merge two stores to same address and sink into \p BB 246 /// 247 /// Also sinks GEP instruction computing the store address 248 /// 249 bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0, 250 StoreInst *S1) { 251 // Only one definition? 252 auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand()); 253 auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand()); 254 if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() && 255 (A0->getParent() == S0->getParent()) && A1->hasOneUse() && 256 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) { 257 DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump(); 258 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n"; 259 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n"); 260 // Hoist the instruction. 261 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt(); 262 // Intersect optional metadata. 263 S0->andIRFlags(S1); 264 S0->dropUnknownNonDebugMetadata(); 265 266 // Create the new store to be inserted at the join point. 267 StoreInst *SNew = cast<StoreInst>(S0->clone()); 268 Instruction *ANew = A0->clone(); 269 SNew->insertBefore(&*InsertPt); 270 ANew->insertBefore(SNew); 271 272 assert(S0->getParent() == A0->getParent()); 273 assert(S1->getParent() == A1->getParent()); 274 275 // New PHI operand? Use it. 276 if (PHINode *NewPN = getPHIOperand(BB, S0, S1)) 277 SNew->setOperand(0, NewPN); 278 removeInstruction(S0); 279 removeInstruction(S1); 280 A0->replaceAllUsesWith(ANew); 281 removeInstruction(A0); 282 A1->replaceAllUsesWith(ANew); 283 removeInstruction(A1); 284 return true; 285 } 286 return false; 287 } 288 289 /// 290 /// \brief True when two stores are equivalent and can sink into the footer 291 /// 292 /// Starting from a diamond tail block, iterate over the instructions in one 293 /// predecessor block and try to match a store in the second predecessor. 294 /// 295 bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) { 296 297 bool MergedStores = false; 298 assert(T && "Footer of a diamond cannot be empty"); 299 300 pred_iterator PI = pred_begin(T), E = pred_end(T); 301 assert(PI != E); 302 BasicBlock *Pred0 = *PI; 303 ++PI; 304 BasicBlock *Pred1 = *PI; 305 ++PI; 306 // tail block of a diamond/hammock? 307 if (Pred0 == Pred1) 308 return false; // No. 309 if (PI != E) 310 return false; // No. More than 2 predecessors. 311 312 // #Instructions in Succ1 for Compile Time Control 313 int Size1 = Pred1->size(); 314 int NStores = 0; 315 316 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend(); 317 RBI != RBE;) { 318 319 Instruction *I = &*RBI; 320 ++RBI; 321 322 // Don't sink non-simple (atomic, volatile) stores. 323 auto *S0 = dyn_cast<StoreInst>(I); 324 if (!S0 || !S0->isSimple()) 325 continue; 326 327 ++NStores; 328 if (NStores * Size1 >= MagicCompileTimeControl) 329 break; 330 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) { 331 bool Res = sinkStore(T, S0, S1); 332 MergedStores |= Res; 333 // Don't attempt to sink below stores that had to stick around 334 // But after removal of a store and some of its feeding 335 // instruction search again from the beginning since the iterator 336 // is likely stale at this point. 337 if (!Res) 338 break; 339 RBI = Pred0->rbegin(); 340 RBE = Pred0->rend(); 341 DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump()); 342 } 343 } 344 return MergedStores; 345 } 346 347 bool MergedLoadStoreMotion::run(Function &F, MemoryDependenceResults *MD, 348 AliasAnalysis &AA) { 349 this->MD = MD; 350 this->AA = &AA; 351 352 bool Changed = false; 353 DEBUG(dbgs() << "Instruction Merger\n"); 354 355 // Merge unconditional branches, allowing PRE to catch more 356 // optimization opportunities. 357 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) { 358 BasicBlock *BB = &*FI++; 359 360 // Hoist equivalent loads and sink stores 361 // outside diamonds when possible 362 if (isDiamondHead(BB)) { 363 Changed |= mergeStores(getDiamondTail(BB)); 364 } 365 } 366 return Changed; 367 } 368 369 namespace { 370 class MergedLoadStoreMotionLegacyPass : public FunctionPass { 371 public: 372 static char ID; // Pass identification, replacement for typeid 373 MergedLoadStoreMotionLegacyPass() : FunctionPass(ID) { 374 initializeMergedLoadStoreMotionLegacyPassPass( 375 *PassRegistry::getPassRegistry()); 376 } 377 378 /// 379 /// \brief Run the transformation for each function 380 /// 381 bool runOnFunction(Function &F) override { 382 if (skipFunction(F)) 383 return false; 384 MergedLoadStoreMotion Impl; 385 auto *MDWP = getAnalysisIfAvailable<MemoryDependenceWrapperPass>(); 386 return Impl.run(F, MDWP ? &MDWP->getMemDep() : nullptr, 387 getAnalysis<AAResultsWrapperPass>().getAAResults()); 388 } 389 390 private: 391 void getAnalysisUsage(AnalysisUsage &AU) const override { 392 AU.setPreservesCFG(); 393 AU.addRequired<AAResultsWrapperPass>(); 394 AU.addPreserved<GlobalsAAWrapperPass>(); 395 AU.addPreserved<MemoryDependenceWrapperPass>(); 396 } 397 }; 398 399 char MergedLoadStoreMotionLegacyPass::ID = 0; 400 } // anonymous namespace 401 402 /// 403 /// \brief createMergedLoadStoreMotionPass - The public interface to this file. 404 /// 405 FunctionPass *llvm::createMergedLoadStoreMotionPass() { 406 return new MergedLoadStoreMotionLegacyPass(); 407 } 408 409 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion", 410 "MergedLoadStoreMotion", false, false) 411 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 412 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 413 INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion", 414 "MergedLoadStoreMotion", false, false) 415 416 PreservedAnalyses 417 MergedLoadStoreMotionPass::run(Function &F, FunctionAnalysisManager &AM) { 418 MergedLoadStoreMotion Impl; 419 auto *MD = AM.getCachedResult<MemoryDependenceAnalysis>(F); 420 auto &AA = AM.getResult<AAManager>(F); 421 if (!Impl.run(F, MD, AA)) 422 return PreservedAnalyses::all(); 423 424 PreservedAnalyses PA; 425 PA.preserveSet<CFGAnalyses>(); 426 PA.preserve<GlobalsAA>(); 427 PA.preserve<MemoryDependenceAnalysis>(); 428 return PA; 429 } 430