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 //! 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/ValueTracking.h"
84 #include "llvm/IR/Metadata.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include "llvm/Transforms/Scalar.h"
88 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
92 #define DEBUG_TYPE "mldst-motion"
95 //===----------------------------------------------------------------------===//
96 // MergedLoadStoreMotion Pass
97 //===----------------------------------------------------------------------===//
98 class MergedLoadStoreMotion {
99 AliasAnalysis *AA = nullptr;
101 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
102 // where Size0 and Size1 are the #instructions on the two sides of
103 // the diamond. The constant chosen here is arbitrary. Compiler Time
104 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
105 const int MagicCompileTimeControl = 250;
108 bool run(Function &F, AliasAnalysis &AA);
111 BasicBlock *getDiamondTail(BasicBlock *BB);
112 bool isDiamondHead(BasicBlock *BB);
113 // Routines for sinking stores
114 StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
115 PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
116 bool isStoreSinkBarrierInRange(const Instruction &Start,
117 const Instruction &End, MemoryLocation Loc);
118 bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
119 bool mergeStores(BasicBlock *BB);
121 } // end anonymous namespace
124 /// Return tail block of a diamond.
126 BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
127 assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
128 return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor();
132 /// True when BB is the head of a diamond (hammock)
134 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
137 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
138 if (!BI || !BI->isConditional())
141 BasicBlock *Succ0 = BI->getSuccessor(0);
142 BasicBlock *Succ1 = BI->getSuccessor(1);
144 if (!Succ0->getSinglePredecessor())
146 if (!Succ1->getSinglePredecessor())
149 BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
150 BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
152 if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
159 /// True when instruction is a sink barrier for a store
162 /// Whenever an instruction could possibly read or modify the
163 /// value being stored or protect against the store from
164 /// happening it is considered a sink barrier.
166 bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
167 const Instruction &End,
168 MemoryLocation Loc) {
169 for (const Instruction &Inst :
170 make_range(Start.getIterator(), End.getIterator()))
173 return AA->canInstructionRangeModRef(Start, End, Loc, ModRefInfo::ModRef);
177 /// Check if \p BB contains a store to the same address as \p SI
179 /// \return The store in \p when it is safe to sink. Otherwise return Null.
181 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
183 LLVM_DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
184 BasicBlock *BB0 = Store0->getParent();
185 for (Instruction &Inst : reverse(*BB1)) {
186 auto *Store1 = dyn_cast<StoreInst>(&Inst);
190 MemoryLocation Loc0 = MemoryLocation::get(Store0);
191 MemoryLocation Loc1 = MemoryLocation::get(Store1);
192 if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
193 !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1) &&
194 !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0)) {
202 /// Create a PHI node in BB for the operands of S0 and S1
204 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
206 // Create a phi if the values mismatch.
207 Value *Opd1 = S0->getValueOperand();
208 Value *Opd2 = S1->getValueOperand();
212 auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
214 NewPN->applyMergedLocation(S0->getDebugLoc(), S1->getDebugLoc());
215 NewPN->addIncoming(Opd1, S0->getParent());
216 NewPN->addIncoming(Opd2, S1->getParent());
221 /// Merge two stores to same address and sink into \p BB
223 /// Also sinks GEP instruction computing the store address
225 bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
227 // Only one definition?
228 auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
229 auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
230 if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
231 (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
232 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
233 LLVM_DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
234 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
235 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
236 // Hoist the instruction.
237 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
238 // Intersect optional metadata.
240 S0->dropUnknownNonDebugMetadata();
242 // Create the new store to be inserted at the join point.
243 StoreInst *SNew = cast<StoreInst>(S0->clone());
244 Instruction *ANew = A0->clone();
245 SNew->insertBefore(&*InsertPt);
246 ANew->insertBefore(SNew);
248 assert(S0->getParent() == A0->getParent());
249 assert(S1->getParent() == A1->getParent());
251 // New PHI operand? Use it.
252 if (PHINode *NewPN = getPHIOperand(BB, S0, S1))
253 SNew->setOperand(0, NewPN);
254 S0->eraseFromParent();
255 S1->eraseFromParent();
256 A0->replaceAllUsesWith(ANew);
257 A0->eraseFromParent();
258 A1->replaceAllUsesWith(ANew);
259 A1->eraseFromParent();
266 /// True when two stores are equivalent and can sink into the footer
268 /// Starting from a diamond tail block, iterate over the instructions in one
269 /// predecessor block and try to match a store in the second predecessor.
271 bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
273 bool MergedStores = false;
274 assert(T && "Footer of a diamond cannot be empty");
276 pred_iterator PI = pred_begin(T), E = pred_end(T);
278 BasicBlock *Pred0 = *PI;
280 BasicBlock *Pred1 = *PI;
282 // tail block of a diamond/hammock?
286 return false; // No. More than 2 predecessors.
288 // #Instructions in Succ1 for Compile Time Control
289 auto InstsNoDbg = Pred1->instructionsWithoutDebug();
290 int Size1 = std::distance(InstsNoDbg.begin(), InstsNoDbg.end());
293 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
296 Instruction *I = &*RBI;
299 // Don't sink non-simple (atomic, volatile) stores.
300 auto *S0 = dyn_cast<StoreInst>(I);
301 if (!S0 || !S0->isSimple())
305 if (NStores * Size1 >= MagicCompileTimeControl)
307 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
308 bool Res = sinkStore(T, S0, S1);
310 // Don't attempt to sink below stores that had to stick around
311 // But after removal of a store and some of its feeding
312 // instruction search again from the beginning since the iterator
313 // is likely stale at this point.
316 RBI = Pred0->rbegin();
318 LLVM_DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
324 bool MergedLoadStoreMotion::run(Function &F, AliasAnalysis &AA) {
327 bool Changed = false;
328 LLVM_DEBUG(dbgs() << "Instruction Merger\n");
330 // Merge unconditional branches, allowing PRE to catch more
331 // optimization opportunities.
332 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
333 BasicBlock *BB = &*FI++;
335 // Hoist equivalent loads and sink stores
336 // outside diamonds when possible
337 if (isDiamondHead(BB)) {
338 Changed |= mergeStores(getDiamondTail(BB));
345 class MergedLoadStoreMotionLegacyPass : public FunctionPass {
347 static char ID; // Pass identification, replacement for typeid
348 MergedLoadStoreMotionLegacyPass() : FunctionPass(ID) {
349 initializeMergedLoadStoreMotionLegacyPassPass(
350 *PassRegistry::getPassRegistry());
354 /// Run the transformation for each function
356 bool runOnFunction(Function &F) override {
359 MergedLoadStoreMotion Impl;
360 return Impl.run(F, getAnalysis<AAResultsWrapperPass>().getAAResults());
364 void getAnalysisUsage(AnalysisUsage &AU) const override {
365 AU.setPreservesCFG();
366 AU.addRequired<AAResultsWrapperPass>();
367 AU.addPreserved<GlobalsAAWrapperPass>();
371 char MergedLoadStoreMotionLegacyPass::ID = 0;
372 } // anonymous namespace
375 /// createMergedLoadStoreMotionPass - The public interface to this file.
377 FunctionPass *llvm::createMergedLoadStoreMotionPass() {
378 return new MergedLoadStoreMotionLegacyPass();
381 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion",
382 "MergedLoadStoreMotion", false, false)
383 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
384 INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion",
385 "MergedLoadStoreMotion", false, false)
388 MergedLoadStoreMotionPass::run(Function &F, FunctionAnalysisManager &AM) {
389 MergedLoadStoreMotion Impl;
390 auto &AA = AM.getResult<AAManager>(F);
391 if (!Impl.run(F, AA))
392 return PreservedAnalyses::all();
394 PreservedAnalyses PA;
395 PA.preserveSet<CFGAnalyses>();
396 PA.preserve<GlobalsAA>();