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