1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass transforms loops that contain branches on loop-invariant conditions
11 // to have multiple loops. For example, it turns the left into the right code:
20 // This can increase the size of the code exponentially (doubling it every time
21 // a loop is unswitched) so we only unswitch if the resultant code will be
22 // smaller than a threshold.
24 // This pass expects LICM to be run before it to hoist invariant conditions out
25 // of the loop, to make the unswitching opportunity obvious.
27 //===----------------------------------------------------------------------===//
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Analysis/AssumptionCache.h"
34 #include "llvm/Analysis/CodeMetrics.h"
35 #include "llvm/Analysis/InstructionSimplify.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Analysis/ScalarEvolution.h"
39 #include "llvm/Analysis/TargetTransformInfo.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/MDBuilder.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
51 #include "llvm/Transforms/Utils/Cloning.h"
52 #include "llvm/Transforms/Utils/Local.h"
58 #define DEBUG_TYPE "loop-unswitch"
60 STATISTIC(NumBranches, "Number of branches unswitched");
61 STATISTIC(NumSwitches, "Number of switches unswitched");
62 STATISTIC(NumSelects , "Number of selects unswitched");
63 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
64 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
65 STATISTIC(TotalInsts, "Total number of instructions analyzed");
67 // The specific value of 100 here was chosen based only on intuition and a
68 // few specific examples.
69 static cl::opt<unsigned>
70 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
71 cl::init(100), cl::Hidden);
75 class LUAnalysisCache {
77 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
80 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
82 struct LoopProperties {
83 unsigned CanBeUnswitchedCount;
84 unsigned SizeEstimation;
85 UnswitchedValsMap UnswitchedVals;
88 // Here we use std::map instead of DenseMap, since we need to keep valid
89 // LoopProperties pointer for current loop for better performance.
90 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
91 typedef LoopPropsMap::iterator LoopPropsMapIt;
93 LoopPropsMap LoopsProperties;
94 UnswitchedValsMap *CurLoopInstructions;
95 LoopProperties *CurrentLoopProperties;
97 // Max size of code we can produce on remained iterations.
103 CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
107 // Analyze loop. Check its size, calculate is it possible to unswitch
108 // it. Returns true if we can unswitch this loop.
109 bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
110 AssumptionCache *AC);
112 // Clean all data related to given loop.
113 void forgetLoop(const Loop *L);
115 // Mark case value as unswitched.
116 // Since SI instruction can be partly unswitched, in order to avoid
117 // extra unswitching in cloned loops keep track all unswitched values.
118 void setUnswitched(const SwitchInst *SI, const Value *V);
120 // Check was this case value unswitched before or not.
121 bool isUnswitched(const SwitchInst *SI, const Value *V);
123 // Clone all loop-unswitch related loop properties.
124 // Redistribute unswitching quotas.
125 // Note, that new loop data is stored inside the VMap.
126 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
127 const ValueToValueMapTy &VMap);
130 class LoopUnswitch : public LoopPass {
131 LoopInfo *LI; // Loop information
135 // LoopProcessWorklist - Used to check if second loop needs processing
136 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
137 std::vector<Loop*> LoopProcessWorklist;
139 LUAnalysisCache BranchesInfo;
141 bool OptimizeForSize;
146 BasicBlock *loopHeader;
147 BasicBlock *loopPreheader;
149 // LoopBlocks contains all of the basic blocks of the loop, including the
150 // preheader of the loop, the body of the loop, and the exit blocks of the
151 // loop, in that order.
152 std::vector<BasicBlock*> LoopBlocks;
153 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
154 std::vector<BasicBlock*> NewBlocks;
157 static char ID; // Pass ID, replacement for typeid
158 explicit LoopUnswitch(bool Os = false) :
159 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
160 currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
161 loopPreheader(nullptr) {
162 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
165 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
166 bool processCurrentLoop();
168 /// This transformation requires natural loop information & requires that
169 /// loop preheaders be inserted into the CFG.
171 void getAnalysisUsage(AnalysisUsage &AU) const override {
172 AU.addRequired<AssumptionCacheTracker>();
173 AU.addRequiredID(LoopSimplifyID);
174 AU.addPreservedID(LoopSimplifyID);
175 AU.addRequired<LoopInfoWrapperPass>();
176 AU.addPreserved<LoopInfoWrapperPass>();
177 AU.addRequiredID(LCSSAID);
178 AU.addPreservedID(LCSSAID);
179 AU.addPreserved<DominatorTreeWrapperPass>();
180 AU.addPreserved<ScalarEvolution>();
181 AU.addRequired<TargetTransformInfoWrapperPass>();
186 void releaseMemory() override {
187 BranchesInfo.forgetLoop(currentLoop);
190 void initLoopData() {
191 loopHeader = currentLoop->getHeader();
192 loopPreheader = currentLoop->getLoopPreheader();
195 /// Split all of the edges from inside the loop to their exit blocks.
196 /// Update the appropriate Phi nodes as we do so.
197 void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
199 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
200 TerminatorInst *TI = nullptr);
201 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
202 BasicBlock *ExitBlock, TerminatorInst *TI);
203 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
206 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
207 Constant *Val, bool isEqual);
209 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
210 BasicBlock *TrueDest,
211 BasicBlock *FalseDest,
212 Instruction *InsertPt,
215 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
216 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = nullptr,
217 BasicBlock **LoopExit = nullptr);
222 // Analyze loop. Check its size, calculate is it possible to unswitch
223 // it. Returns true if we can unswitch this loop.
224 bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
225 AssumptionCache *AC) {
227 LoopPropsMapIt PropsIt;
229 std::tie(PropsIt, Inserted) =
230 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
232 LoopProperties &Props = PropsIt->second;
237 // Limit the number of instructions to avoid causing significant code
238 // expansion, and the number of basic blocks, to avoid loops with
239 // large numbers of branches which cause loop unswitching to go crazy.
240 // This is a very ad-hoc heuristic.
242 SmallPtrSet<const Value *, 32> EphValues;
243 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
245 // FIXME: This is overly conservative because it does not take into
246 // consideration code simplification opportunities and code that can
247 // be shared by the resultant unswitched loops.
249 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
251 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
253 Props.SizeEstimation = std::min(Metrics.NumInsts, Metrics.NumBlocks * 5);
254 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
255 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
257 if (Metrics.notDuplicatable) {
258 DEBUG(dbgs() << "NOT unswitching loop %"
259 << L->getHeader()->getName() << ", contents cannot be "
265 if (!Props.CanBeUnswitchedCount) {
266 DEBUG(dbgs() << "NOT unswitching loop %"
267 << L->getHeader()->getName() << ", cost too high: "
268 << L->getBlocks().size() << "\n");
272 // Be careful. This links are good only before new loop addition.
273 CurrentLoopProperties = &Props;
274 CurLoopInstructions = &Props.UnswitchedVals;
279 // Clean all data related to given loop.
280 void LUAnalysisCache::forgetLoop(const Loop *L) {
282 LoopPropsMapIt LIt = LoopsProperties.find(L);
284 if (LIt != LoopsProperties.end()) {
285 LoopProperties &Props = LIt->second;
286 MaxSize += Props.CanBeUnswitchedCount * Props.SizeEstimation;
287 LoopsProperties.erase(LIt);
290 CurrentLoopProperties = nullptr;
291 CurLoopInstructions = nullptr;
294 // Mark case value as unswitched.
295 // Since SI instruction can be partly unswitched, in order to avoid
296 // extra unswitching in cloned loops keep track all unswitched values.
297 void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
298 (*CurLoopInstructions)[SI].insert(V);
301 // Check was this case value unswitched before or not.
302 bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
303 return (*CurLoopInstructions)[SI].count(V);
306 // Clone all loop-unswitch related loop properties.
307 // Redistribute unswitching quotas.
308 // Note, that new loop data is stored inside the VMap.
309 void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
310 const ValueToValueMapTy &VMap) {
312 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
313 LoopProperties &OldLoopProps = *CurrentLoopProperties;
314 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
316 // Reallocate "can-be-unswitched quota"
318 --OldLoopProps.CanBeUnswitchedCount;
319 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
320 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
321 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
323 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
325 // Clone unswitched values info:
326 // for new loop switches we clone info about values that was
327 // already unswitched and has redundant successors.
328 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
329 const SwitchInst *OldInst = I->first;
330 Value *NewI = VMap.lookup(OldInst);
331 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
332 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
334 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
338 char LoopUnswitch::ID = 0;
339 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
341 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
342 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
343 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
344 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
345 INITIALIZE_PASS_DEPENDENCY(LCSSA)
346 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
349 Pass *llvm::createLoopUnswitchPass(bool Os) {
350 return new LoopUnswitch(Os);
353 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
354 /// invariant in the loop, or has an invariant piece, return the invariant.
355 /// Otherwise, return null.
356 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
358 // We started analyze new instruction, increment scanned instructions counter.
361 // We can never unswitch on vector conditions.
362 if (Cond->getType()->isVectorTy())
365 // Constants should be folded, not unswitched on!
366 if (isa<Constant>(Cond)) return nullptr;
368 // TODO: Handle: br (VARIANT|INVARIANT).
370 // Hoist simple values out.
371 if (L->makeLoopInvariant(Cond, Changed))
374 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
375 if (BO->getOpcode() == Instruction::And ||
376 BO->getOpcode() == Instruction::Or) {
377 // If either the left or right side is invariant, we can unswitch on this,
378 // which will cause the branch to go away in one loop and the condition to
379 // simplify in the other one.
380 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
382 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
389 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
390 if (skipOptnoneFunction(L))
393 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
394 *L->getHeader()->getParent());
395 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
397 DominatorTreeWrapperPass *DTWP =
398 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
399 DT = DTWP ? &DTWP->getDomTree() : nullptr;
401 Function *F = currentLoop->getHeader()->getParent();
402 bool Changed = false;
404 assert(currentLoop->isLCSSAForm(*DT));
406 Changed |= processCurrentLoop();
410 // FIXME: Reconstruct dom info, because it is not preserved properly.
417 /// processCurrentLoop - Do actual work and unswitch loop if possible
419 bool LoopUnswitch::processCurrentLoop() {
420 bool Changed = false;
424 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
428 // Loops with indirectbr cannot be cloned.
429 if (!currentLoop->isSafeToClone())
432 // Without dedicated exits, splitting the exit edge may fail.
433 if (!currentLoop->hasDedicatedExits())
436 LLVMContext &Context = loopHeader->getContext();
438 // Probably we reach the quota of branches for this loop. If so
440 if (!BranchesInfo.countLoop(
441 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
442 *currentLoop->getHeader()->getParent()),
446 // Loop over all of the basic blocks in the loop. If we find an interior
447 // block that is branching on a loop-invariant condition, we can unswitch this
449 for (Loop::block_iterator I = currentLoop->block_begin(),
450 E = currentLoop->block_end(); I != E; ++I) {
451 TerminatorInst *TI = (*I)->getTerminator();
452 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
453 // If this isn't branching on an invariant condition, we can't unswitch
455 if (BI->isConditional()) {
456 // See if this, or some part of it, is loop invariant. If so, we can
457 // unswitch on it if we desire.
458 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
459 currentLoop, Changed);
461 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
466 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
467 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
468 currentLoop, Changed);
469 unsigned NumCases = SI->getNumCases();
470 if (LoopCond && NumCases) {
471 // Find a value to unswitch on:
472 // FIXME: this should chose the most expensive case!
473 // FIXME: scan for a case with a non-critical edge?
474 Constant *UnswitchVal = nullptr;
476 // Do not process same value again and again.
477 // At this point we have some cases already unswitched and
478 // some not yet unswitched. Let's find the first not yet unswitched one.
479 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
481 Constant *UnswitchValCandidate = i.getCaseValue();
482 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
483 UnswitchVal = UnswitchValCandidate;
491 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
498 // Scan the instructions to check for unswitchable values.
499 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
501 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
502 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
503 currentLoop, Changed);
504 if (LoopCond && UnswitchIfProfitable(LoopCond,
505 ConstantInt::getTrue(Context))) {
514 /// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
515 /// loop with no side effects (including infinite loops).
517 /// If true, we return true and set ExitBB to the block we
520 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
522 std::set<BasicBlock*> &Visited) {
523 if (!Visited.insert(BB).second) {
524 // Already visited. Without more analysis, this could indicate an infinite
528 if (!L->contains(BB)) {
529 // Otherwise, this is a loop exit, this is fine so long as this is the
531 if (ExitBB) return false;
536 // Otherwise, this is an unvisited intra-loop node. Check all successors.
537 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
538 // Check to see if the successor is a trivial loop exit.
539 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
543 // Okay, everything after this looks good, check to make sure that this block
544 // doesn't include any side effects.
545 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
546 if (I->mayHaveSideEffects())
552 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
553 /// leads to an exit from the specified loop, and has no side-effects in the
554 /// process. If so, return the block that is exited to, otherwise return null.
555 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
556 std::set<BasicBlock*> Visited;
557 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
558 BasicBlock *ExitBB = nullptr;
559 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
564 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
565 /// trivial: that is, that the condition controls whether or not the loop does
566 /// anything at all. If this is a trivial condition, unswitching produces no
567 /// code duplications (equivalently, it produces a simpler loop and a new empty
568 /// loop, which gets deleted).
570 /// If this is a trivial condition, return true, otherwise return false. When
571 /// returning true, this sets Cond and Val to the condition that controls the
572 /// trivial condition: when Cond dynamically equals Val, the loop is known to
573 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
576 bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
577 BasicBlock **LoopExit) {
578 BasicBlock *Header = currentLoop->getHeader();
579 TerminatorInst *HeaderTerm = Header->getTerminator();
580 LLVMContext &Context = Header->getContext();
582 BasicBlock *LoopExitBB = nullptr;
583 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
584 // If the header block doesn't end with a conditional branch on Cond, we
586 if (!BI->isConditional() || BI->getCondition() != Cond)
589 // Check to see if a successor of the branch is guaranteed to
590 // exit through a unique exit block without having any
591 // side-effects. If so, determine the value of Cond that causes it to do
593 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
594 BI->getSuccessor(0)))) {
595 if (Val) *Val = ConstantInt::getTrue(Context);
596 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
597 BI->getSuccessor(1)))) {
598 if (Val) *Val = ConstantInt::getFalse(Context);
600 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
601 // If this isn't a switch on Cond, we can't handle it.
602 if (SI->getCondition() != Cond) return false;
604 // Check to see if a successor of the switch is guaranteed to go to the
605 // latch block or exit through a one exit block without having any
606 // side-effects. If so, determine the value of Cond that causes it to do
608 // Note that we can't trivially unswitch on the default case or
609 // on already unswitched cases.
610 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
612 BasicBlock *LoopExitCandidate;
613 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
614 i.getCaseSuccessor()))) {
615 // Okay, we found a trivial case, remember the value that is trivial.
616 ConstantInt *CaseVal = i.getCaseValue();
618 // Check that it was not unswitched before, since already unswitched
619 // trivial vals are looks trivial too.
620 if (BranchesInfo.isUnswitched(SI, CaseVal))
622 LoopExitBB = LoopExitCandidate;
623 if (Val) *Val = CaseVal;
629 // If we didn't find a single unique LoopExit block, or if the loop exit block
630 // contains phi nodes, this isn't trivial.
631 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
632 return false; // Can't handle this.
634 if (LoopExit) *LoopExit = LoopExitBB;
636 // We already know that nothing uses any scalar values defined inside of this
637 // loop. As such, we just have to check to see if this loop will execute any
638 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
639 // part of the loop that the code *would* execute. We already checked the
640 // tail, check the header now.
641 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
642 if (I->mayHaveSideEffects())
647 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
648 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
649 /// unswitch the loop, reprocess the pieces, then return true.
650 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
651 TerminatorInst *TI) {
652 Function *F = loopHeader->getParent();
653 Constant *CondVal = nullptr;
654 BasicBlock *ExitBlock = nullptr;
656 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
657 // If the condition is trivial, always unswitch. There is no code growth
659 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock, TI);
663 // Check to see if it would be profitable to unswitch current loop.
665 // Do not do non-trivial unswitch while optimizing for size.
666 if (OptimizeForSize || F->hasFnAttribute(Attribute::OptimizeForSize))
669 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
673 /// CloneLoop - Recursively clone the specified loop and all of its children,
674 /// mapping the blocks with the specified map.
675 static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
676 LoopInfo *LI, LPPassManager *LPM) {
677 Loop *New = new Loop();
678 LPM->insertLoop(New, PL);
680 // Add all of the blocks in L to the new loop.
681 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
683 if (LI->getLoopFor(*I) == L)
684 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
686 // Add all of the subloops to the new loop.
687 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
688 CloneLoop(*I, New, VM, LI, LPM);
693 static void copyMetadata(Instruction *DstInst, const Instruction *SrcInst,
695 if (!SrcInst || !SrcInst->hasMetadata())
698 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
699 SrcInst->getAllMetadata(MDs);
700 for (auto &MD : MDs) {
704 case LLVMContext::MD_prof:
705 if (Swapped && MD.second->getNumOperands() == 3 &&
706 isa<MDString>(MD.second->getOperand(0))) {
707 MDString *MDName = cast<MDString>(MD.second->getOperand(0));
708 if (MDName->getString() == "branch_weights") {
709 auto *ValT = cast_or_null<ConstantAsMetadata>(
710 MD.second->getOperand(1))->getValue();
711 auto *ValF = cast_or_null<ConstantAsMetadata>(
712 MD.second->getOperand(2))->getValue();
713 assert(ValT && ValF && "Invalid Operands of branch_weights");
715 MDBuilder(DstInst->getParent()->getContext())
716 .createBranchWeights(cast<ConstantInt>(ValF)->getZExtValue(),
717 cast<ConstantInt>(ValT)->getZExtValue());
722 case LLVMContext::MD_dbg:
723 DstInst->setMetadata(MD.first, MD.second);
728 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
729 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
730 /// code immediately before InsertPt.
731 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
732 BasicBlock *TrueDest,
733 BasicBlock *FalseDest,
734 Instruction *InsertPt,
735 TerminatorInst *TI) {
736 // Insert a conditional branch on LIC to the two preheaders. The original
737 // code is the true version and the new code is the false version.
738 Value *BranchVal = LIC;
739 bool Swapped = false;
740 if (!isa<ConstantInt>(Val) ||
741 Val->getType() != Type::getInt1Ty(LIC->getContext()))
742 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
743 else if (Val != ConstantInt::getTrue(Val->getContext())) {
744 // We want to enter the new loop when the condition is true.
745 std::swap(TrueDest, FalseDest);
749 // Insert the new branch.
750 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
751 copyMetadata(BI, TI, Swapped);
753 // If either edge is critical, split it. This helps preserve LoopSimplify
754 // form for enclosing loops.
755 auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
756 SplitCriticalEdge(BI, 0, Options);
757 SplitCriticalEdge(BI, 1, Options);
760 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
761 /// condition in it (a cond branch from its header block to its latch block,
762 /// where the path through the loop that doesn't execute its body has no
763 /// side-effects), unswitch it. This doesn't involve any code duplication, just
764 /// moving the conditional branch outside of the loop and updating loop info.
765 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
766 BasicBlock *ExitBlock,
767 TerminatorInst *TI) {
768 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
769 << loopHeader->getName() << " [" << L->getBlocks().size()
770 << " blocks] in Function "
771 << L->getHeader()->getParent()->getName() << " on cond: " << *Val
772 << " == " << *Cond << "\n");
774 // First step, split the preheader, so that we know that there is a safe place
775 // to insert the conditional branch. We will change loopPreheader to have a
776 // conditional branch on Cond.
777 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
779 // Now that we have a place to insert the conditional branch, create a place
780 // to branch to: this is the exit block out of the loop that we should
783 // Split this block now, so that the loop maintains its exit block, and so
784 // that the jump from the preheader can execute the contents of the exit block
785 // without actually branching to it (the exit block should be dominated by the
786 // loop header, not the preheader).
787 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
788 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), DT, LI);
790 // Okay, now we have a position to branch from and a position to branch to,
791 // insert the new conditional branch.
792 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
793 loopPreheader->getTerminator(), TI);
794 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
795 loopPreheader->getTerminator()->eraseFromParent();
797 // We need to reprocess this loop, it could be unswitched again.
800 // Now that we know that the loop is never entered when this condition is a
801 // particular value, rewrite the loop with this info. We know that this will
802 // at least eliminate the old branch.
803 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
807 /// SplitExitEdges - Split all of the edges from inside the loop to their exit
808 /// blocks. Update the appropriate Phi nodes as we do so.
809 void LoopUnswitch::SplitExitEdges(Loop *L,
810 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
812 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
813 BasicBlock *ExitBlock = ExitBlocks[i];
814 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
815 pred_end(ExitBlock));
817 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
818 // general, if we call it on all predecessors of all exits then it does.
819 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa",
820 /*AliasAnalysis*/ nullptr, DT, LI,
821 /*PreserveLCSSA*/ true);
825 /// UnswitchNontrivialCondition - We determined that the loop is profitable
826 /// to unswitch when LIC equal Val. Split it into loop versions and test the
827 /// condition outside of either loop. Return the loops created as Out1/Out2.
828 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
829 Loop *L, TerminatorInst *TI) {
830 Function *F = loopHeader->getParent();
831 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
832 << loopHeader->getName() << " [" << L->getBlocks().size()
833 << " blocks] in Function " << F->getName()
834 << " when '" << *Val << "' == " << *LIC << "\n");
836 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
842 // First step, split the preheader and exit blocks, and add these blocks to
843 // the LoopBlocks list.
844 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
845 LoopBlocks.push_back(NewPreheader);
847 // We want the loop to come after the preheader, but before the exit blocks.
848 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
850 SmallVector<BasicBlock*, 8> ExitBlocks;
851 L->getUniqueExitBlocks(ExitBlocks);
853 // Split all of the edges from inside the loop to their exit blocks. Update
854 // the appropriate Phi nodes as we do so.
855 SplitExitEdges(L, ExitBlocks);
857 // The exit blocks may have been changed due to edge splitting, recompute.
859 L->getUniqueExitBlocks(ExitBlocks);
861 // Add exit blocks to the loop blocks.
862 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
864 // Next step, clone all of the basic blocks that make up the loop (including
865 // the loop preheader and exit blocks), keeping track of the mapping between
866 // the instructions and blocks.
867 NewBlocks.reserve(LoopBlocks.size());
868 ValueToValueMapTy VMap;
869 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
870 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
872 NewBlocks.push_back(NewBB);
873 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
874 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
877 // Splice the newly inserted blocks into the function right before the
878 // original preheader.
879 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
880 NewBlocks[0], F->end());
882 // FIXME: We could register any cloned assumptions instead of clearing the
883 // whole function's cache.
886 // Now we create the new Loop object for the versioned loop.
887 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
889 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
890 // Probably clone more loop-unswitch related loop properties.
891 BranchesInfo.cloneData(NewLoop, L, VMap);
893 Loop *ParentLoop = L->getParentLoop();
895 // Make sure to add the cloned preheader and exit blocks to the parent loop
897 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
900 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
901 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
902 // The new exit block should be in the same loop as the old one.
903 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
904 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
906 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
907 "Exit block should have been split to have one successor!");
908 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
910 // If the successor of the exit block had PHI nodes, add an entry for
912 for (BasicBlock::iterator I = ExitSucc->begin();
913 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
914 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
915 ValueToValueMapTy::iterator It = VMap.find(V);
916 if (It != VMap.end()) V = It->second;
917 PN->addIncoming(V, NewExit);
920 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
921 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
922 ExitSucc->getFirstInsertionPt());
924 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
927 LandingPadInst *LPI = BB->getLandingPadInst();
928 LPI->replaceAllUsesWith(PN);
929 PN->addIncoming(LPI, BB);
934 // Rewrite the code to refer to itself.
935 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
936 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
937 E = NewBlocks[i]->end(); I != E; ++I)
938 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
940 // Rewrite the original preheader to select between versions of the loop.
941 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
942 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
943 "Preheader splitting did not work correctly!");
945 // Emit the new branch that selects between the two versions of this loop.
946 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
948 LPM->deleteSimpleAnalysisValue(OldBR, L);
949 OldBR->eraseFromParent();
951 LoopProcessWorklist.push_back(NewLoop);
954 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
955 // deletes the instruction (for example by simplifying a PHI that feeds into
956 // the condition that we're unswitching on), we don't rewrite the second
958 WeakVH LICHandle(LIC);
960 // Now we rewrite the original code to know that the condition is true and the
961 // new code to know that the condition is false.
962 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
964 // It's possible that simplifying one loop could cause the other to be
965 // changed to another value or a constant. If its a constant, don't simplify
967 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
968 LICHandle && !isa<Constant>(LICHandle))
969 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
972 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
974 static void RemoveFromWorklist(Instruction *I,
975 std::vector<Instruction*> &Worklist) {
977 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
981 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
982 /// program, replacing all uses with V and update the worklist.
983 static void ReplaceUsesOfWith(Instruction *I, Value *V,
984 std::vector<Instruction*> &Worklist,
985 Loop *L, LPPassManager *LPM) {
986 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
988 // Add uses to the worklist, which may be dead now.
989 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
990 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
991 Worklist.push_back(Use);
993 // Add users to the worklist which may be simplified now.
994 for (User *U : I->users())
995 Worklist.push_back(cast<Instruction>(U));
996 LPM->deleteSimpleAnalysisValue(I, L);
997 RemoveFromWorklist(I, Worklist);
998 I->replaceAllUsesWith(V);
999 I->eraseFromParent();
1003 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1004 // the value specified by Val in the specified loop, or we know it does NOT have
1005 // that value. Rewrite any uses of LIC or of properties correlated to it.
1006 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1009 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1011 // FIXME: Support correlated properties, like:
1018 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1019 // selects, switches.
1020 std::vector<Instruction*> Worklist;
1021 LLVMContext &Context = Val->getContext();
1023 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1024 // in the loop with the appropriate one directly.
1025 if (IsEqual || (isa<ConstantInt>(Val) &&
1026 Val->getType()->isIntegerTy(1))) {
1031 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
1032 !cast<ConstantInt>(Val)->getZExtValue());
1034 for (User *U : LIC->users()) {
1035 Instruction *UI = dyn_cast<Instruction>(U);
1036 if (!UI || !L->contains(UI))
1038 Worklist.push_back(UI);
1041 for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
1042 UE = Worklist.end(); UI != UE; ++UI)
1043 (*UI)->replaceUsesOfWith(LIC, Replacement);
1045 SimplifyCode(Worklist, L);
1049 // Otherwise, we don't know the precise value of LIC, but we do know that it
1050 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1051 // can. This case occurs when we unswitch switch statements.
1052 for (User *U : LIC->users()) {
1053 Instruction *UI = dyn_cast<Instruction>(U);
1054 if (!UI || !L->contains(UI))
1057 Worklist.push_back(UI);
1059 // TODO: We could do other simplifications, for example, turning
1060 // 'icmp eq LIC, Val' -> false.
1062 // If we know that LIC is not Val, use this info to simplify code.
1063 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
1064 if (!SI || !isa<ConstantInt>(Val)) continue;
1066 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
1067 // Default case is live for multiple values.
1068 if (DeadCase == SI->case_default()) continue;
1070 // Found a dead case value. Don't remove PHI nodes in the
1071 // successor if they become single-entry, those PHI nodes may
1072 // be in the Users list.
1074 BasicBlock *Switch = SI->getParent();
1075 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
1076 BasicBlock *Latch = L->getLoopLatch();
1078 BranchesInfo.setUnswitched(SI, Val);
1080 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
1081 // If the DeadCase successor dominates the loop latch, then the
1082 // transformation isn't safe since it will delete the sole predecessor edge
1084 if (Latch && DT->dominates(SISucc, Latch))
1087 // FIXME: This is a hack. We need to keep the successor around
1088 // and hooked up so as to preserve the loop structure, because
1089 // trying to update it is complicated. So instead we preserve the
1090 // loop structure and put the block on a dead code path.
1091 SplitEdge(Switch, SISucc, DT, LI);
1092 // Compute the successors instead of relying on the return value
1093 // of SplitEdge, since it may have split the switch successor
1095 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
1096 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1097 // Create an "unreachable" destination.
1098 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1099 Switch->getParent(),
1101 new UnreachableInst(Context, Abort);
1102 // Force the new case destination to branch to the "unreachable"
1103 // block while maintaining a (dead) CFG edge to the old block.
1104 NewSISucc->getTerminator()->eraseFromParent();
1105 BranchInst::Create(Abort, OldSISucc,
1106 ConstantInt::getTrue(Context), NewSISucc);
1107 // Release the PHI operands for this edge.
1108 for (BasicBlock::iterator II = NewSISucc->begin();
1109 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1110 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1111 UndefValue::get(PN->getType()));
1112 // Tell the domtree about the new block. We don't fully update the
1113 // domtree here -- instead we force it to do a full recomputation
1114 // after the pass is complete -- but we do need to inform it of
1117 DT->addNewBlock(Abort, NewSISucc);
1120 SimplifyCode(Worklist, L);
1123 /// SimplifyCode - Okay, now that we have simplified some instructions in the
1124 /// loop, walk over it and constant prop, dce, and fold control flow where
1125 /// possible. Note that this is effectively a very simple loop-structure-aware
1126 /// optimizer. During processing of this loop, L could very well be deleted, so
1127 /// it must not be used.
1129 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1132 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1133 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1134 while (!Worklist.empty()) {
1135 Instruction *I = Worklist.back();
1136 Worklist.pop_back();
1139 if (isInstructionTriviallyDead(I)) {
1140 DEBUG(dbgs() << "Remove dead instruction '" << *I);
1142 // Add uses to the worklist, which may be dead now.
1143 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1144 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1145 Worklist.push_back(Use);
1146 LPM->deleteSimpleAnalysisValue(I, L);
1147 RemoveFromWorklist(I, Worklist);
1148 I->eraseFromParent();
1153 // See if instruction simplification can hack this up. This is common for
1154 // things like "select false, X, Y" after unswitching made the condition be
1155 // 'false'. TODO: update the domtree properly so we can pass it here.
1156 if (Value *V = SimplifyInstruction(I, DL))
1157 if (LI->replacementPreservesLCSSAForm(I, V)) {
1158 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1162 // Special case hacks that appear commonly in unswitched code.
1163 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1164 if (BI->isUnconditional()) {
1165 // If BI's parent is the only pred of the successor, fold the two blocks
1167 BasicBlock *Pred = BI->getParent();
1168 BasicBlock *Succ = BI->getSuccessor(0);
1169 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1170 if (!SinglePred) continue; // Nothing to do.
1171 assert(SinglePred == Pred && "CFG broken");
1173 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
1174 << Succ->getName() << "\n");
1176 // Resolve any single entry PHI nodes in Succ.
1177 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1178 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1180 // If Succ has any successors with PHI nodes, update them to have
1181 // entries coming from Pred instead of Succ.
1182 Succ->replaceAllUsesWith(Pred);
1184 // Move all of the successor contents from Succ to Pred.
1185 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1187 LPM->deleteSimpleAnalysisValue(BI, L);
1188 BI->eraseFromParent();
1189 RemoveFromWorklist(BI, Worklist);
1191 // Remove Succ from the loop tree.
1192 LI->removeBlock(Succ);
1193 LPM->deleteSimpleAnalysisValue(Succ, L);
1194 Succ->eraseFromParent();