1 //===- MergedLoadStoreMotion.cpp - merge and hoist/sink load/stores -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
22 // NOTE: This code no longer performs load hoisting, it is subsumed by GVNHoist.
24 //===----------------------------------------------------------------------===//
28 // Diamond shaped code before merge:
31 // br %cond, label %if.then, label %if.else
36 // %lt = load %addr_l %le = load %addr_l
37 // <use %lt> <use %le>
39 // store %st, %addr_s store %se, %addr_s
40 // br label %if.end br label %if.end
47 // Diamond shaped code after merge:
51 // br %cond, label %if.then, label %if.else
58 // br label %if.end br label %if.end
63 // %s.sink = phi [%st, if.then], [%se, if.else]
65 // store %s.sink, %addr_s
69 //===----------------------- TODO -----------------------------------------===//
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
75 //===----------------------------------------------------------------------===//
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"
93 #define DEBUG_TYPE "mldst-motion"
96 //===----------------------------------------------------------------------===//
97 // MergedLoadStoreMotion Pass
98 //===----------------------------------------------------------------------===//
99 class MergedLoadStoreMotion {
100 MemoryDependenceResults *MD = nullptr;
101 AliasAnalysis *AA = nullptr;
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;
110 bool run(Function &F, MemoryDependenceResults *MD, AliasAnalysis &AA);
114 /// \brief Remove instruction from parent and update memory dependence
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);
128 } // end anonymous namespace
131 /// \brief Remove instruction from parent and update memory dependence analysis.
133 void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) {
134 // Notify the memory dependence analysis.
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);
143 Inst->eraseFromParent();
147 /// \brief Return tail block of a diamond.
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();
155 /// \brief True when BB is the head of a diamond (hammock)
157 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
160 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
161 if (!BI || !BI->isConditional())
164 BasicBlock *Succ0 = BI->getSuccessor(0);
165 BasicBlock *Succ1 = BI->getSuccessor(1);
167 if (!Succ0->getSinglePredecessor())
169 if (!Succ1->getSinglePredecessor())
172 BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
173 BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
175 if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
182 /// \brief True when instruction is a sink barrier for a store
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.
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()))
196 return AA->canInstructionRangeModRef(Start, End, Loc, ModRefInfo::ModRef);
200 /// \brief Check if \p BB contains a store to the same address as \p SI
202 /// \return The store in \p when it is safe to sink. Otherwise return Null.
204 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
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);
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)) {
225 /// \brief Create a PHI node in BB for the operands of S0 and S1
227 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
229 // Create a phi if the values mismatch.
230 Value *Opd1 = S0->getValueOperand();
231 Value *Opd2 = S1->getValueOperand();
235 auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
237 NewPN->addIncoming(Opd1, S0->getParent());
238 NewPN->addIncoming(Opd2, S1->getParent());
239 if (MD && NewPN->getType()->isPtrOrPtrVectorTy())
240 MD->invalidateCachedPointerInfo(NewPN);
245 /// \brief Merge two stores to same address and sink into \p BB
247 /// Also sinks GEP instruction computing the store address
249 bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
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.
264 S0->dropUnknownNonDebugMetadata();
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);
272 assert(S0->getParent() == A0->getParent());
273 assert(S1->getParent() == A1->getParent());
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);
290 /// \brief True when two stores are equivalent and can sink into the footer
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.
295 bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
297 bool MergedStores = false;
298 assert(T && "Footer of a diamond cannot be empty");
300 pred_iterator PI = pred_begin(T), E = pred_end(T);
302 BasicBlock *Pred0 = *PI;
304 BasicBlock *Pred1 = *PI;
306 // tail block of a diamond/hammock?
310 return false; // No. More than 2 predecessors.
312 // #Instructions in Succ1 for Compile Time Control
313 int Size1 = Pred1->size();
316 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
319 Instruction *I = &*RBI;
322 // Don't sink non-simple (atomic, volatile) stores.
323 auto *S0 = dyn_cast<StoreInst>(I);
324 if (!S0 || !S0->isSimple())
328 if (NStores * Size1 >= MagicCompileTimeControl)
330 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
331 bool Res = sinkStore(T, S0, S1);
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.
339 RBI = Pred0->rbegin();
341 DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
347 bool MergedLoadStoreMotion::run(Function &F, MemoryDependenceResults *MD,
352 bool Changed = false;
353 DEBUG(dbgs() << "Instruction Merger\n");
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++;
360 // Hoist equivalent loads and sink stores
361 // outside diamonds when possible
362 if (isDiamondHead(BB)) {
363 Changed |= mergeStores(getDiamondTail(BB));
370 class MergedLoadStoreMotionLegacyPass : public FunctionPass {
372 static char ID; // Pass identification, replacement for typeid
373 MergedLoadStoreMotionLegacyPass() : FunctionPass(ID) {
374 initializeMergedLoadStoreMotionLegacyPassPass(
375 *PassRegistry::getPassRegistry());
379 /// \brief Run the transformation for each function
381 bool runOnFunction(Function &F) override {
384 MergedLoadStoreMotion Impl;
385 auto *MDWP = getAnalysisIfAvailable<MemoryDependenceWrapperPass>();
386 return Impl.run(F, MDWP ? &MDWP->getMemDep() : nullptr,
387 getAnalysis<AAResultsWrapperPass>().getAAResults());
391 void getAnalysisUsage(AnalysisUsage &AU) const override {
392 AU.setPreservesCFG();
393 AU.addRequired<AAResultsWrapperPass>();
394 AU.addPreserved<GlobalsAAWrapperPass>();
395 AU.addPreserved<MemoryDependenceWrapperPass>();
399 char MergedLoadStoreMotionLegacyPass::ID = 0;
400 } // anonymous namespace
403 /// \brief createMergedLoadStoreMotionPass - The public interface to this file.
405 FunctionPass *llvm::createMergedLoadStoreMotionPass() {
406 return new MergedLoadStoreMotionLegacyPass();
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)
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();
424 PreservedAnalyses PA;
425 PA.preserveSet<CFGAnalyses>();
426 PA.preserve<GlobalsAA>();
427 PA.preserve<MemoryDependenceAnalysis>();