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