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