1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass forwards branches to unconditional branches to make them branch
11 // directly to the target block. This pass often results in dead MBB's, which
14 // Note that this pass must be run after register allocation, it cannot handle
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/MachineDebugInfo.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/STLExtras.h"
30 static Statistic<> NumDeadBlocks("branchfold", "Number of dead blocks removed");
31 static Statistic<> NumBranchOpts("branchfold", "Number of branches optimized");
32 static Statistic<> NumTailMerge ("branchfold", "Number of block tails merged");
33 static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
36 struct BranchFolder : public MachineFunctionPass {
37 virtual bool runOnMachineFunction(MachineFunction &MF);
38 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
39 const TargetInstrInfo *TII;
40 MachineDebugInfo *MDI;
44 bool TailMergeBlocks(MachineFunction &MF);
45 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
46 MachineBasicBlock *NewDest);
47 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
48 MachineBasicBlock::iterator BBI1);
51 bool OptimizeBranches(MachineFunction &MF);
52 void OptimizeBlock(MachineBasicBlock *MBB);
53 void RemoveDeadBlock(MachineBasicBlock *MBB);
55 bool CanFallThrough(MachineBasicBlock *CurBB);
56 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
57 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
58 const std::vector<MachineOperand> &Cond);
62 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
64 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
65 /// function, updating the CFG.
66 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
67 assert(MBB->pred_empty() && "MBB must be dead!");
69 MachineFunction *MF = MBB->getParent();
70 // drop all successors.
71 while (!MBB->succ_empty())
72 MBB->removeSuccessor(MBB->succ_end()-1);
74 // If there is DWARF info to active, check to see if there are any DWARF_LABEL
75 // records in the basic block. If so, unregister them from MachineDebugInfo.
76 if (MDI && !MBB->empty()) {
77 unsigned DWARF_LABELOpc = TII->getDWARF_LABELOpcode();
78 assert(DWARF_LABELOpc &&
79 "Target supports dwarf but didn't implement getDWARF_LABELOpcode!");
81 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
83 if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
84 // The label ID # is always operand #0, an immediate.
85 MDI->InvalidateLabel(I->getOperand(0).getImm());
91 MF->getBasicBlockList().erase(MBB);
94 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
95 TII = MF.getTarget().getInstrInfo();
96 if (!TII) return false;
98 MDI = getAnalysisToUpdate<MachineDebugInfo>();
100 bool EverMadeChange = false;
101 bool MadeChangeThisIteration = true;
102 while (MadeChangeThisIteration) {
103 MadeChangeThisIteration = false;
104 MadeChangeThisIteration |= TailMergeBlocks(MF);
105 MadeChangeThisIteration |= OptimizeBranches(MF);
106 EverMadeChange |= MadeChangeThisIteration;
109 // See if any jump tables have become mergable or dead as the code generator
111 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
112 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
114 // Figure out how these jump tables should be merged.
115 std::vector<unsigned> JTMapping;
116 JTMapping.reserve(JTs.size());
118 // We always keep the 0th jump table.
119 JTMapping.push_back(0);
121 // Scan the jump tables, seeing if there are any duplicates. Note that this
122 // is N^2, which should be fixed someday.
123 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
124 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
126 // If a jump table was merge with another one, walk the function rewriting
127 // references to jump tables to reference the new JT ID's. Keep track of
128 // whether we see a jump table idx, if not, we can delete the JT.
129 std::vector<bool> JTIsLive;
130 JTIsLive.resize(JTs.size());
131 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
133 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
135 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
136 MachineOperand &Op = I->getOperand(op);
137 if (!Op.isJumpTableIndex()) continue;
138 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
139 Op.setJumpTableIndex(NewIdx);
141 // Remember that this JT is live.
142 JTIsLive[NewIdx] = true;
146 // Finally, remove dead jump tables. This happens either because the
147 // indirect jump was unreachable (and thus deleted) or because the jump
148 // table was merged with some other one.
149 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
151 JTI->RemoveJumpTable(i);
152 EverMadeChange = true;
156 return EverMadeChange;
159 //===----------------------------------------------------------------------===//
160 // Tail Merging of Blocks
161 //===----------------------------------------------------------------------===//
163 /// HashMachineInstr - Compute a hash value for MI and its operands.
164 static unsigned HashMachineInstr(const MachineInstr *MI) {
165 unsigned Hash = MI->getOpcode();
166 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
167 const MachineOperand &Op = MI->getOperand(i);
169 // Merge in bits from the operand if easy.
170 unsigned OperandHash = 0;
171 switch (Op.getType()) {
172 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
173 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
174 case MachineOperand::MO_MachineBasicBlock:
175 OperandHash = Op.getMachineBasicBlock()->getNumber();
177 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
178 case MachineOperand::MO_ConstantPoolIndex:
179 OperandHash = Op.getConstantPoolIndex();
181 case MachineOperand::MO_JumpTableIndex:
182 OperandHash = Op.getJumpTableIndex();
184 case MachineOperand::MO_GlobalAddress:
185 case MachineOperand::MO_ExternalSymbol:
186 // Global address / external symbol are too hard, don't bother, but do
187 // pull in the offset.
188 OperandHash = Op.getOffset();
193 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
198 /// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
199 /// instructions, because cross-jumping only saves code when at least two
200 /// instructions are removed (since a branch must be inserted).
201 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
202 MachineBasicBlock::const_iterator I = MBB->end();
203 if (I == MBB->begin())
204 return 0; // Empty MBB.
207 unsigned Hash = HashMachineInstr(I);
209 if (I == MBB->begin())
210 return Hash; // Single instr MBB.
213 // Hash in the second-to-last instruction.
214 Hash ^= HashMachineInstr(I) << 2;
218 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
219 /// of instructions they actually have in common together at their end. Return
220 /// iterators for the first shared instruction in each block.
221 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
222 MachineBasicBlock *MBB2,
223 MachineBasicBlock::iterator &I1,
224 MachineBasicBlock::iterator &I2) {
228 unsigned TailLen = 0;
229 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
231 if (!I1->isIdenticalTo(I2)) {
240 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
241 /// after it, replacing it with an unconditional branch to NewDest. This
242 /// returns true if OldInst's block is modified, false if NewDest is modified.
243 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
244 MachineBasicBlock *NewDest) {
245 MachineBasicBlock *OldBB = OldInst->getParent();
247 // Remove all the old successors of OldBB from the CFG.
248 while (!OldBB->succ_empty())
249 OldBB->removeSuccessor(OldBB->succ_begin());
251 // Remove all the dead instructions from the end of OldBB.
252 OldBB->erase(OldInst, OldBB->end());
254 // If OldBB isn't immediately before OldBB, insert a branch to it.
255 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
256 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
257 OldBB->addSuccessor(NewDest);
261 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
262 /// MBB so that the part before the iterator falls into the part starting at the
263 /// iterator. This returns the new MBB.
264 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
265 MachineBasicBlock::iterator BBI1) {
266 // Create the fall-through block.
267 MachineFunction::iterator MBBI = &CurMBB;
268 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
269 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
271 // Move all the successors of this block to the specified block.
272 while (!CurMBB.succ_empty()) {
273 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
274 NewMBB->addSuccessor(S);
275 CurMBB.removeSuccessor(S);
278 // Add an edge from CurMBB to NewMBB for the fall-through.
279 CurMBB.addSuccessor(NewMBB);
281 // Splice the code over.
282 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
286 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
289 if (!EnableTailMerge) return false;
291 // Find blocks with no successors.
292 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
293 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
295 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
298 // Sort by hash value so that blocks with identical end sequences sort
300 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
302 // Walk through equivalence sets looking for actual exact matches.
303 while (MergePotentials.size() > 1) {
304 unsigned CurHash = (MergePotentials.end()-1)->first;
305 unsigned PrevHash = (MergePotentials.end()-2)->first;
306 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
308 // If there is nothing that matches the hash of the current basic block,
310 if (CurHash != PrevHash) {
311 MergePotentials.pop_back();
315 // Determine the actual length of the shared tail between these two basic
316 // blocks. Because the hash can have collisions, it's possible that this is
318 MachineBasicBlock::iterator BBI1, BBI2;
319 unsigned CommonTailLen =
320 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
323 // If the tails don't have at least two instructions in common, see if there
324 // is anything else in the equivalence class that does match.
325 if (CommonTailLen < 2) {
326 unsigned FoundMatch = ~0U;
327 for (int i = MergePotentials.size()-2;
328 i != -1 && MergePotentials[i].first == CurHash; --i) {
329 CommonTailLen = ComputeCommonTailLength(CurMBB,
330 MergePotentials[i].second,
332 if (CommonTailLen >= 2) {
338 // If we didn't find anything that has at least two instructions matching
339 // this one, bail out.
340 if (FoundMatch == ~0U) {
341 MergePotentials.pop_back();
345 // Otherwise, move the matching block to the right position.
346 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
349 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
351 // If neither block is the entire common tail, split the tail of one block
352 // to make it redundant with the other tail.
353 if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
354 if (0) { // Enable this to disable partial tail merges.
355 MergePotentials.pop_back();
358 // TODO: if we had some notion of which block was hotter, we could split
359 // the hot block, so it is the fall-through. For now, just split the
361 MBB2 = SplitMBBAt(*MBB2, BBI2);
362 BBI2 = MBB2->begin();
363 (MergePotentials.end()-2)->second = MBB2;
366 if (MBB2->begin() == BBI2) {
367 // Hack the end off CurMBB, making it jump to MBBI@ instead.
368 ReplaceTailWithBranchTo(BBI1, MBB2);
369 // This modifies CurMBB, so remove it from the worklist.
370 MergePotentials.pop_back();
372 assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
373 // Hack the end off MBB2, making it jump to CurMBB instead.
374 ReplaceTailWithBranchTo(BBI2, CurMBB);
375 // This modifies MBB2, so remove it from the worklist.
376 MergePotentials.erase(MergePotentials.end()-2);
385 //===----------------------------------------------------------------------===//
386 // Branch Optimization
387 //===----------------------------------------------------------------------===//
389 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
392 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
393 MachineBasicBlock *MBB = I++;
396 // If it is dead, remove it.
397 if (MBB->pred_empty()) {
398 RemoveDeadBlock(MBB);
407 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
408 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
409 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can
411 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
412 MachineBasicBlock *DestA,
413 MachineBasicBlock *DestB,
415 MachineFunction::iterator FallThru) {
416 bool MadeChange = false;
417 bool AddedFallThrough = false;
419 // If this block ends with a conditional branch that falls through to its
420 // successor, set DestB as the successor.
422 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
424 AddedFallThrough = true;
427 // If this is an unconditional branch with no explicit dest, it must just be
428 // a fallthrough into DestB.
429 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
431 AddedFallThrough = true;
435 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
436 while (SI != MBB.succ_end()) {
440 } else if (*SI == DestB) {
444 // Otherwise, this is a superfluous edge, remove it.
445 MBB.removeSuccessor(SI);
449 if (!AddedFallThrough) {
450 assert(DestA == 0 && DestB == 0 &&
451 "MachineCFG is missing edges!");
453 assert(DestA == 0 && "MachineCFG is missing edges!");
459 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
460 /// 'Old', change the code and CFG so that it branches to 'New' instead.
461 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
462 MachineBasicBlock *Old,
463 MachineBasicBlock *New,
464 const TargetInstrInfo *TII) {
465 assert(Old != New && "Cannot replace self with self!");
467 MachineBasicBlock::iterator I = BB->end();
468 while (I != BB->begin()) {
470 if (!TII->isTerminatorInstr(I->getOpcode())) break;
472 // Scan the operands of this machine instruction, replacing any uses of Old
474 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
475 if (I->getOperand(i).isMachineBasicBlock() &&
476 I->getOperand(i).getMachineBasicBlock() == Old)
477 I->getOperand(i).setMachineBasicBlock(New);
480 // Update the successor information.
481 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
482 for (int i = Succs.size()-1; i >= 0; --i)
483 if (Succs[i] == Old) {
484 BB->removeSuccessor(Old);
485 BB->addSuccessor(New);
489 /// CanFallThrough - Return true if the specified block (with the specified
490 /// branch condition) can implicitly transfer control to the block after it by
491 /// falling off the end of it. This should return false if it can reach the
492 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
494 /// True is a conservative answer.
496 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
497 bool BranchUnAnalyzable,
498 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
499 const std::vector<MachineOperand> &Cond) {
500 MachineFunction::iterator Fallthrough = CurBB;
502 // If FallthroughBlock is off the end of the function, it can't fall through.
503 if (Fallthrough == CurBB->getParent()->end())
506 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
507 if (!CurBB->isSuccessor(Fallthrough))
510 // If we couldn't analyze the branch, assume it could fall through.
511 if (BranchUnAnalyzable) return true;
513 // If there is no branch, control always falls through.
514 if (TBB == 0) return true;
516 // If there is some explicit branch to the fallthrough block, it can obviously
517 // reach, even though the branch should get folded to fall through implicitly.
518 if (MachineFunction::iterator(TBB) == Fallthrough ||
519 MachineFunction::iterator(FBB) == Fallthrough)
522 // If it's an unconditional branch to some block not the fall through, it
523 // doesn't fall through.
524 if (Cond.empty()) return false;
526 // Otherwise, if it is conditional and has no explicit false block, it falls
531 /// CanFallThrough - Return true if the specified can implicitly transfer
532 /// control to the block after it by falling off the end of it. This should
533 /// return false if it can reach the block after it, but it uses an explicit
534 /// branch to do so (e.g. a table jump).
536 /// True is a conservative answer.
538 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
539 MachineBasicBlock *TBB = 0, *FBB = 0;
540 std::vector<MachineOperand> Cond;
541 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
542 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
545 /// OptimizeBlock - Analyze and optimize control flow related to the specified
546 /// block. This is never called on the entry block.
547 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
548 MachineFunction::iterator FallThrough = MBB;
551 // If this block is empty, make everyone use its fall-through, not the block
554 // Dead block? Leave for cleanup later.
555 if (MBB->pred_empty()) return;
557 if (FallThrough == MBB->getParent()->end()) {
558 // TODO: Simplify preds to not branch here if possible!
560 // Rewrite all predecessors of the old block to go to the fallthrough
562 while (!MBB->pred_empty()) {
563 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
564 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
567 // If MBB was the target of a jump table, update jump tables to go to the
568 // fallthrough instead.
569 MBB->getParent()->getJumpTableInfo()->
570 ReplaceMBBInJumpTables(MBB, FallThrough);
576 // Check to see if we can simplify the terminator of the block before this
578 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
580 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
581 std::vector<MachineOperand> PriorCond;
582 bool PriorUnAnalyzable =
583 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
584 if (!PriorUnAnalyzable) {
585 // If the CFG for the prior block has extra edges, remove them.
586 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
587 !PriorCond.empty(), MBB);
589 // If the previous branch is conditional and both conditions go to the same
590 // destination, remove the branch, replacing it with an unconditional one or
592 if (PriorTBB && PriorTBB == PriorFBB) {
593 TII->RemoveBranch(PrevBB);
596 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
599 return OptimizeBlock(MBB);
602 // If the previous branch *only* branches to *this* block (conditional or
603 // not) remove the branch.
604 if (PriorTBB == MBB && PriorFBB == 0) {
605 TII->RemoveBranch(PrevBB);
608 return OptimizeBlock(MBB);
611 // If the prior block branches somewhere else on the condition and here if
612 // the condition is false, remove the uncond second branch.
613 if (PriorFBB == MBB) {
614 TII->RemoveBranch(PrevBB);
615 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
618 return OptimizeBlock(MBB);
621 // If the prior block branches here on true and somewhere else on false, and
622 // if the branch condition is reversible, reverse the branch to create a
624 if (PriorTBB == MBB) {
625 std::vector<MachineOperand> NewPriorCond(PriorCond);
626 if (!TII->ReverseBranchCondition(NewPriorCond)) {
627 TII->RemoveBranch(PrevBB);
628 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
631 return OptimizeBlock(MBB);
636 // Analyze the branch in the current block.
637 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
638 std::vector<MachineOperand> CurCond;
639 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
640 if (!CurUnAnalyzable) {
641 // If the CFG for the prior block has extra edges, remove them.
642 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
644 ++MachineFunction::iterator(MBB));
646 // If this branch is the only thing in its block, see if we can forward
647 // other blocks across it.
648 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
649 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
650 // This block may contain just an unconditional branch. Because there can
651 // be 'non-branch terminators' in the block, try removing the branch and
652 // then seeing if the block is empty.
653 TII->RemoveBranch(*MBB);
655 // If this block is just an unconditional branch to CurTBB, we can
656 // usually completely eliminate the block. The only case we cannot
657 // completely eliminate the block is when the block before this one
658 // falls through into MBB and we can't understand the prior block's branch
661 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
662 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
663 !PrevBB.isSuccessor(MBB)) {
664 // If the prior block falls through into us, turn it into an
665 // explicit branch to us to make updates simpler.
666 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
667 PriorTBB != MBB && PriorFBB != MBB) {
669 assert(PriorCond.empty() && PriorFBB == 0 &&
670 "Bad branch analysis");
673 assert(PriorFBB == 0 && "Machine CFG out of date!");
676 TII->RemoveBranch(PrevBB);
677 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
680 // Iterate through all the predecessors, revectoring each in-turn.
681 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
682 bool DidChange = false;
683 bool HasBranchToSelf = false;
684 while (PI != MBB->pred_end()) {
686 // If this block has an uncond branch to itself, leave it.
688 HasBranchToSelf = true;
691 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
695 // Change any jumptables to go to the new MBB.
696 MBB->getParent()->getJumpTableInfo()->
697 ReplaceMBBInJumpTables(MBB, CurTBB);
701 if (!HasBranchToSelf) return;
706 // Add the branch back if the block is more than just an uncond branch.
707 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
711 // If the prior block doesn't fall through into this block, and if this
712 // block doesn't fall through into some other block, see if we can find a
713 // place to move this block where a fall-through will happen.
714 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
715 PriorTBB, PriorFBB, PriorCond)) {
716 // Now we know that there was no fall-through into this block, check to
717 // see if it has a fall-through into its successor.
718 if (!CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, CurCond)) {
719 // Check all the predecessors of this block. If one of them has no fall
720 // throughs, move this block right after it.
721 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
722 E = MBB->pred_end(); PI != E; ++PI) {
723 // Analyze the branch at the end of the pred.
724 MachineBasicBlock *PredBB = *PI;
725 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
726 MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
727 std::vector<MachineOperand> PredCond;
728 if (PredBB != MBB && !CanFallThrough(PredBB)) {
729 MBB->moveAfter(PredBB);
731 return OptimizeBlock(MBB);
735 // Check all successors to see if we can move this block before it.
736 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
737 E = MBB->succ_end(); SI != E; ++SI) {
738 // Analyze the branch at the end of the block before the succ.
739 MachineBasicBlock *SuccBB = *SI;
740 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
741 MachineBasicBlock *SuccPrevTBB = 0, *SuccPrevFBB = 0;
742 std::vector<MachineOperand> SuccPrevCond;
743 if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
744 MBB->moveBefore(SuccBB);
746 return OptimizeBlock(MBB);
750 // Okay, there is no really great place to put this block. If, however,
751 // the block before this one would be a fall-through if this block were
752 // removed, move this block to the end of the function.
753 if (FallThrough != MBB->getParent()->end() &&
754 PrevBB.isSuccessor(FallThrough)) {
755 MBB->moveAfter(--MBB->getParent()->end());