LLVM  11.0.0git
MergedLoadStoreMotion.cpp
Go to the documentation of this file.
1 //===- MergedLoadStoreMotion.cpp - merge and hoist/sink load/stores -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //! \file
10 //! This pass performs merges of loads and stores on both sides of a
11 // diamond (hammock). It hoists the loads and sinks the stores.
12 //
13 // The algorithm iteratively hoists two loads to the same address out of a
14 // diamond (hammock) and merges them into a single load in the header. Similar
15 // it sinks and merges two stores to the tail block (footer). The algorithm
16 // iterates over the instructions of one side of the diamond and attempts to
17 // find a matching load/store on the other side. New tail/footer block may be
18 // insterted if the tail/footer block has more predecessors (not only the two
19 // predecessors that are forming the diamond). It hoists / sinks when it thinks
20 // it safe to do so. This optimization helps with eg. hiding load latencies,
21 // triggering if-conversion, and reducing static code size.
22 //
23 // NOTE: This code no longer performs load hoisting, it is subsumed by GVNHoist.
24 //
25 //===----------------------------------------------------------------------===//
26 //
27 //
28 // Example:
29 // Diamond shaped code before merge:
30 //
31 // header:
32 // br %cond, label %if.then, label %if.else
33 // + +
34 // + +
35 // + +
36 // if.then: if.else:
37 // %lt = load %addr_l %le = load %addr_l
38 // <use %lt> <use %le>
39 // <...> <...>
40 // store %st, %addr_s store %se, %addr_s
41 // br label %if.end br label %if.end
42 // + +
43 // + +
44 // + +
45 // if.end ("footer"):
46 // <...>
47 //
48 // Diamond shaped code after merge:
49 //
50 // header:
51 // %l = load %addr_l
52 // br %cond, label %if.then, label %if.else
53 // + +
54 // + +
55 // + +
56 // if.then: if.else:
57 // <use %l> <use %l>
58 // <...> <...>
59 // br label %if.end br label %if.end
60 // + +
61 // + +
62 // + +
63 // if.end ("footer"):
64 // %s.sink = phi [%st, if.then], [%se, if.else]
65 // <...>
66 // store %s.sink, %addr_s
67 // <...>
68 //
69 //
70 //===----------------------- TODO -----------------------------------------===//
71 //
72 // 1) Generalize to regions other than diamonds
73 // 2) Be more aggressive merging memory operations
74 // Note that both changes require register pressure control
75 //
76 //===----------------------------------------------------------------------===//
77 
79 #include "llvm/ADT/Statistic.h"
81 #include "llvm/Analysis/CFG.h"
83 #include "llvm/Analysis/Loads.h"
85 #include "llvm/IR/Metadata.h"
86 #include "llvm/InitializePasses.h"
87 #include "llvm/Support/Debug.h"
89 #include "llvm/Transforms/Scalar.h"
91 
92 using namespace llvm;
93 
94 #define DEBUG_TYPE "mldst-motion"
95 
96 namespace {
97 //===----------------------------------------------------------------------===//
98 // MergedLoadStoreMotion Pass
99 //===----------------------------------------------------------------------===//
100 class MergedLoadStoreMotion {
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  const bool SplitFooterBB;
110 public:
111  MergedLoadStoreMotion(bool SplitFooterBB) : SplitFooterBB(SplitFooterBB) {}
112  bool run(Function &F, AliasAnalysis &AA);
113 
114 private:
115  BasicBlock *getDiamondTail(BasicBlock *BB);
116  bool isDiamondHead(BasicBlock *BB);
117  // Routines for sinking stores
118  StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
119  PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
120  bool isStoreSinkBarrierInRange(const Instruction &Start,
121  const Instruction &End, MemoryLocation Loc);
122  bool canSinkStoresAndGEPs(StoreInst *S0, StoreInst *S1) const;
123  void sinkStoresAndGEPs(BasicBlock *BB, StoreInst *SinkCand,
124  StoreInst *ElseInst);
125  bool mergeStores(BasicBlock *BB);
126 };
127 } // end anonymous namespace
128 
129 ///
130 /// Return tail block of a diamond.
131 ///
132 BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
133  assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
134  return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor();
135 }
136 
137 ///
138 /// True when BB is the head of a diamond (hammock)
139 ///
140 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
141  if (!BB)
142  return false;
143  auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
144  if (!BI || !BI->isConditional())
145  return false;
146 
147  BasicBlock *Succ0 = BI->getSuccessor(0);
148  BasicBlock *Succ1 = BI->getSuccessor(1);
149 
150  if (!Succ0->getSinglePredecessor())
151  return false;
152  if (!Succ1->getSinglePredecessor())
153  return false;
154 
155  BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
156  BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
157  // Ignore triangles.
158  if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
159  return false;
160  return true;
161 }
162 
163 
164 ///
165 /// True when instruction is a sink barrier for a store
166 /// located in Loc
167 ///
168 /// Whenever an instruction could possibly read or modify the
169 /// value being stored or protect against the store from
170 /// happening it is considered a sink barrier.
171 ///
172 bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
173  const Instruction &End,
174  MemoryLocation Loc) {
175  for (const Instruction &Inst :
176  make_range(Start.getIterator(), End.getIterator()))
177  if (Inst.mayThrow())
178  return true;
179  return AA->canInstructionRangeModRef(Start, End, Loc, ModRefInfo::ModRef);
180 }
181 
182 ///
183 /// Check if \p BB contains a store to the same address as \p SI
184 ///
185 /// \return The store in \p when it is safe to sink. Otherwise return Null.
186 ///
187 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
188  StoreInst *Store0) {
189  LLVM_DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
190  BasicBlock *BB0 = Store0->getParent();
191  for (Instruction &Inst : reverse(*BB1)) {
192  auto *Store1 = dyn_cast<StoreInst>(&Inst);
193  if (!Store1)
194  continue;
195 
196  MemoryLocation Loc0 = MemoryLocation::get(Store0);
197  MemoryLocation Loc1 = MemoryLocation::get(Store1);
198  if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
199  !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1) &&
200  !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0)) {
201  return Store1;
202  }
203  }
204  return nullptr;
205 }
206 
207 ///
208 /// Create a PHI node in BB for the operands of S0 and S1
209 ///
210 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
211  StoreInst *S1) {
212  // Create a phi if the values mismatch.
213  Value *Opd1 = S0->getValueOperand();
214  Value *Opd2 = S1->getValueOperand();
215  if (Opd1 == Opd2)
216  return nullptr;
217 
218  auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
219  &BB->front());
220  NewPN->applyMergedLocation(S0->getDebugLoc(), S1->getDebugLoc());
221  NewPN->addIncoming(Opd1, S0->getParent());
222  NewPN->addIncoming(Opd2, S1->getParent());
223  return NewPN;
224 }
225 
226 ///
227 /// Check if 2 stores can be sunk together with corresponding GEPs
228 ///
229 bool MergedLoadStoreMotion::canSinkStoresAndGEPs(StoreInst *S0,
230  StoreInst *S1) const {
231  auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
232  auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
233  return A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
234  (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
235  (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0);
236 }
237 
238 ///
239 /// Merge two stores to same address and sink into \p BB
240 ///
241 /// Also sinks GEP instruction computing the store address
242 ///
243 void MergedLoadStoreMotion::sinkStoresAndGEPs(BasicBlock *BB, StoreInst *S0,
244  StoreInst *S1) {
245  // Only one definition?
246  auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
247  auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
248  LLVM_DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
249  dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
250  dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
251  // Hoist the instruction.
252  BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
253  // Intersect optional metadata.
254  S0->andIRFlags(S1);
256 
257  // Create the new store to be inserted at the join point.
258  StoreInst *SNew = cast<StoreInst>(S0->clone());
259  Instruction *ANew = A0->clone();
260  SNew->insertBefore(&*InsertPt);
261  ANew->insertBefore(SNew);
262 
263  assert(S0->getParent() == A0->getParent());
264  assert(S1->getParent() == A1->getParent());
265 
266  // New PHI operand? Use it.
267  if (PHINode *NewPN = getPHIOperand(BB, S0, S1))
268  SNew->setOperand(0, NewPN);
269  S0->eraseFromParent();
270  S1->eraseFromParent();
271  A0->replaceAllUsesWith(ANew);
272  A0->eraseFromParent();
273  A1->replaceAllUsesWith(ANew);
274  A1->eraseFromParent();
275 }
276 
277 ///
278 /// True when two stores are equivalent and can sink into the footer
279 ///
280 /// Starting from a diamond head block, iterate over the instructions in one
281 /// successor block and try to match a store in the second successor.
282 ///
283 bool MergedLoadStoreMotion::mergeStores(BasicBlock *HeadBB) {
284 
285  bool MergedStores = false;
286  BasicBlock *TailBB = getDiamondTail(HeadBB);
287  BasicBlock *SinkBB = TailBB;
288  assert(SinkBB && "Footer of a diamond cannot be empty");
289 
290  succ_iterator SI = succ_begin(HeadBB);
291  assert(SI != succ_end(HeadBB) && "Diamond head cannot have zero successors");
292  BasicBlock *Pred0 = *SI;
293  ++SI;
294  assert(SI != succ_end(HeadBB) && "Diamond head cannot have single successor");
295  BasicBlock *Pred1 = *SI;
296  // tail block of a diamond/hammock?
297  if (Pred0 == Pred1)
298  return false; // No.
299  // bail out early if we can not merge into the footer BB
300  if (!SplitFooterBB && TailBB->hasNPredecessorsOrMore(3))
301  return false;
302  // #Instructions in Pred1 for Compile Time Control
303  auto InstsNoDbg = Pred1->instructionsWithoutDebug();
304  int Size1 = std::distance(InstsNoDbg.begin(), InstsNoDbg.end());
305  int NStores = 0;
306 
307  for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
308  RBI != RBE;) {
309 
310  Instruction *I = &*RBI;
311  ++RBI;
312 
313  // Don't sink non-simple (atomic, volatile) stores.
314  auto *S0 = dyn_cast<StoreInst>(I);
315  if (!S0 || !S0->isSimple())
316  continue;
317 
318  ++NStores;
319  if (NStores * Size1 >= MagicCompileTimeControl)
320  break;
321  if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
322  if (!canSinkStoresAndGEPs(S0, S1))
323  // Don't attempt to sink below stores that had to stick around
324  // But after removal of a store and some of its feeding
325  // instruction search again from the beginning since the iterator
326  // is likely stale at this point.
327  break;
328 
329  if (SinkBB == TailBB && TailBB->hasNPredecessorsOrMore(3)) {
330  // We have more than 2 predecessors. Insert a new block
331  // postdominating 2 predecessors we're going to sink from.
332  SinkBB = SplitBlockPredecessors(TailBB, {Pred0, Pred1}, ".sink.split");
333  if (!SinkBB)
334  break;
335  }
336 
337  MergedStores = true;
338  sinkStoresAndGEPs(SinkBB, S0, S1);
339  RBI = Pred0->rbegin();
340  RBE = Pred0->rend();
341  LLVM_DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
342  }
343  }
344  return MergedStores;
345 }
346 
347 bool MergedLoadStoreMotion::run(Function &F, AliasAnalysis &AA) {
348  this->AA = &AA;
349 
350  bool Changed = false;
351  LLVM_DEBUG(dbgs() << "Instruction Merger\n");
352 
353  // Merge unconditional branches, allowing PRE to catch more
354  // optimization opportunities.
355  // This loop doesn't care about newly inserted/split blocks
356  // since they never will be diamond heads.
357  for (BasicBlock &BB : make_early_inc_range(F))
358  // Hoist equivalent loads and sink stores
359  // outside diamonds when possible
360  if (isDiamondHead(&BB))
361  Changed |= mergeStores(&BB);
362  return Changed;
363 }
364 
365 namespace {
366 class MergedLoadStoreMotionLegacyPass : public FunctionPass {
367  const bool SplitFooterBB;
368 public:
369  static char ID; // Pass identification, replacement for typeid
370  MergedLoadStoreMotionLegacyPass(bool SplitFooterBB = false)
371  : FunctionPass(ID), SplitFooterBB(SplitFooterBB) {
374  }
375 
376  ///
377  /// Run the transformation for each function
378  ///
379  bool runOnFunction(Function &F) override {
380  if (skipFunction(F))
381  return false;
382  MergedLoadStoreMotion Impl(SplitFooterBB);
383  return Impl.run(F, getAnalysis<AAResultsWrapperPass>().getAAResults());
384  }
385 
386 private:
387  void getAnalysisUsage(AnalysisUsage &AU) const override {
388  if (!SplitFooterBB)
389  AU.setPreservesCFG();
392  }
393 };
394 
396 } // anonymous namespace
397 
398 ///
399 /// createMergedLoadStoreMotionPass - The public interface to this file.
400 ///
402  return new MergedLoadStoreMotionLegacyPass(SplitFooterBB);
403 }
404 
405 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion",
406  "MergedLoadStoreMotion", false, false)
408 INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion",
410 
413  MergedLoadStoreMotion Impl(Options.SplitFooterBB);
414  auto &AA = AM.getResult<AAManager>(F);
415  if (!Impl.run(F, AA))
416  return PreservedAnalyses::all();
417 
419  if (!Options.SplitFooterBB)
420  PA.preserveSet<CFGAnalyses>();
421  PA.preserve<GlobalsAA>();
422  return PA;
423 }
Legacy wrapper pass to provide the GlobalsAAResult object.
The access may reference and may modify the value stored in memory.
Value * getValueOperand()
Definition: Instructions.h:381
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:80
LLVM_NODISCARD std::enable_if_t< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type > dyn_cast(const Y &Val)
Definition: Casting.h:328
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
This function determines if the specified instruction executes the same operation as the current one...
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:288
This class represents lattice values for constants.
Definition: AllocatorList.h:23
This is the interface for a simple mod/ref and alias analysis over globals.
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
Definition: Metadata.cpp:1197
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion", "MergedLoadStoreMotion", false, false) INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass
This file contains the declarations for metadata subclasses.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:584
F(f)
reverse_iterator rend()
Definition: BasicBlock.h:289
reverse_iterator rbegin()
Definition: BasicBlock.h:287
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:150
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:4536
AnalysisUsage & addRequired()
FunctionPass * createMergedLoadStoreMotionPass(bool SplitFooterBB=false)
createMergedLoadStoreMotionPass - The public interface to this file.
mldst motion
mldst MergedLoadStoreMotion
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:102
Instruction * clone() const
Create a copy of &#39;this&#39; instruction that is identical in all ways except the following: ...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
void andIRFlags(const Value *V)
Logical &#39;and&#39; of any supported wrapping, exact, and fast-math flags of V and this instruction...
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:293
An instruction for storing to memory.
Definition: Instructions.h:291
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:105
static bool runOnFunction(Function &F, bool PostInlining)
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:241
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:258
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Definition: Instruction.cpp:86
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
Conditional or Unconditional Branch instruction.
iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug() const
Return a const iterator range over the instructions in the block, skipping any debug instructions...
Definition: BasicBlock.cpp:100
const Instruction & front() const
Definition: BasicBlock.h:294
A manager for alias analyses.
Represent the analysis usage information of a pass.
const Instruction & back() const
Definition: BasicBlock.h:296
Analysis pass providing a never-invalidated alias analysis result.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:281
self_iterator getIterator()
Definition: ilist_node.h:81
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Representation for a specific memory location.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
Definition: BasicBlock.cpp:289
Iterator for intrusive lists based on ilist_node.
void applyMergedLocation(const DILocation *LocA, const DILocation *LocB)
Merge 2 debug locations and apply it to the Instruction.
Definition: DebugInfo.cpp:694
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:253
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Represents analyses that only rely on functions&#39; control flow.
Definition: PassManager.h:115
This pass performs merges of loads and stores on both sides of a.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:342
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:190
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:266
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
#define I(x, y, z)
Definition: MD5.cpp:59
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:175
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:74
A container for analyses that lazily runs them and caches their results.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
bool isSimple() const
Definition: Instructions.h:373
auto reverse(ContainerTy &&C, std::enable_if_t< has_rbegin< ContainerTy >::value > *=nullptr)
Definition: STLExtras.h:341
#define LLVM_DEBUG(X)
Definition: Debug.h:122
void initializeMergedLoadStoreMotionLegacyPassPass(PassRegistry &)
Value * getPointerOperand()
Definition: Instructions.h:384
const BasicBlock * getParent() const
Definition: Instruction.h:70
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)