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 //===----------------------------------------------------------------------===//
26 // Diamond shaped code before merge:
29 // br %cond, label %if.then, label %if.else
34 // %lt = load %addr_l %le = load %addr_l
35 // <use %lt> <use %le>
37 // store %st, %addr_s store %se, %addr_s
38 // br label %if.end br label %if.end
45 // Diamond shaped code after merge:
49 // br %cond, label %if.then, label %if.else
56 // br label %if.end br label %if.end
61 // %s.sink = phi [%st, if.then], [%se, if.else]
63 // store %s.sink, %addr_s
67 //===----------------------- TODO -----------------------------------------===//
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
73 //===----------------------------------------------------------------------===//
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/IR/Metadata.h"
85 #include "llvm/IR/PatternMatch.h"
86 #include "llvm/Support/Allocator.h"
87 #include "llvm/Support/CommandLine.h"
88 #include "llvm/Support/Debug.h"
89 #include "llvm/Target/TargetLibraryInfo.h"
90 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
91 #include "llvm/Transforms/Utils/SSAUpdater.h"
95 #define DEBUG_TYPE "mldst-motion"
97 //===----------------------------------------------------------------------===//
98 // MergedLoadStoreMotion Pass
99 //===----------------------------------------------------------------------===//
101 EnableMLSM("mlsm", cl::desc("Enable motion of merged load and store"),
105 class MergedLoadStoreMotion : public FunctionPass {
107 MemoryDependenceAnalysis *MD;
110 static char ID; // Pass identification, replacement for typeid
111 explicit MergedLoadStoreMotion(void)
112 : FunctionPass(ID), MD(nullptr), MagicCompileTimeControl(250) {
113 initializeMergedLoadStoreMotionPass(*PassRegistry::getPassRegistry());
116 bool runOnFunction(Function &F) override;
119 // This transformation requires dominator postdominator info
120 void getAnalysisUsage(AnalysisUsage &AU) const override {
121 AU.addRequired<TargetLibraryInfo>();
122 AU.addRequired<MemoryDependenceAnalysis>();
123 AU.addRequired<AliasAnalysis>();
124 AU.addPreserved<AliasAnalysis>();
130 /// \brief Remove instruction from parent and update memory dependence
133 void removeInstruction(Instruction *Inst);
134 BasicBlock *getDiamondTail(BasicBlock *BB);
135 bool isDiamondHead(BasicBlock *BB);
136 // Routines for hoisting loads
137 bool isLoadHoistBarrier(Instruction *Inst);
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 isStoreSinkBarrier(Instruction *Inst);
148 bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
149 bool mergeStores(BasicBlock *BB);
150 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
151 // where Size0 and Size1 are the #instructions on the two sides of
152 // the diamond. The constant chosen here is arbitrary. Compiler Time
153 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
154 const int MagicCompileTimeControl;
157 char MergedLoadStoreMotion::ID = 0;
161 /// \brief createMergedLoadStoreMotionPass - The public interface to this file.
163 FunctionPass *llvm::createMergedLoadStoreMotionPass() {
164 return new MergedLoadStoreMotion();
167 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotion, "mldst-motion",
168 "MergedLoadStoreMotion", false, false)
169 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
170 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
171 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
172 INITIALIZE_PASS_END(MergedLoadStoreMotion, "mldst-motion",
173 "MergedLoadStoreMotion", false, false)
176 /// \brief Remove instruction from parent and update memory dependence analysis.
178 void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) {
179 // Notify the memory dependence analysis.
181 MD->removeInstruction(Inst);
182 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
183 MD->invalidateCachedPointerInfo(LI->getPointerOperand());
184 if (Inst->getType()->getScalarType()->isPointerTy()) {
185 MD->invalidateCachedPointerInfo(Inst);
188 Inst->eraseFromParent();
192 /// \brief Return tail block of a diamond.
194 BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
195 assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
196 BranchInst *BI = (BranchInst *)(BB->getTerminator());
197 BasicBlock *Succ0 = BI->getSuccessor(0);
198 BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
203 /// \brief True when BB is the head of a diamond (hammock)
205 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
208 if (!isa<BranchInst>(BB->getTerminator()))
210 if (BB->getTerminator()->getNumSuccessors() != 2)
213 BranchInst *BI = (BranchInst *)(BB->getTerminator());
214 BasicBlock *Succ0 = BI->getSuccessor(0);
215 BasicBlock *Succ1 = BI->getSuccessor(1);
217 if (!Succ0->getSinglePredecessor() ||
218 Succ0->getTerminator()->getNumSuccessors() != 1)
220 if (!Succ1->getSinglePredecessor() ||
221 Succ1->getTerminator()->getNumSuccessors() != 1)
224 BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
226 if (Succ1->getTerminator()->getSuccessor(0) != Tail)
232 /// \brief True when instruction is a hoist barrier for a load
234 /// Whenever an instruction could possibly modify the value
235 /// being loaded or protect against the load from happening
236 /// it is considered a hoist barrier.
238 bool MergedLoadStoreMotion::isLoadHoistBarrier(Instruction *Inst) {
239 // FIXME: A call with no side effects should not be a barrier.
240 // Aren't all such calls covered by mayHaveSideEffects() below?
241 // Then this check can be removed.
242 if (isa<CallInst>(Inst))
244 if (isa<TerminatorInst>(Inst))
246 // Note: mayHaveSideEffects covers all instructions that could
247 // trigger a change to state. Eg. in-flight stores have to be executed
248 // before ordered loads or fences, calls could invoke functions that store
249 // data to memory etc.
250 if (Inst->mayHaveSideEffects()) {
253 DEBUG(dbgs() << "No Hoist Barrier\n");
258 /// \brief Decide if a load can be hoisted
260 /// When there is a load in \p BB to the same address as \p LI
261 /// and it can be hoisted from \p BB, return that load.
262 /// Otherwise return Null.
264 LoadInst *MergedLoadStoreMotion::canHoistFromBlock(BasicBlock *BB,
266 LoadInst *I = nullptr;
267 assert(isa<LoadInst>(LI));
268 if (LI->isUsedOutsideOfBlock(LI->getParent()))
271 for (BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); BBI != BBE;
273 Instruction *Inst = BBI;
275 // Only merge and hoist loads when their result in used only in BB
276 if (isLoadHoistBarrier(Inst))
278 if (!isa<LoadInst>(Inst))
280 if (Inst->isUsedOutsideOfBlock(Inst->getParent()))
283 AliasAnalysis::Location LocLI = AA->getLocation(LI);
284 AliasAnalysis::Location LocInst = AA->getLocation((LoadInst *)Inst);
285 if (AA->isMustAlias(LocLI, LocInst) && LI->getType() == Inst->getType()) {
286 I = (LoadInst *)Inst;
294 /// \brief Merge two equivalent instructions \p HoistCand and \p ElseInst into
297 /// BB is the head of a diamond
299 void MergedLoadStoreMotion::hoistInstruction(BasicBlock *BB,
300 Instruction *HoistCand,
301 Instruction *ElseInst) {
302 DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump();
303 dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n";
304 dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n");
305 // Hoist the instruction.
306 assert(HoistCand->getParent() != BB);
308 // Intersect optional metadata.
309 HoistCand->intersectOptionalDataWith(ElseInst);
310 HoistCand->dropUnknownMetadata();
312 // Prepend point for instruction insert
313 Instruction *HoistPt = BB->getTerminator();
315 // Merged instruction
316 Instruction *HoistedInst = HoistCand->clone();
318 // Notify AA of the new value.
319 if (isa<LoadInst>(HoistCand))
320 AA->copyValue(HoistCand, HoistedInst);
322 // Hoist instruction.
323 HoistedInst->insertBefore(HoistPt);
325 HoistCand->replaceAllUsesWith(HoistedInst);
326 removeInstruction(HoistCand);
327 // Replace the else block instruction.
328 ElseInst->replaceAllUsesWith(HoistedInst);
329 removeInstruction(ElseInst);
333 /// \brief Return true if no operand of \p I is defined in I's parent block
335 bool MergedLoadStoreMotion::isSafeToHoist(Instruction *I) const {
336 BasicBlock *Parent = I->getParent();
337 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
338 Instruction *Instr = dyn_cast<Instruction>(I->getOperand(i));
339 if (Instr && Instr->getParent() == Parent)
346 /// \brief Merge two equivalent loads and GEPs and hoist into diamond head
348 bool MergedLoadStoreMotion::hoistLoad(BasicBlock *BB, LoadInst *L0,
350 // Only one definition?
351 Instruction *A0 = dyn_cast<Instruction>(L0->getPointerOperand());
352 Instruction *A1 = dyn_cast<Instruction>(L1->getPointerOperand());
353 if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) &&
354 A0->hasOneUse() && (A0->getParent() == L0->getParent()) &&
355 A1->hasOneUse() && (A1->getParent() == L1->getParent()) &&
356 isa<GetElementPtrInst>(A0)) {
357 DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump();
358 dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n";
359 dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n");
360 hoistInstruction(BB, A0, A1);
361 hoistInstruction(BB, L0, L1);
368 /// \brief Try to hoist two loads to same address into diamond header
370 /// Starting from a diamond head block, iterate over the instructions in one
371 /// successor block and try to match a load in the second successor.
373 bool MergedLoadStoreMotion::mergeLoads(BasicBlock *BB) {
374 bool MergedLoads = false;
375 assert(isDiamondHead(BB));
376 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
377 BasicBlock *Succ0 = BI->getSuccessor(0);
378 BasicBlock *Succ1 = BI->getSuccessor(1);
379 // #Instructions in Succ1 for Compile Time Control
380 int Size1 = Succ1->size();
382 for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
385 Instruction *I = BBI;
387 if (isLoadHoistBarrier(I))
390 // Only move non-simple (atomic, volatile) loads.
391 if (!isa<LoadInst>(I))
394 LoadInst *L0 = (LoadInst *)I;
399 if (NLoads * Size1 >= MagicCompileTimeControl)
401 if (LoadInst *L1 = canHoistFromBlock(Succ1, L0)) {
402 bool Res = hoistLoad(BB, L0, L1);
404 // Don't attempt to hoist above loads that had not been hoisted.
413 /// \brief True when instruction is sink barrier for a store
415 bool MergedLoadStoreMotion::isStoreSinkBarrier(Instruction *Inst) {
416 if (isa<CallInst>(Inst))
418 if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst))
420 // Note: mayHaveSideEffects covers all instructions that could
421 // trigger a change to state. Eg. in-flight stores have to be executed
422 // before ordered loads or fences, calls could invoke functions that store
423 // data to memory etc.
424 if (!isa<StoreInst>(Inst) && Inst->mayHaveSideEffects()) {
427 DEBUG(dbgs() << "No Sink Barrier\n");
432 /// \brief Check if \p BB contains a store to the same address as \p SI
434 /// \return The store in \p when it is safe to sink. Otherwise return Null.
436 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB,
439 DEBUG(dbgs() << "can Sink? : "; SI->dump(); dbgs() << "\n");
440 for (BasicBlock::reverse_iterator RBI = BB->rbegin(), RBE = BB->rend();
442 Instruction *Inst = &*RBI;
444 // Only move loads if they are used in the block.
445 if (isStoreSinkBarrier(Inst))
447 if (isa<StoreInst>(Inst)) {
448 AliasAnalysis::Location LocSI = AA->getLocation(SI);
449 AliasAnalysis::Location LocInst = AA->getLocation((StoreInst *)Inst);
450 if (AA->isMustAlias(LocSI, LocInst)) {
451 I = (StoreInst *)Inst;
460 /// \brief Create a PHI node in BB for the operands of S0 and S1
462 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
464 // Create a phi if the values mismatch.
466 Value *Opd1 = S0->getValueOperand();
467 Value *Opd2 = S1->getValueOperand();
469 NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
471 NewPN->addIncoming(Opd1, S0->getParent());
472 NewPN->addIncoming(Opd2, S1->getParent());
473 if (NewPN->getType()->getScalarType()->isPointerTy()) {
474 // Notify AA of the new value.
475 AA->copyValue(Opd1, NewPN);
476 AA->copyValue(Opd2, NewPN);
477 // AA needs to be informed when a PHI-use of the pointer value is added
478 for (unsigned I = 0, E = NewPN->getNumIncomingValues(); I != E; ++I) {
479 unsigned J = PHINode::getOperandNumForIncomingValue(I);
480 AA->addEscapingUse(NewPN->getOperandUse(J));
483 MD->invalidateCachedPointerInfo(NewPN);
490 /// \brief Merge two stores to same address and sink into \p BB
492 /// Also sinks GEP instruction computing the store address
494 bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
496 // Only one definition?
497 Instruction *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
498 Instruction *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
499 if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
500 (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
501 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
502 DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
503 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
504 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
505 // Hoist the instruction.
506 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
507 // Intersect optional metadata.
508 S0->intersectOptionalDataWith(S1);
509 S0->dropUnknownMetadata();
511 // Create the new store to be inserted at the join point.
512 StoreInst *SNew = (StoreInst *)(S0->clone());
513 Instruction *ANew = A0->clone();
514 AA->copyValue(S0, SNew);
515 SNew->insertBefore(InsertPt);
516 ANew->insertBefore(SNew);
518 assert(S0->getParent() == A0->getParent());
519 assert(S1->getParent() == A1->getParent());
521 PHINode *NewPN = getPHIOperand(BB, S0, S1);
522 // New PHI operand? Use it.
524 SNew->setOperand(0, NewPN);
525 removeInstruction(S0);
526 removeInstruction(S1);
527 A0->replaceAllUsesWith(ANew);
528 removeInstruction(A0);
529 A1->replaceAllUsesWith(ANew);
530 removeInstruction(A1);
537 /// \brief True when two stores are equivalent and can sink into the footer
539 /// Starting from a diamond tail block, iterate over the instructions in one
540 /// predecessor block and try to match a store in the second predecessor.
542 bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
544 bool MergedStores = false;
545 assert(T && "Footer of a diamond cannot be empty");
547 pred_iterator PI = pred_begin(T), E = pred_end(T);
549 BasicBlock *Pred0 = *PI;
551 BasicBlock *Pred1 = *PI;
553 // tail block of a diamond/hammock?
557 return false; // No. More than 2 predecessors.
559 // #Instructions in Succ1 for Compile Time Control
560 int Size1 = Pred1->size();
563 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
566 Instruction *I = &*RBI;
568 if (isStoreSinkBarrier(I))
570 // Sink move non-simple (atomic, volatile) stores
571 if (!isa<StoreInst>(I))
573 StoreInst *S0 = (StoreInst *)I;
578 if (NStores * Size1 >= MagicCompileTimeControl)
580 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
581 bool Res = sinkStore(T, S0, S1);
583 // Don't attempt to sink below stores that had to stick around
584 // But after removal of a store and some of its feeding
585 // instruction search again from the beginning since the iterator
586 // is likely stale at this point.
590 RBI = Pred0->rbegin();
592 DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
599 /// \brief Run the transformation for each function
601 bool MergedLoadStoreMotion::runOnFunction(Function &F) {
602 MD = &getAnalysis<MemoryDependenceAnalysis>();
603 AA = &getAnalysis<AliasAnalysis>();
605 bool Changed = false;
608 DEBUG(dbgs() << "Instruction Merger\n");
610 // Merge unconditional branches, allowing PRE to catch more
611 // optimization opportunities.
612 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
613 BasicBlock *BB = FI++;
615 // Hoist equivalent loads and sink stores
616 // outside diamonds when possible
617 // Run outside core GVN
618 if (isDiamondHead(BB)) {
619 Changed |= mergeLoads(BB);
620 Changed |= mergeStores(getDiamondTail(BB));