LLVM  3.7.0
LICM.cpp
Go to the documentation of this file.
1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
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 // This pass performs loop invariant code motion, attempting to remove as much
11 // code from the body of a loop as possible. It does this by either hoisting
12 // code into the preheader block, or by sinking code to the exit blocks if it is
13 // safe. This pass also promotes must-aliased memory locations in the loop to
14 // live in registers, thus hoisting and sinking "invariant" loads and stores.
15 //
16 // This pass uses alias analysis for two purposes:
17 //
18 // 1. Moving loop invariant loads and calls out of loops. If we can determine
19 // that a load or call inside of a loop never aliases anything stored to,
20 // we can hoist it or sink it like any other instruction.
21 // 2. Scalar Promotion of Memory - If there is a store instruction inside of
22 // the loop, we try to move the store to happen AFTER the loop instead of
23 // inside of the loop. This can only happen if a few conditions are true:
24 // A. The pointer stored through is loop invariant
25 // B. There are no stores or loads in the loop which _may_ alias the
26 // pointer. There are no calls in the loop which mod/ref the pointer.
27 // If these conditions are true, we can promote the loads and stores in the
28 // loop of the pointer to use a temporary alloca'd variable. We then use
29 // the SSAUpdater to construct the appropriate SSA form for the value.
30 //
31 //===----------------------------------------------------------------------===//
32 
33 #include "llvm/Transforms/Scalar.h"
34 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Analysis/LoopInfo.h"
39 #include "llvm/Analysis/LoopPass.h"
43 #include "llvm/IR/CFG.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DerivedTypes.h"
47 #include "llvm/IR/Dominators.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Metadata.h"
54 #include "llvm/Support/Debug.h"
59 #include <algorithm>
60 using namespace llvm;
61 
62 #define DEBUG_TYPE "licm"
63 
64 STATISTIC(NumSunk , "Number of instructions sunk out of loop");
65 STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
66 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
67 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
68 STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
69 
70 static cl::opt<bool>
71 DisablePromotion("disable-licm-promotion", cl::Hidden,
72  cl::desc("Disable memory promotion in LICM pass"));
73 
74 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
75 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop);
76 static bool hoist(Instruction &I, BasicBlock *Preheader);
77 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
78  const Loop *CurLoop, AliasSetTracker *CurAST );
79 static bool isGuaranteedToExecute(const Instruction &Inst,
80  const DominatorTree *DT,
81  const Loop *CurLoop,
82  const LICMSafetyInfo *SafetyInfo);
83 static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
84  const DominatorTree *DT,
85  const TargetLibraryInfo *TLI,
86  const Loop *CurLoop,
87  const LICMSafetyInfo *SafetyInfo,
88  const Instruction *CtxI = nullptr);
89 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
90  const AAMDNodes &AAInfo,
91  AliasSetTracker *CurAST);
93  BasicBlock &ExitBlock,
94  PHINode &PN,
95  const LoopInfo *LI);
98  Loop *CurLoop, AliasSetTracker *CurAST,
99  LICMSafetyInfo *SafetyInfo);
100 
101 namespace {
102  struct LICM : public LoopPass {
103  static char ID; // Pass identification, replacement for typeid
104  LICM() : LoopPass(ID) {
106  }
107 
108  bool runOnLoop(Loop *L, LPPassManager &LPM) override;
109 
110  /// This transformation requires natural loop information & requires that
111  /// loop preheaders be inserted into the CFG...
112  ///
113  void getAnalysisUsage(AnalysisUsage &AU) const override {
114  AU.setPreservesCFG();
125  }
126 
128 
129  bool doFinalization() override {
130  assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
131  return false;
132  }
133 
134  private:
135  AliasAnalysis *AA; // Current AliasAnalysis information
136  LoopInfo *LI; // Current LoopInfo
137  DominatorTree *DT; // Dominator Tree for the current Loop.
138 
139  TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding.
140 
141  // State that is updated as we process loops.
142  bool Changed; // Set to true when we change anything.
143  BasicBlock *Preheader; // The preheader block of the current loop...
144  Loop *CurLoop; // The current loop we are working on...
145  AliasSetTracker *CurAST; // AliasSet information for the current loop...
146  DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
147 
148  /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
149  void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
150  Loop *L) override;
151 
152  /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
153  /// set.
154  void deleteAnalysisValue(Value *V, Loop *L) override;
155 
156  /// Simple Analysis hook. Delete loop L from alias set map.
157  void deleteAnalysisLoop(Loop *L) override;
158  };
159 }
160 
161 char LICM::ID = 0;
162 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
165 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
170 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
171 
172 Pass *llvm::createLICMPass() { return new LICM(); }
173 
174 /// Hoist expressions out of the specified loop. Note, alias info for inner
175 /// loop is not preserved so it is not a good idea to run LICM multiple
176 /// times on one loop.
177 ///
178 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
179  if (skipOptnoneFunction(L))
180  return false;
181 
182  Changed = false;
183 
184  // Get our Loop and Alias Analysis information...
185  LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
186  AA = &getAnalysis<AliasAnalysis>();
187  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
188 
189  TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
190 
191  assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
192 
193  CurAST = new AliasSetTracker(*AA);
194  // Collect Alias info from subloops.
195  for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
196  LoopItr != LoopItrE; ++LoopItr) {
197  Loop *InnerL = *LoopItr;
198  AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
199  assert(InnerAST && "Where is my AST?");
200 
201  // What if InnerLoop was modified by other passes ?
202  CurAST->add(*InnerAST);
203 
204  // Once we've incorporated the inner loop's AST into ours, we don't need the
205  // subloop's anymore.
206  delete InnerAST;
207  LoopToAliasSetMap.erase(InnerL);
208  }
209 
210  CurLoop = L;
211 
212  // Get the preheader block to move instructions into...
213  Preheader = L->getLoopPreheader();
214 
215  // Loop over the body of this loop, looking for calls, invokes, and stores.
216  // Because subloops have already been incorporated into AST, we skip blocks in
217  // subloops.
218  //
219  for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
220  I != E; ++I) {
221  BasicBlock *BB = *I;
222  if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
223  CurAST->add(*BB); // Incorporate the specified basic block
224  }
225 
226  // Compute loop safety information.
227  LICMSafetyInfo SafetyInfo;
228  computeLICMSafetyInfo(&SafetyInfo, CurLoop);
229 
230  // We want to visit all of the instructions in this loop... that are not parts
231  // of our subloops (they have already had their invariants hoisted out of
232  // their loop, into this loop, so there is no need to process the BODIES of
233  // the subloops).
234  //
235  // Traverse the body of the loop in depth first order on the dominator tree so
236  // that we are guaranteed to see definitions before we see uses. This allows
237  // us to sink instructions in one pass, without iteration. After sinking
238  // instructions, we perform another pass to hoist them out of the loop.
239  //
240  if (L->hasDedicatedExits())
241  Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, CurLoop,
242  CurAST, &SafetyInfo);
243  if (Preheader)
244  Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI,
245  CurLoop, CurAST, &SafetyInfo);
246 
247  // Now that all loop invariants have been removed from the loop, promote any
248  // memory references to scalars that we can.
249  if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
250  SmallVector<BasicBlock *, 8> ExitBlocks;
252  PredIteratorCache PIC;
253 
254  // Loop over all of the alias sets in the tracker object.
255  for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
256  I != E; ++I)
257  Changed |= promoteLoopAccessesToScalars(*I, ExitBlocks, InsertPts,
258  PIC, LI, DT, CurLoop,
259  CurAST, &SafetyInfo);
260 
261  // Once we have promoted values across the loop body we have to recursively
262  // reform LCSSA as any nested loop may now have values defined within the
263  // loop used in the outer loop.
264  // FIXME: This is really heavy handed. It would be a bit better to use an
265  // SSAUpdater strategy during promotion that was LCSSA aware and reformed
266  // it as it went.
267  if (Changed)
268  formLCSSARecursively(*L, *DT, LI,
269  getAnalysisIfAvailable<ScalarEvolution>());
270  }
271 
272  // Check that neither this loop nor its parent have had LCSSA broken. LICM is
273  // specifically moving instructions across the loop boundary and so it is
274  // especially in need of sanity checking here.
275  assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
276  assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
277  "Parent loop not left in LCSSA form after LICM!");
278 
279  // Clear out loops state information for the next iteration
280  CurLoop = nullptr;
281  Preheader = nullptr;
282 
283  // If this loop is nested inside of another one, save the alias information
284  // for when we process the outer loop.
285  if (L->getParentLoop())
286  LoopToAliasSetMap[L] = CurAST;
287  else
288  delete CurAST;
289  return Changed;
290 }
291 
292 /// Walk the specified region of the CFG (defined by all blocks dominated by
293 /// the specified block, and that are in the current loop) in reverse depth
294 /// first order w.r.t the DominatorTree. This allows us to visit uses before
295 /// definitions, allowing us to sink a loop body in one pass without iteration.
296 ///
298  DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
299  AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
300 
301  // Verify inputs.
302  assert(N != nullptr && AA != nullptr && LI != nullptr &&
303  DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
304  SafetyInfo != nullptr && "Unexpected input to sinkRegion");
305 
306  // Set changed as false.
307  bool Changed = false;
308  // Get basic block
309  BasicBlock *BB = N->getBlock();
310  // If this subregion is not in the top level loop at all, exit.
311  if (!CurLoop->contains(BB)) return Changed;
312 
313  // We are processing blocks in reverse dfo, so process children first.
314  const std::vector<DomTreeNode*> &Children = N->getChildren();
315  for (unsigned i = 0, e = Children.size(); i != e; ++i)
316  Changed |=
317  sinkRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
318  // Only need to process the contents of this block if it is not part of a
319  // subloop (which would already have been processed).
320  if (inSubLoop(BB,CurLoop,LI)) return Changed;
321 
322  for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
323  Instruction &I = *--II;
324 
325  // If the instruction is dead, we would try to sink it because it isn't used
326  // in the loop, instead, just delete it.
327  if (isInstructionTriviallyDead(&I, TLI)) {
328  DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
329  ++II;
330  CurAST->deleteValue(&I);
331  I.eraseFromParent();
332  Changed = true;
333  continue;
334  }
335 
336  // Check to see if we can sink this instruction to the exit blocks
337  // of the loop. We can do this if the all users of the instruction are
338  // outside of the loop. In this case, it doesn't even matter if the
339  // operands of the instruction are loop invariant.
340  //
341  if (isNotUsedInLoop(I, CurLoop) &&
342  canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) {
343  ++II;
344  Changed |= sink(I, LI, DT, CurLoop, CurAST);
345  }
346  }
347  return Changed;
348 }
349 
350 /// Walk the specified region of the CFG (defined by all blocks dominated by
351 /// the specified block, and that are in the current loop) in depth first
352 /// order w.r.t the DominatorTree. This allows us to visit definitions before
353 /// uses, allowing us to hoist a loop body in one pass without iteration.
354 ///
356  DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
357  AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
358  // Verify inputs.
359  assert(N != nullptr && AA != nullptr && LI != nullptr &&
360  DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
361  SafetyInfo != nullptr && "Unexpected input to hoistRegion");
362  // Set changed as false.
363  bool Changed = false;
364  // Get basic block
365  BasicBlock *BB = N->getBlock();
366  // If this subregion is not in the top level loop at all, exit.
367  if (!CurLoop->contains(BB)) return Changed;
368  // Only need to process the contents of this block if it is not part of a
369  // subloop (which would already have been processed).
370  if (!inSubLoop(BB, CurLoop, LI))
371  for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
372  Instruction &I = *II++;
373  // Try constant folding this instruction. If all the operands are
374  // constants, it is technically hoistable, but it would be better to just
375  // fold it.
377  &I, I.getModule()->getDataLayout(), TLI)) {
378  DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
379  CurAST->copyValue(&I, C);
380  CurAST->deleteValue(&I);
381  I.replaceAllUsesWith(C);
382  I.eraseFromParent();
383  continue;
384  }
385 
386  // Try hoisting the instruction out to the preheader. We can only do this
387  // if all of the operands of the instruction are loop invariant and if it
388  // is safe to hoist the instruction.
389  //
390  if (CurLoop->hasLoopInvariantOperands(&I) &&
391  canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) &&
392  isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
393  CurLoop->getLoopPreheader()->getTerminator()))
394  Changed |= hoist(I, CurLoop->getLoopPreheader());
395  }
396 
397  const std::vector<DomTreeNode*> &Children = N->getChildren();
398  for (unsigned i = 0, e = Children.size(); i != e; ++i)
399  Changed |=
400  hoistRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
401  return Changed;
402 }
403 
404 /// Computes loop safety information, checks loop body & header
405 /// for the possiblity of may throw exception.
406 ///
407 void llvm::computeLICMSafetyInfo(LICMSafetyInfo * SafetyInfo, Loop * CurLoop) {
408  assert(CurLoop != nullptr && "CurLoop cant be null");
409  BasicBlock *Header = CurLoop->getHeader();
410  // Setting default safety values.
411  SafetyInfo->MayThrow = false;
412  SafetyInfo->HeaderMayThrow = false;
413  // Iterate over header and compute dafety info.
414  for (BasicBlock::iterator I = Header->begin(), E = Header->end();
415  (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
416  SafetyInfo->HeaderMayThrow |= I->mayThrow();
417 
418  SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
419  // Iterate over loop instructions and compute safety info.
420  for (Loop::block_iterator BB = CurLoop->block_begin(),
421  BBE = CurLoop->block_end(); (BB != BBE) && !SafetyInfo->MayThrow ; ++BB)
422  for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
423  (I != E) && !SafetyInfo->MayThrow; ++I)
424  SafetyInfo->MayThrow |= I->mayThrow();
425 }
426 
427 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
428 /// instruction.
429 ///
431  TargetLibraryInfo *TLI, Loop *CurLoop,
432  AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
433  // Loads have extra constraints we have to verify before we can hoist them.
434  if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
435  if (!LI->isUnordered())
436  return false; // Don't hoist volatile/atomic loads!
437 
438  // Loads from constant memory are always safe to move, even if they end up
439  // in the same alias set as something that ends up being modified.
440  if (AA->pointsToConstantMemory(LI->getOperand(0)))
441  return true;
442  if (LI->getMetadata(LLVMContext::MD_invariant_load))
443  return true;
444 
445  // Don't hoist loads which have may-aliased stores in loop.
446  uint64_t Size = 0;
447  if (LI->getType()->isSized())
448  Size = AA->getTypeStoreSize(LI->getType());
449 
450  AAMDNodes AAInfo;
451  LI->getAAMetadata(AAInfo);
452 
453  return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
454  } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
455  // Don't sink or hoist dbg info; it's legal, but not useful.
456  if (isa<DbgInfoIntrinsic>(I))
457  return false;
458 
459  // Handle simple cases by querying alias analysis.
461  if (Behavior == AliasAnalysis::DoesNotAccessMemory)
462  return true;
463  if (AliasAnalysis::onlyReadsMemory(Behavior)) {
464  // If this call only reads from memory and there are no writes to memory
465  // in the loop, we can hoist or sink the call as appropriate.
466  bool FoundMod = false;
467  for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
468  I != E; ++I) {
469  AliasSet &AS = *I;
470  if (!AS.isForwardingAliasSet() && AS.isMod()) {
471  FoundMod = true;
472  break;
473  }
474  }
475  if (!FoundMod) return true;
476  }
477 
478  // FIXME: This should use mod/ref information to see if we can hoist or
479  // sink the call.
480 
481  return false;
482  }
483 
484  // Only these instructions are hoistable/sinkable.
485  if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
486  !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
487  !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
488  !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
489  !isa<InsertValueInst>(I))
490  return false;
491 
492  // TODO: Plumb the context instruction through to make hoisting and sinking
493  // more powerful. Hoisting of loads already works due to the special casing
494  // above.
495  return isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
496  nullptr);
497 }
498 
499 /// Returns true if a PHINode is a trivially replaceable with an
500 /// Instruction.
501 /// This is true when all incoming values are that instruction.
502 /// This pattern occurs most often with LCSSA PHI nodes.
503 ///
504 static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
505  for (const Value *IncValue : PN.incoming_values())
506  if (IncValue != &I)
507  return false;
508 
509  return true;
510 }
511 
512 /// Return true if the only users of this instruction are outside of
513 /// the loop. If this is true, we can sink the instruction to the exit
514 /// blocks of the loop.
515 ///
516 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop) {
517  for (const User *U : I.users()) {
518  const Instruction *UI = cast<Instruction>(U);
519  if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
520  // A PHI node where all of the incoming values are this instruction are
521  // special -- they can just be RAUW'ed with the instruction and thus
522  // don't require a use in the predecessor. This is a particular important
523  // special case because it is the pattern found in LCSSA form.
524  if (isTriviallyReplacablePHI(*PN, I)) {
525  if (CurLoop->contains(PN))
526  return false;
527  else
528  continue;
529  }
530 
531  // Otherwise, PHI node uses occur in predecessor blocks if the incoming
532  // values. Check for such a use being inside the loop.
533  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
534  if (PN->getIncomingValue(i) == &I)
535  if (CurLoop->contains(PN->getIncomingBlock(i)))
536  return false;
537 
538  continue;
539  }
540 
541  if (CurLoop->contains(UI))
542  return false;
543  }
544  return true;
545 }
546 
548  BasicBlock &ExitBlock,
549  PHINode &PN,
550  const LoopInfo *LI) {
551  Instruction *New = I.clone();
552  ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
553  if (!I.getName().empty()) New->setName(I.getName() + ".le");
554 
555  // Build LCSSA PHI nodes for any in-loop operands. Note that this is
556  // particularly cheap because we can rip off the PHI node that we're
557  // replacing for the number and blocks of the predecessors.
558  // OPT: If this shows up in a profile, we can instead finish sinking all
559  // invariant instructions, and then walk their operands to re-establish
560  // LCSSA. That will eliminate creating PHI nodes just to nuke them when
561  // sinking bottom-up.
562  for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
563  ++OI)
564  if (Instruction *OInst = dyn_cast<Instruction>(*OI))
565  if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
566  if (!OLoop->contains(&PN)) {
567  PHINode *OpPN =
568  PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
569  OInst->getName() + ".lcssa", ExitBlock.begin());
570  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
571  OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
572  *OI = OpPN;
573  }
574  return New;
575 }
576 
577 /// When an instruction is found to only be used outside of the loop, this
578 /// function moves it to the exit blocks and patches up SSA form as needed.
579 /// This method is guaranteed to remove the original instruction from its
580 /// position, and may either delete it or move it to outside of the loop.
581 ///
582 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
583  const Loop *CurLoop, AliasSetTracker *CurAST ) {
584  DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
585  bool Changed = false;
586  if (isa<LoadInst>(I)) ++NumMovedLoads;
587  else if (isa<CallInst>(I)) ++NumMovedCalls;
588  ++NumSunk;
589  Changed = true;
590 
591 #ifndef NDEBUG
593  CurLoop->getUniqueExitBlocks(ExitBlocks);
594  SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
595  ExitBlocks.end());
596 #endif
597 
598  // Clones of this instruction. Don't create more than one per exit block!
600 
601  // If this instruction is only used outside of the loop, then all users are
602  // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
603  // the instruction.
604  while (!I.use_empty()) {
606  auto *User = cast<Instruction>(*UI);
607  if (!DT->isReachableFromEntry(User->getParent())) {
609  continue;
610  }
611  // The user must be a PHI node.
612  PHINode *PN = cast<PHINode>(User);
613 
614  // Surprisingly, instructions can be used outside of loops without any
615  // exits. This can only happen in PHI nodes if the incoming block is
616  // unreachable.
617  Use &U = UI.getUse();
618  BasicBlock *BB = PN->getIncomingBlock(U);
619  if (!DT->isReachableFromEntry(BB)) {
620  U = UndefValue::get(I.getType());
621  continue;
622  }
623 
624  BasicBlock *ExitBlock = PN->getParent();
625  assert(ExitBlockSet.count(ExitBlock) &&
626  "The LCSSA PHI is not in an exit block!");
627 
628  Instruction *New;
629  auto It = SunkCopies.find(ExitBlock);
630  if (It != SunkCopies.end())
631  New = It->second;
632  else
633  New = SunkCopies[ExitBlock] =
634  CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI);
635 
636  PN->replaceAllUsesWith(New);
637  PN->eraseFromParent();
638  }
639 
640  CurAST->deleteValue(&I);
641  I.eraseFromParent();
642  return Changed;
643 }
644 
645 /// When an instruction is found to only use loop invariant operands that
646 /// is safe to hoist, this instruction is called to do the dirty work.
647 ///
648 static bool hoist(Instruction &I, BasicBlock *Preheader) {
649  DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
650  << I << "\n");
651  // Move the new node to the Preheader, before its terminator.
652  I.moveBefore(Preheader->getTerminator());
653 
654  if (isa<LoadInst>(I)) ++NumMovedLoads;
655  else if (isa<CallInst>(I)) ++NumMovedCalls;
656  ++NumHoisted;
657  return true;
658 }
659 
660 /// Only sink or hoist an instruction if it is not a trapping instruction,
661 /// or if the instruction is known not to trap when moved to the preheader.
662 /// or if it is a trapping instruction and is guaranteed to execute.
664  const DominatorTree *DT,
665  const TargetLibraryInfo *TLI,
666  const Loop *CurLoop,
667  const LICMSafetyInfo *SafetyInfo,
668  const Instruction *CtxI) {
669  if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI))
670  return true;
671 
672  return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
673 }
674 
675 static bool isGuaranteedToExecute(const Instruction &Inst,
676  const DominatorTree *DT,
677  const Loop *CurLoop,
678  const LICMSafetyInfo * SafetyInfo) {
679 
680  // We have to check to make sure that the instruction dominates all
681  // of the exit blocks. If it doesn't, then there is a path out of the loop
682  // which does not execute this instruction, so we can't hoist it.
683 
684  // If the instruction is in the header block for the loop (which is very
685  // common), it is always guaranteed to dominate the exit blocks. Since this
686  // is a common case, and can save some work, check it now.
687  if (Inst.getParent() == CurLoop->getHeader())
688  // If there's a throw in the header block, we can't guarantee we'll reach
689  // Inst.
690  return !SafetyInfo->HeaderMayThrow;
691 
692  // Somewhere in this loop there is an instruction which may throw and make us
693  // exit the loop.
694  if (SafetyInfo->MayThrow)
695  return false;
696 
697  // Get the exit blocks for the current loop.
698  SmallVector<BasicBlock*, 8> ExitBlocks;
699  CurLoop->getExitBlocks(ExitBlocks);
700 
701  // Verify that the block dominates each of the exit blocks of the loop.
702  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
703  if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
704  return false;
705 
706  // As a degenerate case, if the loop is statically infinite then we haven't
707  // proven anything since there are no exit blocks.
708  if (ExitBlocks.empty())
709  return false;
710 
711  return true;
712 }
713 
714 namespace {
715  class LoopPromoter : public LoadAndStorePromoter {
716  Value *SomePtr; // Designated pointer to store to.
717  SmallPtrSetImpl<Value*> &PointerMustAliases;
718  SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
719  SmallVectorImpl<Instruction*> &LoopInsertPts;
720  PredIteratorCache &PredCache;
721  AliasSetTracker &AST;
722  LoopInfo &LI;
723  DebugLoc DL;
724  int Alignment;
725  AAMDNodes AATags;
726 
727  Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
728  if (Instruction *I = dyn_cast<Instruction>(V))
729  if (Loop *L = LI.getLoopFor(I->getParent()))
730  if (!L->contains(BB)) {
731  // We need to create an LCSSA PHI node for the incoming value and
732  // store that.
733  PHINode *PN = PHINode::Create(
734  I->getType(), PredCache.size(BB),
735  I->getName() + ".lcssa", BB->begin());
736  for (BasicBlock *Pred : PredCache.get(BB))
737  PN->addIncoming(I, Pred);
738  return PN;
739  }
740  return V;
741  }
742 
743  public:
744  LoopPromoter(Value *SP,
749  AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
750  const AAMDNodes &AATags)
751  : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
752  LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
753  LI(li), DL(dl), Alignment(alignment), AATags(AATags) {}
754 
755  bool isInstInList(Instruction *I,
756  const SmallVectorImpl<Instruction*> &) const override {
757  Value *Ptr;
758  if (LoadInst *LI = dyn_cast<LoadInst>(I))
759  Ptr = LI->getOperand(0);
760  else
761  Ptr = cast<StoreInst>(I)->getPointerOperand();
762  return PointerMustAliases.count(Ptr);
763  }
764 
765  void doExtraRewritesBeforeFinalDeletion() const override {
766  // Insert stores after in the loop exit blocks. Each exit block gets a
767  // store of the live-out values that feed them. Since we've already told
768  // the SSA updater about the defs in the loop and the preheader
769  // definition, it is all set and we can start using it.
770  for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
771  BasicBlock *ExitBlock = LoopExitBlocks[i];
772  Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
773  LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
774  Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
775  Instruction *InsertPos = LoopInsertPts[i];
776  StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
777  NewSI->setAlignment(Alignment);
778  NewSI->setDebugLoc(DL);
779  if (AATags) NewSI->setAAMetadata(AATags);
780  }
781  }
782 
783  void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
784  // Update alias analysis.
785  AST.copyValue(LI, V);
786  }
787  void instructionDeleted(Instruction *I) const override {
788  AST.deleteValue(I);
789  }
790  };
791 } // end anon namespace
792 
793 /// Try to promote memory values to scalars by sinking stores out of the
794 /// loop and moving loads to before the loop. We do this by looping over
795 /// the stores in the loop, looking for stores to Must pointers which are
796 /// loop invariant.
797 ///
799  SmallVectorImpl<BasicBlock*>&ExitBlocks,
801  PredIteratorCache &PIC, LoopInfo *LI,
802  DominatorTree *DT, Loop *CurLoop,
803  AliasSetTracker *CurAST,
804  LICMSafetyInfo * SafetyInfo) {
805  // Verify inputs.
806  assert(LI != nullptr && DT != nullptr &&
807  CurLoop != nullptr && CurAST != nullptr &&
808  SafetyInfo != nullptr &&
809  "Unexpected Input to promoteLoopAccessesToScalars");
810  // Initially set Changed status to false.
811  bool Changed = false;
812  // We can promote this alias set if it has a store, if it is a "Must" alias
813  // set, if the pointer is loop invariant, and if we are not eliminating any
814  // volatile loads or stores.
815  if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
816  AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
817  return Changed;
818 
819  assert(!AS.empty() &&
820  "Must alias set should have at least one pointer element in it!");
821 
822  Value *SomePtr = AS.begin()->getValue();
823  BasicBlock * Preheader = CurLoop->getLoopPreheader();
824 
825  // It isn't safe to promote a load/store from the loop if the load/store is
826  // conditional. For example, turning:
827  //
828  // for () { if (c) *P += 1; }
829  //
830  // into:
831  //
832  // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
833  //
834  // is not safe, because *P may only be valid to access if 'c' is true.
835  //
836  // It is safe to promote P if all uses are direct load/stores and if at
837  // least one is guaranteed to be executed.
838  bool GuaranteedToExecute = false;
839 
841  SmallPtrSet<Value*, 4> PointerMustAliases;
842 
843  // We start with an alignment of one and try to find instructions that allow
844  // us to prove better alignment.
845  unsigned Alignment = 1;
846  AAMDNodes AATags;
847  bool HasDedicatedExits = CurLoop->hasDedicatedExits();
848 
849  // Check that all of the pointers in the alias set have the same type. We
850  // cannot (yet) promote a memory location that is loaded and stored in
851  // different sizes. While we are at it, collect alignment and AA info.
852  for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
853  Value *ASIV = ASI->getValue();
854  PointerMustAliases.insert(ASIV);
855 
856  // Check that all of the pointers in the alias set have the same type. We
857  // cannot (yet) promote a memory location that is loaded and stored in
858  // different sizes.
859  if (SomePtr->getType() != ASIV->getType())
860  return Changed;
861 
862  for (User *U : ASIV->users()) {
863  // Ignore instructions that are outside the loop.
864  Instruction *UI = dyn_cast<Instruction>(U);
865  if (!UI || !CurLoop->contains(UI))
866  continue;
867 
868  // If there is an non-load/store instruction in the loop, we can't promote
869  // it.
870  if (const LoadInst *load = dyn_cast<LoadInst>(UI)) {
871  assert(!load->isVolatile() && "AST broken");
872  if (!load->isSimple())
873  return Changed;
874  } else if (const StoreInst *store = dyn_cast<StoreInst>(UI)) {
875  // Stores *of* the pointer are not interesting, only stores *to* the
876  // pointer.
877  if (UI->getOperand(1) != ASIV)
878  continue;
879  assert(!store->isVolatile() && "AST broken");
880  if (!store->isSimple())
881  return Changed;
882  // Don't sink stores from loops without dedicated block exits. Exits
883  // containing indirect branches are not transformed by loop simplify,
884  // make sure we catch that. An additional load may be generated in the
885  // preheader for SSA updater, so also avoid sinking when no preheader
886  // is available.
887  if (!HasDedicatedExits || !Preheader)
888  return Changed;
889 
890  // Note that we only check GuaranteedToExecute inside the store case
891  // so that we do not introduce stores where they did not exist before
892  // (which would break the LLVM concurrency model).
893 
894  // If the alignment of this instruction allows us to specify a more
895  // restrictive (and performant) alignment and if we are sure this
896  // instruction will be executed, update the alignment.
897  // Larger is better, with the exception of 0 being the best alignment.
898  unsigned InstAlignment = store->getAlignment();
899  if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
900  if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
901  GuaranteedToExecute = true;
902  Alignment = InstAlignment;
903  }
904 
905  if (!GuaranteedToExecute)
906  GuaranteedToExecute = isGuaranteedToExecute(*UI, DT,
907  CurLoop, SafetyInfo);
908 
909  } else
910  return Changed; // Not a load or store.
911 
912  // Merge the AA tags.
913  if (LoopUses.empty()) {
914  // On the first load/store, just take its AA tags.
915  UI->getAAMetadata(AATags);
916  } else if (AATags) {
917  UI->getAAMetadata(AATags, /* Merge = */ true);
918  }
919 
920  LoopUses.push_back(UI);
921  }
922  }
923 
924  // If there isn't a guaranteed-to-execute instruction, we can't promote.
925  if (!GuaranteedToExecute)
926  return Changed;
927 
928  // Otherwise, this is safe to promote, lets do it!
929  DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
930  Changed = true;
931  ++NumPromoted;
932 
933  // Grab a debug location for the inserted loads/stores; given that the
934  // inserted loads/stores have little relation to the original loads/stores,
935  // this code just arbitrarily picks a location from one, since any debug
936  // location is better than none.
937  DebugLoc DL = LoopUses[0]->getDebugLoc();
938 
939  // Figure out the loop exits and their insertion points, if this is the
940  // first promotion.
941  if (ExitBlocks.empty()) {
942  CurLoop->getUniqueExitBlocks(ExitBlocks);
943  InsertPts.resize(ExitBlocks.size());
944  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
945  InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
946  }
947 
948  // We use the SSAUpdater interface to insert phi nodes as required.
950  SSAUpdater SSA(&NewPHIs);
951  LoopPromoter Promoter(SomePtr, LoopUses, SSA,
952  PointerMustAliases, ExitBlocks,
953  InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
954 
955  // Set up the preheader to have a definition of the value. It is the live-out
956  // value from the preheader that uses in the loop will use.
957  LoadInst *PreheaderLoad =
958  new LoadInst(SomePtr, SomePtr->getName()+".promoted",
959  Preheader->getTerminator());
960  PreheaderLoad->setAlignment(Alignment);
961  PreheaderLoad->setDebugLoc(DL);
962  if (AATags) PreheaderLoad->setAAMetadata(AATags);
963  SSA.AddAvailableValue(Preheader, PreheaderLoad);
964 
965  // Rewrite all the loads in the loop and remember all the definitions from
966  // stores in the loop.
967  Promoter.run(LoopUses);
968 
969  // If the SSAUpdater didn't use the load in the preheader, just zap it now.
970  if (PreheaderLoad->use_empty())
971  PreheaderLoad->eraseFromParent();
972 
973  return Changed;
974 }
975 
976 /// Simple Analysis hook. Clone alias set info.
977 ///
978 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
979  AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
980  if (!AST)
981  return;
982 
983  AST->copyValue(From, To);
984 }
985 
986 /// Simple Analysis hook. Delete value V from alias set
987 ///
988 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
989  AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
990  if (!AST)
991  return;
992 
993  AST->deleteValue(V);
994 }
995 
996 /// Simple Analysis hook. Delete value L from alias set map.
997 ///
998 void LICM::deleteAnalysisLoop(Loop *L) {
999  AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
1000  if (!AST)
1001  return;
1002 
1003  delete AST;
1004  LoopToAliasSetMap.erase(L);
1005 }
1006 
1007 
1008 /// Return true if the body of this loop may store into the memory
1009 /// location pointed to by V.
1010 ///
1011 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
1012  const AAMDNodes &AAInfo,
1013  AliasSetTracker *CurAST) {
1014  // Check to see if any of the basic blocks in CurLoop invalidate *V.
1015  return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1016 }
1017 
1018 /// Little predicate that returns true if the specified basic block is in
1019 /// a subloop of the current one, not the current one itself.
1020 ///
1021 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1022  assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1023  return LI->getLoopFor(BB) != CurLoop;
1024 }
1025 
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:82
static bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop, const LICMSafetyInfo *SafetyInfo)
Definition: LICM.cpp:675
iplist< Instruction >::iterator eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing basic block and deletes it...
Definition: Instruction.cpp:70
void computeLICMSafetyInfo(LICMSafetyInfo *, Loop *)
Computes safety information for a loop checks loop body & header for the possiblity of may throw exce...
Definition: LICM.cpp:407
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition: SSAUpdater.h:38
void addIncoming(Value *V, BasicBlock *BB)
addIncoming - Add an incoming value to the end of the PHI list
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isForwardingAliasSet() const
isForwardingAliasSet - Return true if this alias set should be ignored as part of the AliasSetTracker...
bool sinkRegion(DomTreeNode *, AliasAnalysis *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, Loop *, AliasSetTracker *, LICMSafetyInfo *)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block...
Definition: LICM.cpp:297
STATISTIC(NumFunctions,"Total number of functions")
Define an iterator for alias sets... this is just a forward iterator.
iterator begin() const
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
Definition: SSAUpdater.cpp:58
ScalarEvolution - This class is the main scalar evolution driver.
ModRefBehavior
ModRefBehavior - Summary of how a function affects memory in the program.
bool hoistRegion(DomTreeNode *, AliasAnalysis *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, Loop *, AliasSetTracker *, LICMSafetyInfo *)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block...
Definition: LICM.cpp:355
CallInst - This class represents a function call, abstracting a target machine's calling convention...
This file contains the declarations for metadata subclasses.
static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo)
canSinkOrHoistInst - Return true if the hoister and sinker can handle this instruction.
Definition: LICM.cpp:430
Captures loop safety information.
Definition: LoopUtils.h:38
static cl::opt< bool > DisablePromotion("disable-licm-promotion", cl::Hidden, cl::desc("Disable memory promotion in LICM pass"))
LoopT * getParentLoop() const
Definition: LoopInfo.h:97
A debug info location.
Definition: DebugLoc.h:34
bool hasLoopInvariantOperands(const Instruction *I) const
hasLoopInvariantOperands - Return true if all the operands of the specified instruction are loop inva...
Definition: LoopInfo.cpp:67
LoadInst - an instruction for reading from memory.
Definition: Instructions.h:177
LoopT * getLoopFor(const BlockT *BB) const
getLoopFor - Return the inner most loop that BB lives in.
Definition: LoopInfo.h:540
op_iterator op_begin()
Definition: User.h:183
BlockT * getHeader() const
Definition: LoopInfo.h:96
static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I)
Returns true if a PHINode is a trivially replaceable with an Instruction.
Definition: LICM.cpp:504
virtual bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal=false)
pointsToConstantMemory - If the specified memory location is known to be constant, return true.
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:188
AliasSet & getAliasSetForPointer(Value *P, uint64_t Size, const AAMDNodes &AAInfo, bool *New=nullptr)
getAliasSetForPointer - Return the alias set that the specified pointer lives in. ...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:242
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:231
bool isMustAlias() const
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:70
static Value * getPointerOperand(Instruction &Inst)
static Instruction * CloneInstructionInExitBlock(const Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI)
Definition: LICM.cpp:547
const_iterator end() const
A Use represents the edge between a Value definition and its users.
Definition: Use.h:69
virtual bool doFinalization(Module &)
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
Definition: Pass.h:116
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APInt.h:33
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:75
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:250
bool isLoopInvariant(const Value *V) const
isLoopInvariant - Return true if the specified value is loop invariant
Definition: LoopInfo.cpp:59
Instruction * clone() const
clone() - Create a copy of 'this' instruction that is identical in all ways except the following: ...
#define false
Definition: ConvertUTF.c:65
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
getExitBlocks - Return all of the successor blocks of this loop.
Definition: LoopInfoImpl.h:64
bool promoteLoopAccessesToScalars(AliasSet &, SmallVectorImpl< BasicBlock * > &, SmallVectorImpl< Instruction * > &, PredIteratorCache &, LoopInfo *, DominatorTree *, Loop *, AliasSetTracker *, LICMSafetyInfo *)
Try to promote memory values to scalars by sinking stores out of the loop and moving loads to before ...
Definition: LICM.cpp:798
const_iterator begin() const
user_iterator_impl< User > user_iterator
Definition: Value.h:292
static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, const AAMDNodes &AAInfo, AliasSetTracker *CurAST)
Return true if the body of this loop may store into the memory location pointed to by V...
Definition: LICM.cpp:1011
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:57
PredIteratorCache - This class is an extremely trivial cache for predecessor iterator queries...
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:265
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: ArrayRef.h:31
uint64_t getTypeStoreSize(Type *Ty)
getTypeStoreSize - Return the DataLayout store size for the given type, if known, or a conservative v...
AnalysisUsage & addPreservedID(const void *ID)
StoreInst - an instruction for storing to memory.
Definition: Instructions.h:316
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:351
bool isMod() const
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:67
static bool hoist(Instruction &I, BasicBlock *Preheader)
When an instruction is found to only use loop invariant operands that is safe to hoist, this instruction is called to do the dirty work.
Definition: LICM.cpp:648
bool onlyReadsMemory(ImmutableCallSite CS)
onlyReadsMemory - If the specified call is known to only read from non-volatile memory (or not access...
unsigned getNumIncomingValues() const
getNumIncomingValues - Return the number of incoming edges
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition: User.cpp:24
iterator begin() const
Definition: LoopInfo.h:131
iterator end() const
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
void setDebugLoc(DebugLoc Loc)
setDebugLoc - Set the debug location information for this instruction.
Definition: Instruction.h:227
BlockT * getLoopPreheader() const
getLoopPreheader - If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:108
void setAAMetadata(const AAMDNodes &N)
setAAMetadata - Sets the metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1122
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
This is an important base class in LLVM.
Definition: Constant.h:41
bool isVolatile() const
bool empty() const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
char & LCSSAID
Definition: LCSSA.cpp:312
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:264
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
iterator end() const
Definition: LoopInfo.h:132
Represent the analysis usage information of a pass.
op_iterator op_end()
Definition: User.h:185
BasicBlock * getIncomingBlock(unsigned i) const
getIncomingBlock - Return incoming basic block number i.
bool contains(const LoopT *L) const
contains - Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:105
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:252
iterator insert(iterator where, NodeTy *New)
Definition: ilist.h:412
Value * getOperand(unsigned i) const
Definition: User.h:118
const std::vector< DomTreeNodeBase< NodeT > * > & getChildren() const
void setAlignment(unsigned Align)
void initializeLICMPass(PassRegistry &)
#define INITIALIZE_AG_DEPENDENCY(depName)
Definition: PassSupport.h:72
bool hasDedicatedExits() const
hasDedicatedExits - Return true if no exit block for the loop has a predecessor that is outside the l...
Definition: LoopInfo.cpp:328
static UndefValue * get(Type *T)
get() - Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1473
void getUniqueExitBlocks(SmallVectorImpl< BasicBlock * > &ExitBlocks) const
getUniqueExitBlocks - Return all unique successor blocks of this loop.
Definition: LoopInfo.cpp:347
virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS)
getModRefBehavior - Return the behavior when calling the given call site.
char & LoopSimplifyID
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:214
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
iterator end()
Definition: BasicBlock.h:233
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:276
Helper class for promoting a collection of loads and stores into SSA Form using the SSAUpdater...
Definition: SSAUpdater.h:134
void copyValue(Value *From, Value *To)
copyValue - This method should be used whenever a preexisting value in the program is copied or clone...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:57
bool isLCSSAForm(DominatorTree &DT) const
isLCSSAForm - Return true if the Loop is in LCSSA form
Definition: LoopInfo.cpp:172
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
Provides information about what library functions are available for the current target.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:67
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:548
static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT, const Loop *CurLoop, AliasSetTracker *CurAST)
When an instruction is found to only be used outside of the loop, this function moves it to the exit ...
Definition: LICM.cpp:582
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:263
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:123
Pass * createLICMPass()
Definition: LICM.cpp:172
iterator_range< user_iterator > users()
Definition: Value.h:300
NodeT * getBlock() const
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
std::vector< BlockT * >::const_iterator block_iterator
Definition: LoopInfo.h:140
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE=nullptr)
Put a loop nest into LCSSA form.
Definition: LCSSA.cpp:264
block_iterator block_end() const
Definition: LoopInfo.h:142
iterator end() const
Definition: SmallPtrSet.h:289
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:372
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
getAAMetadata - Fills the AAMDNodes structure with AA metadata from this instruction.
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:124
DoesNotAccessMemory - This function does not perform any non-local loads or stores to memory...
bool use_empty() const
Definition: Value.h:275
Machine Loop Invariant Code Motion
static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI)
Little predicate that returns true if the specified basic block is in a subloop of the current one...
Definition: LICM.cpp:1021
user_iterator user_begin()
Definition: Value.h:294
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
isInstructionTriviallyDead - Return true if the result produced by the instruction is not used...
Definition: Local.cpp:282
LLVM Value Representation.
Definition: Value.h:69
void setAlignment(unsigned Align)
static bool isSafeToExecuteUnconditionally(const Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI, const Loop *CurLoop, const LICMSafetyInfo *SafetyInfo, const Instruction *CtxI=nullptr)
Only sink or hoist an instruction if it is not a trapping instruction, or if the instruction is known...
Definition: LICM.cpp:663
static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop)
Return true if the only users of this instruction are outside of the loop.
Definition: LICM.cpp:516
void moveBefore(Instruction *MovePos)
moveBefore - Unlink this instruction from its current basic block and insert it into the basic block ...
Definition: Instruction.cpp:89
#define DEBUG(X)
Definition: Debug.h:92
block_iterator block_begin() const
Definition: LoopInfo.h:141
The legacy pass manager's analysis pass to compute loop information.
Definition: LoopInfo.h:737
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
isSafeToSpeculativelyExecute - Return true if the instruction does not have any effects besides calcu...
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:203
std::vector< LoopT * >::const_iterator iterator
Definition: LoopInfo.h:128
iterator getFirstInsertionPt()
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:194
op_range incoming_values()
const BasicBlock * getParent() const
Definition: Instruction.h:72
void deleteValue(Value *PtrVal)
deleteValue method - This method is used to remove a pointer value from the AliasSetTracker entirely...
bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:110
void resize(size_type N)
Definition: SmallVector.h:376