1 //===-- TailDuplication.cpp - Duplicate blocks into predecessors' tails ---===//
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 duplicates basic blocks ending in unconditional branches into
11 // the tails of their predecessors.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "tailduplication"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/MachineSSAUpdater.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
38 STATISTIC(NumTails , "Number of tails duplicated");
39 STATISTIC(NumTailDups , "Number of tail duplicated blocks");
40 STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
41 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
42 STATISTIC(NumAddedPHIs , "Number of phis added");
44 // Heuristic for tail duplication.
45 static cl::opt<unsigned>
46 TailDuplicateSize("tail-dup-size",
47 cl::desc("Maximum instructions to consider tail duplicating"),
48 cl::init(2), cl::Hidden);
51 TailDupVerify("tail-dup-verify",
52 cl::desc("Verify sanity of PHI instructions during taildup"),
53 cl::init(false), cl::Hidden);
55 static cl::opt<unsigned>
56 TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
58 typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
61 /// TailDuplicatePass - Perform tail duplication.
62 class TailDuplicatePass : public MachineFunctionPass {
63 const TargetInstrInfo *TII;
64 const TargetRegisterInfo *TRI;
65 const MachineBranchProbabilityInfo *MBPI;
66 MachineModuleInfo *MMI;
67 MachineRegisterInfo *MRI;
68 OwningPtr<RegScavenger> RS;
71 // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
72 SmallVector<unsigned, 16> SSAUpdateVRs;
74 // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
75 // source virtual registers.
76 DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
80 explicit TailDuplicatePass() :
81 MachineFunctionPass(ID), PreRegAlloc(false) {}
83 virtual bool runOnMachineFunction(MachineFunction &MF);
85 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
88 void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
89 MachineBasicBlock *BB);
90 void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
91 MachineBasicBlock *PredBB,
92 DenseMap<unsigned, unsigned> &LocalVRMap,
93 SmallVectorImpl<std::pair<unsigned,unsigned> > &Copies,
94 const DenseSet<unsigned> &UsedByPhi,
96 void DuplicateInstruction(MachineInstr *MI,
97 MachineBasicBlock *TailBB,
98 MachineBasicBlock *PredBB,
100 DenseMap<unsigned, unsigned> &LocalVRMap,
101 const DenseSet<unsigned> &UsedByPhi);
102 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
103 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
104 SmallSetVector<MachineBasicBlock*, 8> &Succs);
105 bool TailDuplicateBlocks(MachineFunction &MF);
106 bool shouldTailDuplicate(const MachineFunction &MF,
107 bool IsSimple, MachineBasicBlock &TailBB);
108 bool isSimpleBB(MachineBasicBlock *TailBB);
109 bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
110 bool duplicateSimpleBB(MachineBasicBlock *TailBB,
111 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
112 const DenseSet<unsigned> &RegsUsedByPhi,
113 SmallVectorImpl<MachineInstr *> &Copies);
114 bool TailDuplicate(MachineBasicBlock *TailBB,
117 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
118 SmallVectorImpl<MachineInstr *> &Copies);
119 bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
121 MachineFunction &MF);
123 void RemoveDeadBlock(MachineBasicBlock *MBB);
126 char TailDuplicatePass::ID = 0;
129 char &llvm::TailDuplicateID = TailDuplicatePass::ID;
131 INITIALIZE_PASS(TailDuplicatePass, "tailduplication", "Tail Duplication",
134 bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
135 TII = MF.getTarget().getInstrInfo();
136 TRI = MF.getTarget().getRegisterInfo();
137 MRI = &MF.getRegInfo();
138 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
139 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
141 PreRegAlloc = MRI->isSSA();
143 if (MRI->tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
144 RS.reset(new RegScavenger());
146 bool MadeChange = false;
147 while (TailDuplicateBlocks(MF))
153 void TailDuplicatePass::getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.addRequired<MachineBranchProbabilityInfo>();
155 MachineFunctionPass::getAnalysisUsage(AU);
158 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
159 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
160 MachineBasicBlock *MBB = I;
161 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
163 MachineBasicBlock::iterator MI = MBB->begin();
164 while (MI != MBB->end()) {
167 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
168 PE = Preds.end(); PI != PE; ++PI) {
169 MachineBasicBlock *PredBB = *PI;
171 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
172 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
173 if (PHIBB == PredBB) {
179 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
180 dbgs() << " missing input from predecessor BB#"
181 << PredBB->getNumber() << '\n';
186 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
187 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
188 if (CheckExtra && !Preds.count(PHIBB)) {
189 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
191 dbgs() << " extra input from predecessor BB#"
192 << PHIBB->getNumber() << '\n';
195 if (PHIBB->getNumber() < 0) {
196 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
197 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
206 /// TailDuplicateAndUpdate - Tail duplicate the block and cleanup.
208 TailDuplicatePass::TailDuplicateAndUpdate(MachineBasicBlock *MBB,
210 MachineFunction &MF) {
211 // Save the successors list.
212 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
215 SmallVector<MachineBasicBlock*, 8> TDBBs;
216 SmallVector<MachineInstr*, 16> Copies;
217 if (!TailDuplicate(MBB, IsSimple, MF, TDBBs, Copies))
222 SmallVector<MachineInstr*, 8> NewPHIs;
223 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
225 // TailBB's immediate successors are now successors of those predecessors
226 // which duplicated TailBB. Add the predecessors as sources to the PHI
228 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
230 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
232 // If it is dead, remove it.
234 NumInstrDups -= MBB->size();
235 RemoveDeadBlock(MBB);
240 if (!SSAUpdateVRs.empty()) {
241 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
242 unsigned VReg = SSAUpdateVRs[i];
243 SSAUpdate.Initialize(VReg);
245 // If the original definition is still around, add it as an available
247 MachineInstr *DefMI = MRI->getVRegDef(VReg);
248 MachineBasicBlock *DefBB = 0;
250 DefBB = DefMI->getParent();
251 SSAUpdate.AddAvailableValue(DefBB, VReg);
254 // Add the new vregs as available values.
255 DenseMap<unsigned, AvailableValsTy>::iterator LI =
256 SSAUpdateVals.find(VReg);
257 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
258 MachineBasicBlock *SrcBB = LI->second[j].first;
259 unsigned SrcReg = LI->second[j].second;
260 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
263 // Rewrite uses that are outside of the original def's block.
264 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
265 while (UI != MRI->use_end()) {
266 MachineOperand &UseMO = UI.getOperand();
267 MachineInstr *UseMI = &*UI;
269 if (UseMI->isDebugValue()) {
270 // SSAUpdate can replace the use with an undef. That creates
271 // a debug instruction that is a kill.
272 // FIXME: Should it SSAUpdate job to delete debug instructions
273 // instead of replacing the use with undef?
274 UseMI->eraseFromParent();
277 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
279 SSAUpdate.RewriteUse(UseMO);
283 SSAUpdateVRs.clear();
284 SSAUpdateVals.clear();
287 // Eliminate some of the copies inserted by tail duplication to maintain
289 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
290 MachineInstr *Copy = Copies[i];
293 unsigned Dst = Copy->getOperand(0).getReg();
294 unsigned Src = Copy->getOperand(1).getReg();
295 if (MRI->hasOneNonDBGUse(Src) &&
296 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
297 // Copy is the only use. Do trivial copy propagation here.
298 MRI->replaceRegWith(Dst, Src);
299 Copy->eraseFromParent();
304 NumAddedPHIs += NewPHIs.size();
309 /// TailDuplicateBlocks - Look for small blocks that are unconditionally
310 /// branched to and do not fall through. Tail-duplicate their instructions
311 /// into their predecessors to eliminate (dynamic) branches.
312 bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
313 bool MadeChange = false;
315 if (PreRegAlloc && TailDupVerify) {
316 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
317 VerifyPHIs(MF, true);
320 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
321 MachineBasicBlock *MBB = I++;
323 if (NumTails == TailDupLimit)
326 bool IsSimple = isSimpleBB(MBB);
328 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
331 MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
334 if (PreRegAlloc && TailDupVerify)
335 VerifyPHIs(MF, false);
340 static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
341 const MachineRegisterInfo *MRI) {
342 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
343 UE = MRI->use_end(); UI != UE; ++UI) {
344 MachineInstr *UseMI = &*UI;
345 if (UseMI->isDebugValue())
347 if (UseMI->getParent() != BB)
353 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
354 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
355 if (MI->getOperand(i+1).getMBB() == SrcBB)
361 // Remember which registers are used by phis in this block. This is
362 // used to determine which registers are liveout while modifying the
363 // block (which is why we need to copy the information).
364 static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
365 DenseSet<unsigned> *UsedByPhi) {
366 for(MachineBasicBlock::const_iterator I = BB.begin(), E = BB.end();
368 const MachineInstr &MI = *I;
371 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
372 unsigned SrcReg = MI.getOperand(i).getReg();
373 UsedByPhi->insert(SrcReg);
378 /// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
380 void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
381 MachineBasicBlock *BB) {
382 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
383 if (LI != SSAUpdateVals.end())
384 LI->second.push_back(std::make_pair(BB, NewReg));
386 AvailableValsTy Vals;
387 Vals.push_back(std::make_pair(BB, NewReg));
388 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
389 SSAUpdateVRs.push_back(OrigReg);
393 /// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
394 /// Remember the source register that's contributed by PredBB and update SSA
396 void TailDuplicatePass::ProcessPHI(
397 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
398 DenseMap<unsigned, unsigned> &LocalVRMap,
399 SmallVectorImpl<std::pair<unsigned, unsigned> > &Copies,
400 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
401 unsigned DefReg = MI->getOperand(0).getReg();
402 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
403 assert(SrcOpIdx && "Unable to find matching PHI source?");
404 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
405 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
406 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
408 // Insert a copy from source to the end of the block. The def register is the
409 // available value liveout of the block.
410 unsigned NewDef = MRI->createVirtualRegister(RC);
411 Copies.push_back(std::make_pair(NewDef, SrcReg));
412 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
413 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
418 // Remove PredBB from the PHI node.
419 MI->RemoveOperand(SrcOpIdx+1);
420 MI->RemoveOperand(SrcOpIdx);
421 if (MI->getNumOperands() == 1)
422 MI->eraseFromParent();
425 /// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
426 /// the source operands due to earlier PHI translation.
427 void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
428 MachineBasicBlock *TailBB,
429 MachineBasicBlock *PredBB,
431 DenseMap<unsigned, unsigned> &LocalVRMap,
432 const DenseSet<unsigned> &UsedByPhi) {
433 MachineInstr *NewMI = TII->duplicate(MI, MF);
434 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
435 MachineOperand &MO = NewMI->getOperand(i);
438 unsigned Reg = MO.getReg();
439 if (!TargetRegisterInfo::isVirtualRegister(Reg))
442 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
443 unsigned NewReg = MRI->createVirtualRegister(RC);
445 LocalVRMap.insert(std::make_pair(Reg, NewReg));
446 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
447 AddSSAUpdateEntry(Reg, NewReg, PredBB);
449 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
450 if (VI != LocalVRMap.end()) {
451 MO.setReg(VI->second);
452 MRI->constrainRegClass(VI->second, MRI->getRegClass(Reg));
456 PredBB->insert(PredBB->instr_end(), NewMI);
459 /// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
460 /// blocks, the successors have gained new predecessors. Update the PHI
461 /// instructions in them accordingly.
463 TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
464 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
465 SmallSetVector<MachineBasicBlock*,8> &Succs) {
466 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
467 SE = Succs.end(); SI != SE; ++SI) {
468 MachineBasicBlock *SuccBB = *SI;
469 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
473 MachineInstrBuilder MIB(*FromBB->getParent(), II);
475 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
476 MachineOperand &MO = II->getOperand(i+1);
477 if (MO.getMBB() == FromBB) {
484 MachineOperand &MO0 = II->getOperand(Idx);
485 unsigned Reg = MO0.getReg();
487 // Folded into the previous BB.
488 // There could be duplicate phi source entries. FIXME: Should sdisel
489 // or earlier pass fixed this?
490 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
491 MachineOperand &MO = II->getOperand(i+1);
492 if (MO.getMBB() == FromBB) {
493 II->RemoveOperand(i+1);
494 II->RemoveOperand(i);
500 // If Idx is set, the operands at Idx and Idx+1 must be removed.
501 // We reuse the location to avoid expensive RemoveOperand calls.
503 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
504 if (LI != SSAUpdateVals.end()) {
505 // This register is defined in the tail block.
506 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
507 MachineBasicBlock *SrcBB = LI->second[j].first;
508 // If we didn't duplicate a bb into a particular predecessor, we
509 // might still have added an entry to SSAUpdateVals to correcly
510 // recompute SSA. If that case, avoid adding a dummy extra argument
512 if (!SrcBB->isSuccessor(SuccBB))
515 unsigned SrcReg = LI->second[j].second;
517 II->getOperand(Idx).setReg(SrcReg);
518 II->getOperand(Idx+1).setMBB(SrcBB);
521 MIB.addReg(SrcReg).addMBB(SrcBB);
525 // Live in tail block, must also be live in predecessors.
526 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
527 MachineBasicBlock *SrcBB = TDBBs[j];
529 II->getOperand(Idx).setReg(Reg);
530 II->getOperand(Idx+1).setMBB(SrcBB);
533 MIB.addReg(Reg).addMBB(SrcBB);
538 II->RemoveOperand(Idx+1);
539 II->RemoveOperand(Idx);
545 /// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
547 TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
549 MachineBasicBlock &TailBB) {
550 // Only duplicate blocks that end with unconditional branches.
551 if (TailBB.canFallThrough())
554 // Don't try to tail-duplicate single-block loops.
555 if (TailBB.isSuccessor(&TailBB))
558 // Set the limit on the cost to duplicate. When optimizing for size,
559 // duplicate only one, because one branch instruction can be eliminated to
560 // compensate for the duplication.
561 unsigned MaxDuplicateCount;
562 if (TailDuplicateSize.getNumOccurrences() == 0 &&
563 MF.getFunction()->getAttributes().
564 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize))
565 MaxDuplicateCount = 1;
567 MaxDuplicateCount = TailDuplicateSize;
569 // If the target has hardware branch prediction that can handle indirect
570 // branches, duplicating them can often make them predictable when there
571 // are common paths through the code. The limit needs to be high enough
572 // to allow undoing the effects of tail merging and other optimizations
573 // that rearrange the predecessors of the indirect branch.
575 bool HasIndirectbr = false;
577 HasIndirectbr = TailBB.back().isIndirectBranch();
579 if (HasIndirectbr && PreRegAlloc)
580 MaxDuplicateCount = 20;
582 // Check the instructions in the block to determine whether tail-duplication
583 // is invalid or unlikely to be profitable.
584 unsigned InstrCount = 0;
585 for (MachineBasicBlock::iterator I = TailBB.begin(); I != TailBB.end(); ++I) {
586 // Non-duplicable things shouldn't be tail-duplicated.
587 if (I->isNotDuplicable())
590 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
591 // A return may expand into a lot more instructions (e.g. reload of callee
592 // saved registers) after PEI.
593 if (PreRegAlloc && I->isReturn())
596 // Avoid duplicating calls before register allocation. Calls presents a
597 // barrier to register allocation so duplicating them may end up increasing
599 if (PreRegAlloc && I->isCall())
602 if (!I->isPHI() && !I->isDebugValue())
605 if (InstrCount > MaxDuplicateCount)
609 if (HasIndirectbr && PreRegAlloc)
618 return canCompletelyDuplicateBB(TailBB);
621 /// isSimpleBB - True if this BB has only one unconditional jump.
623 TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
624 if (TailBB->succ_size() != 1)
626 if (TailBB->pred_empty())
628 MachineBasicBlock::iterator I = TailBB->begin();
629 MachineBasicBlock::iterator E = TailBB->end();
630 while (I != E && I->isDebugValue())
634 return I->isUnconditionalBranch();
638 bothUsedInPHI(const MachineBasicBlock &A,
639 SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
640 for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
641 SE = A.succ_end(); SI != SE; ++SI) {
642 MachineBasicBlock *BB = *SI;
643 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
651 TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
652 for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
653 PE = BB.pred_end(); PI != PE; ++PI) {
654 MachineBasicBlock *PredBB = *PI;
656 if (PredBB->succ_size() > 1)
659 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
660 SmallVector<MachineOperand, 4> PredCond;
661 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
664 if (!PredCond.empty())
671 TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
672 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
673 const DenseSet<unsigned> &UsedByPhi,
674 SmallVectorImpl<MachineInstr *> &Copies) {
675 SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
677 SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
679 bool Changed = false;
680 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
681 PE = Preds.end(); PI != PE; ++PI) {
682 MachineBasicBlock *PredBB = *PI;
684 if (PredBB->getLandingPadSuccessor())
687 if (bothUsedInPHI(*PredBB, Succs))
690 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
691 SmallVector<MachineOperand, 4> PredCond;
692 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
696 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
697 << "From simple Succ: " << *TailBB);
699 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
700 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(PredBB));
702 // Make PredFBB explicit.
703 if (PredCond.empty())
706 // Make fall through explicit.
713 if (PredFBB == TailBB)
715 if (PredTBB == TailBB)
718 // Make the branch unconditional if possible
719 if (PredTBB == PredFBB) {
724 // Avoid adding fall through branches.
725 if (PredFBB == NextBB)
727 if (PredTBB == NextBB && PredFBB == NULL)
730 TII->RemoveBranch(*PredBB);
733 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
735 uint32_t Weight = MBPI->getEdgeWeight(PredBB, TailBB);
736 PredBB->removeSuccessor(TailBB);
737 unsigned NumSuccessors = PredBB->succ_size();
738 assert(NumSuccessors <= 1);
739 if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
740 PredBB->addSuccessor(NewTarget, Weight);
742 TDBBs.push_back(PredBB);
747 /// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
748 /// of its predecessors.
750 TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
753 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
754 SmallVectorImpl<MachineInstr *> &Copies) {
755 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
757 DenseSet<unsigned> UsedByPhi;
758 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
761 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
763 // Iterate through all the unique predecessors and tail-duplicate this
764 // block into them, if possible. Copying the list ahead of time also
765 // avoids trouble with the predecessor list reallocating.
766 bool Changed = false;
767 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
769 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
770 PE = Preds.end(); PI != PE; ++PI) {
771 MachineBasicBlock *PredBB = *PI;
773 assert(TailBB != PredBB &&
774 "Single-block loop should have been rejected earlier!");
775 // EH edges are ignored by AnalyzeBranch.
776 if (PredBB->succ_size() > 1)
779 MachineBasicBlock *PredTBB, *PredFBB;
780 SmallVector<MachineOperand, 4> PredCond;
781 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
783 if (!PredCond.empty())
785 // Don't duplicate into a fall-through predecessor (at least for now).
786 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
789 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
790 << "From Succ: " << *TailBB);
792 TDBBs.push_back(PredBB);
794 // Remove PredBB's unconditional branch.
795 TII->RemoveBranch(*PredBB);
797 if (RS && !TailBB->livein_empty()) {
798 // Update PredBB livein.
799 RS->enterBasicBlock(PredBB);
800 if (!PredBB->empty())
801 RS->forward(prior(PredBB->end()));
802 BitVector RegsLiveAtExit(TRI->getNumRegs());
803 RS->getRegsUsed(RegsLiveAtExit, false);
804 for (MachineBasicBlock::livein_iterator I = TailBB->livein_begin(),
805 E = TailBB->livein_end(); I != E; ++I) {
806 if (!RegsLiveAtExit[*I])
807 // If a register is previously livein to the tail but it's not live
808 // at the end of predecessor BB, then it should be added to its
810 PredBB->addLiveIn(*I);
814 // Clone the contents of TailBB into PredBB.
815 DenseMap<unsigned, unsigned> LocalVRMap;
816 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
817 // Use instr_iterator here to properly handle bundles, e.g.
818 // ARM Thumb2 IT block.
819 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
820 while (I != TailBB->instr_end()) {
821 MachineInstr *MI = &*I;
824 // Replace the uses of the def of the PHI with the register coming
826 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
828 // Replace def of virtual registers with new registers, and update
829 // uses with PHI source register or the new registers.
830 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
833 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
834 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
835 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
836 TII->get(TargetOpcode::COPY),
837 CopyInfos[i].first).addReg(CopyInfos[i].second));
841 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
843 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
846 PredBB->removeSuccessor(PredBB->succ_begin());
847 assert(PredBB->succ_empty() &&
848 "TailDuplicate called on block with multiple successors!");
849 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
850 E = TailBB->succ_end(); I != E; ++I)
851 PredBB->addSuccessor(*I, MBPI->getEdgeWeight(TailBB, I));
857 // If TailBB was duplicated into all its predecessors except for the prior
858 // block, which falls through unconditionally, move the contents of this
859 // block into the prior block.
860 MachineBasicBlock *PrevBB = prior(MachineFunction::iterator(TailBB));
861 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
862 SmallVector<MachineOperand, 4> PriorCond;
863 // This has to check PrevBB->succ_size() because EH edges are ignored by
865 if (PrevBB->succ_size() == 1 &&
866 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
867 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
868 !TailBB->hasAddressTaken()) {
869 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
870 << "From MBB: " << *TailBB);
872 DenseMap<unsigned, unsigned> LocalVRMap;
873 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
874 MachineBasicBlock::iterator I = TailBB->begin();
875 // Process PHI instructions first.
876 while (I != TailBB->end() && I->isPHI()) {
877 // Replace the uses of the def of the PHI with the register coming
879 MachineInstr *MI = &*I++;
880 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
882 MI->eraseFromParent();
885 // Now copy the non-PHI instructions.
886 while (I != TailBB->end()) {
887 // Replace def of virtual registers with new registers, and update
888 // uses with PHI source register or the new registers.
889 MachineInstr *MI = &*I++;
890 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
891 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
892 MI->eraseFromParent();
894 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
895 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
896 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
897 TII->get(TargetOpcode::COPY),
899 .addReg(CopyInfos[i].second));
902 // No PHIs to worry about, just splice the instructions over.
903 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
905 PrevBB->removeSuccessor(PrevBB->succ_begin());
906 assert(PrevBB->succ_empty());
907 PrevBB->transferSuccessors(TailBB);
908 TDBBs.push_back(PrevBB);
912 // If this is after register allocation, there are no phis to fix.
916 // If we made no changes so far, we are safe.
921 // Handle the nasty case in that we duplicated a block that is part of a loop
922 // into some but not all of its predecessors. For example:
926 // if we duplicate 2 into 1 but not into 3, we end up with
927 // 12 -> 3 <-> 2 -> rest |
930 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
931 // with a phi in 3 (which now dominates 2).
932 // What we do here is introduce a copy in 3 of the register defined by the
933 // phi, just like when we are duplicating 2 into 3, but we don't copy any
934 // real instructions or remove the 3 -> 2 edge from the phi in 2.
935 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
936 PE = Preds.end(); PI != PE; ++PI) {
937 MachineBasicBlock *PredBB = *PI;
938 if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
942 if (PredBB->succ_size() != 1)
945 DenseMap<unsigned, unsigned> LocalVRMap;
946 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
947 MachineBasicBlock::iterator I = TailBB->begin();
948 // Process PHI instructions first.
949 while (I != TailBB->end() && I->isPHI()) {
950 // Replace the uses of the def of the PHI with the register coming
952 MachineInstr *MI = &*I++;
953 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
955 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
956 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
957 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
958 TII->get(TargetOpcode::COPY),
959 CopyInfos[i].first).addReg(CopyInfos[i].second));
966 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
967 /// function, updating the CFG.
968 void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
969 assert(MBB->pred_empty() && "MBB must be dead!");
970 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
972 // Remove all successors.
973 while (!MBB->succ_empty())
974 MBB->removeSuccessor(MBB->succ_end()-1);
977 MBB->eraseFromParent();