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 /// EstimateRuntime - Make a rough estimate for how long it will take to run
287 /// the specified code.
288 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
289 MachineBasicBlock::iterator E,
290 const TargetInstrInfo *TII) {
292 for (; I != E; ++I) {
293 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
294 if (TID.Flags & M_CALL_FLAG)
296 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
304 /// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
305 /// MBB2I and then insert an unconditional branch in the other block. Determine
306 /// which is the best to split
307 static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
308 MachineBasicBlock::iterator MBB1I,
309 MachineBasicBlock *MBB2,
310 MachineBasicBlock::iterator MBB2I,
311 const TargetInstrInfo *TII) {
312 // TODO: if we had some notion of which block was hotter, we could split
313 // the hot block, so it is the fall-through. Since we don't have profile info
314 // make a decision based on which will hurt most to split.
315 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
316 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
318 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
319 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
320 // have a lower overall impact on the program execution.
321 return MBB1Time < MBB2Time;
324 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
327 if (!EnableTailMerge) return false;
329 // Find blocks with no successors.
330 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
331 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
333 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
336 // Sort by hash value so that blocks with identical end sequences sort
338 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
340 // Walk through equivalence sets looking for actual exact matches.
341 while (MergePotentials.size() > 1) {
342 unsigned CurHash = (MergePotentials.end()-1)->first;
343 unsigned PrevHash = (MergePotentials.end()-2)->first;
344 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
346 // If there is nothing that matches the hash of the current basic block,
348 if (CurHash != PrevHash) {
349 MergePotentials.pop_back();
353 // Determine the actual length of the shared tail between these two basic
354 // blocks. Because the hash can have collisions, it's possible that this is
356 MachineBasicBlock::iterator BBI1, BBI2;
357 unsigned CommonTailLen =
358 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
361 // If the tails don't have at least two instructions in common, see if there
362 // is anything else in the equivalence class that does match.
363 if (CommonTailLen < 2) {
364 unsigned FoundMatch = ~0U;
365 for (int i = MergePotentials.size()-2;
366 i != -1 && MergePotentials[i].first == CurHash; --i) {
367 CommonTailLen = ComputeCommonTailLength(CurMBB,
368 MergePotentials[i].second,
370 if (CommonTailLen >= 2) {
376 // If we didn't find anything that has at least two instructions matching
377 // this one, bail out.
378 if (FoundMatch == ~0U) {
379 MergePotentials.pop_back();
383 // Otherwise, move the matching block to the right position.
384 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
387 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
389 // If neither block is the entire common tail, split the tail of one block
390 // to make it redundant with the other tail.
391 if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
392 if (0) { // Enable this to disable partial tail merges.
393 MergePotentials.pop_back();
397 // Decide whether we want to split CurMBB or MBB2.
398 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
399 CurMBB = SplitMBBAt(*CurMBB, BBI1);
400 BBI1 = CurMBB->begin();
401 MergePotentials.back().second = CurMBB;
403 MBB2 = SplitMBBAt(*MBB2, BBI2);
404 BBI2 = MBB2->begin();
405 (MergePotentials.end()-2)->second = MBB2;
409 if (MBB2->begin() == BBI2) {
410 // Hack the end off CurMBB, making it jump to MBBI@ instead.
411 ReplaceTailWithBranchTo(BBI1, MBB2);
412 // This modifies CurMBB, so remove it from the worklist.
413 MergePotentials.pop_back();
415 assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
416 // Hack the end off MBB2, making it jump to CurMBB instead.
417 ReplaceTailWithBranchTo(BBI2, CurMBB);
418 // This modifies MBB2, so remove it from the worklist.
419 MergePotentials.erase(MergePotentials.end()-2);
428 //===----------------------------------------------------------------------===//
429 // Branch Optimization
430 //===----------------------------------------------------------------------===//
432 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
435 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
436 MachineBasicBlock *MBB = I++;
439 // If it is dead, remove it.
440 if (MBB->pred_empty()) {
441 RemoveDeadBlock(MBB);
450 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
451 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
452 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can
454 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
455 MachineBasicBlock *DestA,
456 MachineBasicBlock *DestB,
458 MachineFunction::iterator FallThru) {
459 bool MadeChange = false;
460 bool AddedFallThrough = false;
462 // If this block ends with a conditional branch that falls through to its
463 // successor, set DestB as the successor.
465 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
467 AddedFallThrough = true;
470 // If this is an unconditional branch with no explicit dest, it must just be
471 // a fallthrough into DestB.
472 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
474 AddedFallThrough = true;
478 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
479 while (SI != MBB.succ_end()) {
483 } else if (*SI == DestB) {
487 // Otherwise, this is a superfluous edge, remove it.
488 MBB.removeSuccessor(SI);
492 if (!AddedFallThrough) {
493 assert(DestA == 0 && DestB == 0 &&
494 "MachineCFG is missing edges!");
496 assert(DestA == 0 && "MachineCFG is missing edges!");
502 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
503 /// 'Old', change the code and CFG so that it branches to 'New' instead.
504 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
505 MachineBasicBlock *Old,
506 MachineBasicBlock *New,
507 const TargetInstrInfo *TII) {
508 assert(Old != New && "Cannot replace self with self!");
510 MachineBasicBlock::iterator I = BB->end();
511 while (I != BB->begin()) {
513 if (!TII->isTerminatorInstr(I->getOpcode())) break;
515 // Scan the operands of this machine instruction, replacing any uses of Old
517 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
518 if (I->getOperand(i).isMachineBasicBlock() &&
519 I->getOperand(i).getMachineBasicBlock() == Old)
520 I->getOperand(i).setMachineBasicBlock(New);
523 // Update the successor information.
524 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
525 for (int i = Succs.size()-1; i >= 0; --i)
526 if (Succs[i] == Old) {
527 BB->removeSuccessor(Old);
528 BB->addSuccessor(New);
532 /// CanFallThrough - Return true if the specified block (with the specified
533 /// branch condition) can implicitly transfer control to the block after it by
534 /// falling off the end of it. This should return false if it can reach the
535 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
537 /// True is a conservative answer.
539 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
540 bool BranchUnAnalyzable,
541 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
542 const std::vector<MachineOperand> &Cond) {
543 MachineFunction::iterator Fallthrough = CurBB;
545 // If FallthroughBlock is off the end of the function, it can't fall through.
546 if (Fallthrough == CurBB->getParent()->end())
549 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
550 if (!CurBB->isSuccessor(Fallthrough))
553 // If we couldn't analyze the branch, assume it could fall through.
554 if (BranchUnAnalyzable) return true;
556 // If there is no branch, control always falls through.
557 if (TBB == 0) return true;
559 // If there is some explicit branch to the fallthrough block, it can obviously
560 // reach, even though the branch should get folded to fall through implicitly.
561 if (MachineFunction::iterator(TBB) == Fallthrough ||
562 MachineFunction::iterator(FBB) == Fallthrough)
565 // If it's an unconditional branch to some block not the fall through, it
566 // doesn't fall through.
567 if (Cond.empty()) return false;
569 // Otherwise, if it is conditional and has no explicit false block, it falls
574 /// CanFallThrough - Return true if the specified can implicitly transfer
575 /// control to the block after it by falling off the end of it. This should
576 /// return false if it can reach the block after it, but it uses an explicit
577 /// branch to do so (e.g. a table jump).
579 /// True is a conservative answer.
581 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
582 MachineBasicBlock *TBB = 0, *FBB = 0;
583 std::vector<MachineOperand> Cond;
584 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
585 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
588 /// OptimizeBlock - Analyze and optimize control flow related to the specified
589 /// block. This is never called on the entry block.
590 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
591 MachineFunction::iterator FallThrough = MBB;
594 // If this block is empty, make everyone use its fall-through, not the block
597 // Dead block? Leave for cleanup later.
598 if (MBB->pred_empty()) return;
600 if (FallThrough == MBB->getParent()->end()) {
601 // TODO: Simplify preds to not branch here if possible!
603 // Rewrite all predecessors of the old block to go to the fallthrough
605 while (!MBB->pred_empty()) {
606 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
607 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
610 // If MBB was the target of a jump table, update jump tables to go to the
611 // fallthrough instead.
612 MBB->getParent()->getJumpTableInfo()->
613 ReplaceMBBInJumpTables(MBB, FallThrough);
619 // Check to see if we can simplify the terminator of the block before this
621 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
623 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
624 std::vector<MachineOperand> PriorCond;
625 bool PriorUnAnalyzable =
626 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
627 if (!PriorUnAnalyzable) {
628 // If the CFG for the prior block has extra edges, remove them.
629 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
630 !PriorCond.empty(), MBB);
632 // If the previous branch is conditional and both conditions go to the same
633 // destination, remove the branch, replacing it with an unconditional one or
635 if (PriorTBB && PriorTBB == PriorFBB) {
636 TII->RemoveBranch(PrevBB);
639 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
642 return OptimizeBlock(MBB);
645 // If the previous branch *only* branches to *this* block (conditional or
646 // not) remove the branch.
647 if (PriorTBB == MBB && PriorFBB == 0) {
648 TII->RemoveBranch(PrevBB);
651 return OptimizeBlock(MBB);
654 // If the prior block branches somewhere else on the condition and here if
655 // the condition is false, remove the uncond second branch.
656 if (PriorFBB == MBB) {
657 TII->RemoveBranch(PrevBB);
658 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
661 return OptimizeBlock(MBB);
664 // If the prior block branches here on true and somewhere else on false, and
665 // if the branch condition is reversible, reverse the branch to create a
667 if (PriorTBB == MBB) {
668 std::vector<MachineOperand> NewPriorCond(PriorCond);
669 if (!TII->ReverseBranchCondition(NewPriorCond)) {
670 TII->RemoveBranch(PrevBB);
671 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
674 return OptimizeBlock(MBB);
679 // Analyze the branch in the current block.
680 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
681 std::vector<MachineOperand> CurCond;
682 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
683 if (!CurUnAnalyzable) {
684 // If the CFG for the prior block has extra edges, remove them.
685 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
687 ++MachineFunction::iterator(MBB));
689 // If this branch is the only thing in its block, see if we can forward
690 // other blocks across it.
691 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
692 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
693 // This block may contain just an unconditional branch. Because there can
694 // be 'non-branch terminators' in the block, try removing the branch and
695 // then seeing if the block is empty.
696 TII->RemoveBranch(*MBB);
698 // If this block is just an unconditional branch to CurTBB, we can
699 // usually completely eliminate the block. The only case we cannot
700 // completely eliminate the block is when the block before this one
701 // falls through into MBB and we can't understand the prior block's branch
704 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
705 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
706 !PrevBB.isSuccessor(MBB)) {
707 // If the prior block falls through into us, turn it into an
708 // explicit branch to us to make updates simpler.
709 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
710 PriorTBB != MBB && PriorFBB != MBB) {
712 assert(PriorCond.empty() && PriorFBB == 0 &&
713 "Bad branch analysis");
716 assert(PriorFBB == 0 && "Machine CFG out of date!");
719 TII->RemoveBranch(PrevBB);
720 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
723 // Iterate through all the predecessors, revectoring each in-turn.
724 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
725 bool DidChange = false;
726 bool HasBranchToSelf = false;
727 while (PI != MBB->pred_end()) {
729 // If this block has an uncond branch to itself, leave it.
731 HasBranchToSelf = true;
734 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
738 // Change any jumptables to go to the new MBB.
739 MBB->getParent()->getJumpTableInfo()->
740 ReplaceMBBInJumpTables(MBB, CurTBB);
744 if (!HasBranchToSelf) return;
749 // Add the branch back if the block is more than just an uncond branch.
750 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
754 // If the prior block doesn't fall through into this block, and if this
755 // block doesn't fall through into some other block, see if we can find a
756 // place to move this block where a fall-through will happen.
757 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
758 PriorTBB, PriorFBB, PriorCond)) {
759 // Now we know that there was no fall-through into this block, check to
760 // see if it has a fall-through into its successor.
761 if (!CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, CurCond)) {
762 // Check all the predecessors of this block. If one of them has no fall
763 // throughs, move this block right after it.
764 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
765 E = MBB->pred_end(); PI != E; ++PI) {
766 // Analyze the branch at the end of the pred.
767 MachineBasicBlock *PredBB = *PI;
768 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
769 std::vector<MachineOperand> PredCond;
770 if (PredBB != MBB && !CanFallThrough(PredBB)) {
771 MBB->moveAfter(PredBB);
773 return OptimizeBlock(MBB);
777 // Check all successors to see if we can move this block before it.
778 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
779 E = MBB->succ_end(); SI != E; ++SI) {
780 // Analyze the branch at the end of the block before the succ.
781 MachineBasicBlock *SuccBB = *SI;
782 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
783 std::vector<MachineOperand> SuccPrevCond;
784 if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
785 MBB->moveBefore(SuccBB);
787 return OptimizeBlock(MBB);
791 // Okay, there is no really great place to put this block. If, however,
792 // the block before this one would be a fall-through if this block were
793 // removed, move this block to the end of the function.
794 if (FallThrough != MBB->getParent()->end() &&
795 PrevBB.isSuccessor(FallThrough)) {
796 MBB->moveAfter(--MBB->getParent()->end());