Remove some unneeded branches. (spotted by Evan, thanks)
[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 #define DEBUG_TYPE "branchfolding"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include <algorithm>
33 using namespace llvm;
34
35 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
36 STATISTIC(NumBranchOpts, "Number of branches optimized");
37 STATISTIC(NumTailMerge , "Number of block tails merged");
38 static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
39
40 namespace {
41   struct BranchFolder : public MachineFunctionPass {
42     static char ID;
43     BranchFolder() : MachineFunctionPass((intptr_t)&ID) {}
44
45     virtual bool runOnMachineFunction(MachineFunction &MF);
46     virtual const char *getPassName() const { return "Control Flow Optimizer"; }
47     const TargetInstrInfo *TII;
48     MachineModuleInfo *MMI;
49     bool MadeChange;
50   private:
51     // Tail Merging.
52     bool TailMergeBlocks(MachineFunction &MF);
53     bool TryMergeBlocks(MachineBasicBlock* SuccBB,
54                         MachineBasicBlock* PredBB);
55     void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
56                                  MachineBasicBlock *NewDest);
57     MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
58                                   MachineBasicBlock::iterator BBI1);
59
60     std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
61     const MRegisterInfo *RegInfo;
62     RegScavenger *RS;
63     // Branch optzn.
64     bool OptimizeBranches(MachineFunction &MF);
65     void OptimizeBlock(MachineBasicBlock *MBB);
66     void RemoveDeadBlock(MachineBasicBlock *MBB);
67     
68     bool CanFallThrough(MachineBasicBlock *CurBB);
69     bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
70                         MachineBasicBlock *TBB, MachineBasicBlock *FBB,
71                         const std::vector<MachineOperand> &Cond);
72   };
73   char BranchFolder::ID = 0;
74 }
75
76 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB, 
77                                  MachineBasicBlock *DestA,
78                                  MachineBasicBlock *DestB,
79                                  bool isCond, 
80                                  MachineFunction::iterator FallThru);
81
82 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
83
84 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
85 /// function, updating the CFG.
86 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
87   assert(MBB->pred_empty() && "MBB must be dead!");
88   DOUT << "\nRemoving MBB: " << *MBB;
89   
90   MachineFunction *MF = MBB->getParent();
91   // drop all successors.
92   while (!MBB->succ_empty())
93     MBB->removeSuccessor(MBB->succ_end()-1);
94   
95   // If there is DWARF info to active, check to see if there are any LABEL
96   // records in the basic block.  If so, unregister them from MachineModuleInfo.
97   if (MMI && !MBB->empty()) {
98     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
99          I != E; ++I) {
100       if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
101         // The label ID # is always operand #0, an immediate.
102         MMI->InvalidateLabel(I->getOperand(0).getImm());
103       }
104     }
105   }
106   
107   // Remove the block.
108   MF->getBasicBlockList().erase(MBB);
109 }
110
111 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
112   TII = MF.getTarget().getInstrInfo();
113   if (!TII) return false;
114
115   // Fix CFG.  The later algorithms expect it to be right.
116   bool EverMadeChange = false;
117   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
118     MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
119     std::vector<MachineOperand> Cond;
120     if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
121       EverMadeChange |= CorrectExtraCFGEdges(*MBB, TBB, FBB, 
122                         !Cond.empty(), next(I));
123   }
124
125   RegInfo = MF.getTarget().getRegisterInfo();
126   RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
127
128   MMI = getAnalysisToUpdate<MachineModuleInfo>();
129
130   bool MadeChangeThisIteration = true;
131   while (MadeChangeThisIteration) {
132     MadeChangeThisIteration = false;
133     MadeChangeThisIteration |= TailMergeBlocks(MF);
134     MadeChangeThisIteration |= OptimizeBranches(MF);
135     EverMadeChange |= MadeChangeThisIteration;
136   }
137
138   // See if any jump tables have become mergable or dead as the code generator
139   // did its thing.
140   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
141   const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
142   if (!JTs.empty()) {
143     // Figure out how these jump tables should be merged.
144     std::vector<unsigned> JTMapping;
145     JTMapping.reserve(JTs.size());
146     
147     // We always keep the 0th jump table.
148     JTMapping.push_back(0);
149
150     // Scan the jump tables, seeing if there are any duplicates.  Note that this
151     // is N^2, which should be fixed someday.
152     for (unsigned i = 1, e = JTs.size(); i != e; ++i)
153       JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
154     
155     // If a jump table was merge with another one, walk the function rewriting
156     // references to jump tables to reference the new JT ID's.  Keep track of
157     // whether we see a jump table idx, if not, we can delete the JT.
158     std::vector<bool> JTIsLive;
159     JTIsLive.resize(JTs.size());
160     for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
161          BB != E; ++BB) {
162       for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
163            I != E; ++I)
164         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
165           MachineOperand &Op = I->getOperand(op);
166           if (!Op.isJumpTableIndex()) continue;
167           unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
168           Op.setJumpTableIndex(NewIdx);
169
170           // Remember that this JT is live.
171           JTIsLive[NewIdx] = true;
172         }
173     }
174    
175     // Finally, remove dead jump tables.  This happens either because the
176     // indirect jump was unreachable (and thus deleted) or because the jump
177     // table was merged with some other one.
178     for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
179       if (!JTIsLive[i]) {
180         JTI->RemoveJumpTable(i);
181         EverMadeChange = true;
182       }
183   }
184   
185   delete RS;
186   return EverMadeChange;
187 }
188
189 //===----------------------------------------------------------------------===//
190 //  Tail Merging of Blocks
191 //===----------------------------------------------------------------------===//
192
193 /// HashMachineInstr - Compute a hash value for MI and its operands.
194 static unsigned HashMachineInstr(const MachineInstr *MI) {
195   unsigned Hash = MI->getOpcode();
196   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
197     const MachineOperand &Op = MI->getOperand(i);
198     
199     // Merge in bits from the operand if easy.
200     unsigned OperandHash = 0;
201     switch (Op.getType()) {
202     case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
203     case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
204     case MachineOperand::MO_MachineBasicBlock:
205       OperandHash = Op.getMachineBasicBlock()->getNumber();
206       break;
207     case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
208     case MachineOperand::MO_ConstantPoolIndex:
209       OperandHash = Op.getConstantPoolIndex();
210       break;
211     case MachineOperand::MO_JumpTableIndex:
212       OperandHash = Op.getJumpTableIndex();
213       break;
214     case MachineOperand::MO_GlobalAddress:
215     case MachineOperand::MO_ExternalSymbol:
216       // Global address / external symbol are too hard, don't bother, but do
217       // pull in the offset.
218       OperandHash = Op.getOffset();
219       break;
220     default: break;
221     }
222     
223     Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
224   }
225   return Hash;
226 }
227
228 /// HashEndOfMBB - Hash the last two instructions in the MBB.  We hash two
229 /// instructions, because cross-jumping only saves code when at least two
230 /// instructions are removed (since a branch must be inserted).
231 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
232   MachineBasicBlock::const_iterator I = MBB->end();
233   if (I == MBB->begin())
234     return 0;   // Empty MBB.
235   
236   --I;
237   unsigned Hash = HashMachineInstr(I);
238     
239   if (I == MBB->begin())
240     return Hash;   // Single instr MBB.
241   
242   --I;
243   // Hash in the second-to-last instruction.
244   Hash ^= HashMachineInstr(I) << 2;
245   return Hash;
246 }
247
248 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
249 /// of instructions they actually have in common together at their end.  Return
250 /// iterators for the first shared instruction in each block.
251 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
252                                         MachineBasicBlock *MBB2,
253                                         MachineBasicBlock::iterator &I1,
254                                         MachineBasicBlock::iterator &I2) {
255   I1 = MBB1->end();
256   I2 = MBB2->end();
257   
258   unsigned TailLen = 0;
259   while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
260     --I1; --I2;
261     if (!I1->isIdenticalTo(I2)) {
262       ++I1; ++I2;
263       break;
264     }
265     ++TailLen;
266   }
267   return TailLen;
268 }
269
270 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
271 /// after it, replacing it with an unconditional branch to NewDest.  This
272 /// returns true if OldInst's block is modified, false if NewDest is modified.
273 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
274                                            MachineBasicBlock *NewDest) {
275   MachineBasicBlock *OldBB = OldInst->getParent();
276   
277   // Remove all the old successors of OldBB from the CFG.
278   while (!OldBB->succ_empty())
279     OldBB->removeSuccessor(OldBB->succ_begin());
280   
281   // Remove all the dead instructions from the end of OldBB.
282   OldBB->erase(OldInst, OldBB->end());
283
284   // If OldBB isn't immediately before OldBB, insert a branch to it.
285   if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
286     TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
287   OldBB->addSuccessor(NewDest);
288   ++NumTailMerge;
289 }
290
291 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
292 /// MBB so that the part before the iterator falls into the part starting at the
293 /// iterator.  This returns the new MBB.
294 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
295                                             MachineBasicBlock::iterator BBI1) {
296   // Create the fall-through block.
297   MachineFunction::iterator MBBI = &CurMBB;
298   MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
299   CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
300
301   // Move all the successors of this block to the specified block.
302   while (!CurMBB.succ_empty()) {
303     MachineBasicBlock *S = *(CurMBB.succ_end()-1);
304     NewMBB->addSuccessor(S);
305     CurMBB.removeSuccessor(S);
306   }
307  
308   // Add an edge from CurMBB to NewMBB for the fall-through.
309   CurMBB.addSuccessor(NewMBB);
310   
311   // Splice the code over.
312   NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
313
314   // For targets that use the register scavenger, we must maintain LiveIns.
315   if (RS) {
316     RS->enterBasicBlock(&CurMBB);
317     if (!CurMBB.empty())
318       RS->forward(prior(CurMBB.end()));
319     BitVector RegsLiveAtExit(RegInfo->getNumRegs());
320     RS->getRegsUsed(RegsLiveAtExit, false);
321     for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
322       if (RegsLiveAtExit[i])
323         NewMBB->addLiveIn(i);
324   }
325
326   return NewMBB;
327 }
328
329 /// EstimateRuntime - Make a rough estimate for how long it will take to run
330 /// the specified code.
331 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
332                                 MachineBasicBlock::iterator E,
333                                 const TargetInstrInfo *TII) {
334   unsigned Time = 0;
335   for (; I != E; ++I) {
336     const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
337     if (TID.Flags & M_CALL_FLAG)
338       Time += 10;
339     else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
340       Time += 2;
341     else
342       ++Time;
343   }
344   return Time;
345 }
346
347 /// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
348 /// MBB2I and then insert an unconditional branch in the other block.  Determine
349 /// which is the best to split
350 static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
351                                   MachineBasicBlock::iterator MBB1I,
352                                   MachineBasicBlock *MBB2,
353                                   MachineBasicBlock::iterator MBB2I,
354                                   const TargetInstrInfo *TII,
355                                   MachineBasicBlock *PredBB) {
356   // If one block is the entry block, split the other one; we can't generate
357   // a branch to the entry block, as its label is not emitted.
358   MachineBasicBlock *Entry = MBB1->getParent()->begin();
359   if (MBB1 == Entry)
360     return false;
361   if (MBB2 == Entry)
362     return true;
363
364   // If one block falls through into the common successor, choose that
365   // one to split; it is one instruction less to do that.
366   if (PredBB) {
367     if (MBB1 == PredBB)
368       return true;
369     else if (MBB2 == PredBB)
370       return false;
371   }
372   // TODO: if we had some notion of which block was hotter, we could split
373   // the hot block, so it is the fall-through.  Since we don't have profile info
374   // make a decision based on which will hurt most to split.
375   unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
376   unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
377   
378   // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
379   // MBB1 block so it falls through.  This will penalize the MBB2 path, but will
380   // have a lower overall impact on the program execution.
381   return MBB1Time < MBB2Time;
382 }
383
384 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
385 // branches temporarily for tail merging).  In the case where CurMBB ends
386 // with a conditional branch to the next block, optimize by reversing the
387 // test and conditionally branching to SuccMBB instead.
388
389 static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
390                     const TargetInstrInfo *TII) {
391   MachineFunction *MF = CurMBB->getParent();
392   MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
393   MachineBasicBlock *TBB = 0, *FBB = 0;
394   std::vector<MachineOperand> Cond;
395   if (I != MF->end() &&
396       !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
397     MachineBasicBlock *NextBB = I;
398     if (TBB == NextBB && Cond.size() && !FBB) {
399       if (!TII->ReverseBranchCondition(Cond)) {
400         TII->RemoveBranch(*CurMBB);
401         TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
402         return;
403       }
404     }
405   }
406   TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
407 }
408
409 // See if any of the blocks in MergePotentials (which all have a common single
410 // successor, or all have no successor) can be tail-merged.  If there is a
411 // successor, any blocks in MergePotentials that are not tail-merged and
412 // are not immediately before Succ must have an unconditional branch to
413 // Succ added (but the predecessor/successor lists need no adjustment).  
414 // The lone predecessor of Succ that falls through into Succ,
415 // if any, is given in PredBB.
416
417 bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
418                                   MachineBasicBlock* PredBB) {
419   MadeChange = false;
420   
421   // Sort by hash value so that blocks with identical end sequences sort
422   // together.
423   std::stable_sort(MergePotentials.begin(), MergePotentials.end());
424
425   // Walk through equivalence sets looking for actual exact matches.
426   while (MergePotentials.size() > 1) {
427     unsigned CurHash  = (MergePotentials.end()-1)->first;
428     unsigned PrevHash = (MergePotentials.end()-2)->first;
429     MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
430     
431     // If there is nothing that matches the hash of the current basic block,
432     // give up.
433     if (CurHash != PrevHash) {
434       if (SuccBB && CurMBB != PredBB)
435         FixTail(CurMBB, SuccBB, TII);
436       MergePotentials.pop_back();
437       continue;
438     }
439     
440     // Determine the actual length of the shared tail between these two basic
441     // blocks.  Because the hash can have collisions, it's possible that this is
442     // less than 2.
443     MachineBasicBlock::iterator BBI1, BBI2;
444     unsigned CommonTailLen = 
445       ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second, 
446                               BBI1, BBI2);
447     
448     // If the tails don't have at least two instructions in common, see if there
449     // is anything else in the equivalence class that does match.
450     // Since instructions may get combined later (e.g. single stores into
451     // store multiple) this measure is not particularly accurate.
452     if (CommonTailLen < 2) {
453       unsigned FoundMatch = ~0U;
454       for (int i = MergePotentials.size()-2;
455            i != -1 && MergePotentials[i].first == CurHash; --i) {
456         CommonTailLen = ComputeCommonTailLength(CurMBB, 
457                                                 MergePotentials[i].second,
458                                                 BBI1, BBI2);
459         if (CommonTailLen >= 2) {
460           FoundMatch = i;
461           break;
462         }
463       }
464       
465       // If we didn't find anything that has at least two instructions matching
466       // this one, bail out.
467       if (FoundMatch == ~0U) {
468         // Put the unconditional branch back, if we need one.
469         if (SuccBB && CurMBB != PredBB)
470           FixTail(CurMBB, SuccBB, TII);
471         MergePotentials.pop_back();
472         continue;
473       }
474       
475       // Otherwise, move the matching block to the right position.
476       std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
477     }
478
479     MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
480
481     // If neither block is the entire common tail, split the tail of one block
482     // to make it redundant with the other tail.  Also, we cannot jump to the
483     // entry block, so if one block is the entry block, split the other one.
484     MachineBasicBlock *Entry = CurMBB->getParent()->begin();
485     if (CurMBB->begin() == BBI1 && CurMBB != Entry)
486       ;   // CurMBB is common tail
487     else if (MBB2->begin() == BBI2 && MBB2 != Entry)
488       ;   // MBB2 is common tail
489     else {
490       if (0) { // Enable this to disable partial tail merges.
491         MergePotentials.pop_back();
492         continue;
493       }
494       
495       // Decide whether we want to split CurMBB or MBB2.
496       if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII, PredBB)) {
497         CurMBB = SplitMBBAt(*CurMBB, BBI1);
498         BBI1 = CurMBB->begin();
499         MergePotentials.back().second = CurMBB;
500       } else {
501         MBB2 = SplitMBBAt(*MBB2, BBI2);
502         BBI2 = MBB2->begin();
503         (MergePotentials.end()-2)->second = MBB2;
504       }
505     }
506     
507     if (MBB2->begin() == BBI2 && MBB2 != Entry) {
508       // Hack the end off CurMBB, making it jump to MBBI@ instead.
509       ReplaceTailWithBranchTo(BBI1, MBB2);
510       // This modifies CurMBB, so remove it from the worklist.
511       MergePotentials.pop_back();
512     } else {
513       assert(CurMBB->begin() == BBI1 && CurMBB != Entry && 
514              "Didn't split block correctly?");
515       // Hack the end off MBB2, making it jump to CurMBB instead.
516       ReplaceTailWithBranchTo(BBI2, CurMBB);
517       // This modifies MBB2, so remove it from the worklist.
518       MergePotentials.erase(MergePotentials.end()-2);
519     }
520     MadeChange = true;
521   }
522   return MadeChange;
523 }
524
525 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
526
527   if (!EnableTailMerge) return false;
528  
529   MadeChange = false;
530
531   // First find blocks with no successors.
532   MergePotentials.clear();
533   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
534     if (I->succ_empty())
535       MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
536   }
537   // See if we can do any tail merging on those.
538   MadeChange |= TryMergeBlocks(NULL, NULL);
539
540   // Look at blocks (IBB) with multiple predecessors (PBB).
541   // We change each predecessor to a canonical form, by
542   // (1) temporarily removing any unconditional branch from the predecessor
543   // to IBB, and
544   // (2) alter conditional branches so they branch to the other block
545   // not IBB; this may require adding back an unconditional branch to IBB 
546   // later, where there wasn't one coming in.  E.g.
547   //   Bcc IBB
548   //   fallthrough to QBB
549   // here becomes
550   //   Bncc QBB
551   // with a conceptual B to IBB after that, which never actually exists.
552   // With those changes, we see whether the predecessors' tails match,
553   // and merge them if so.  We change things out of canonical form and
554   // back to the way they were later in the process.  (OptimizeBranches
555   // would undo some of this, but we can't use it, because we'd get into
556   // a compile-time infinite loop repeatedly doing and undoing the same
557   // transformations.)
558
559   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
560     if (!I->succ_empty() && I->pred_size() >= 2) {
561       MachineBasicBlock *IBB = I;
562       MachineBasicBlock *PredBB = prior(I);
563       MergePotentials.clear();
564       for (MachineBasicBlock::pred_iterator P = I->pred_begin(), E2 = I->pred_end(); 
565            P != E2; ++P) {
566         MachineBasicBlock* PBB = *P;
567         // Skip blocks that loop to themselves, can't tail merge these.
568         if (PBB==IBB)
569           continue;
570         MachineBasicBlock *TBB = 0, *FBB = 0;
571         std::vector<MachineOperand> Cond;
572         if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
573           // Failing case:  IBB is the target of a cbr, and
574           // we cannot reverse the branch.
575           std::vector<MachineOperand> NewCond(Cond);
576           if (Cond.size() && TBB==IBB) {
577             if (TII->ReverseBranchCondition(NewCond))
578               continue;
579             // This is the QBB case described above
580             if (!FBB)
581               FBB = next(MachineFunction::iterator(PBB));
582           }
583           // Remove the unconditional branch at the end, if any.
584           if (TBB && (Cond.size()==0 || FBB)) {
585             TII->RemoveBranch(*PBB);
586             if (Cond.size())
587               // reinsert conditional branch only, for now
588               TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
589           }
590           MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB), *P));
591         }
592       }
593     if (MergePotentials.size() >= 2)
594       MadeChange |= TryMergeBlocks(I, PredBB);
595     // Reinsert an unconditional branch if needed.
596     // The 1 below can be either an original single predecessor, or a result
597     // of removing blocks in TryMergeBlocks.
598     PredBB = prior(I);      // this may have been changed in TryMergeBlocks
599     if (MergePotentials.size()==1 && 
600         (MergePotentials.begin())->second != PredBB)
601       FixTail((MergePotentials.begin())->second, I, TII);
602     }
603   }
604   return MadeChange;
605 }
606
607 //===----------------------------------------------------------------------===//
608 //  Branch Optimization
609 //===----------------------------------------------------------------------===//
610
611 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
612   MadeChange = false;
613   
614   // Make sure blocks are numbered in order
615   MF.RenumberBlocks();
616
617   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
618     MachineBasicBlock *MBB = I++;
619     OptimizeBlock(MBB);
620     
621     // If it is dead, remove it.
622     if (MBB->pred_empty()) {
623       RemoveDeadBlock(MBB);
624       MadeChange = true;
625       ++NumDeadBlocks;
626     }
627   }
628   return MadeChange;
629 }
630
631
632 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
633 /// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
634 /// DestB, remove any other MBB successors from the CFG.  DestA and DestB can
635 /// be null.
636 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB, 
637                                  MachineBasicBlock *DestA,
638                                  MachineBasicBlock *DestB,
639                                  bool isCond, 
640                                  MachineFunction::iterator FallThru) {
641   bool MadeChange = false;
642   bool AddedFallThrough = false;
643   
644   // If this block ends with a conditional branch that falls through to its
645   // successor, set DestB as the successor.
646   if (isCond) {
647     if (DestB == 0 && FallThru != MBB.getParent()->end()) {
648       DestB = FallThru;
649       AddedFallThrough = true;
650     }
651   } else {
652     // If this is an unconditional branch with no explicit dest, it must just be
653     // a fallthrough into DestB.
654     if (DestA == 0 && FallThru != MBB.getParent()->end()) {
655       DestA = FallThru;
656       AddedFallThrough = true;
657     }
658   }
659   
660   MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
661   while (SI != MBB.succ_end()) {
662     if (*SI == DestA) {
663       DestA = 0;
664       ++SI;
665     } else if (*SI == DestB) {
666       DestB = 0;
667       ++SI;
668     } else if ((*SI)->isLandingPad()) {
669       ++SI;
670     } else {
671       // Otherwise, this is a superfluous edge, remove it.
672       MBB.removeSuccessor(SI);
673       MadeChange = true;
674     }
675   }
676   if (!AddedFallThrough) {
677     assert(DestA == 0 && DestB == 0 &&
678            "MachineCFG is missing edges!");
679   } else if (isCond) {
680     assert(DestA == 0 && "MachineCFG is missing edges!");
681   }
682   return MadeChange;
683 }
684
685
686 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
687 /// 'Old', change the code and CFG so that it branches to 'New' instead.
688 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
689                                    MachineBasicBlock *Old,
690                                    MachineBasicBlock *New,
691                                    const TargetInstrInfo *TII) {
692   assert(Old != New && "Cannot replace self with self!");
693
694   MachineBasicBlock::iterator I = BB->end();
695   while (I != BB->begin()) {
696     --I;
697     if (!TII->isTerminatorInstr(I->getOpcode())) break;
698
699     // Scan the operands of this machine instruction, replacing any uses of Old
700     // with New.
701     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
702       if (I->getOperand(i).isMachineBasicBlock() &&
703           I->getOperand(i).getMachineBasicBlock() == Old)
704         I->getOperand(i).setMachineBasicBlock(New);
705   }
706
707   // Update the successor information.
708   std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
709   for (int i = Succs.size()-1; i >= 0; --i)
710     if (Succs[i] == Old) {
711       BB->removeSuccessor(Old);
712       BB->addSuccessor(New);
713     }
714 }
715
716 /// CanFallThrough - Return true if the specified block (with the specified
717 /// branch condition) can implicitly transfer control to the block after it by
718 /// falling off the end of it.  This should return false if it can reach the
719 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
720 ///
721 /// True is a conservative answer.
722 ///
723 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
724                                   bool BranchUnAnalyzable,
725                                   MachineBasicBlock *TBB, MachineBasicBlock *FBB,
726                                   const std::vector<MachineOperand> &Cond) {
727   MachineFunction::iterator Fallthrough = CurBB;
728   ++Fallthrough;
729   // If FallthroughBlock is off the end of the function, it can't fall through.
730   if (Fallthrough == CurBB->getParent()->end())
731     return false;
732   
733   // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
734   if (!CurBB->isSuccessor(Fallthrough))
735     return false;
736   
737   // If we couldn't analyze the branch, assume it could fall through.
738   if (BranchUnAnalyzable) return true;
739   
740   // If there is no branch, control always falls through.
741   if (TBB == 0) return true;
742
743   // If there is some explicit branch to the fallthrough block, it can obviously
744   // reach, even though the branch should get folded to fall through implicitly.
745   if (MachineFunction::iterator(TBB) == Fallthrough ||
746       MachineFunction::iterator(FBB) == Fallthrough)
747     return true;
748   
749   // If it's an unconditional branch to some block not the fall through, it 
750   // doesn't fall through.
751   if (Cond.empty()) return false;
752   
753   // Otherwise, if it is conditional and has no explicit false block, it falls
754   // through.
755   return FBB == 0;
756 }
757
758 /// CanFallThrough - Return true if the specified can implicitly transfer
759 /// control to the block after it by falling off the end of it.  This should
760 /// return false if it can reach the block after it, but it uses an explicit
761 /// branch to do so (e.g. a table jump).
762 ///
763 /// True is a conservative answer.
764 ///
765 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
766   MachineBasicBlock *TBB = 0, *FBB = 0;
767   std::vector<MachineOperand> Cond;
768   bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
769   return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
770 }
771
772 /// IsBetterFallthrough - Return true if it would be clearly better to
773 /// fall-through to MBB1 than to fall through into MBB2.  This has to return
774 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
775 /// result in infinite loops.
776 static bool IsBetterFallthrough(MachineBasicBlock *MBB1, 
777                                 MachineBasicBlock *MBB2,
778                                 const TargetInstrInfo &TII) {
779   // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
780   // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
781   // optimize branches that branch to either a return block or an assert block
782   // into a fallthrough to the return.
783   if (MBB1->empty() || MBB2->empty()) return false;
784
785   MachineInstr *MBB1I = --MBB1->end();
786   MachineInstr *MBB2I = --MBB2->end();
787   return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
788 }
789
790 /// OptimizeBlock - Analyze and optimize control flow related to the specified
791 /// block.  This is never called on the entry block.
792 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
793   MachineFunction::iterator FallThrough = MBB;
794   ++FallThrough;
795   
796   // If this block is empty, make everyone use its fall-through, not the block
797   // explicitly.
798   if (MBB->empty()) {
799     // Dead block?  Leave for cleanup later.
800     if (MBB->pred_empty()) return;
801     
802     if (FallThrough == MBB->getParent()->end()) {
803       // TODO: Simplify preds to not branch here if possible!
804     } else {
805       // Rewrite all predecessors of the old block to go to the fallthrough
806       // instead.
807       while (!MBB->pred_empty()) {
808         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
809         ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
810       }
811       
812       // If MBB was the target of a jump table, update jump tables to go to the
813       // fallthrough instead.
814       MBB->getParent()->getJumpTableInfo()->
815         ReplaceMBBInJumpTables(MBB, FallThrough);
816       MadeChange = true;
817     }
818     return;
819   }
820
821   // Check to see if we can simplify the terminator of the block before this
822   // one.
823   MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
824
825   MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
826   std::vector<MachineOperand> PriorCond;
827   bool PriorUnAnalyzable =
828     TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
829   if (!PriorUnAnalyzable) {
830     // If the CFG for the prior block has extra edges, remove them.
831     MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
832                                        !PriorCond.empty(), MBB);
833     
834     // If the previous branch is conditional and both conditions go to the same
835     // destination, remove the branch, replacing it with an unconditional one or
836     // a fall-through.
837     if (PriorTBB && PriorTBB == PriorFBB) {
838       TII->RemoveBranch(PrevBB);
839       PriorCond.clear(); 
840       if (PriorTBB != MBB)
841         TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
842       MadeChange = true;
843       ++NumBranchOpts;
844       return OptimizeBlock(MBB);
845     }
846     
847     // If the previous branch *only* branches to *this* block (conditional or
848     // not) remove the branch.
849     if (PriorTBB == MBB && PriorFBB == 0) {
850       TII->RemoveBranch(PrevBB);
851       MadeChange = true;
852       ++NumBranchOpts;
853       return OptimizeBlock(MBB);
854     }
855     
856     // If the prior block branches somewhere else on the condition and here if
857     // the condition is false, remove the uncond second branch.
858     if (PriorFBB == MBB) {
859       TII->RemoveBranch(PrevBB);
860       TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
861       MadeChange = true;
862       ++NumBranchOpts;
863       return OptimizeBlock(MBB);
864     }
865     
866     // If the prior block branches here on true and somewhere else on false, and
867     // if the branch condition is reversible, reverse the branch to create a
868     // fall-through.
869     if (PriorTBB == MBB) {
870       std::vector<MachineOperand> NewPriorCond(PriorCond);
871       if (!TII->ReverseBranchCondition(NewPriorCond)) {
872         TII->RemoveBranch(PrevBB);
873         TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
874         MadeChange = true;
875         ++NumBranchOpts;
876         return OptimizeBlock(MBB);
877       }
878     }
879     
880     // If this block doesn't fall through (e.g. it ends with an uncond branch or
881     // has no successors) and if the pred falls through into this block, and if
882     // it would otherwise fall through into the block after this, move this
883     // block to the end of the function.
884     //
885     // We consider it more likely that execution will stay in the function (e.g.
886     // due to loops) than it is to exit it.  This asserts in loops etc, moving
887     // the assert condition out of the loop body.
888     if (!PriorCond.empty() && PriorFBB == 0 &&
889         MachineFunction::iterator(PriorTBB) == FallThrough &&
890         !CanFallThrough(MBB)) {
891       bool DoTransform = true;
892       
893       // We have to be careful that the succs of PredBB aren't both no-successor
894       // blocks.  If neither have successors and if PredBB is the second from
895       // last block in the function, we'd just keep swapping the two blocks for
896       // last.  Only do the swap if one is clearly better to fall through than
897       // the other.
898       if (FallThrough == --MBB->getParent()->end() &&
899           !IsBetterFallthrough(PriorTBB, MBB, *TII))
900         DoTransform = false;
901
902       // We don't want to do this transformation if we have control flow like:
903       //   br cond BB2
904       // BB1:
905       //   ..
906       //   jmp BBX
907       // BB2:
908       //   ..
909       //   ret
910       //
911       // In this case, we could actually be moving the return block *into* a
912       // loop!
913       if (DoTransform && !MBB->succ_empty() &&
914           (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
915         DoTransform = false;
916       
917       
918       if (DoTransform) {
919         // Reverse the branch so we will fall through on the previous true cond.
920         std::vector<MachineOperand> NewPriorCond(PriorCond);
921         if (!TII->ReverseBranchCondition(NewPriorCond)) {
922           DOUT << "\nMoving MBB: " << *MBB;
923           DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
924           
925           TII->RemoveBranch(PrevBB);
926           TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
927
928           // Move this block to the end of the function.
929           MBB->moveAfter(--MBB->getParent()->end());
930           MadeChange = true;
931           ++NumBranchOpts;
932           return;
933         }
934       }
935     }
936   }
937   
938   // Analyze the branch in the current block.
939   MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
940   std::vector<MachineOperand> CurCond;
941   bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
942   if (!CurUnAnalyzable) {
943     // If the CFG for the prior block has extra edges, remove them.
944     MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
945                                        !CurCond.empty(),
946                                        ++MachineFunction::iterator(MBB));
947
948     // If this is a two-way branch, and the FBB branches to this block, reverse 
949     // the condition so the single-basic-block loop is faster.  Instead of:
950     //    Loop: xxx; jcc Out; jmp Loop
951     // we want:
952     //    Loop: xxx; jncc Loop; jmp Out
953     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
954       std::vector<MachineOperand> NewCond(CurCond);
955       if (!TII->ReverseBranchCondition(NewCond)) {
956         TII->RemoveBranch(*MBB);
957         TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
958         MadeChange = true;
959         ++NumBranchOpts;
960         return OptimizeBlock(MBB);
961       }
962     }
963     
964     
965     // If this branch is the only thing in its block, see if we can forward
966     // other blocks across it.
967     if (CurTBB && CurCond.empty() && CurFBB == 0 && 
968         TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
969       // This block may contain just an unconditional branch.  Because there can
970       // be 'non-branch terminators' in the block, try removing the branch and
971       // then seeing if the block is empty.
972       TII->RemoveBranch(*MBB);
973
974       // If this block is just an unconditional branch to CurTBB, we can
975       // usually completely eliminate the block.  The only case we cannot
976       // completely eliminate the block is when the block before this one
977       // falls through into MBB and we can't understand the prior block's branch
978       // condition.
979       if (MBB->empty()) {
980         bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
981         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
982             !PrevBB.isSuccessor(MBB)) {
983           // If the prior block falls through into us, turn it into an
984           // explicit branch to us to make updates simpler.
985           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) && 
986               PriorTBB != MBB && PriorFBB != MBB) {
987             if (PriorTBB == 0) {
988               assert(PriorCond.empty() && PriorFBB == 0 &&
989                      "Bad branch analysis");
990               PriorTBB = MBB;
991             } else {
992               assert(PriorFBB == 0 && "Machine CFG out of date!");
993               PriorFBB = MBB;
994             }
995             TII->RemoveBranch(PrevBB);
996             TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
997           }
998
999           // Iterate through all the predecessors, revectoring each in-turn.
1000           MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
1001           bool DidChange = false;
1002           bool HasBranchToSelf = false;
1003           while (PI != MBB->pred_end()) {
1004             if (*PI == MBB) {
1005               // If this block has an uncond branch to itself, leave it.
1006               ++PI;
1007               HasBranchToSelf = true;
1008             } else {
1009               DidChange = true;
1010               ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
1011             }
1012           }
1013
1014           // Change any jumptables to go to the new MBB.
1015           MBB->getParent()->getJumpTableInfo()->
1016             ReplaceMBBInJumpTables(MBB, CurTBB);
1017           if (DidChange) {
1018             ++NumBranchOpts;
1019             MadeChange = true;
1020             if (!HasBranchToSelf) return;
1021           }
1022         }
1023       }
1024       
1025       // Add the branch back if the block is more than just an uncond branch.
1026       TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1027     }
1028   }
1029
1030   // If the prior block doesn't fall through into this block, and if this
1031   // block doesn't fall through into some other block, see if we can find a
1032   // place to move this block where a fall-through will happen.
1033   if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1034                       PriorTBB, PriorFBB, PriorCond)) {
1035     // Now we know that there was no fall-through into this block, check to
1036     // see if it has a fall-through into its successor.
1037     bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, 
1038                                        CurCond);
1039
1040     if (!MBB->isLandingPad()) {
1041       // Check all the predecessors of this block.  If one of them has no fall
1042       // throughs, move this block right after it.
1043       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1044            E = MBB->pred_end(); PI != E; ++PI) {
1045         // Analyze the branch at the end of the pred.
1046         MachineBasicBlock *PredBB = *PI;
1047         MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1048         if (PredBB != MBB && !CanFallThrough(PredBB)
1049             && (!CurFallsThru || !CurTBB || !CurFBB)
1050             && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1051           // If the current block doesn't fall through, just move it.
1052           // If the current block can fall through and does not end with a
1053           // conditional branch, we need to append an unconditional jump to 
1054           // the (current) next block.  To avoid a possible compile-time
1055           // infinite loop, move blocks only backward in this case.
1056           // Also, if there are already 2 branches here, we cannot add a third;
1057           // this means we have the case
1058           // Bcc next
1059           // B elsewhere
1060           // next:
1061           if (CurFallsThru) {
1062             MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1063             CurCond.clear();
1064             TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1065           }
1066           MBB->moveAfter(PredBB);
1067           MadeChange = true;
1068           return OptimizeBlock(MBB);
1069         }
1070       }
1071     }
1072         
1073     if (!CurFallsThru) {
1074       // Check all successors to see if we can move this block before it.
1075       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1076            E = MBB->succ_end(); SI != E; ++SI) {
1077         // Analyze the branch at the end of the block before the succ.
1078         MachineBasicBlock *SuccBB = *SI;
1079         MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1080         std::vector<MachineOperand> SuccPrevCond;
1081         
1082         // If this block doesn't already fall-through to that successor, and if
1083         // the succ doesn't already have a block that can fall through into it,
1084         // and if the successor isn't an EH destination, we can arrange for the
1085         // fallthrough to happen.
1086         if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1087             !SuccBB->isLandingPad()) {
1088           MBB->moveBefore(SuccBB);
1089           MadeChange = true;
1090           return OptimizeBlock(MBB);
1091         }
1092       }
1093       
1094       // Okay, there is no really great place to put this block.  If, however,
1095       // the block before this one would be a fall-through if this block were
1096       // removed, move this block to the end of the function.
1097       if (FallThrough != MBB->getParent()->end() &&
1098           PrevBB.isSuccessor(FallThrough)) {
1099         MBB->moveAfter(--MBB->getParent()->end());
1100         MadeChange = true;
1101         return;
1102       }
1103     }
1104   }
1105 }