Fix PR number.
[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     if (MergePotentials.size()==1 && 
599         (MergePotentials.begin())->second != PredBB)
600       FixTail((MergePotentials.begin())->second, I, TII);
601     }
602   }
603   return MadeChange;
604 }
605
606 //===----------------------------------------------------------------------===//
607 //  Branch Optimization
608 //===----------------------------------------------------------------------===//
609
610 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
611   MadeChange = false;
612   
613   // Make sure blocks are numbered in order
614   MF.RenumberBlocks();
615
616   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
617     MachineBasicBlock *MBB = I++;
618     OptimizeBlock(MBB);
619     
620     // If it is dead, remove it.
621     if (MBB->pred_empty()) {
622       RemoveDeadBlock(MBB);
623       MadeChange = true;
624       ++NumDeadBlocks;
625     }
626   }
627   return MadeChange;
628 }
629
630
631 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
632 /// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
633 /// DestB, remove any other MBB successors from the CFG.  DestA and DestB can
634 /// be null.
635 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB, 
636                                  MachineBasicBlock *DestA,
637                                  MachineBasicBlock *DestB,
638                                  bool isCond, 
639                                  MachineFunction::iterator FallThru) {
640   bool MadeChange = false;
641   bool AddedFallThrough = false;
642   
643   // If this block ends with a conditional branch that falls through to its
644   // successor, set DestB as the successor.
645   if (isCond) {
646     if (DestB == 0 && FallThru != MBB.getParent()->end()) {
647       DestB = FallThru;
648       AddedFallThrough = true;
649     }
650   } else {
651     // If this is an unconditional branch with no explicit dest, it must just be
652     // a fallthrough into DestB.
653     if (DestA == 0 && FallThru != MBB.getParent()->end()) {
654       DestA = FallThru;
655       AddedFallThrough = true;
656     }
657   }
658   
659   MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
660   while (SI != MBB.succ_end()) {
661     if (*SI == DestA) {
662       DestA = 0;
663       ++SI;
664     } else if (*SI == DestB) {
665       DestB = 0;
666       ++SI;
667     } else if ((*SI)->isLandingPad()) {
668       ++SI;
669     } else {
670       // Otherwise, this is a superfluous edge, remove it.
671       MBB.removeSuccessor(SI);
672       MadeChange = true;
673     }
674   }
675   if (!AddedFallThrough) {
676     assert(DestA == 0 && DestB == 0 &&
677            "MachineCFG is missing edges!");
678   } else if (isCond) {
679     assert(DestA == 0 && "MachineCFG is missing edges!");
680   }
681   return MadeChange;
682 }
683
684
685 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
686 /// 'Old', change the code and CFG so that it branches to 'New' instead.
687 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
688                                    MachineBasicBlock *Old,
689                                    MachineBasicBlock *New,
690                                    const TargetInstrInfo *TII) {
691   assert(Old != New && "Cannot replace self with self!");
692
693   MachineBasicBlock::iterator I = BB->end();
694   while (I != BB->begin()) {
695     --I;
696     if (!TII->isTerminatorInstr(I->getOpcode())) break;
697
698     // Scan the operands of this machine instruction, replacing any uses of Old
699     // with New.
700     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
701       if (I->getOperand(i).isMachineBasicBlock() &&
702           I->getOperand(i).getMachineBasicBlock() == Old)
703         I->getOperand(i).setMachineBasicBlock(New);
704   }
705
706   // Update the successor information.
707   std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
708   for (int i = Succs.size()-1; i >= 0; --i)
709     if (Succs[i] == Old) {
710       BB->removeSuccessor(Old);
711       BB->addSuccessor(New);
712     }
713 }
714
715 /// CanFallThrough - Return true if the specified block (with the specified
716 /// branch condition) can implicitly transfer control to the block after it by
717 /// falling off the end of it.  This should return false if it can reach the
718 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
719 ///
720 /// True is a conservative answer.
721 ///
722 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
723                                   bool BranchUnAnalyzable,
724                                   MachineBasicBlock *TBB, MachineBasicBlock *FBB,
725                                   const std::vector<MachineOperand> &Cond) {
726   MachineFunction::iterator Fallthrough = CurBB;
727   ++Fallthrough;
728   // If FallthroughBlock is off the end of the function, it can't fall through.
729   if (Fallthrough == CurBB->getParent()->end())
730     return false;
731   
732   // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
733   if (!CurBB->isSuccessor(Fallthrough))
734     return false;
735   
736   // If we couldn't analyze the branch, assume it could fall through.
737   if (BranchUnAnalyzable) return true;
738   
739   // If there is no branch, control always falls through.
740   if (TBB == 0) return true;
741
742   // If there is some explicit branch to the fallthrough block, it can obviously
743   // reach, even though the branch should get folded to fall through implicitly.
744   if (MachineFunction::iterator(TBB) == Fallthrough ||
745       MachineFunction::iterator(FBB) == Fallthrough)
746     return true;
747   
748   // If it's an unconditional branch to some block not the fall through, it 
749   // doesn't fall through.
750   if (Cond.empty()) return false;
751   
752   // Otherwise, if it is conditional and has no explicit false block, it falls
753   // through.
754   return FBB == 0;
755 }
756
757 /// CanFallThrough - Return true if the specified can implicitly transfer
758 /// control to the block after it by falling off the end of it.  This should
759 /// return false if it can reach the block after it, but it uses an explicit
760 /// branch to do so (e.g. a table jump).
761 ///
762 /// True is a conservative answer.
763 ///
764 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
765   MachineBasicBlock *TBB = 0, *FBB = 0;
766   std::vector<MachineOperand> Cond;
767   bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
768   return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
769 }
770
771 /// IsBetterFallthrough - Return true if it would be clearly better to
772 /// fall-through to MBB1 than to fall through into MBB2.  This has to return
773 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
774 /// result in infinite loops.
775 static bool IsBetterFallthrough(MachineBasicBlock *MBB1, 
776                                 MachineBasicBlock *MBB2,
777                                 const TargetInstrInfo &TII) {
778   // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
779   // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
780   // optimize branches that branch to either a return block or an assert block
781   // into a fallthrough to the return.
782   if (MBB1->empty() || MBB2->empty()) return false;
783
784   MachineInstr *MBB1I = --MBB1->end();
785   MachineInstr *MBB2I = --MBB2->end();
786   return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
787 }
788
789 /// OptimizeBlock - Analyze and optimize control flow related to the specified
790 /// block.  This is never called on the entry block.
791 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
792   MachineFunction::iterator FallThrough = MBB;
793   ++FallThrough;
794   
795   // If this block is empty, make everyone use its fall-through, not the block
796   // explicitly.
797   if (MBB->empty()) {
798     // Dead block?  Leave for cleanup later.
799     if (MBB->pred_empty()) return;
800     
801     if (FallThrough == MBB->getParent()->end()) {
802       // TODO: Simplify preds to not branch here if possible!
803     } else {
804       // Rewrite all predecessors of the old block to go to the fallthrough
805       // instead.
806       while (!MBB->pred_empty()) {
807         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
808         ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
809       }
810       
811       // If MBB was the target of a jump table, update jump tables to go to the
812       // fallthrough instead.
813       MBB->getParent()->getJumpTableInfo()->
814         ReplaceMBBInJumpTables(MBB, FallThrough);
815       MadeChange = true;
816     }
817     return;
818   }
819
820   // Check to see if we can simplify the terminator of the block before this
821   // one.
822   MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
823
824   MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
825   std::vector<MachineOperand> PriorCond;
826   bool PriorUnAnalyzable =
827     TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
828   if (!PriorUnAnalyzable) {
829     // If the CFG for the prior block has extra edges, remove them.
830     MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
831                                        !PriorCond.empty(), MBB);
832     
833     // If the previous branch is conditional and both conditions go to the same
834     // destination, remove the branch, replacing it with an unconditional one or
835     // a fall-through.
836     if (PriorTBB && PriorTBB == PriorFBB) {
837       TII->RemoveBranch(PrevBB);
838       PriorCond.clear(); 
839       if (PriorTBB != MBB)
840         TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
841       MadeChange = true;
842       ++NumBranchOpts;
843       return OptimizeBlock(MBB);
844     }
845     
846     // If the previous branch *only* branches to *this* block (conditional or
847     // not) remove the branch.
848     if (PriorTBB == MBB && PriorFBB == 0) {
849       TII->RemoveBranch(PrevBB);
850       MadeChange = true;
851       ++NumBranchOpts;
852       return OptimizeBlock(MBB);
853     }
854     
855     // If the prior block branches somewhere else on the condition and here if
856     // the condition is false, remove the uncond second branch.
857     if (PriorFBB == MBB) {
858       TII->RemoveBranch(PrevBB);
859       TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
860       MadeChange = true;
861       ++NumBranchOpts;
862       return OptimizeBlock(MBB);
863     }
864     
865     // If the prior block branches here on true and somewhere else on false, and
866     // if the branch condition is reversible, reverse the branch to create a
867     // fall-through.
868     if (PriorTBB == MBB) {
869       std::vector<MachineOperand> NewPriorCond(PriorCond);
870       if (!TII->ReverseBranchCondition(NewPriorCond)) {
871         TII->RemoveBranch(PrevBB);
872         TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
873         MadeChange = true;
874         ++NumBranchOpts;
875         return OptimizeBlock(MBB);
876       }
877     }
878     
879     // If this block doesn't fall through (e.g. it ends with an uncond branch or
880     // has no successors) and if the pred falls through into this block, and if
881     // it would otherwise fall through into the block after this, move this
882     // block to the end of the function.
883     //
884     // We consider it more likely that execution will stay in the function (e.g.
885     // due to loops) than it is to exit it.  This asserts in loops etc, moving
886     // the assert condition out of the loop body.
887     if (!PriorCond.empty() && PriorFBB == 0 &&
888         MachineFunction::iterator(PriorTBB) == FallThrough &&
889         !CanFallThrough(MBB)) {
890       bool DoTransform = true;
891       
892       // We have to be careful that the succs of PredBB aren't both no-successor
893       // blocks.  If neither have successors and if PredBB is the second from
894       // last block in the function, we'd just keep swapping the two blocks for
895       // last.  Only do the swap if one is clearly better to fall through than
896       // the other.
897       if (FallThrough == --MBB->getParent()->end() &&
898           !IsBetterFallthrough(PriorTBB, MBB, *TII))
899         DoTransform = false;
900
901       // We don't want to do this transformation if we have control flow like:
902       //   br cond BB2
903       // BB1:
904       //   ..
905       //   jmp BBX
906       // BB2:
907       //   ..
908       //   ret
909       //
910       // In this case, we could actually be moving the return block *into* a
911       // loop!
912       if (DoTransform && !MBB->succ_empty() &&
913           (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
914         DoTransform = false;
915       
916       
917       if (DoTransform) {
918         // Reverse the branch so we will fall through on the previous true cond.
919         std::vector<MachineOperand> NewPriorCond(PriorCond);
920         if (!TII->ReverseBranchCondition(NewPriorCond)) {
921           DOUT << "\nMoving MBB: " << *MBB;
922           DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
923           
924           TII->RemoveBranch(PrevBB);
925           TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
926
927           // Move this block to the end of the function.
928           MBB->moveAfter(--MBB->getParent()->end());
929           MadeChange = true;
930           ++NumBranchOpts;
931           return;
932         }
933       }
934     }
935   }
936   
937   // Analyze the branch in the current block.
938   MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
939   std::vector<MachineOperand> CurCond;
940   bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
941   if (!CurUnAnalyzable) {
942     // If the CFG for the prior block has extra edges, remove them.
943     MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
944                                        !CurCond.empty(),
945                                        ++MachineFunction::iterator(MBB));
946
947     // If this is a two-way branch, and the FBB branches to this block, reverse 
948     // the condition so the single-basic-block loop is faster.  Instead of:
949     //    Loop: xxx; jcc Out; jmp Loop
950     // we want:
951     //    Loop: xxx; jncc Loop; jmp Out
952     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
953       std::vector<MachineOperand> NewCond(CurCond);
954       if (!TII->ReverseBranchCondition(NewCond)) {
955         TII->RemoveBranch(*MBB);
956         TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
957         MadeChange = true;
958         ++NumBranchOpts;
959         return OptimizeBlock(MBB);
960       }
961     }
962     
963     
964     // If this branch is the only thing in its block, see if we can forward
965     // other blocks across it.
966     if (CurTBB && CurCond.empty() && CurFBB == 0 && 
967         TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
968       // This block may contain just an unconditional branch.  Because there can
969       // be 'non-branch terminators' in the block, try removing the branch and
970       // then seeing if the block is empty.
971       TII->RemoveBranch(*MBB);
972
973       // If this block is just an unconditional branch to CurTBB, we can
974       // usually completely eliminate the block.  The only case we cannot
975       // completely eliminate the block is when the block before this one
976       // falls through into MBB and we can't understand the prior block's branch
977       // condition.
978       if (MBB->empty()) {
979         bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
980         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
981             !PrevBB.isSuccessor(MBB)) {
982           // If the prior block falls through into us, turn it into an
983           // explicit branch to us to make updates simpler.
984           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) && 
985               PriorTBB != MBB && PriorFBB != MBB) {
986             if (PriorTBB == 0) {
987               assert(PriorCond.empty() && PriorFBB == 0 &&
988                      "Bad branch analysis");
989               PriorTBB = MBB;
990             } else {
991               assert(PriorFBB == 0 && "Machine CFG out of date!");
992               PriorFBB = MBB;
993             }
994             TII->RemoveBranch(PrevBB);
995             TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
996           }
997
998           // Iterate through all the predecessors, revectoring each in-turn.
999           MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
1000           bool DidChange = false;
1001           bool HasBranchToSelf = false;
1002           while (PI != MBB->pred_end()) {
1003             if (*PI == MBB) {
1004               // If this block has an uncond branch to itself, leave it.
1005               ++PI;
1006               HasBranchToSelf = true;
1007             } else {
1008               DidChange = true;
1009               ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
1010             }
1011           }
1012
1013           // Change any jumptables to go to the new MBB.
1014           MBB->getParent()->getJumpTableInfo()->
1015             ReplaceMBBInJumpTables(MBB, CurTBB);
1016           if (DidChange) {
1017             ++NumBranchOpts;
1018             MadeChange = true;
1019             if (!HasBranchToSelf) return;
1020           }
1021         }
1022       }
1023       
1024       // Add the branch back if the block is more than just an uncond branch.
1025       TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1026     }
1027   }
1028
1029   // If the prior block doesn't fall through into this block, and if this
1030   // block doesn't fall through into some other block, see if we can find a
1031   // place to move this block where a fall-through will happen.
1032   if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1033                       PriorTBB, PriorFBB, PriorCond)) {
1034     // Now we know that there was no fall-through into this block, check to
1035     // see if it has a fall-through into its successor.
1036     bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, 
1037                                        CurCond);
1038
1039     if (!MBB->isLandingPad()) {
1040       // Check all the predecessors of this block.  If one of them has no fall
1041       // throughs, move this block right after it.
1042       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1043            E = MBB->pred_end(); PI != E; ++PI) {
1044         // Analyze the branch at the end of the pred.
1045         MachineBasicBlock *PredBB = *PI;
1046         MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1047         if (PredBB != MBB && !CanFallThrough(PredBB)
1048             && (!CurFallsThru || !CurTBB || !CurFBB)
1049             && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1050           // If the current block doesn't fall through, just move it.
1051           // If the current block can fall through and does not end with a
1052           // conditional branch, we need to append an unconditional jump to 
1053           // the (current) next block.  To avoid a possible compile-time
1054           // infinite loop, move blocks only backward in this case.
1055           // Also, if there are already 2 branches here, we cannot add a third;
1056           // this means we have the case
1057           // Bcc next
1058           // B elsewhere
1059           // next:
1060           if (CurFallsThru) {
1061             MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1062             CurCond.clear();
1063             TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1064           }
1065           MBB->moveAfter(PredBB);
1066           MadeChange = true;
1067           return OptimizeBlock(MBB);
1068         }
1069       }
1070     }
1071         
1072     if (!CurFallsThru) {
1073       // Check all successors to see if we can move this block before it.
1074       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1075            E = MBB->succ_end(); SI != E; ++SI) {
1076         // Analyze the branch at the end of the block before the succ.
1077         MachineBasicBlock *SuccBB = *SI;
1078         MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1079         std::vector<MachineOperand> SuccPrevCond;
1080         
1081         // If this block doesn't already fall-through to that successor, and if
1082         // the succ doesn't already have a block that can fall through into it,
1083         // and if the successor isn't an EH destination, we can arrange for the
1084         // fallthrough to happen.
1085         if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1086             !SuccBB->isLandingPad()) {
1087           MBB->moveBefore(SuccBB);
1088           MadeChange = true;
1089           return OptimizeBlock(MBB);
1090         }
1091       }
1092       
1093       // Okay, there is no really great place to put this block.  If, however,
1094       // the block before this one would be a fall-through if this block were
1095       // removed, move this block to the end of the function.
1096       if (FallThrough != MBB->getParent()->end() &&
1097           PrevBB.isSuccessor(FallThrough)) {
1098         MBB->moveAfter(--MBB->getParent()->end());
1099         MadeChange = true;
1100         return;
1101       }
1102     }
1103   }
1104 }