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