ac243f3e42ca1cce3b2d573c26e3e686cfe7c1d4
[oota-llvm.git] / lib / CodeGen / BranchFolding.cpp
1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
12 // it then removes.
13 //
14 // Note that this pass must be run after register allocation, it cannot handle
15 // SSA form.
16 //
17 //===----------------------------------------------------------------------===//
18
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"
28 using namespace llvm;
29
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);
34
35 namespace {
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;
41     bool MadeChange;
42   private:
43     // Tail Merging.
44     bool TailMergeBlocks(MachineFunction &MF);
45     void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
46                                  MachineBasicBlock *NewDest);
47     MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
48                                   MachineBasicBlock::iterator BBI1);
49         
50     // Branch optzn.
51     bool OptimizeBranches(MachineFunction &MF);
52     void OptimizeBlock(MachineBasicBlock *MBB);
53     void RemoveDeadBlock(MachineBasicBlock *MBB);
54     
55     bool CanFallThrough(MachineBasicBlock *CurBB);
56     bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
57                         MachineBasicBlock *TBB, MachineBasicBlock *FBB,
58                         const std::vector<MachineOperand> &Cond);
59   };
60 }
61
62 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
63
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!");
68   
69   MachineFunction *MF = MBB->getParent();
70   // drop all successors.
71   while (!MBB->succ_empty())
72     MBB->removeSuccessor(MBB->succ_end()-1);
73   
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!");
80     
81     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
82          I != E; ++I) {
83       if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
84         // The label ID # is always operand #0, an immediate.
85         MDI->InvalidateLabel(I->getOperand(0).getImm());
86       }
87     }
88   }
89   
90   // Remove the block.
91   MF->getBasicBlockList().erase(MBB);
92 }
93
94 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
95   TII = MF.getTarget().getInstrInfo();
96   if (!TII) return false;
97
98   MDI = getAnalysisToUpdate<MachineDebugInfo>();
99   
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;
107   }
108
109   // See if any jump tables have become mergable or dead as the code generator
110   // did its thing.
111   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
112   const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
113   if (!JTs.empty()) {
114     // Figure out how these jump tables should be merged.
115     std::vector<unsigned> JTMapping;
116     JTMapping.reserve(JTs.size());
117     
118     // We always keep the 0th jump table.
119     JTMapping.push_back(0);
120
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));
125     
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();
132          BB != E; ++BB) {
133       for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
134            I != E; ++I)
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);
140
141           // Remember that this JT is live.
142           JTIsLive[NewIdx] = true;
143         }
144     }
145    
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)
150       if (!JTIsLive[i]) {
151         JTI->RemoveJumpTable(i);
152         EverMadeChange = true;
153       }
154   }
155   
156   return EverMadeChange;
157 }
158
159 //===----------------------------------------------------------------------===//
160 //  Tail Merging of Blocks
161 //===----------------------------------------------------------------------===//
162
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);
168     
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();
176       break;
177     case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
178     case MachineOperand::MO_ConstantPoolIndex:
179       OperandHash = Op.getConstantPoolIndex();
180       break;
181     case MachineOperand::MO_JumpTableIndex:
182       OperandHash = Op.getJumpTableIndex();
183       break;
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();
189       break;
190     default: break;
191     }
192     
193     Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
194   }
195   return Hash;
196 }
197
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.
205   
206   --I;
207   unsigned Hash = HashMachineInstr(I);
208     
209   if (I == MBB->begin())
210     return Hash;   // Single instr MBB.
211   
212   --I;
213   // Hash in the second-to-last instruction.
214   Hash ^= HashMachineInstr(I) << 2;
215   return Hash;
216 }
217
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) {
225   I1 = MBB1->end();
226   I2 = MBB2->end();
227   
228   unsigned TailLen = 0;
229   while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
230     --I1; --I2;
231     if (!I1->isIdenticalTo(I2)) {
232       ++I1; ++I2;
233       break;
234     }
235     ++TailLen;
236   }
237   return TailLen;
238 }
239
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();
246   
247   // Remove all the old successors of OldBB from the CFG.
248   while (!OldBB->succ_empty())
249     OldBB->removeSuccessor(OldBB->succ_begin());
250   
251   // Remove all the dead instructions from the end of OldBB.
252   OldBB->erase(OldInst, OldBB->end());
253
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);
258   ++NumTailMerge;
259 }
260
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);
270
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);
276   }
277  
278   // Add an edge from CurMBB to NewMBB for the fall-through.
279   CurMBB.addSuccessor(NewMBB);
280   
281   // Splice the code over.
282   NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
283   return NewMBB;
284 }
285
286 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
287   MadeChange = false;
288   
289   if (!EnableTailMerge) return false;
290   
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) {
294     if (I->succ_empty())
295       MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
296   }
297   
298   // Sort by hash value so that blocks with identical end sequences sort
299   // together.
300   std::stable_sort(MergePotentials.begin(), MergePotentials.end());
301
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;
307     
308     // If there is nothing that matches the hash of the current basic block,
309     // give up.
310     if (CurHash != PrevHash) {
311       MergePotentials.pop_back();
312       continue;
313     }
314     
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
317     // less than 2.
318     MachineBasicBlock::iterator BBI1, BBI2;
319     unsigned CommonTailLen = 
320       ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second, 
321                               BBI1, BBI2);
322     
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,
331                                                 BBI1, BBI2);
332         if (CommonTailLen >= 2) {
333           FoundMatch = i;
334           break;
335         }
336       }
337       
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();
342         continue;
343       }
344       
345       // Otherwise, move the matching block to the right position.
346       std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
347     }
348
349     MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
350
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();
356         continue;
357       }
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
360       // second block.
361       MBB2 = SplitMBBAt(*MBB2, BBI2);
362       BBI2 = MBB2->begin();
363       (MergePotentials.end()-2)->second = MBB2;
364     }
365     
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();
371     } else {
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);
377     }
378     MadeChange = true;
379   }
380   
381   return MadeChange;
382 }
383
384
385 //===----------------------------------------------------------------------===//
386 //  Branch Optimization
387 //===----------------------------------------------------------------------===//
388
389 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
390   MadeChange = false;
391   
392   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
393     MachineBasicBlock *MBB = I++;
394     OptimizeBlock(MBB);
395     
396     // If it is dead, remove it.
397     if (MBB->pred_empty()) {
398       RemoveDeadBlock(MBB);
399       MadeChange = true;
400       ++NumDeadBlocks;
401     }
402   }
403   return MadeChange;
404 }
405
406
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
410 /// be null.
411 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB, 
412                                  MachineBasicBlock *DestA,
413                                  MachineBasicBlock *DestB,
414                                  bool isCond, 
415                                  MachineFunction::iterator FallThru) {
416   bool MadeChange = false;
417   bool AddedFallThrough = false;
418   
419   // If this block ends with a conditional branch that falls through to its
420   // successor, set DestB as the successor.
421   if (isCond) {
422     if (DestB == 0 && FallThru != MBB.getParent()->end()) {
423       DestB = FallThru;
424       AddedFallThrough = true;
425     }
426   } else {
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()) {
430       DestA = FallThru;
431       AddedFallThrough = true;
432     }
433   }
434   
435   MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
436   while (SI != MBB.succ_end()) {
437     if (*SI == DestA) {
438       DestA = 0;
439       ++SI;
440     } else if (*SI == DestB) {
441       DestB = 0;
442       ++SI;
443     } else {
444       // Otherwise, this is a superfluous edge, remove it.
445       MBB.removeSuccessor(SI);
446       MadeChange = true;
447     }
448   }
449   if (!AddedFallThrough) {
450     assert(DestA == 0 && DestB == 0 &&
451            "MachineCFG is missing edges!");
452   } else if (isCond) {
453     assert(DestA == 0 && "MachineCFG is missing edges!");
454   }
455   return MadeChange;
456 }
457
458
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!");
466
467   MachineBasicBlock::iterator I = BB->end();
468   while (I != BB->begin()) {
469     --I;
470     if (!TII->isTerminatorInstr(I->getOpcode())) break;
471
472     // Scan the operands of this machine instruction, replacing any uses of Old
473     // with New.
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);
478   }
479
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);
486     }
487 }
488
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).
493 ///
494 /// True is a conservative answer.
495 ///
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;
501   ++Fallthrough;
502   // If FallthroughBlock is off the end of the function, it can't fall through.
503   if (Fallthrough == CurBB->getParent()->end())
504     return false;
505   
506   // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
507   if (!CurBB->isSuccessor(Fallthrough))
508     return false;
509   
510   // If we couldn't analyze the branch, assume it could fall through.
511   if (BranchUnAnalyzable) return true;
512   
513   // If there is no branch, control always falls through.
514   if (TBB == 0) return true;
515
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)
520     return true;
521   
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;
525   
526   // Otherwise, if it is conditional and has no explicit false block, it falls
527   // through.
528   return FBB == 0;
529 }
530
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).
535 ///
536 /// True is a conservative answer.
537 ///
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);
543 }
544
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;
549   ++FallThrough;
550   
551   // If this block is empty, make everyone use its fall-through, not the block
552   // explicitly.
553   if (MBB->empty()) {
554     // Dead block?  Leave for cleanup later.
555     if (MBB->pred_empty()) return;
556     
557     if (FallThrough == MBB->getParent()->end()) {
558       // TODO: Simplify preds to not branch here if possible!
559     } else {
560       // Rewrite all predecessors of the old block to go to the fallthrough
561       // instead.
562       while (!MBB->pred_empty()) {
563         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
564         ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
565       }
566       
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);
571       MadeChange = true;
572     }
573     return;
574   }
575
576   // Check to see if we can simplify the terminator of the block before this
577   // one.
578   MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
579
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);
588     
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
591     // a fall-through.
592     if (PriorTBB && PriorTBB == PriorFBB) {
593       TII->RemoveBranch(PrevBB);
594       PriorCond.clear(); 
595       if (PriorTBB != MBB)
596         TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
597       MadeChange = true;
598       ++NumBranchOpts;
599       return OptimizeBlock(MBB);
600     }
601     
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);
606       MadeChange = true;
607       ++NumBranchOpts;
608       return OptimizeBlock(MBB);
609     }
610     
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);
616       MadeChange = true;
617       ++NumBranchOpts;
618       return OptimizeBlock(MBB);
619     }
620     
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
623     // fall-through.
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);
629         MadeChange = true;
630         ++NumBranchOpts;
631         return OptimizeBlock(MBB);
632       }
633     }
634   }
635   
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,
643                                        !CurCond.empty(),
644                                        ++MachineFunction::iterator(MBB));
645
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);
654
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
659       // condition.
660       if (MBB->empty()) {
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) {
668             if (PriorTBB == 0) {
669               assert(PriorCond.empty() && PriorFBB == 0 &&
670                      "Bad branch analysis");
671               PriorTBB = MBB;
672             } else {
673               assert(PriorFBB == 0 && "Machine CFG out of date!");
674               PriorFBB = MBB;
675             }
676             TII->RemoveBranch(PrevBB);
677             TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
678           }
679
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()) {
685             if (*PI == MBB) {
686               // If this block has an uncond branch to itself, leave it.
687               ++PI;
688               HasBranchToSelf = true;
689             } else {
690               DidChange = true;
691               ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
692             }
693           }
694
695           // Change any jumptables to go to the new MBB.
696           MBB->getParent()->getJumpTableInfo()->
697             ReplaceMBBInJumpTables(MBB, CurTBB);
698           if (DidChange) {
699             ++NumBranchOpts;
700             MadeChange = true;
701             if (!HasBranchToSelf) return;
702           }
703         }
704       }
705       
706       // Add the branch back if the block is more than just an uncond branch.
707       TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
708     }
709   }
710
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);
730           MadeChange = true;
731           return OptimizeBlock(MBB);
732         }
733       }
734         
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);
745           MadeChange = true;
746           return OptimizeBlock(MBB);
747         }
748       }
749       
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());
756         MadeChange = true;
757         return;
758       }
759     }
760   }
761 }