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/Function.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/MachineSSAUpdater.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/ADT/DenseSet.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SetVector.h"
31 #include "llvm/ADT/Statistic.h"
34 STATISTIC(NumTails , "Number of tails duplicated");
35 STATISTIC(NumTailDups , "Number of tail duplicated blocks");
36 STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
37 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
38 STATISTIC(NumAddedPHIs , "Number of phis added");
40 // Heuristic for tail duplication.
41 static cl::opt<unsigned>
42 TailDuplicateSize("tail-dup-size",
43 cl::desc("Maximum instructions to consider tail duplicating"),
44 cl::init(2), cl::Hidden);
47 TailDupVerify("tail-dup-verify",
48 cl::desc("Verify sanity of PHI instructions during taildup"),
49 cl::init(false), cl::Hidden);
51 static cl::opt<unsigned>
52 TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
54 typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
57 /// TailDuplicatePass - Perform tail duplication.
58 class TailDuplicatePass : public MachineFunctionPass {
60 const TargetInstrInfo *TII;
61 MachineModuleInfo *MMI;
62 MachineRegisterInfo *MRI;
64 // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
65 SmallVector<unsigned, 16> SSAUpdateVRs;
67 // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
68 // source virtual registers.
69 DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
73 explicit TailDuplicatePass(bool PreRA) :
74 MachineFunctionPass(ID), PreRegAlloc(PreRA) {}
76 virtual bool runOnMachineFunction(MachineFunction &MF);
77 virtual const char *getPassName() const { return "Tail Duplication"; }
80 void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
81 MachineBasicBlock *BB);
82 void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
83 MachineBasicBlock *PredBB,
84 DenseMap<unsigned, unsigned> &LocalVRMap,
85 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies,
86 const DenseSet<unsigned> &UsedByPhi,
88 void DuplicateInstruction(MachineInstr *MI,
89 MachineBasicBlock *TailBB,
90 MachineBasicBlock *PredBB,
92 DenseMap<unsigned, unsigned> &LocalVRMap,
93 const DenseSet<unsigned> &UsedByPhi);
94 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
95 SmallVector<MachineBasicBlock*, 8> &TDBBs,
96 SmallSetVector<MachineBasicBlock*, 8> &Succs);
97 bool TailDuplicateBlocks(MachineFunction &MF);
98 bool shouldTailDuplicate(const MachineFunction &MF,
99 bool IsSimple, MachineBasicBlock &TailBB);
100 bool isSimpleBB(MachineBasicBlock *TailBB);
101 bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
102 bool duplicateSimpleBB(MachineBasicBlock *TailBB,
103 SmallVector<MachineBasicBlock*, 8> &TDBBs,
104 const DenseSet<unsigned> &RegsUsedByPhi,
105 SmallVector<MachineInstr*, 16> &Copies);
106 bool TailDuplicate(MachineBasicBlock *TailBB,
109 SmallVector<MachineBasicBlock*, 8> &TDBBs,
110 SmallVector<MachineInstr*, 16> &Copies);
111 bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
113 MachineFunction &MF);
115 void RemoveDeadBlock(MachineBasicBlock *MBB);
118 char TailDuplicatePass::ID = 0;
121 FunctionPass *llvm::createTailDuplicatePass(bool PreRegAlloc) {
122 return new TailDuplicatePass(PreRegAlloc);
125 bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
126 TII = MF.getTarget().getInstrInfo();
127 MRI = &MF.getRegInfo();
128 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
130 bool MadeChange = false;
131 while (TailDuplicateBlocks(MF))
137 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
138 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
139 MachineBasicBlock *MBB = I;
140 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
142 MachineBasicBlock::iterator MI = MBB->begin();
143 while (MI != MBB->end()) {
146 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
147 PE = Preds.end(); PI != PE; ++PI) {
148 MachineBasicBlock *PredBB = *PI;
150 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
151 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
152 if (PHIBB == PredBB) {
158 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
159 dbgs() << " missing input from predecessor BB#"
160 << PredBB->getNumber() << '\n';
165 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
166 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
167 if (CheckExtra && !Preds.count(PHIBB)) {
168 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
170 dbgs() << " extra input from predecessor BB#"
171 << PHIBB->getNumber() << '\n';
174 if (PHIBB->getNumber() < 0) {
175 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
176 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
185 /// TailDuplicateAndUpdate - Tail duplicate the block and cleanup.
187 TailDuplicatePass::TailDuplicateAndUpdate(MachineBasicBlock *MBB,
189 MachineFunction &MF) {
190 // Save the successors list.
191 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
194 SmallVector<MachineBasicBlock*, 8> TDBBs;
195 SmallVector<MachineInstr*, 16> Copies;
196 if (!TailDuplicate(MBB, IsSimple, MF, TDBBs, Copies))
201 SmallVector<MachineInstr*, 8> NewPHIs;
202 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
204 // TailBB's immediate successors are now successors of those predecessors
205 // which duplicated TailBB. Add the predecessors as sources to the PHI
207 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
209 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
211 // If it is dead, remove it.
213 NumInstrDups -= MBB->size();
214 RemoveDeadBlock(MBB);
219 if (!SSAUpdateVRs.empty()) {
220 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
221 unsigned VReg = SSAUpdateVRs[i];
222 SSAUpdate.Initialize(VReg);
224 // If the original definition is still around, add it as an available
226 MachineInstr *DefMI = MRI->getVRegDef(VReg);
227 MachineBasicBlock *DefBB = 0;
229 DefBB = DefMI->getParent();
230 SSAUpdate.AddAvailableValue(DefBB, VReg);
233 // Add the new vregs as available values.
234 DenseMap<unsigned, AvailableValsTy>::iterator LI =
235 SSAUpdateVals.find(VReg);
236 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
237 MachineBasicBlock *SrcBB = LI->second[j].first;
238 unsigned SrcReg = LI->second[j].second;
239 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
242 // Rewrite uses that are outside of the original def's block.
243 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
244 while (UI != MRI->use_end()) {
245 MachineOperand &UseMO = UI.getOperand();
246 MachineInstr *UseMI = &*UI;
248 if (UseMI->isDebugValue()) {
249 // SSAUpdate can replace the use with an undef. That creates
250 // a debug instruction that is a kill.
251 // FIXME: Should it SSAUpdate job to delete debug instructions
252 // instead of replacing the use with undef?
253 UseMI->eraseFromParent();
256 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
258 SSAUpdate.RewriteUse(UseMO);
262 SSAUpdateVRs.clear();
263 SSAUpdateVals.clear();
266 // Eliminate some of the copies inserted by tail duplication to maintain
268 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
269 MachineInstr *Copy = Copies[i];
272 unsigned Dst = Copy->getOperand(0).getReg();
273 unsigned Src = Copy->getOperand(1).getReg();
274 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Src);
275 if (++UI == MRI->use_end()) {
276 // Copy is the only use. Do trivial copy propagation here.
277 MRI->replaceRegWith(Dst, Src);
278 Copy->eraseFromParent();
283 NumAddedPHIs += NewPHIs.size();
288 /// TailDuplicateBlocks - Look for small blocks that are unconditionally
289 /// branched to and do not fall through. Tail-duplicate their instructions
290 /// into their predecessors to eliminate (dynamic) branches.
291 bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
292 bool MadeChange = false;
294 if (PreRegAlloc && TailDupVerify) {
295 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
296 VerifyPHIs(MF, true);
299 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
300 MachineBasicBlock *MBB = I++;
302 if (NumTails == TailDupLimit)
305 bool IsSimple = isSimpleBB(MBB);
307 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
310 MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
313 if (PreRegAlloc && TailDupVerify)
314 VerifyPHIs(MF, false);
319 static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
320 const MachineRegisterInfo *MRI) {
321 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
322 UE = MRI->use_end(); UI != UE; ++UI) {
323 MachineInstr *UseMI = &*UI;
324 if (UseMI->isDebugValue())
326 if (UseMI->getParent() != BB)
332 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
333 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
334 if (MI->getOperand(i+1).getMBB() == SrcBB)
340 // Remember which registers are used by phis in this block. This is
341 // used to determine which registers are liveout while modifying the
342 // block (which is why we need to copy the information).
343 static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
344 DenseSet<unsigned> *UsedByPhi) {
345 for(MachineBasicBlock::const_iterator I = BB.begin(), E = BB.end();
347 const MachineInstr &MI = *I;
350 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
351 unsigned SrcReg = MI.getOperand(i).getReg();
352 UsedByPhi->insert(SrcReg);
357 /// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
359 void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
360 MachineBasicBlock *BB) {
361 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
362 if (LI != SSAUpdateVals.end())
363 LI->second.push_back(std::make_pair(BB, NewReg));
365 AvailableValsTy Vals;
366 Vals.push_back(std::make_pair(BB, NewReg));
367 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
368 SSAUpdateVRs.push_back(OrigReg);
372 /// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
373 /// Remember the source register that's contributed by PredBB and update SSA
375 void TailDuplicatePass::ProcessPHI(MachineInstr *MI,
376 MachineBasicBlock *TailBB,
377 MachineBasicBlock *PredBB,
378 DenseMap<unsigned, unsigned> &LocalVRMap,
379 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies,
380 const DenseSet<unsigned> &RegsUsedByPhi,
382 unsigned DefReg = MI->getOperand(0).getReg();
383 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
384 assert(SrcOpIdx && "Unable to find matching PHI source?");
385 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
386 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
387 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
389 // Insert a copy from source to the end of the block. The def register is the
390 // available value liveout of the block.
391 unsigned NewDef = MRI->createVirtualRegister(RC);
392 Copies.push_back(std::make_pair(NewDef, SrcReg));
393 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
394 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
399 // Remove PredBB from the PHI node.
400 MI->RemoveOperand(SrcOpIdx+1);
401 MI->RemoveOperand(SrcOpIdx);
402 if (MI->getNumOperands() == 1)
403 MI->eraseFromParent();
406 /// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
407 /// the source operands due to earlier PHI translation.
408 void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
409 MachineBasicBlock *TailBB,
410 MachineBasicBlock *PredBB,
412 DenseMap<unsigned, unsigned> &LocalVRMap,
413 const DenseSet<unsigned> &UsedByPhi) {
414 MachineInstr *NewMI = TII->duplicate(MI, MF);
415 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
416 MachineOperand &MO = NewMI->getOperand(i);
419 unsigned Reg = MO.getReg();
420 if (!TargetRegisterInfo::isVirtualRegister(Reg))
423 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
424 unsigned NewReg = MRI->createVirtualRegister(RC);
426 LocalVRMap.insert(std::make_pair(Reg, NewReg));
427 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
428 AddSSAUpdateEntry(Reg, NewReg, PredBB);
430 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
431 if (VI != LocalVRMap.end())
432 MO.setReg(VI->second);
435 PredBB->insert(PredBB->end(), NewMI);
438 /// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
439 /// blocks, the successors have gained new predecessors. Update the PHI
440 /// instructions in them accordingly.
442 TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
443 SmallVector<MachineBasicBlock*, 8> &TDBBs,
444 SmallSetVector<MachineBasicBlock*,8> &Succs) {
445 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
446 SE = Succs.end(); SI != SE; ++SI) {
447 MachineBasicBlock *SuccBB = *SI;
448 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
453 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
454 MachineOperand &MO = II->getOperand(i+1);
455 if (MO.getMBB() == FromBB) {
462 MachineOperand &MO0 = II->getOperand(Idx);
463 unsigned Reg = MO0.getReg();
465 // Folded into the previous BB.
466 // There could be duplicate phi source entries. FIXME: Should sdisel
467 // or earlier pass fixed this?
468 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
469 MachineOperand &MO = II->getOperand(i+1);
470 if (MO.getMBB() == FromBB) {
471 II->RemoveOperand(i+1);
472 II->RemoveOperand(i);
478 // If Idx is set, the operands at Idx and Idx+1 must be removed.
479 // We reuse the location to avoid expensive RemoveOperand calls.
481 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
482 if (LI != SSAUpdateVals.end()) {
483 // This register is defined in the tail block.
484 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
485 MachineBasicBlock *SrcBB = LI->second[j].first;
486 // If we didn't duplicate a bb into a particular predecessor, we
487 // might still have added an entry to SSAUpdateVals to correcly
488 // recompute SSA. If that case, avoid adding a dummy extra argument
490 if (!SrcBB->isSuccessor(SuccBB))
493 unsigned SrcReg = LI->second[j].second;
495 II->getOperand(Idx).setReg(SrcReg);
496 II->getOperand(Idx+1).setMBB(SrcBB);
499 II->addOperand(MachineOperand::CreateReg(SrcReg, false));
500 II->addOperand(MachineOperand::CreateMBB(SrcBB));
504 // Live in tail block, must also be live in predecessors.
505 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
506 MachineBasicBlock *SrcBB = TDBBs[j];
508 II->getOperand(Idx).setReg(Reg);
509 II->getOperand(Idx+1).setMBB(SrcBB);
512 II->addOperand(MachineOperand::CreateReg(Reg, false));
513 II->addOperand(MachineOperand::CreateMBB(SrcBB));
518 II->RemoveOperand(Idx+1);
519 II->RemoveOperand(Idx);
525 /// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
527 TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
529 MachineBasicBlock &TailBB) {
530 // Only duplicate blocks that end with unconditional branches.
531 if (TailBB.canFallThrough())
534 // Don't try to tail-duplicate single-block loops.
535 if (TailBB.isSuccessor(&TailBB))
538 // Set the limit on the cost to duplicate. When optimizing for size,
539 // duplicate only one, because one branch instruction can be eliminated to
540 // compensate for the duplication.
541 unsigned MaxDuplicateCount;
542 if (TailDuplicateSize.getNumOccurrences() == 0 &&
543 MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
544 MaxDuplicateCount = 1;
546 MaxDuplicateCount = TailDuplicateSize;
548 // If the target has hardware branch prediction that can handle indirect
549 // branches, duplicating them can often make them predictable when there
550 // are common paths through the code. The limit needs to be high enough
551 // to allow undoing the effects of tail merging and other optimizations
552 // that rearrange the predecessors of the indirect branch.
554 bool HasIndirectbr = false;
556 HasIndirectbr = TailBB.back().isIndirectBranch();
558 if (HasIndirectbr && PreRegAlloc)
559 MaxDuplicateCount = 20;
561 // Check the instructions in the block to determine whether tail-duplication
562 // is invalid or unlikely to be profitable.
563 unsigned InstrCount = 0;
564 for (MachineBasicBlock::iterator I = TailBB.begin(); I != TailBB.end(); ++I) {
565 // Non-duplicable things shouldn't be tail-duplicated.
566 if (I->isNotDuplicable())
569 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
570 // A return may expand into a lot more instructions (e.g. reload of callee
571 // saved registers) after PEI.
572 if (PreRegAlloc && I->isReturn())
575 // Avoid duplicating calls before register allocation. Calls presents a
576 // barrier to register allocation so duplicating them may end up increasing
578 if (PreRegAlloc && I->isCall())
581 if (!I->isPHI() && !I->isDebugValue())
584 if (InstrCount > MaxDuplicateCount)
588 if (HasIndirectbr && PreRegAlloc)
597 return canCompletelyDuplicateBB(TailBB);
600 /// isSimpleBB - True if this BB has only one unconditional jump.
602 TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
603 if (TailBB->succ_size() != 1)
605 if (TailBB->pred_empty())
607 MachineBasicBlock::iterator I = TailBB->begin();
608 MachineBasicBlock::iterator E = TailBB->end();
609 while (I != E && I->isDebugValue())
613 return I->isUnconditionalBranch();
617 bothUsedInPHI(const MachineBasicBlock &A,
618 SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
619 for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
620 SE = A.succ_end(); SI != SE; ++SI) {
621 MachineBasicBlock *BB = *SI;
622 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
630 TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
631 SmallPtrSet<MachineBasicBlock*, 8> Succs(BB.succ_begin(), BB.succ_end());
633 for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
634 PE = BB.pred_end(); PI != PE; ++PI) {
635 MachineBasicBlock *PredBB = *PI;
637 if (PredBB->succ_size() > 1)
640 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
641 SmallVector<MachineOperand, 4> PredCond;
642 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
645 if (!PredCond.empty())
652 TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
653 SmallVector<MachineBasicBlock*, 8> &TDBBs,
654 const DenseSet<unsigned> &UsedByPhi,
655 SmallVector<MachineInstr*, 16> &Copies) {
656 SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
658 SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
660 bool Changed = false;
661 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
662 PE = Preds.end(); PI != PE; ++PI) {
663 MachineBasicBlock *PredBB = *PI;
665 if (PredBB->getLandingPadSuccessor())
668 if (bothUsedInPHI(*PredBB, Succs))
671 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
672 SmallVector<MachineOperand, 4> PredCond;
673 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
677 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
678 << "From simple Succ: " << *TailBB);
680 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
681 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(PredBB));
683 // Make PredFBB explicit.
684 if (PredCond.empty())
687 // Make fall through explicit.
694 if (PredFBB == TailBB)
696 if (PredTBB == TailBB)
699 // Make the branch unconditional if possible
700 if (PredTBB == PredFBB) {
705 // Avoid adding fall through branches.
706 if (PredFBB == NextBB)
708 if (PredTBB == NextBB && PredFBB == NULL)
711 TII->RemoveBranch(*PredBB);
714 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
716 PredBB->removeSuccessor(TailBB);
717 unsigned NumSuccessors = PredBB->succ_size();
718 assert(NumSuccessors <= 1);
719 if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
720 PredBB->addSuccessor(NewTarget);
722 TDBBs.push_back(PredBB);
727 /// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
728 /// of its predecessors.
730 TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
733 SmallVector<MachineBasicBlock*, 8> &TDBBs,
734 SmallVector<MachineInstr*, 16> &Copies) {
735 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
737 DenseSet<unsigned> UsedByPhi;
738 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
741 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
743 // Iterate through all the unique predecessors and tail-duplicate this
744 // block into them, if possible. Copying the list ahead of time also
745 // avoids trouble with the predecessor list reallocating.
746 bool Changed = false;
747 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
749 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
750 PE = Preds.end(); PI != PE; ++PI) {
751 MachineBasicBlock *PredBB = *PI;
753 assert(TailBB != PredBB &&
754 "Single-block loop should have been rejected earlier!");
755 // EH edges are ignored by AnalyzeBranch.
756 if (PredBB->succ_size() > 1)
759 MachineBasicBlock *PredTBB, *PredFBB;
760 SmallVector<MachineOperand, 4> PredCond;
761 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
763 if (!PredCond.empty())
765 // Don't duplicate into a fall-through predecessor (at least for now).
766 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
769 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
770 << "From Succ: " << *TailBB);
772 TDBBs.push_back(PredBB);
774 // Remove PredBB's unconditional branch.
775 TII->RemoveBranch(*PredBB);
777 // Clone the contents of TailBB into PredBB.
778 DenseMap<unsigned, unsigned> LocalVRMap;
779 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
780 MachineBasicBlock::iterator I = TailBB->begin();
781 while (I != TailBB->end()) {
782 MachineInstr *MI = &*I;
785 // Replace the uses of the def of the PHI with the register coming
787 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
789 // Replace def of virtual registers with new registers, and update
790 // uses with PHI source register or the new registers.
791 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
794 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
795 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
796 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
797 TII->get(TargetOpcode::COPY),
798 CopyInfos[i].first).addReg(CopyInfos[i].second));
802 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
804 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
807 PredBB->removeSuccessor(PredBB->succ_begin());
808 assert(PredBB->succ_empty() &&
809 "TailDuplicate called on block with multiple successors!");
810 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
811 E = TailBB->succ_end(); I != E; ++I)
812 PredBB->addSuccessor(*I);
818 // If TailBB was duplicated into all its predecessors except for the prior
819 // block, which falls through unconditionally, move the contents of this
820 // block into the prior block.
821 MachineBasicBlock *PrevBB = prior(MachineFunction::iterator(TailBB));
822 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
823 SmallVector<MachineOperand, 4> PriorCond;
824 // This has to check PrevBB->succ_size() because EH edges are ignored by
826 if (PrevBB->succ_size() == 1 &&
827 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
828 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
829 !TailBB->hasAddressTaken()) {
830 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
831 << "From MBB: " << *TailBB);
833 DenseMap<unsigned, unsigned> LocalVRMap;
834 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
835 MachineBasicBlock::iterator I = TailBB->begin();
836 // Process PHI instructions first.
837 while (I != TailBB->end() && I->isPHI()) {
838 // Replace the uses of the def of the PHI with the register coming
840 MachineInstr *MI = &*I++;
841 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
843 MI->eraseFromParent();
846 // Now copy the non-PHI instructions.
847 while (I != TailBB->end()) {
848 // Replace def of virtual registers with new registers, and update
849 // uses with PHI source register or the new registers.
850 MachineInstr *MI = &*I++;
851 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
852 MI->eraseFromParent();
854 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
855 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
856 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
857 TII->get(TargetOpcode::COPY),
859 .addReg(CopyInfos[i].second));
862 // No PHIs to worry about, just splice the instructions over.
863 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
865 PrevBB->removeSuccessor(PrevBB->succ_begin());
866 assert(PrevBB->succ_empty());
867 PrevBB->transferSuccessors(TailBB);
868 TDBBs.push_back(PrevBB);
872 // If this is after register allocation, there are no phis to fix.
876 // If we made no changes so far, we are safe.
881 // Handle the nasty case in that we duplicated a block that is part of a loop
882 // into some but not all of its predecessors. For example:
886 // if we duplicate 2 into 1 but not into 3, we end up with
887 // 12 -> 3 <-> 2 -> rest |
890 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
891 // with a phi in 3 (which now dominates 2).
892 // What we do here is introduce a copy in 3 of the register defined by the
893 // phi, just like when we are duplicating 2 into 3, but we don't copy any
894 // real instructions or remove the 3 -> 2 edge from the phi in 2.
895 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
896 PE = Preds.end(); PI != PE; ++PI) {
897 MachineBasicBlock *PredBB = *PI;
898 if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
902 if (PredBB->succ_size() != 1)
905 DenseMap<unsigned, unsigned> LocalVRMap;
906 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
907 MachineBasicBlock::iterator I = TailBB->begin();
908 // Process PHI instructions first.
909 while (I != TailBB->end() && I->isPHI()) {
910 // Replace the uses of the def of the PHI with the register coming
912 MachineInstr *MI = &*I++;
913 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
915 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
916 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
917 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
918 TII->get(TargetOpcode::COPY),
919 CopyInfos[i].first).addReg(CopyInfos[i].second));
926 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
927 /// function, updating the CFG.
928 void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
929 assert(MBB->pred_empty() && "MBB must be dead!");
930 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
932 // Remove all successors.
933 while (!MBB->succ_empty())
934 MBB->removeSuccessor(MBB->succ_end()-1);
937 MBB->eraseFromParent();