ddd3bca03b9799fe7658b8e23dcd71d3b20c066d
[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 #include <algorithm>
29 using namespace llvm;
30
31 static Statistic<> NumDeadBlocks("branchfold", "Number of dead blocks removed");
32 static Statistic<> NumBranchOpts("branchfold", "Number of branches optimized");
33 static Statistic<> NumTailMerge ("branchfold", "Number of block tails merged");
34 static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
35
36 namespace {
37   struct BranchFolder : public MachineFunctionPass {
38     virtual bool runOnMachineFunction(MachineFunction &MF);
39     virtual const char *getPassName() const { return "Control Flow Optimizer"; }
40     const TargetInstrInfo *TII;
41     MachineDebugInfo *MDI;
42     bool MadeChange;
43   private:
44     // Tail Merging.
45     bool TailMergeBlocks(MachineFunction &MF);
46     void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
47                                  MachineBasicBlock *NewDest);
48     MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
49                                   MachineBasicBlock::iterator BBI1);
50         
51     // Branch optzn.
52     bool OptimizeBranches(MachineFunction &MF);
53     void OptimizeBlock(MachineBasicBlock *MBB);
54     void RemoveDeadBlock(MachineBasicBlock *MBB);
55     
56     bool CanFallThrough(MachineBasicBlock *CurBB);
57     bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
58                         MachineBasicBlock *TBB, MachineBasicBlock *FBB,
59                         const std::vector<MachineOperand> &Cond);
60   };
61 }
62
63 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
64
65 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
66 /// function, updating the CFG.
67 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
68   assert(MBB->pred_empty() && "MBB must be dead!");
69   
70   MachineFunction *MF = MBB->getParent();
71   // drop all successors.
72   while (!MBB->succ_empty())
73     MBB->removeSuccessor(MBB->succ_end()-1);
74   
75   // If there is DWARF info to active, check to see if there are any DWARF_LABEL
76   // records in the basic block.  If so, unregister them from MachineDebugInfo.
77   if (MDI && !MBB->empty()) {
78     unsigned DWARF_LABELOpc = TII->getDWARF_LABELOpcode();
79     assert(DWARF_LABELOpc &&
80            "Target supports dwarf but didn't implement getDWARF_LABELOpcode!");
81     
82     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
83          I != E; ++I) {
84       if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
85         // The label ID # is always operand #0, an immediate.
86         MDI->InvalidateLabel(I->getOperand(0).getImm());
87       }
88     }
89   }
90   
91   // Remove the block.
92   MF->getBasicBlockList().erase(MBB);
93 }
94
95 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
96   TII = MF.getTarget().getInstrInfo();
97   if (!TII) return false;
98
99   MDI = getAnalysisToUpdate<MachineDebugInfo>();
100   
101   bool EverMadeChange = false;
102   bool MadeChangeThisIteration = true;
103   while (MadeChangeThisIteration) {
104     MadeChangeThisIteration = false;
105     MadeChangeThisIteration |= TailMergeBlocks(MF);
106     MadeChangeThisIteration |= OptimizeBranches(MF);
107     EverMadeChange |= MadeChangeThisIteration;
108   }
109
110   // See if any jump tables have become mergable or dead as the code generator
111   // did its thing.
112   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
113   const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
114   if (!JTs.empty()) {
115     // Figure out how these jump tables should be merged.
116     std::vector<unsigned> JTMapping;
117     JTMapping.reserve(JTs.size());
118     
119     // We always keep the 0th jump table.
120     JTMapping.push_back(0);
121
122     // Scan the jump tables, seeing if there are any duplicates.  Note that this
123     // is N^2, which should be fixed someday.
124     for (unsigned i = 1, e = JTs.size(); i != e; ++i)
125       JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
126     
127     // If a jump table was merge with another one, walk the function rewriting
128     // references to jump tables to reference the new JT ID's.  Keep track of
129     // whether we see a jump table idx, if not, we can delete the JT.
130     std::vector<bool> JTIsLive;
131     JTIsLive.resize(JTs.size());
132     for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
133          BB != E; ++BB) {
134       for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
135            I != E; ++I)
136         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
137           MachineOperand &Op = I->getOperand(op);
138           if (!Op.isJumpTableIndex()) continue;
139           unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
140           Op.setJumpTableIndex(NewIdx);
141
142           // Remember that this JT is live.
143           JTIsLive[NewIdx] = true;
144         }
145     }
146    
147     // Finally, remove dead jump tables.  This happens either because the
148     // indirect jump was unreachable (and thus deleted) or because the jump
149     // table was merged with some other one.
150     for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
151       if (!JTIsLive[i]) {
152         JTI->RemoveJumpTable(i);
153         EverMadeChange = true;
154       }
155   }
156   
157   return EverMadeChange;
158 }
159
160 //===----------------------------------------------------------------------===//
161 //  Tail Merging of Blocks
162 //===----------------------------------------------------------------------===//
163
164 /// HashMachineInstr - Compute a hash value for MI and its operands.
165 static unsigned HashMachineInstr(const MachineInstr *MI) {
166   unsigned Hash = MI->getOpcode();
167   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
168     const MachineOperand &Op = MI->getOperand(i);
169     
170     // Merge in bits from the operand if easy.
171     unsigned OperandHash = 0;
172     switch (Op.getType()) {
173     case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
174     case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
175     case MachineOperand::MO_MachineBasicBlock:
176       OperandHash = Op.getMachineBasicBlock()->getNumber();
177       break;
178     case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
179     case MachineOperand::MO_ConstantPoolIndex:
180       OperandHash = Op.getConstantPoolIndex();
181       break;
182     case MachineOperand::MO_JumpTableIndex:
183       OperandHash = Op.getJumpTableIndex();
184       break;
185     case MachineOperand::MO_GlobalAddress:
186     case MachineOperand::MO_ExternalSymbol:
187       // Global address / external symbol are too hard, don't bother, but do
188       // pull in the offset.
189       OperandHash = Op.getOffset();
190       break;
191     default: break;
192     }
193     
194     Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
195   }
196   return Hash;
197 }
198
199 /// HashEndOfMBB - Hash the last two instructions in the MBB.  We hash two
200 /// instructions, because cross-jumping only saves code when at least two
201 /// instructions are removed (since a branch must be inserted).
202 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
203   MachineBasicBlock::const_iterator I = MBB->end();
204   if (I == MBB->begin())
205     return 0;   // Empty MBB.
206   
207   --I;
208   unsigned Hash = HashMachineInstr(I);
209     
210   if (I == MBB->begin())
211     return Hash;   // Single instr MBB.
212   
213   --I;
214   // Hash in the second-to-last instruction.
215   Hash ^= HashMachineInstr(I) << 2;
216   return Hash;
217 }
218
219 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
220 /// of instructions they actually have in common together at their end.  Return
221 /// iterators for the first shared instruction in each block.
222 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
223                                         MachineBasicBlock *MBB2,
224                                         MachineBasicBlock::iterator &I1,
225                                         MachineBasicBlock::iterator &I2) {
226   I1 = MBB1->end();
227   I2 = MBB2->end();
228   
229   unsigned TailLen = 0;
230   while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
231     --I1; --I2;
232     if (!I1->isIdenticalTo(I2)) {
233       ++I1; ++I2;
234       break;
235     }
236     ++TailLen;
237   }
238   return TailLen;
239 }
240
241 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
242 /// after it, replacing it with an unconditional branch to NewDest.  This
243 /// returns true if OldInst's block is modified, false if NewDest is modified.
244 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
245                                            MachineBasicBlock *NewDest) {
246   MachineBasicBlock *OldBB = OldInst->getParent();
247   
248   // Remove all the old successors of OldBB from the CFG.
249   while (!OldBB->succ_empty())
250     OldBB->removeSuccessor(OldBB->succ_begin());
251   
252   // Remove all the dead instructions from the end of OldBB.
253   OldBB->erase(OldInst, OldBB->end());
254
255   // If OldBB isn't immediately before OldBB, insert a branch to it.
256   if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
257     TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
258   OldBB->addSuccessor(NewDest);
259   ++NumTailMerge;
260 }
261
262 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
263 /// MBB so that the part before the iterator falls into the part starting at the
264 /// iterator.  This returns the new MBB.
265 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
266                                             MachineBasicBlock::iterator BBI1) {
267   // Create the fall-through block.
268   MachineFunction::iterator MBBI = &CurMBB;
269   MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
270   CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
271
272   // Move all the successors of this block to the specified block.
273   while (!CurMBB.succ_empty()) {
274     MachineBasicBlock *S = *(CurMBB.succ_end()-1);
275     NewMBB->addSuccessor(S);
276     CurMBB.removeSuccessor(S);
277   }
278  
279   // Add an edge from CurMBB to NewMBB for the fall-through.
280   CurMBB.addSuccessor(NewMBB);
281   
282   // Splice the code over.
283   NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
284   return NewMBB;
285 }
286
287 /// EstimateRuntime - Make a rough estimate for how long it will take to run
288 /// the specified code.
289 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
290                                 MachineBasicBlock::iterator E,
291                                 const TargetInstrInfo *TII) {
292   unsigned Time = 0;
293   for (; I != E; ++I) {
294     const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
295     if (TID.Flags & M_CALL_FLAG)
296       Time += 10;
297     else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
298       Time += 2;
299     else
300       ++Time;
301   }
302   return Time;
303 }
304
305 /// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
306 /// MBB2I and then insert an unconditional branch in the other block.  Determine
307 /// which is the best to split
308 static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
309                                   MachineBasicBlock::iterator MBB1I,
310                                   MachineBasicBlock *MBB2,
311                                   MachineBasicBlock::iterator MBB2I,
312                                   const TargetInstrInfo *TII) {
313   // TODO: if we had some notion of which block was hotter, we could split
314   // the hot block, so it is the fall-through.  Since we don't have profile info
315   // make a decision based on which will hurt most to split.
316   unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
317   unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
318   
319   // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
320   // MBB1 block so it falls through.  This will penalize the MBB2 path, but will
321   // have a lower overall impact on the program execution.
322   return MBB1Time < MBB2Time;
323 }
324
325 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
326   MadeChange = false;
327   
328   if (!EnableTailMerge) return false;
329   
330   // Find blocks with no successors.
331   std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
332   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
333     if (I->succ_empty())
334       MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
335   }
336   
337   // Sort by hash value so that blocks with identical end sequences sort
338   // together.
339   std::stable_sort(MergePotentials.begin(), MergePotentials.end());
340
341   // Walk through equivalence sets looking for actual exact matches.
342   while (MergePotentials.size() > 1) {
343     unsigned CurHash  = (MergePotentials.end()-1)->first;
344     unsigned PrevHash = (MergePotentials.end()-2)->first;
345     MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
346     
347     // If there is nothing that matches the hash of the current basic block,
348     // give up.
349     if (CurHash != PrevHash) {
350       MergePotentials.pop_back();
351       continue;
352     }
353     
354     // Determine the actual length of the shared tail between these two basic
355     // blocks.  Because the hash can have collisions, it's possible that this is
356     // less than 2.
357     MachineBasicBlock::iterator BBI1, BBI2;
358     unsigned CommonTailLen = 
359       ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second, 
360                               BBI1, BBI2);
361     
362     // If the tails don't have at least two instructions in common, see if there
363     // is anything else in the equivalence class that does match.
364     if (CommonTailLen < 2) {
365       unsigned FoundMatch = ~0U;
366       for (int i = MergePotentials.size()-2;
367            i != -1 && MergePotentials[i].first == CurHash; --i) {
368         CommonTailLen = ComputeCommonTailLength(CurMBB, 
369                                                 MergePotentials[i].second,
370                                                 BBI1, BBI2);
371         if (CommonTailLen >= 2) {
372           FoundMatch = i;
373           break;
374         }
375       }
376       
377       // If we didn't find anything that has at least two instructions matching
378       // this one, bail out.
379       if (FoundMatch == ~0U) {
380         MergePotentials.pop_back();
381         continue;
382       }
383       
384       // Otherwise, move the matching block to the right position.
385       std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
386     }
387
388     MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
389
390     // If neither block is the entire common tail, split the tail of one block
391     // to make it redundant with the other tail.
392     if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
393       if (0) { // Enable this to disable partial tail merges.
394         MergePotentials.pop_back();
395         continue;
396       }
397       
398       // Decide whether we want to split CurMBB or MBB2.
399       if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
400         CurMBB = SplitMBBAt(*CurMBB, BBI1);
401         BBI1 = CurMBB->begin();
402         MergePotentials.back().second = CurMBB;
403       } else {
404         MBB2 = SplitMBBAt(*MBB2, BBI2);
405         BBI2 = MBB2->begin();
406         (MergePotentials.end()-2)->second = MBB2;
407       }
408     }
409     
410     if (MBB2->begin() == BBI2) {
411       // Hack the end off CurMBB, making it jump to MBBI@ instead.
412       ReplaceTailWithBranchTo(BBI1, MBB2);
413       // This modifies CurMBB, so remove it from the worklist.
414       MergePotentials.pop_back();
415     } else {
416       assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
417       // Hack the end off MBB2, making it jump to CurMBB instead.
418       ReplaceTailWithBranchTo(BBI2, CurMBB);
419       // This modifies MBB2, so remove it from the worklist.
420       MergePotentials.erase(MergePotentials.end()-2);
421     }
422     MadeChange = true;
423   }
424   
425   return MadeChange;
426 }
427
428
429 //===----------------------------------------------------------------------===//
430 //  Branch Optimization
431 //===----------------------------------------------------------------------===//
432
433 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
434   MadeChange = false;
435   
436   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
437     MachineBasicBlock *MBB = I++;
438     OptimizeBlock(MBB);
439     
440     // If it is dead, remove it.
441     if (MBB->pred_empty()) {
442       RemoveDeadBlock(MBB);
443       MadeChange = true;
444       ++NumDeadBlocks;
445     }
446   }
447   return MadeChange;
448 }
449
450
451 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
452 /// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
453 /// DestB, remove any other MBB successors from the CFG.  DestA and DestB can
454 /// be null.
455 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB, 
456                                  MachineBasicBlock *DestA,
457                                  MachineBasicBlock *DestB,
458                                  bool isCond, 
459                                  MachineFunction::iterator FallThru) {
460   bool MadeChange = false;
461   bool AddedFallThrough = false;
462   
463   // If this block ends with a conditional branch that falls through to its
464   // successor, set DestB as the successor.
465   if (isCond) {
466     if (DestB == 0 && FallThru != MBB.getParent()->end()) {
467       DestB = FallThru;
468       AddedFallThrough = true;
469     }
470   } else {
471     // If this is an unconditional branch with no explicit dest, it must just be
472     // a fallthrough into DestB.
473     if (DestA == 0 && FallThru != MBB.getParent()->end()) {
474       DestA = FallThru;
475       AddedFallThrough = true;
476     }
477   }
478   
479   MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
480   while (SI != MBB.succ_end()) {
481     if (*SI == DestA) {
482       DestA = 0;
483       ++SI;
484     } else if (*SI == DestB) {
485       DestB = 0;
486       ++SI;
487     } else {
488       // Otherwise, this is a superfluous edge, remove it.
489       MBB.removeSuccessor(SI);
490       MadeChange = true;
491     }
492   }
493   if (!AddedFallThrough) {
494     assert(DestA == 0 && DestB == 0 &&
495            "MachineCFG is missing edges!");
496   } else if (isCond) {
497     assert(DestA == 0 && "MachineCFG is missing edges!");
498   }
499   return MadeChange;
500 }
501
502
503 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
504 /// 'Old', change the code and CFG so that it branches to 'New' instead.
505 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
506                                    MachineBasicBlock *Old,
507                                    MachineBasicBlock *New,
508                                    const TargetInstrInfo *TII) {
509   assert(Old != New && "Cannot replace self with self!");
510
511   MachineBasicBlock::iterator I = BB->end();
512   while (I != BB->begin()) {
513     --I;
514     if (!TII->isTerminatorInstr(I->getOpcode())) break;
515
516     // Scan the operands of this machine instruction, replacing any uses of Old
517     // with New.
518     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
519       if (I->getOperand(i).isMachineBasicBlock() &&
520           I->getOperand(i).getMachineBasicBlock() == Old)
521         I->getOperand(i).setMachineBasicBlock(New);
522   }
523
524   // Update the successor information.
525   std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
526   for (int i = Succs.size()-1; i >= 0; --i)
527     if (Succs[i] == Old) {
528       BB->removeSuccessor(Old);
529       BB->addSuccessor(New);
530     }
531 }
532
533 /// CanFallThrough - Return true if the specified block (with the specified
534 /// branch condition) can implicitly transfer control to the block after it by
535 /// falling off the end of it.  This should return false if it can reach the
536 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
537 ///
538 /// True is a conservative answer.
539 ///
540 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
541                                   bool BranchUnAnalyzable,
542                                   MachineBasicBlock *TBB, MachineBasicBlock *FBB,
543                                   const std::vector<MachineOperand> &Cond) {
544   MachineFunction::iterator Fallthrough = CurBB;
545   ++Fallthrough;
546   // If FallthroughBlock is off the end of the function, it can't fall through.
547   if (Fallthrough == CurBB->getParent()->end())
548     return false;
549   
550   // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
551   if (!CurBB->isSuccessor(Fallthrough))
552     return false;
553   
554   // If we couldn't analyze the branch, assume it could fall through.
555   if (BranchUnAnalyzable) return true;
556   
557   // If there is no branch, control always falls through.
558   if (TBB == 0) return true;
559
560   // If there is some explicit branch to the fallthrough block, it can obviously
561   // reach, even though the branch should get folded to fall through implicitly.
562   if (MachineFunction::iterator(TBB) == Fallthrough ||
563       MachineFunction::iterator(FBB) == Fallthrough)
564     return true;
565   
566   // If it's an unconditional branch to some block not the fall through, it 
567   // doesn't fall through.
568   if (Cond.empty()) return false;
569   
570   // Otherwise, if it is conditional and has no explicit false block, it falls
571   // through.
572   return FBB == 0;
573 }
574
575 /// CanFallThrough - Return true if the specified can implicitly transfer
576 /// control to the block after it by falling off the end of it.  This should
577 /// return false if it can reach the block after it, but it uses an explicit
578 /// branch to do so (e.g. a table jump).
579 ///
580 /// True is a conservative answer.
581 ///
582 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
583   MachineBasicBlock *TBB = 0, *FBB = 0;
584   std::vector<MachineOperand> Cond;
585   bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
586   return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
587 }
588
589 /// OptimizeBlock - Analyze and optimize control flow related to the specified
590 /// block.  This is never called on the entry block.
591 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
592   MachineFunction::iterator FallThrough = MBB;
593   ++FallThrough;
594   
595   // If this block is empty, make everyone use its fall-through, not the block
596   // explicitly.
597   if (MBB->empty()) {
598     // Dead block?  Leave for cleanup later.
599     if (MBB->pred_empty()) return;
600     
601     if (FallThrough == MBB->getParent()->end()) {
602       // TODO: Simplify preds to not branch here if possible!
603     } else {
604       // Rewrite all predecessors of the old block to go to the fallthrough
605       // instead.
606       while (!MBB->pred_empty()) {
607         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
608         ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
609       }
610       
611       // If MBB was the target of a jump table, update jump tables to go to the
612       // fallthrough instead.
613       MBB->getParent()->getJumpTableInfo()->
614         ReplaceMBBInJumpTables(MBB, FallThrough);
615       MadeChange = true;
616     }
617     return;
618   }
619
620   // Check to see if we can simplify the terminator of the block before this
621   // one.
622   MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
623
624   MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
625   std::vector<MachineOperand> PriorCond;
626   bool PriorUnAnalyzable =
627     TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
628   if (!PriorUnAnalyzable) {
629     // If the CFG for the prior block has extra edges, remove them.
630     MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
631                                        !PriorCond.empty(), MBB);
632     
633     // If the previous branch is conditional and both conditions go to the same
634     // destination, remove the branch, replacing it with an unconditional one or
635     // a fall-through.
636     if (PriorTBB && PriorTBB == PriorFBB) {
637       TII->RemoveBranch(PrevBB);
638       PriorCond.clear(); 
639       if (PriorTBB != MBB)
640         TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
641       MadeChange = true;
642       ++NumBranchOpts;
643       return OptimizeBlock(MBB);
644     }
645     
646     // If the previous branch *only* branches to *this* block (conditional or
647     // not) remove the branch.
648     if (PriorTBB == MBB && PriorFBB == 0) {
649       TII->RemoveBranch(PrevBB);
650       MadeChange = true;
651       ++NumBranchOpts;
652       return OptimizeBlock(MBB);
653     }
654     
655     // If the prior block branches somewhere else on the condition and here if
656     // the condition is false, remove the uncond second branch.
657     if (PriorFBB == MBB) {
658       TII->RemoveBranch(PrevBB);
659       TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
660       MadeChange = true;
661       ++NumBranchOpts;
662       return OptimizeBlock(MBB);
663     }
664     
665     // If the prior block branches here on true and somewhere else on false, and
666     // if the branch condition is reversible, reverse the branch to create a
667     // fall-through.
668     if (PriorTBB == MBB) {
669       std::vector<MachineOperand> NewPriorCond(PriorCond);
670       if (!TII->ReverseBranchCondition(NewPriorCond)) {
671         TII->RemoveBranch(PrevBB);
672         TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
673         MadeChange = true;
674         ++NumBranchOpts;
675         return OptimizeBlock(MBB);
676       }
677     }
678   }
679   
680   // Analyze the branch in the current block.
681   MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
682   std::vector<MachineOperand> CurCond;
683   bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
684   if (!CurUnAnalyzable) {
685     // If the CFG for the prior block has extra edges, remove them.
686     MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
687                                        !CurCond.empty(),
688                                        ++MachineFunction::iterator(MBB));
689
690     // If this is a two-way branch, and the FBB branches to this block, reverse 
691     // the condition so the single-basic-block loop is faster.  Instead of:
692     //    Loop: xxx; jcc Out; jmp Loop
693     // we want:
694     //    Loop: xxx; jncc Loop; jmp Out
695     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
696       std::vector<MachineOperand> NewCond(CurCond);
697       if (!TII->ReverseBranchCondition(NewCond)) {
698         TII->RemoveBranch(*MBB);
699         TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
700         MadeChange = true;
701         ++NumBranchOpts;
702         return OptimizeBlock(MBB);
703       }
704     }
705     
706     
707     // If this branch is the only thing in its block, see if we can forward
708     // other blocks across it.
709     if (CurTBB && CurCond.empty() && CurFBB == 0 && 
710         TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
711       // This block may contain just an unconditional branch.  Because there can
712       // be 'non-branch terminators' in the block, try removing the branch and
713       // then seeing if the block is empty.
714       TII->RemoveBranch(*MBB);
715
716       // If this block is just an unconditional branch to CurTBB, we can
717       // usually completely eliminate the block.  The only case we cannot
718       // completely eliminate the block is when the block before this one
719       // falls through into MBB and we can't understand the prior block's branch
720       // condition.
721       if (MBB->empty()) {
722         bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
723         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
724             !PrevBB.isSuccessor(MBB)) {
725           // If the prior block falls through into us, turn it into an
726           // explicit branch to us to make updates simpler.
727           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) && 
728               PriorTBB != MBB && PriorFBB != MBB) {
729             if (PriorTBB == 0) {
730               assert(PriorCond.empty() && PriorFBB == 0 &&
731                      "Bad branch analysis");
732               PriorTBB = MBB;
733             } else {
734               assert(PriorFBB == 0 && "Machine CFG out of date!");
735               PriorFBB = MBB;
736             }
737             TII->RemoveBranch(PrevBB);
738             TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
739           }
740
741           // Iterate through all the predecessors, revectoring each in-turn.
742           MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
743           bool DidChange = false;
744           bool HasBranchToSelf = false;
745           while (PI != MBB->pred_end()) {
746             if (*PI == MBB) {
747               // If this block has an uncond branch to itself, leave it.
748               ++PI;
749               HasBranchToSelf = true;
750             } else {
751               DidChange = true;
752               ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
753             }
754           }
755
756           // Change any jumptables to go to the new MBB.
757           MBB->getParent()->getJumpTableInfo()->
758             ReplaceMBBInJumpTables(MBB, CurTBB);
759           if (DidChange) {
760             ++NumBranchOpts;
761             MadeChange = true;
762             if (!HasBranchToSelf) return;
763           }
764         }
765       }
766       
767       // Add the branch back if the block is more than just an uncond branch.
768       TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
769     }
770   }
771
772   // If the prior block doesn't fall through into this block, and if this
773   // block doesn't fall through into some other block, see if we can find a
774   // place to move this block where a fall-through will happen.
775   if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
776                       PriorTBB, PriorFBB, PriorCond)) {
777     // Now we know that there was no fall-through into this block, check to
778     // see if it has a fall-through into its successor.
779     if (!CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, CurCond)) {
780       // Check all the predecessors of this block.  If one of them has no fall
781       // throughs, move this block right after it.
782       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
783            E = MBB->pred_end(); PI != E; ++PI) {
784         // Analyze the branch at the end of the pred.
785         MachineBasicBlock *PredBB = *PI;
786         MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
787         std::vector<MachineOperand> PredCond;
788         if (PredBB != MBB && !CanFallThrough(PredBB)) {
789           MBB->moveAfter(PredBB);
790           MadeChange = true;
791           return OptimizeBlock(MBB);
792         }
793       }
794         
795       // Check all successors to see if we can move this block before it.
796       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
797            E = MBB->succ_end(); SI != E; ++SI) {
798         // Analyze the branch at the end of the block before the succ.
799         MachineBasicBlock *SuccBB = *SI;
800         MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
801         std::vector<MachineOperand> SuccPrevCond;
802         if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
803           MBB->moveBefore(SuccBB);
804           MadeChange = true;
805           return OptimizeBlock(MBB);
806         }
807       }
808       
809       // Okay, there is no really great place to put this block.  If, however,
810       // the block before this one would be a fall-through if this block were
811       // removed, move this block to the end of the function.
812       if (FallThrough != MBB->getParent()->end() &&
813           PrevBB.isSuccessor(FallThrough)) {
814         MBB->moveAfter(--MBB->getParent()->end());
815         MadeChange = true;
816         return;
817       }
818     }
819   }
820 }