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/SetVector.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/MachineSSAUpdater.h"
27 #include "llvm/CodeGen/RegisterScavenging.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
37 STATISTIC(NumTails , "Number of tails duplicated");
38 STATISTIC(NumTailDups , "Number of tail duplicated blocks");
39 STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
40 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
41 STATISTIC(NumAddedPHIs , "Number of phis added");
43 // Heuristic for tail duplication.
44 static cl::opt<unsigned>
45 TailDuplicateSize("tail-dup-size",
46 cl::desc("Maximum instructions to consider tail duplicating"),
47 cl::init(2), cl::Hidden);
50 TailDupVerify("tail-dup-verify",
51 cl::desc("Verify sanity of PHI instructions during taildup"),
52 cl::init(false), cl::Hidden);
54 static cl::opt<unsigned>
55 TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
57 typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
60 /// TailDuplicatePass - Perform tail duplication.
61 class TailDuplicatePass : public MachineFunctionPass {
62 const TargetInstrInfo *TII;
63 const TargetRegisterInfo *TRI;
64 const MachineBranchProbabilityInfo *MBPI;
65 MachineModuleInfo *MMI;
66 MachineRegisterInfo *MRI;
67 std::unique_ptr<RegScavenger> RS;
70 // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
71 SmallVector<unsigned, 16> SSAUpdateVRs;
73 // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
74 // source virtual registers.
75 DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
79 explicit TailDuplicatePass() :
80 MachineFunctionPass(ID), PreRegAlloc(false) {}
82 bool runOnMachineFunction(MachineFunction &MF) override;
84 void getAnalysisUsage(AnalysisUsage &AU) const override;
87 void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
88 MachineBasicBlock *BB);
89 void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
90 MachineBasicBlock *PredBB,
91 DenseMap<unsigned, unsigned> &LocalVRMap,
92 SmallVectorImpl<std::pair<unsigned,unsigned> > &Copies,
93 const DenseSet<unsigned> &UsedByPhi,
95 void DuplicateInstruction(MachineInstr *MI,
96 MachineBasicBlock *TailBB,
97 MachineBasicBlock *PredBB,
99 DenseMap<unsigned, unsigned> &LocalVRMap,
100 const DenseSet<unsigned> &UsedByPhi);
101 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
102 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
103 SmallSetVector<MachineBasicBlock*, 8> &Succs);
104 bool TailDuplicateBlocks(MachineFunction &MF);
105 bool shouldTailDuplicate(const MachineFunction &MF,
106 bool IsSimple, MachineBasicBlock &TailBB);
107 bool isSimpleBB(MachineBasicBlock *TailBB);
108 bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
109 bool duplicateSimpleBB(MachineBasicBlock *TailBB,
110 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
111 const DenseSet<unsigned> &RegsUsedByPhi,
112 SmallVectorImpl<MachineInstr *> &Copies);
113 bool TailDuplicate(MachineBasicBlock *TailBB,
116 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
117 SmallVectorImpl<MachineInstr *> &Copies);
118 bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
120 MachineFunction &MF);
122 void RemoveDeadBlock(MachineBasicBlock *MBB);
125 char TailDuplicatePass::ID = 0;
128 char &llvm::TailDuplicateID = TailDuplicatePass::ID;
130 INITIALIZE_PASS(TailDuplicatePass, "tailduplication", "Tail Duplication",
133 bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
134 TII = MF.getTarget().getInstrInfo();
135 TRI = MF.getTarget().getRegisterInfo();
136 MRI = &MF.getRegInfo();
137 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
138 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
140 PreRegAlloc = MRI->isSSA();
142 if (MRI->tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
143 RS.reset(new RegScavenger());
145 bool MadeChange = false;
146 while (TailDuplicateBlocks(MF))
152 void TailDuplicatePass::getAnalysisUsage(AnalysisUsage &AU) const {
153 AU.addRequired<MachineBranchProbabilityInfo>();
154 MachineFunctionPass::getAnalysisUsage(AU);
157 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
158 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
159 MachineBasicBlock *MBB = I;
160 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
162 MachineBasicBlock::iterator MI = MBB->begin();
163 while (MI != MBB->end()) {
166 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
167 PE = Preds.end(); PI != PE; ++PI) {
168 MachineBasicBlock *PredBB = *PI;
170 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
171 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
172 if (PHIBB == PredBB) {
178 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
179 dbgs() << " missing input from predecessor BB#"
180 << PredBB->getNumber() << '\n';
185 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
186 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
187 if (CheckExtra && !Preds.count(PHIBB)) {
188 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
190 dbgs() << " extra input from predecessor BB#"
191 << PHIBB->getNumber() << '\n';
194 if (PHIBB->getNumber() < 0) {
195 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
196 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
205 /// TailDuplicateAndUpdate - Tail duplicate the block and cleanup.
207 TailDuplicatePass::TailDuplicateAndUpdate(MachineBasicBlock *MBB,
209 MachineFunction &MF) {
210 // Save the successors list.
211 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
214 SmallVector<MachineBasicBlock*, 8> TDBBs;
215 SmallVector<MachineInstr*, 16> Copies;
216 if (!TailDuplicate(MBB, IsSimple, MF, TDBBs, Copies))
221 SmallVector<MachineInstr*, 8> NewPHIs;
222 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
224 // TailBB's immediate successors are now successors of those predecessors
225 // which duplicated TailBB. Add the predecessors as sources to the PHI
227 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
229 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
231 // If it is dead, remove it.
233 NumInstrDups -= MBB->size();
234 RemoveDeadBlock(MBB);
239 if (!SSAUpdateVRs.empty()) {
240 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
241 unsigned VReg = SSAUpdateVRs[i];
242 SSAUpdate.Initialize(VReg);
244 // If the original definition is still around, add it as an available
246 MachineInstr *DefMI = MRI->getVRegDef(VReg);
247 MachineBasicBlock *DefBB = 0;
249 DefBB = DefMI->getParent();
250 SSAUpdate.AddAvailableValue(DefBB, VReg);
253 // Add the new vregs as available values.
254 DenseMap<unsigned, AvailableValsTy>::iterator LI =
255 SSAUpdateVals.find(VReg);
256 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
257 MachineBasicBlock *SrcBB = LI->second[j].first;
258 unsigned SrcReg = LI->second[j].second;
259 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
262 // Rewrite uses that are outside of the original def's block.
263 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
264 while (UI != MRI->use_end()) {
265 MachineOperand &UseMO = *UI;
266 MachineInstr *UseMI = UseMO.getParent();
268 if (UseMI->isDebugValue()) {
269 // SSAUpdate can replace the use with an undef. That creates
270 // a debug instruction that is a kill.
271 // FIXME: Should it SSAUpdate job to delete debug instructions
272 // instead of replacing the use with undef?
273 UseMI->eraseFromParent();
276 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
278 SSAUpdate.RewriteUse(UseMO);
282 SSAUpdateVRs.clear();
283 SSAUpdateVals.clear();
286 // Eliminate some of the copies inserted by tail duplication to maintain
288 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
289 MachineInstr *Copy = Copies[i];
292 unsigned Dst = Copy->getOperand(0).getReg();
293 unsigned Src = Copy->getOperand(1).getReg();
294 if (MRI->hasOneNonDBGUse(Src) &&
295 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
296 // Copy is the only use. Do trivial copy propagation here.
297 MRI->replaceRegWith(Dst, Src);
298 Copy->eraseFromParent();
303 NumAddedPHIs += NewPHIs.size();
308 /// TailDuplicateBlocks - Look for small blocks that are unconditionally
309 /// branched to and do not fall through. Tail-duplicate their instructions
310 /// into their predecessors to eliminate (dynamic) branches.
311 bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
312 bool MadeChange = false;
314 if (PreRegAlloc && TailDupVerify) {
315 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
316 VerifyPHIs(MF, true);
319 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
320 MachineBasicBlock *MBB = I++;
322 if (NumTails == TailDupLimit)
325 bool IsSimple = isSimpleBB(MBB);
327 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
330 MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
333 if (PreRegAlloc && TailDupVerify)
334 VerifyPHIs(MF, false);
339 static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
340 const MachineRegisterInfo *MRI) {
341 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
342 if (UseMI.isDebugValue())
344 if (UseMI.getParent() != BB)
350 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
351 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
352 if (MI->getOperand(i+1).getMBB() == SrcBB)
358 // Remember which registers are used by phis in this block. This is
359 // used to determine which registers are liveout while modifying the
360 // block (which is why we need to copy the information).
361 static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
362 DenseSet<unsigned> *UsedByPhi) {
363 for(MachineBasicBlock::const_iterator I = BB.begin(), E = BB.end();
365 const MachineInstr &MI = *I;
368 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
369 unsigned SrcReg = MI.getOperand(i).getReg();
370 UsedByPhi->insert(SrcReg);
375 /// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
377 void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
378 MachineBasicBlock *BB) {
379 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
380 if (LI != SSAUpdateVals.end())
381 LI->second.push_back(std::make_pair(BB, NewReg));
383 AvailableValsTy Vals;
384 Vals.push_back(std::make_pair(BB, NewReg));
385 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
386 SSAUpdateVRs.push_back(OrigReg);
390 /// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
391 /// Remember the source register that's contributed by PredBB and update SSA
393 void TailDuplicatePass::ProcessPHI(
394 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
395 DenseMap<unsigned, unsigned> &LocalVRMap,
396 SmallVectorImpl<std::pair<unsigned, unsigned> > &Copies,
397 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
398 unsigned DefReg = MI->getOperand(0).getReg();
399 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
400 assert(SrcOpIdx && "Unable to find matching PHI source?");
401 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
402 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
403 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
405 // Insert a copy from source to the end of the block. The def register is the
406 // available value liveout of the block.
407 unsigned NewDef = MRI->createVirtualRegister(RC);
408 Copies.push_back(std::make_pair(NewDef, SrcReg));
409 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
410 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
415 // Remove PredBB from the PHI node.
416 MI->RemoveOperand(SrcOpIdx+1);
417 MI->RemoveOperand(SrcOpIdx);
418 if (MI->getNumOperands() == 1)
419 MI->eraseFromParent();
422 /// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
423 /// the source operands due to earlier PHI translation.
424 void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
425 MachineBasicBlock *TailBB,
426 MachineBasicBlock *PredBB,
428 DenseMap<unsigned, unsigned> &LocalVRMap,
429 const DenseSet<unsigned> &UsedByPhi) {
430 MachineInstr *NewMI = TII->duplicate(MI, MF);
431 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
432 MachineOperand &MO = NewMI->getOperand(i);
435 unsigned Reg = MO.getReg();
436 if (!TargetRegisterInfo::isVirtualRegister(Reg))
439 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
440 unsigned NewReg = MRI->createVirtualRegister(RC);
442 LocalVRMap.insert(std::make_pair(Reg, NewReg));
443 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
444 AddSSAUpdateEntry(Reg, NewReg, PredBB);
446 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
447 if (VI != LocalVRMap.end()) {
448 MO.setReg(VI->second);
449 MRI->constrainRegClass(VI->second, MRI->getRegClass(Reg));
453 PredBB->insert(PredBB->instr_end(), NewMI);
456 /// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
457 /// blocks, the successors have gained new predecessors. Update the PHI
458 /// instructions in them accordingly.
460 TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
461 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
462 SmallSetVector<MachineBasicBlock*,8> &Succs) {
463 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
464 SE = Succs.end(); SI != SE; ++SI) {
465 MachineBasicBlock *SuccBB = *SI;
466 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
470 MachineInstrBuilder MIB(*FromBB->getParent(), II);
472 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
473 MachineOperand &MO = II->getOperand(i+1);
474 if (MO.getMBB() == FromBB) {
481 MachineOperand &MO0 = II->getOperand(Idx);
482 unsigned Reg = MO0.getReg();
484 // Folded into the previous BB.
485 // There could be duplicate phi source entries. FIXME: Should sdisel
486 // or earlier pass fixed this?
487 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
488 MachineOperand &MO = II->getOperand(i+1);
489 if (MO.getMBB() == FromBB) {
490 II->RemoveOperand(i+1);
491 II->RemoveOperand(i);
497 // If Idx is set, the operands at Idx and Idx+1 must be removed.
498 // We reuse the location to avoid expensive RemoveOperand calls.
500 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
501 if (LI != SSAUpdateVals.end()) {
502 // This register is defined in the tail block.
503 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
504 MachineBasicBlock *SrcBB = LI->second[j].first;
505 // If we didn't duplicate a bb into a particular predecessor, we
506 // might still have added an entry to SSAUpdateVals to correcly
507 // recompute SSA. If that case, avoid adding a dummy extra argument
509 if (!SrcBB->isSuccessor(SuccBB))
512 unsigned SrcReg = LI->second[j].second;
514 II->getOperand(Idx).setReg(SrcReg);
515 II->getOperand(Idx+1).setMBB(SrcBB);
518 MIB.addReg(SrcReg).addMBB(SrcBB);
522 // Live in tail block, must also be live in predecessors.
523 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
524 MachineBasicBlock *SrcBB = TDBBs[j];
526 II->getOperand(Idx).setReg(Reg);
527 II->getOperand(Idx+1).setMBB(SrcBB);
530 MIB.addReg(Reg).addMBB(SrcBB);
535 II->RemoveOperand(Idx+1);
536 II->RemoveOperand(Idx);
542 /// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
544 TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
546 MachineBasicBlock &TailBB) {
547 // Only duplicate blocks that end with unconditional branches.
548 if (TailBB.canFallThrough())
551 // Don't try to tail-duplicate single-block loops.
552 if (TailBB.isSuccessor(&TailBB))
555 // Set the limit on the cost to duplicate. When optimizing for size,
556 // duplicate only one, because one branch instruction can be eliminated to
557 // compensate for the duplication.
558 unsigned MaxDuplicateCount;
559 if (TailDuplicateSize.getNumOccurrences() == 0 &&
560 MF.getFunction()->getAttributes().
561 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize))
562 MaxDuplicateCount = 1;
564 MaxDuplicateCount = TailDuplicateSize;
566 // If the target has hardware branch prediction that can handle indirect
567 // branches, duplicating them can often make them predictable when there
568 // are common paths through the code. The limit needs to be high enough
569 // to allow undoing the effects of tail merging and other optimizations
570 // that rearrange the predecessors of the indirect branch.
572 bool HasIndirectbr = false;
574 HasIndirectbr = TailBB.back().isIndirectBranch();
576 if (HasIndirectbr && PreRegAlloc)
577 MaxDuplicateCount = 20;
579 // Check the instructions in the block to determine whether tail-duplication
580 // is invalid or unlikely to be profitable.
581 unsigned InstrCount = 0;
582 for (MachineBasicBlock::iterator I = TailBB.begin(); I != TailBB.end(); ++I) {
583 // Non-duplicable things shouldn't be tail-duplicated.
584 if (I->isNotDuplicable())
587 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
588 // A return may expand into a lot more instructions (e.g. reload of callee
589 // saved registers) after PEI.
590 if (PreRegAlloc && I->isReturn())
593 // Avoid duplicating calls before register allocation. Calls presents a
594 // barrier to register allocation so duplicating them may end up increasing
596 if (PreRegAlloc && I->isCall())
599 if (!I->isPHI() && !I->isDebugValue())
602 if (InstrCount > MaxDuplicateCount)
606 if (HasIndirectbr && PreRegAlloc)
615 return canCompletelyDuplicateBB(TailBB);
618 /// isSimpleBB - True if this BB has only one unconditional jump.
620 TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
621 if (TailBB->succ_size() != 1)
623 if (TailBB->pred_empty())
625 MachineBasicBlock::iterator I = TailBB->begin();
626 MachineBasicBlock::iterator E = TailBB->end();
627 while (I != E && I->isDebugValue())
631 return I->isUnconditionalBranch();
635 bothUsedInPHI(const MachineBasicBlock &A,
636 SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
637 for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
638 SE = A.succ_end(); SI != SE; ++SI) {
639 MachineBasicBlock *BB = *SI;
640 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
648 TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
649 for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
650 PE = BB.pred_end(); PI != PE; ++PI) {
651 MachineBasicBlock *PredBB = *PI;
653 if (PredBB->succ_size() > 1)
656 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
657 SmallVector<MachineOperand, 4> PredCond;
658 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
661 if (!PredCond.empty())
668 TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
669 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
670 const DenseSet<unsigned> &UsedByPhi,
671 SmallVectorImpl<MachineInstr *> &Copies) {
672 SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
674 SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
676 bool Changed = false;
677 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
678 PE = Preds.end(); PI != PE; ++PI) {
679 MachineBasicBlock *PredBB = *PI;
681 if (PredBB->getLandingPadSuccessor())
684 if (bothUsedInPHI(*PredBB, Succs))
687 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
688 SmallVector<MachineOperand, 4> PredCond;
689 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
693 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
694 << "From simple Succ: " << *TailBB);
696 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
697 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(PredBB));
699 // Make PredFBB explicit.
700 if (PredCond.empty())
703 // Make fall through explicit.
710 if (PredFBB == TailBB)
712 if (PredTBB == TailBB)
715 // Make the branch unconditional if possible
716 if (PredTBB == PredFBB) {
721 // Avoid adding fall through branches.
722 if (PredFBB == NextBB)
724 if (PredTBB == NextBB && PredFBB == NULL)
727 TII->RemoveBranch(*PredBB);
730 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
732 uint32_t Weight = MBPI->getEdgeWeight(PredBB, TailBB);
733 PredBB->removeSuccessor(TailBB);
734 unsigned NumSuccessors = PredBB->succ_size();
735 assert(NumSuccessors <= 1);
736 if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
737 PredBB->addSuccessor(NewTarget, Weight);
739 TDBBs.push_back(PredBB);
744 /// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
745 /// of its predecessors.
747 TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
750 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
751 SmallVectorImpl<MachineInstr *> &Copies) {
752 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
754 DenseSet<unsigned> UsedByPhi;
755 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
758 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
760 // Iterate through all the unique predecessors and tail-duplicate this
761 // block into them, if possible. Copying the list ahead of time also
762 // avoids trouble with the predecessor list reallocating.
763 bool Changed = false;
764 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
766 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
767 PE = Preds.end(); PI != PE; ++PI) {
768 MachineBasicBlock *PredBB = *PI;
770 assert(TailBB != PredBB &&
771 "Single-block loop should have been rejected earlier!");
772 // EH edges are ignored by AnalyzeBranch.
773 if (PredBB->succ_size() > 1)
776 MachineBasicBlock *PredTBB, *PredFBB;
777 SmallVector<MachineOperand, 4> PredCond;
778 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
780 if (!PredCond.empty())
782 // Don't duplicate into a fall-through predecessor (at least for now).
783 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
786 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
787 << "From Succ: " << *TailBB);
789 TDBBs.push_back(PredBB);
791 // Remove PredBB's unconditional branch.
792 TII->RemoveBranch(*PredBB);
794 if (RS && !TailBB->livein_empty()) {
795 // Update PredBB livein.
796 RS->enterBasicBlock(PredBB);
797 if (!PredBB->empty())
798 RS->forward(std::prev(PredBB->end()));
799 BitVector RegsLiveAtExit(TRI->getNumRegs());
800 RS->getRegsUsed(RegsLiveAtExit, false);
801 for (MachineBasicBlock::livein_iterator I = TailBB->livein_begin(),
802 E = TailBB->livein_end(); I != E; ++I) {
803 if (!RegsLiveAtExit[*I])
804 // If a register is previously livein to the tail but it's not live
805 // at the end of predecessor BB, then it should be added to its
807 PredBB->addLiveIn(*I);
811 // Clone the contents of TailBB into PredBB.
812 DenseMap<unsigned, unsigned> LocalVRMap;
813 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
814 // Use instr_iterator here to properly handle bundles, e.g.
815 // ARM Thumb2 IT block.
816 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
817 while (I != TailBB->instr_end()) {
818 MachineInstr *MI = &*I;
821 // Replace the uses of the def of the PHI with the register coming
823 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
825 // Replace def of virtual registers with new registers, and update
826 // uses with PHI source register or the new registers.
827 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
830 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
831 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
832 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
833 TII->get(TargetOpcode::COPY),
834 CopyInfos[i].first).addReg(CopyInfos[i].second));
838 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
840 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
843 PredBB->removeSuccessor(PredBB->succ_begin());
844 assert(PredBB->succ_empty() &&
845 "TailDuplicate called on block with multiple successors!");
846 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
847 E = TailBB->succ_end(); I != E; ++I)
848 PredBB->addSuccessor(*I, MBPI->getEdgeWeight(TailBB, I));
854 // If TailBB was duplicated into all its predecessors except for the prior
855 // block, which falls through unconditionally, move the contents of this
856 // block into the prior block.
857 MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(TailBB));
858 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
859 SmallVector<MachineOperand, 4> PriorCond;
860 // This has to check PrevBB->succ_size() because EH edges are ignored by
862 if (PrevBB->succ_size() == 1 &&
863 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
864 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
865 !TailBB->hasAddressTaken()) {
866 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
867 << "From MBB: " << *TailBB);
869 DenseMap<unsigned, unsigned> LocalVRMap;
870 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
871 MachineBasicBlock::iterator I = TailBB->begin();
872 // Process PHI instructions first.
873 while (I != TailBB->end() && I->isPHI()) {
874 // Replace the uses of the def of the PHI with the register coming
876 MachineInstr *MI = &*I++;
877 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
879 MI->eraseFromParent();
882 // Now copy the non-PHI instructions.
883 while (I != TailBB->end()) {
884 // Replace def of virtual registers with new registers, and update
885 // uses with PHI source register or the new registers.
886 MachineInstr *MI = &*I++;
887 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
888 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
889 MI->eraseFromParent();
891 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
892 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
893 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
894 TII->get(TargetOpcode::COPY),
896 .addReg(CopyInfos[i].second));
899 // No PHIs to worry about, just splice the instructions over.
900 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
902 PrevBB->removeSuccessor(PrevBB->succ_begin());
903 assert(PrevBB->succ_empty());
904 PrevBB->transferSuccessors(TailBB);
905 TDBBs.push_back(PrevBB);
909 // If this is after register allocation, there are no phis to fix.
913 // If we made no changes so far, we are safe.
918 // Handle the nasty case in that we duplicated a block that is part of a loop
919 // into some but not all of its predecessors. For example:
923 // if we duplicate 2 into 1 but not into 3, we end up with
924 // 12 -> 3 <-> 2 -> rest |
927 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
928 // with a phi in 3 (which now dominates 2).
929 // What we do here is introduce a copy in 3 of the register defined by the
930 // phi, just like when we are duplicating 2 into 3, but we don't copy any
931 // real instructions or remove the 3 -> 2 edge from the phi in 2.
932 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
933 PE = Preds.end(); PI != PE; ++PI) {
934 MachineBasicBlock *PredBB = *PI;
935 if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
939 if (PredBB->succ_size() != 1)
942 DenseMap<unsigned, unsigned> LocalVRMap;
943 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
944 MachineBasicBlock::iterator I = TailBB->begin();
945 // Process PHI instructions first.
946 while (I != TailBB->end() && I->isPHI()) {
947 // Replace the uses of the def of the PHI with the register coming
949 MachineInstr *MI = &*I++;
950 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
952 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
953 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
954 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
955 TII->get(TargetOpcode::COPY),
956 CopyInfos[i].first).addReg(CopyInfos[i].second));
963 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
964 /// function, updating the CFG.
965 void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
966 assert(MBB->pred_empty() && "MBB must be dead!");
967 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
969 // Remove all successors.
970 while (!MBB->succ_empty())
971 MBB->removeSuccessor(MBB->succ_end()-1);
974 MBB->eraseFromParent();