xref: /llvm-project/llvm/lib/Transforms/Utils/LoopSimplify.cpp (revision 4c65c3596a6339ef075c9edea2827562ef0cba9d)
1 //===- LoopSimplify.cpp - Loop Canonicalization 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 several transformations to transform natural loops into a
11 // simpler form, which makes subsequent analyses and transformations simpler and
12 // more effective.
13 //
14 // Loop pre-header insertion guarantees that there is a single, non-critical
15 // entry edge from outside of the loop to the loop header.  This simplifies a
16 // number of analyses and transformations, such as LICM.
17 //
18 // Loop exit-block insertion guarantees that all exit blocks from the loop
19 // (blocks which are outside of the loop that have predecessors inside of the
20 // loop) only have predecessors from inside of the loop (and are thus dominated
21 // by the loop header).  This simplifies transformations such as store-sinking
22 // that are built into LICM.
23 //
24 // This pass also guarantees that loops will have exactly one backedge.
25 //
26 // Indirectbr instructions introduce several complications. If the loop
27 // contains or is entered by an indirectbr instruction, it may not be possible
28 // to transform the loop and make these guarantees. Client code should check
29 // that these conditions are true before relying on them.
30 //
31 // Note that the simplifycfg pass will clean up blocks which are split out but
32 // end up being unnecessary, so usage of this pass should not pessimize
33 // generated code.
34 //
35 // This pass obviously modifies the CFG, but updates loop information and
36 // dominator information.
37 //
38 //===----------------------------------------------------------------------===//
39 
40 #include "llvm/Transforms/Utils/LoopSimplify.h"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/ADT/DepthFirstIterator.h"
43 #include "llvm/ADT/SetOperations.h"
44 #include "llvm/ADT/SetVector.h"
45 #include "llvm/ADT/SmallVector.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Analysis/AliasAnalysis.h"
48 #include "llvm/Analysis/BasicAliasAnalysis.h"
49 #include "llvm/Analysis/AssumptionCache.h"
50 #include "llvm/Analysis/DependenceAnalysis.h"
51 #include "llvm/Analysis/GlobalsModRef.h"
52 #include "llvm/Analysis/InstructionSimplify.h"
53 #include "llvm/Analysis/LoopInfo.h"
54 #include "llvm/Analysis/ScalarEvolution.h"
55 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
56 #include "llvm/IR/CFG.h"
57 #include "llvm/IR/Constants.h"
58 #include "llvm/IR/DataLayout.h"
59 #include "llvm/IR/Dominators.h"
60 #include "llvm/IR/Function.h"
61 #include "llvm/IR/Instructions.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/LLVMContext.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/raw_ostream.h"
68 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
69 #include "llvm/Transforms/Utils/Local.h"
70 #include "llvm/Transforms/Utils/LoopUtils.h"
71 using namespace llvm;
72 
73 #define DEBUG_TYPE "loop-simplify"
74 
75 STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
76 STATISTIC(NumNested  , "Number of nested loops split out");
77 
78 // If the block isn't already, move the new block to right after some 'outside
79 // block' block.  This prevents the preheader from being placed inside the loop
80 // body, e.g. when the loop hasn't been rotated.
81 static void placeSplitBlockCarefully(BasicBlock *NewBB,
82                                      SmallVectorImpl<BasicBlock *> &SplitPreds,
83                                      Loop *L) {
84   // Check to see if NewBB is already well placed.
85   Function::iterator BBI = --NewBB->getIterator();
86   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
87     if (&*BBI == SplitPreds[i])
88       return;
89   }
90 
91   // If it isn't already after an outside block, move it after one.  This is
92   // always good as it makes the uncond branch from the outside block into a
93   // fall-through.
94 
95   // Figure out *which* outside block to put this after.  Prefer an outside
96   // block that neighbors a BB actually in the loop.
97   BasicBlock *FoundBB = nullptr;
98   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
99     Function::iterator BBI = SplitPreds[i]->getIterator();
100     if (++BBI != NewBB->getParent()->end() && L->contains(&*BBI)) {
101       FoundBB = SplitPreds[i];
102       break;
103     }
104   }
105 
106   // If our heuristic for a *good* bb to place this after doesn't find
107   // anything, just pick something.  It's likely better than leaving it within
108   // the loop.
109   if (!FoundBB)
110     FoundBB = SplitPreds[0];
111   NewBB->moveAfter(FoundBB);
112 }
113 
114 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
115 /// preheader, this method is called to insert one.  This method has two phases:
116 /// preheader insertion and analysis updating.
117 ///
118 BasicBlock *llvm::InsertPreheaderForLoop(Loop *L, DominatorTree *DT,
119                                          LoopInfo *LI, bool PreserveLCSSA) {
120   BasicBlock *Header = L->getHeader();
121 
122   // Compute the set of predecessors of the loop that are not in the loop.
123   SmallVector<BasicBlock*, 8> OutsideBlocks;
124   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
125        PI != PE; ++PI) {
126     BasicBlock *P = *PI;
127     if (!L->contains(P)) {         // Coming in from outside the loop?
128       // If the loop is branched to from an indirect branch, we won't
129       // be able to fully transform the loop, because it prohibits
130       // edge splitting.
131       if (isa<IndirectBrInst>(P->getTerminator())) return nullptr;
132 
133       // Keep track of it.
134       OutsideBlocks.push_back(P);
135     }
136   }
137 
138   // Split out the loop pre-header.
139   BasicBlock *PreheaderBB;
140   PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader", DT,
141                                        LI, PreserveLCSSA);
142   if (!PreheaderBB)
143     return nullptr;
144 
145   DEBUG(dbgs() << "LoopSimplify: Creating pre-header "
146                << PreheaderBB->getName() << "\n");
147 
148   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
149   // code layout too horribly.
150   placeSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
151 
152   return PreheaderBB;
153 }
154 
155 /// \brief Ensure that the loop preheader dominates all exit blocks.
156 ///
157 /// This method is used to split exit blocks that have predecessors outside of
158 /// the loop.
159 static BasicBlock *rewriteLoopExitBlock(Loop *L, BasicBlock *Exit,
160                                         DominatorTree *DT, LoopInfo *LI,
161                                         bool PreserveLCSSA) {
162   SmallVector<BasicBlock*, 8> LoopBlocks;
163   for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I) {
164     BasicBlock *P = *I;
165     if (L->contains(P)) {
166       // Don't do this if the loop is exited via an indirect branch.
167       if (isa<IndirectBrInst>(P->getTerminator())) return nullptr;
168 
169       LoopBlocks.push_back(P);
170     }
171   }
172 
173   assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
174   BasicBlock *NewExitBB = nullptr;
175 
176   NewExitBB = SplitBlockPredecessors(Exit, LoopBlocks, ".loopexit", DT, LI,
177                                      PreserveLCSSA);
178   if (!NewExitBB)
179     return nullptr;
180 
181   DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
182                << NewExitBB->getName() << "\n");
183   return NewExitBB;
184 }
185 
186 /// Add the specified block, and all of its predecessors, to the specified set,
187 /// if it's not already in there.  Stop predecessor traversal when we reach
188 /// StopBlock.
189 static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
190                                   std::set<BasicBlock*> &Blocks) {
191   SmallVector<BasicBlock *, 8> Worklist;
192   Worklist.push_back(InputBB);
193   do {
194     BasicBlock *BB = Worklist.pop_back_val();
195     if (Blocks.insert(BB).second && BB != StopBlock)
196       // If BB is not already processed and it is not a stop block then
197       // insert its predecessor in the work list
198       for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
199         BasicBlock *WBB = *I;
200         Worklist.push_back(WBB);
201       }
202   } while (!Worklist.empty());
203 }
204 
205 /// \brief The first part of loop-nestification is to find a PHI node that tells
206 /// us how to partition the loops.
207 static PHINode *findPHIToPartitionLoops(Loop *L, DominatorTree *DT,
208                                         AssumptionCache *AC) {
209   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
210   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
211     PHINode *PN = cast<PHINode>(I);
212     ++I;
213     if (Value *V = SimplifyInstruction(PN, DL, nullptr, DT, AC)) {
214       // This is a degenerate PHI already, don't modify it!
215       PN->replaceAllUsesWith(V);
216       PN->eraseFromParent();
217       continue;
218     }
219 
220     // Scan this PHI node looking for a use of the PHI node by itself.
221     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
222       if (PN->getIncomingValue(i) == PN &&
223           L->contains(PN->getIncomingBlock(i)))
224         // We found something tasty to remove.
225         return PN;
226   }
227   return nullptr;
228 }
229 
230 /// \brief If this loop has multiple backedges, try to pull one of them out into
231 /// a nested loop.
232 ///
233 /// This is important for code that looks like
234 /// this:
235 ///
236 ///  Loop:
237 ///     ...
238 ///     br cond, Loop, Next
239 ///     ...
240 ///     br cond2, Loop, Out
241 ///
242 /// To identify this common case, we look at the PHI nodes in the header of the
243 /// loop.  PHI nodes with unchanging values on one backedge correspond to values
244 /// that change in the "outer" loop, but not in the "inner" loop.
245 ///
246 /// If we are able to separate out a loop, return the new outer loop that was
247 /// created.
248 ///
249 static Loop *separateNestedLoop(Loop *L, BasicBlock *Preheader,
250                                 DominatorTree *DT, LoopInfo *LI,
251                                 ScalarEvolution *SE, bool PreserveLCSSA,
252                                 AssumptionCache *AC) {
253   // Don't try to separate loops without a preheader.
254   if (!Preheader)
255     return nullptr;
256 
257   // The header is not a landing pad; preheader insertion should ensure this.
258   BasicBlock *Header = L->getHeader();
259   assert(!Header->isEHPad() && "Can't insert backedge to EH pad");
260 
261   PHINode *PN = findPHIToPartitionLoops(L, DT, AC);
262   if (!PN) return nullptr;  // No known way to partition.
263 
264   // Pull out all predecessors that have varying values in the loop.  This
265   // handles the case when a PHI node has multiple instances of itself as
266   // arguments.
267   SmallVector<BasicBlock*, 8> OuterLoopPreds;
268   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
269     if (PN->getIncomingValue(i) != PN ||
270         !L->contains(PN->getIncomingBlock(i))) {
271       // We can't split indirectbr edges.
272       if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
273         return nullptr;
274       OuterLoopPreds.push_back(PN->getIncomingBlock(i));
275     }
276   }
277   DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n");
278 
279   // If ScalarEvolution is around and knows anything about values in
280   // this loop, tell it to forget them, because we're about to
281   // substantially change it.
282   if (SE)
283     SE->forgetLoop(L);
284 
285   BasicBlock *NewBB = SplitBlockPredecessors(Header, OuterLoopPreds, ".outer",
286                                              DT, LI, PreserveLCSSA);
287 
288   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
289   // code layout too horribly.
290   placeSplitBlockCarefully(NewBB, OuterLoopPreds, L);
291 
292   // Create the new outer loop.
293   Loop *NewOuter = new Loop();
294 
295   // Change the parent loop to use the outer loop as its child now.
296   if (Loop *Parent = L->getParentLoop())
297     Parent->replaceChildLoopWith(L, NewOuter);
298   else
299     LI->changeTopLevelLoop(L, NewOuter);
300 
301   // L is now a subloop of our outer loop.
302   NewOuter->addChildLoop(L);
303 
304   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
305        I != E; ++I)
306     NewOuter->addBlockEntry(*I);
307 
308   // Now reset the header in L, which had been moved by
309   // SplitBlockPredecessors for the outer loop.
310   L->moveToHeader(Header);
311 
312   // Determine which blocks should stay in L and which should be moved out to
313   // the Outer loop now.
314   std::set<BasicBlock*> BlocksInL;
315   for (pred_iterator PI=pred_begin(Header), E = pred_end(Header); PI!=E; ++PI) {
316     BasicBlock *P = *PI;
317     if (DT->dominates(Header, P))
318       addBlockAndPredsToSet(P, Header, BlocksInL);
319   }
320 
321   // Scan all of the loop children of L, moving them to OuterLoop if they are
322   // not part of the inner loop.
323   const std::vector<Loop*> &SubLoops = L->getSubLoops();
324   for (size_t I = 0; I != SubLoops.size(); )
325     if (BlocksInL.count(SubLoops[I]->getHeader()))
326       ++I;   // Loop remains in L
327     else
328       NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
329 
330   SmallVector<BasicBlock *, 8> OuterLoopBlocks;
331   OuterLoopBlocks.push_back(NewBB);
332   // Now that we know which blocks are in L and which need to be moved to
333   // OuterLoop, move any blocks that need it.
334   for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
335     BasicBlock *BB = L->getBlocks()[i];
336     if (!BlocksInL.count(BB)) {
337       // Move this block to the parent, updating the exit blocks sets
338       L->removeBlockFromLoop(BB);
339       if ((*LI)[BB] == L) {
340         LI->changeLoopFor(BB, NewOuter);
341         OuterLoopBlocks.push_back(BB);
342       }
343       --i;
344     }
345   }
346 
347   // Split edges to exit blocks from the inner loop, if they emerged in the
348   // process of separating the outer one.
349   SmallVector<BasicBlock *, 8> ExitBlocks;
350   L->getExitBlocks(ExitBlocks);
351   SmallSetVector<BasicBlock *, 8> ExitBlockSet(ExitBlocks.begin(),
352                                                ExitBlocks.end());
353   for (BasicBlock *ExitBlock : ExitBlockSet) {
354     if (any_of(predecessors(ExitBlock),
355                [L](BasicBlock *BB) { return !L->contains(BB); })) {
356       rewriteLoopExitBlock(L, ExitBlock, DT, LI, PreserveLCSSA);
357     }
358   }
359 
360   if (PreserveLCSSA) {
361     // Fix LCSSA form for L. Some values, which previously were only used inside
362     // L, can now be used in NewOuter loop. We need to insert phi-nodes for them
363     // in corresponding exit blocks.
364 
365     // Go through all instructions in OuterLoopBlocks and check if they are
366     // using operands from the inner loop. In this case we'll need to fix LCSSA
367     // for these instructions.
368     SmallSetVector<Instruction *, 8> WorklistSet;
369     for (BasicBlock *OuterBB: OuterLoopBlocks) {
370       for (Instruction &I : *OuterBB) {
371         for (Value *Op : I.operands()) {
372           Instruction *OpI = dyn_cast<Instruction>(Op);
373           if (!OpI || !L->contains(OpI))
374             continue;
375           WorklistSet.insert(OpI);
376         }
377       }
378     }
379     // We also need to check exit blocks of the outer loop - it might be using
380     // values from what now became an inner loop.
381     SmallVector<BasicBlock*, 8> ExitBlocks;
382     NewOuter->getExitBlocks(ExitBlocks);
383     for (BasicBlock *ExitBB: ExitBlocks) {
384       for (Instruction &I : *ExitBB) {
385         for (Value *Op : I.operands()) {
386           Instruction *OpI = dyn_cast<Instruction>(Op);
387           if (!OpI || !L->contains(OpI))
388             continue;
389           WorklistSet.insert(OpI);
390         }
391       }
392     }
393 
394     SmallVector<Instruction *, 8> Worklist(WorklistSet.begin(),
395                                            WorklistSet.end());
396     formLCSSAForInstructions(Worklist, *DT, *LI);
397     assert(NewOuter->isRecursivelyLCSSAForm(*DT) &&
398            "LCSSA is broken after separating nested loops!");
399   }
400 
401   return NewOuter;
402 }
403 
404 /// \brief This method is called when the specified loop has more than one
405 /// backedge in it.
406 ///
407 /// If this occurs, revector all of these backedges to target a new basic block
408 /// and have that block branch to the loop header.  This ensures that loops
409 /// have exactly one backedge.
410 static BasicBlock *insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader,
411                                              DominatorTree *DT, LoopInfo *LI) {
412   assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
413 
414   // Get information about the loop
415   BasicBlock *Header = L->getHeader();
416   Function *F = Header->getParent();
417 
418   // Unique backedge insertion currently depends on having a preheader.
419   if (!Preheader)
420     return nullptr;
421 
422   // The header is not an EH pad; preheader insertion should ensure this.
423   assert(!Header->isEHPad() && "Can't insert backedge to EH pad");
424 
425   // Figure out which basic blocks contain back-edges to the loop header.
426   std::vector<BasicBlock*> BackedgeBlocks;
427   for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I){
428     BasicBlock *P = *I;
429 
430     // Indirectbr edges cannot be split, so we must fail if we find one.
431     if (isa<IndirectBrInst>(P->getTerminator()))
432       return nullptr;
433 
434     if (P != Preheader) BackedgeBlocks.push_back(P);
435   }
436 
437   // Create and insert the new backedge block...
438   BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
439                                            Header->getName() + ".backedge", F);
440   BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
441   BETerminator->setDebugLoc(Header->getFirstNonPHI()->getDebugLoc());
442 
443   DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block "
444                << BEBlock->getName() << "\n");
445 
446   // Move the new backedge block to right after the last backedge block.
447   Function::iterator InsertPos = ++BackedgeBlocks.back()->getIterator();
448   F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
449 
450   // Now that the block has been inserted into the function, create PHI nodes in
451   // the backedge block which correspond to any PHI nodes in the header block.
452   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
453     PHINode *PN = cast<PHINode>(I);
454     PHINode *NewPN = PHINode::Create(PN->getType(), BackedgeBlocks.size(),
455                                      PN->getName()+".be", BETerminator);
456 
457     // Loop over the PHI node, moving all entries except the one for the
458     // preheader over to the new PHI node.
459     unsigned PreheaderIdx = ~0U;
460     bool HasUniqueIncomingValue = true;
461     Value *UniqueValue = nullptr;
462     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
463       BasicBlock *IBB = PN->getIncomingBlock(i);
464       Value *IV = PN->getIncomingValue(i);
465       if (IBB == Preheader) {
466         PreheaderIdx = i;
467       } else {
468         NewPN->addIncoming(IV, IBB);
469         if (HasUniqueIncomingValue) {
470           if (!UniqueValue)
471             UniqueValue = IV;
472           else if (UniqueValue != IV)
473             HasUniqueIncomingValue = false;
474         }
475       }
476     }
477 
478     // Delete all of the incoming values from the old PN except the preheader's
479     assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
480     if (PreheaderIdx != 0) {
481       PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
482       PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
483     }
484     // Nuke all entries except the zero'th.
485     for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
486       PN->removeIncomingValue(e-i, false);
487 
488     // Finally, add the newly constructed PHI node as the entry for the BEBlock.
489     PN->addIncoming(NewPN, BEBlock);
490 
491     // As an optimization, if all incoming values in the new PhiNode (which is a
492     // subset of the incoming values of the old PHI node) have the same value,
493     // eliminate the PHI Node.
494     if (HasUniqueIncomingValue) {
495       NewPN->replaceAllUsesWith(UniqueValue);
496       BEBlock->getInstList().erase(NewPN);
497     }
498   }
499 
500   // Now that all of the PHI nodes have been inserted and adjusted, modify the
501   // backedge blocks to just to the BEBlock instead of the header.
502   for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
503     TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
504     for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
505       if (TI->getSuccessor(Op) == Header)
506         TI->setSuccessor(Op, BEBlock);
507   }
508 
509   //===--- Update all analyses which we must preserve now -----------------===//
510 
511   // Update Loop Information - we know that this block is now in the current
512   // loop and all parent loops.
513   L->addBasicBlockToLoop(BEBlock, *LI);
514 
515   // Update dominator information
516   DT->splitBlock(BEBlock);
517 
518   return BEBlock;
519 }
520 
521 /// \brief Simplify one loop and queue further loops for simplification.
522 static bool simplifyOneLoop(Loop *L, SmallVectorImpl<Loop *> &Worklist,
523                             DominatorTree *DT, LoopInfo *LI,
524                             ScalarEvolution *SE, AssumptionCache *AC,
525                             bool PreserveLCSSA) {
526   bool Changed = false;
527 ReprocessLoop:
528 
529   // Check to see that no blocks (other than the header) in this loop have
530   // predecessors that are not in the loop.  This is not valid for natural
531   // loops, but can occur if the blocks are unreachable.  Since they are
532   // unreachable we can just shamelessly delete those CFG edges!
533   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
534        BB != E; ++BB) {
535     if (*BB == L->getHeader()) continue;
536 
537     SmallPtrSet<BasicBlock*, 4> BadPreds;
538     for (pred_iterator PI = pred_begin(*BB),
539          PE = pred_end(*BB); PI != PE; ++PI) {
540       BasicBlock *P = *PI;
541       if (!L->contains(P))
542         BadPreds.insert(P);
543     }
544 
545     // Delete each unique out-of-loop (and thus dead) predecessor.
546     for (BasicBlock *P : BadPreds) {
547 
548       DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor "
549                    << P->getName() << "\n");
550 
551       // Zap the dead pred's terminator and replace it with unreachable.
552       TerminatorInst *TI = P->getTerminator();
553       changeToUnreachable(TI, /*UseLLVMTrap=*/false);
554       Changed = true;
555     }
556   }
557 
558   // If there are exiting blocks with branches on undef, resolve the undef in
559   // the direction which will exit the loop. This will help simplify loop
560   // trip count computations.
561   SmallVector<BasicBlock*, 8> ExitingBlocks;
562   L->getExitingBlocks(ExitingBlocks);
563   for (BasicBlock *ExitingBlock : ExitingBlocks)
564     if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
565       if (BI->isConditional()) {
566         if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
567 
568           DEBUG(dbgs() << "LoopSimplify: Resolving \"br i1 undef\" to exit in "
569                        << ExitingBlock->getName() << "\n");
570 
571           BI->setCondition(ConstantInt::get(Cond->getType(),
572                                             !L->contains(BI->getSuccessor(0))));
573 
574           // This may make the loop analyzable, force SCEV recomputation.
575           if (SE)
576             SE->forgetLoop(L);
577 
578           Changed = true;
579         }
580       }
581 
582   // Does the loop already have a preheader?  If so, don't insert one.
583   BasicBlock *Preheader = L->getLoopPreheader();
584   if (!Preheader) {
585     Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
586     if (Preheader) {
587       ++NumInserted;
588       Changed = true;
589     }
590   }
591 
592   // Next, check to make sure that all exit nodes of the loop only have
593   // predecessors that are inside of the loop.  This check guarantees that the
594   // loop preheader/header will dominate the exit blocks.  If the exit block has
595   // predecessors from outside of the loop, split the edge now.
596   SmallVector<BasicBlock*, 8> ExitBlocks;
597   L->getExitBlocks(ExitBlocks);
598 
599   SmallSetVector<BasicBlock *, 8> ExitBlockSet(ExitBlocks.begin(),
600                                                ExitBlocks.end());
601   for (BasicBlock *ExitBlock : ExitBlockSet) {
602     if (any_of(predecessors(ExitBlock),
603                [L](BasicBlock *BB) { return !L->contains(BB); })) {
604       rewriteLoopExitBlock(L, ExitBlock, DT, LI, PreserveLCSSA);
605       ++NumInserted;
606       Changed = true;
607     }
608   }
609 
610   // If the header has more than two predecessors at this point (from the
611   // preheader and from multiple backedges), we must adjust the loop.
612   BasicBlock *LoopLatch = L->getLoopLatch();
613   if (!LoopLatch) {
614     // If this is really a nested loop, rip it out into a child loop.  Don't do
615     // this for loops with a giant number of backedges, just factor them into a
616     // common backedge instead.
617     if (L->getNumBackEdges() < 8) {
618       if (Loop *OuterL =
619               separateNestedLoop(L, Preheader, DT, LI, SE, PreserveLCSSA, AC)) {
620         ++NumNested;
621         // Enqueue the outer loop as it should be processed next in our
622         // depth-first nest walk.
623         Worklist.push_back(OuterL);
624 
625         // This is a big restructuring change, reprocess the whole loop.
626         Changed = true;
627         // GCC doesn't tail recursion eliminate this.
628         // FIXME: It isn't clear we can't rely on LLVM to TRE this.
629         goto ReprocessLoop;
630       }
631     }
632 
633     // If we either couldn't, or didn't want to, identify nesting of the loops,
634     // insert a new block that all backedges target, then make it jump to the
635     // loop header.
636     LoopLatch = insertUniqueBackedgeBlock(L, Preheader, DT, LI);
637     if (LoopLatch) {
638       ++NumInserted;
639       Changed = true;
640     }
641   }
642 
643   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
644 
645   // Scan over the PHI nodes in the loop header.  Since they now have only two
646   // incoming values (the loop is canonicalized), we may have simplified the PHI
647   // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
648   PHINode *PN;
649   for (BasicBlock::iterator I = L->getHeader()->begin();
650        (PN = dyn_cast<PHINode>(I++)); )
651     if (Value *V = SimplifyInstruction(PN, DL, nullptr, DT, AC)) {
652       if (SE) SE->forgetValue(PN);
653       PN->replaceAllUsesWith(V);
654       PN->eraseFromParent();
655     }
656 
657   // If this loop has multiple exits and the exits all go to the same
658   // block, attempt to merge the exits. This helps several passes, such
659   // as LoopRotation, which do not support loops with multiple exits.
660   // SimplifyCFG also does this (and this code uses the same utility
661   // function), however this code is loop-aware, where SimplifyCFG is
662   // not. That gives it the advantage of being able to hoist
663   // loop-invariant instructions out of the way to open up more
664   // opportunities, and the disadvantage of having the responsibility
665   // to preserve dominator information.
666   bool UniqueExit = true;
667   if (!ExitBlocks.empty())
668     for (unsigned i = 1, e = ExitBlocks.size(); i != e; ++i)
669       if (ExitBlocks[i] != ExitBlocks[0]) {
670         UniqueExit = false;
671         break;
672       }
673   if (UniqueExit) {
674     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
675       BasicBlock *ExitingBlock = ExitingBlocks[i];
676       if (!ExitingBlock->getSinglePredecessor()) continue;
677       BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
678       if (!BI || !BI->isConditional()) continue;
679       CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
680       if (!CI || CI->getParent() != ExitingBlock) continue;
681 
682       // Attempt to hoist out all instructions except for the
683       // comparison and the branch.
684       bool AllInvariant = true;
685       bool AnyInvariant = false;
686       for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) {
687         Instruction *Inst = &*I++;
688         // Skip debug info intrinsics.
689         if (isa<DbgInfoIntrinsic>(Inst))
690           continue;
691         if (Inst == CI)
692           continue;
693         if (!L->makeLoopInvariant(Inst, AnyInvariant,
694                                   Preheader ? Preheader->getTerminator()
695                                             : nullptr)) {
696           AllInvariant = false;
697           break;
698         }
699       }
700       if (AnyInvariant) {
701         Changed = true;
702         // The loop disposition of all SCEV expressions that depend on any
703         // hoisted values have also changed.
704         if (SE)
705           SE->forgetLoopDispositions(L);
706       }
707       if (!AllInvariant) continue;
708 
709       // The block has now been cleared of all instructions except for
710       // a comparison and a conditional branch. SimplifyCFG may be able
711       // to fold it now.
712       if (!FoldBranchToCommonDest(BI))
713         continue;
714 
715       // Success. The block is now dead, so remove it from the loop,
716       // update the dominator tree and delete it.
717       DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block "
718                    << ExitingBlock->getName() << "\n");
719 
720       // Notify ScalarEvolution before deleting this block. Currently assume the
721       // parent loop doesn't change (spliting edges doesn't count). If blocks,
722       // CFG edges, or other values in the parent loop change, then we need call
723       // to forgetLoop() for the parent instead.
724       if (SE)
725         SE->forgetLoop(L);
726 
727       assert(pred_begin(ExitingBlock) == pred_end(ExitingBlock));
728       Changed = true;
729       LI->removeBlock(ExitingBlock);
730 
731       DomTreeNode *Node = DT->getNode(ExitingBlock);
732       const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
733         Node->getChildren();
734       while (!Children.empty()) {
735         DomTreeNode *Child = Children.front();
736         DT->changeImmediateDominator(Child, Node->getIDom());
737       }
738       DT->eraseNode(ExitingBlock);
739 
740       BI->getSuccessor(0)->removePredecessor(
741           ExitingBlock, /* DontDeleteUselessPHIs */ PreserveLCSSA);
742       BI->getSuccessor(1)->removePredecessor(
743           ExitingBlock, /* DontDeleteUselessPHIs */ PreserveLCSSA);
744       ExitingBlock->eraseFromParent();
745     }
746   }
747 
748   return Changed;
749 }
750 
751 bool llvm::simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI,
752                         ScalarEvolution *SE, AssumptionCache *AC,
753                         bool PreserveLCSSA) {
754   bool Changed = false;
755 
756   // Worklist maintains our depth-first queue of loops in this nest to process.
757   SmallVector<Loop *, 4> Worklist;
758   Worklist.push_back(L);
759 
760   // Walk the worklist from front to back, pushing newly found sub loops onto
761   // the back. This will let us process loops from back to front in depth-first
762   // order. We can use this simple process because loops form a tree.
763   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
764     Loop *L2 = Worklist[Idx];
765     Worklist.append(L2->begin(), L2->end());
766   }
767 
768   while (!Worklist.empty())
769     Changed |= simplifyOneLoop(Worklist.pop_back_val(), Worklist, DT, LI, SE,
770                                AC, PreserveLCSSA);
771 
772   return Changed;
773 }
774 
775 namespace {
776   struct LoopSimplify : public FunctionPass {
777     static char ID; // Pass identification, replacement for typeid
778     LoopSimplify() : FunctionPass(ID) {
779       initializeLoopSimplifyPass(*PassRegistry::getPassRegistry());
780     }
781 
782     bool runOnFunction(Function &F) override;
783 
784     void getAnalysisUsage(AnalysisUsage &AU) const override {
785       AU.addRequired<AssumptionCacheTracker>();
786 
787       // We need loop information to identify the loops...
788       AU.addRequired<DominatorTreeWrapperPass>();
789       AU.addPreserved<DominatorTreeWrapperPass>();
790 
791       AU.addRequired<LoopInfoWrapperPass>();
792       AU.addPreserved<LoopInfoWrapperPass>();
793 
794       AU.addPreserved<BasicAAWrapperPass>();
795       AU.addPreserved<AAResultsWrapperPass>();
796       AU.addPreserved<GlobalsAAWrapperPass>();
797       AU.addPreserved<ScalarEvolutionWrapperPass>();
798       AU.addPreserved<SCEVAAWrapperPass>();
799       AU.addPreservedID(LCSSAID);
800       AU.addPreserved<DependenceAnalysisWrapperPass>();
801       AU.addPreservedID(BreakCriticalEdgesID);  // No critical edges added.
802     }
803 
804     /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees.
805     void verifyAnalysis() const override;
806   };
807 }
808 
809 char LoopSimplify::ID = 0;
810 INITIALIZE_PASS_BEGIN(LoopSimplify, "loop-simplify",
811                 "Canonicalize natural loops", false, false)
812 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
813 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
814 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
815 INITIALIZE_PASS_END(LoopSimplify, "loop-simplify",
816                 "Canonicalize natural loops", false, false)
817 
818 // Publicly exposed interface to pass...
819 char &llvm::LoopSimplifyID = LoopSimplify::ID;
820 Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
821 
822 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
823 /// it in any convenient order) inserting preheaders...
824 ///
825 bool LoopSimplify::runOnFunction(Function &F) {
826   bool Changed = false;
827   LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
828   DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
829   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
830   ScalarEvolution *SE = SEWP ? &SEWP->getSE() : nullptr;
831   AssumptionCache *AC =
832       &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
833 
834   bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
835 #ifndef NDEBUG
836   if (PreserveLCSSA) {
837     assert(DT && "DT not available.");
838     assert(LI && "LI not available.");
839     bool InLCSSA =
840         all_of(*LI, [&](Loop *L) { return L->isRecursivelyLCSSAForm(*DT); });
841     assert(InLCSSA && "Requested to preserve LCSSA, but it's already broken.");
842   }
843 #endif
844 
845   // Simplify each loop nest in the function.
846   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
847     Changed |= simplifyLoop(*I, DT, LI, SE, AC, PreserveLCSSA);
848 
849 #ifndef NDEBUG
850   if (PreserveLCSSA) {
851     bool InLCSSA =
852         all_of(*LI, [&](Loop *L) { return L->isRecursivelyLCSSAForm(*DT); });
853     assert(InLCSSA && "LCSSA is broken after loop-simplify.");
854   }
855 #endif
856   return Changed;
857 }
858 
859 PreservedAnalyses LoopSimplifyPass::run(Function &F,
860                                         AnalysisManager<Function> &AM) {
861   bool Changed = false;
862   LoopInfo *LI = &AM.getResult<LoopAnalysis>(F);
863   DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
864   ScalarEvolution *SE = AM.getCachedResult<ScalarEvolutionAnalysis>(F);
865   AssumptionCache *AC = &AM.getResult<AssumptionAnalysis>(F);
866 
867   // FIXME: This pass should verify that the loops on which it's operating
868   // are in canonical SSA form, and that the pass itself preserves this form.
869   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
870     Changed |= simplifyLoop(*I, DT, LI, SE, AC, true /* PreserveLCSSA */);
871 
872   if (!Changed)
873     return PreservedAnalyses::all();
874   PreservedAnalyses PA;
875   PA.preserve<DominatorTreeAnalysis>();
876   PA.preserve<LoopAnalysis>();
877   PA.preserve<BasicAA>();
878   PA.preserve<GlobalsAA>();
879   PA.preserve<SCEVAA>();
880   PA.preserve<ScalarEvolutionAnalysis>();
881   PA.preserve<DependenceAnalysis>();
882   return PA;
883 }
884 
885 // FIXME: Restore this code when we re-enable verification in verifyAnalysis
886 // below.
887 #if 0
888 static void verifyLoop(Loop *L) {
889   // Verify subloops.
890   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
891     verifyLoop(*I);
892 
893   // It used to be possible to just assert L->isLoopSimplifyForm(), however
894   // with the introduction of indirectbr, there are now cases where it's
895   // not possible to transform a loop as necessary. We can at least check
896   // that there is an indirectbr near any time there's trouble.
897 
898   // Indirectbr can interfere with preheader and unique backedge insertion.
899   if (!L->getLoopPreheader() || !L->getLoopLatch()) {
900     bool HasIndBrPred = false;
901     for (pred_iterator PI = pred_begin(L->getHeader()),
902          PE = pred_end(L->getHeader()); PI != PE; ++PI)
903       if (isa<IndirectBrInst>((*PI)->getTerminator())) {
904         HasIndBrPred = true;
905         break;
906       }
907     assert(HasIndBrPred &&
908            "LoopSimplify has no excuse for missing loop header info!");
909     (void)HasIndBrPred;
910   }
911 
912   // Indirectbr can interfere with exit block canonicalization.
913   if (!L->hasDedicatedExits()) {
914     bool HasIndBrExiting = false;
915     SmallVector<BasicBlock*, 8> ExitingBlocks;
916     L->getExitingBlocks(ExitingBlocks);
917     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
918       if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
919         HasIndBrExiting = true;
920         break;
921       }
922     }
923 
924     assert(HasIndBrExiting &&
925            "LoopSimplify has no excuse for missing exit block info!");
926     (void)HasIndBrExiting;
927   }
928 }
929 #endif
930 
931 void LoopSimplify::verifyAnalysis() const {
932   // FIXME: This routine is being called mid-way through the loop pass manager
933   // as loop passes destroy this analysis. That's actually fine, but we have no
934   // way of expressing that here. Once all of the passes that destroy this are
935   // hoisted out of the loop pass manager we can add back verification here.
936 #if 0
937   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
938     verifyLoop(*I);
939 #endif
940 }
941