Forgot to reverse conditional.
[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 is distributed under the University of Illinois Open Source
6 // 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 "BranchFolding.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineJumpTableInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/RegisterScavenging.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/SetVector.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
43 STATISTIC(NumBranchOpts, "Number of branches optimized");
44 STATISTIC(NumTailMerge , "Number of block tails merged");
45 STATISTIC(NumHoist     , "Number of times common instructions are hoisted");
46
47 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
48                               cl::init(cl::BOU_UNSET), cl::Hidden);
49
50 // Throttle for huge numbers of predecessors (compile speed problems)
51 static cl::opt<unsigned>
52 TailMergeThreshold("tail-merge-threshold",
53           cl::desc("Max number of predecessors to consider tail merging"),
54           cl::init(150), cl::Hidden);
55
56 // Heuristic for tail merging (and, inversely, tail duplication).
57 // TODO: This should be replaced with a target query.
58 static cl::opt<unsigned>
59 TailMergeSize("tail-merge-size",
60           cl::desc("Min number of instructions to consider tail merging"),
61                               cl::init(3), cl::Hidden);
62
63 namespace {
64   /// BranchFolderPass - Wrap branch folder in a machine function pass.
65   class BranchFolderPass : public MachineFunctionPass {
66   public:
67     static char ID;
68     explicit BranchFolderPass(): MachineFunctionPass(ID) {}
69
70     virtual bool runOnMachineFunction(MachineFunction &MF);
71
72     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73       AU.addRequired<TargetPassConfig>();
74       MachineFunctionPass::getAnalysisUsage(AU);
75     }
76   };
77 }
78
79 char BranchFolderPass::ID = 0;
80 char &llvm::BranchFolderPassID = BranchFolderPass::ID;
81
82 INITIALIZE_PASS(BranchFolderPass, "branch-folder",
83                 "Control Flow Optimizer", false, false)
84
85 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
86   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
87   BranchFolder Folder(PassConfig->getEnableTailMerge(), /*CommonHoist=*/true);
88   return Folder.OptimizeFunction(MF,
89                                  MF.getTarget().getInstrInfo(),
90                                  MF.getTarget().getRegisterInfo(),
91                                  getAnalysisIfAvailable<MachineModuleInfo>());
92 }
93
94
95 BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist) {
96   switch (FlagEnableTailMerge) {
97   case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
98   case cl::BOU_TRUE: EnableTailMerge = true; break;
99   case cl::BOU_FALSE: EnableTailMerge = false; break;
100   }
101
102   EnableHoistCommonCode = CommonHoist;
103 }
104
105 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
106 /// function, updating the CFG.
107 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
108   assert(MBB->pred_empty() && "MBB must be dead!");
109   DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
110
111   MachineFunction *MF = MBB->getParent();
112   // drop all successors.
113   while (!MBB->succ_empty())
114     MBB->removeSuccessor(MBB->succ_end()-1);
115
116   // Avoid matching if this pointer gets reused.
117   TriedMerging.erase(MBB);
118
119   // Remove the block.
120   MF->erase(MBB);
121 }
122
123 /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
124 /// followed by terminators, and if the implicitly defined registers are not
125 /// used by the terminators, remove those implicit_def's. e.g.
126 /// BB1:
127 ///   r0 = implicit_def
128 ///   r1 = implicit_def
129 ///   br
130 /// This block can be optimized away later if the implicit instructions are
131 /// removed.
132 bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
133   SmallSet<unsigned, 4> ImpDefRegs;
134   MachineBasicBlock::iterator I = MBB->begin();
135   while (I != MBB->end()) {
136     if (!I->isImplicitDef())
137       break;
138     unsigned Reg = I->getOperand(0).getReg();
139     ImpDefRegs.insert(Reg);
140     for (const uint16_t *SubRegs = TRI->getSubRegisters(Reg);
141          unsigned SubReg = *SubRegs; ++SubRegs)
142       ImpDefRegs.insert(SubReg);
143     ++I;
144   }
145   if (ImpDefRegs.empty())
146     return false;
147
148   MachineBasicBlock::iterator FirstTerm = I;
149   while (I != MBB->end()) {
150     if (!TII->isUnpredicatedTerminator(I))
151       return false;
152     // See if it uses any of the implicitly defined registers.
153     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
154       MachineOperand &MO = I->getOperand(i);
155       if (!MO.isReg() || !MO.isUse())
156         continue;
157       unsigned Reg = MO.getReg();
158       if (ImpDefRegs.count(Reg))
159         return false;
160     }
161     ++I;
162   }
163
164   I = MBB->begin();
165   while (I != FirstTerm) {
166     MachineInstr *ImpDefMI = &*I;
167     ++I;
168     MBB->erase(ImpDefMI);
169   }
170
171   return true;
172 }
173
174 /// OptimizeFunction - Perhaps branch folding, tail merging and other
175 /// CFG optimizations on the given function.
176 bool BranchFolder::OptimizeFunction(MachineFunction &MF,
177                                     const TargetInstrInfo *tii,
178                                     const TargetRegisterInfo *tri,
179                                     MachineModuleInfo *mmi) {
180   if (!tii) return false;
181
182   TriedMerging.clear();
183
184   TII = tii;
185   TRI = tri;
186   MMI = mmi;
187   RS = NULL;
188
189   // Use a RegScavenger to help update liveness when required.
190   MachineRegisterInfo &MRI = MF.getRegInfo();
191   if (MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
192     RS = new RegScavenger();
193   else
194     MRI.invalidateLiveness();
195
196   // Fix CFG.  The later algorithms expect it to be right.
197   bool MadeChange = false;
198   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
199     MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
200     SmallVector<MachineOperand, 4> Cond;
201     if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
202       MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
203     MadeChange |= OptimizeImpDefsBlock(MBB);
204   }
205
206   bool MadeChangeThisIteration = true;
207   while (MadeChangeThisIteration) {
208     MadeChangeThisIteration    = TailMergeBlocks(MF);
209     MadeChangeThisIteration   |= OptimizeBranches(MF);
210     if (EnableHoistCommonCode)
211       MadeChangeThisIteration |= HoistCommonCode(MF);
212     MadeChange |= MadeChangeThisIteration;
213   }
214
215   // See if any jump tables have become dead as the code generator
216   // did its thing.
217   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
218   if (JTI == 0) {
219     delete RS;
220     return MadeChange;
221   }
222
223   // Walk the function to find jump tables that are live.
224   BitVector JTIsLive(JTI->getJumpTables().size());
225   for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
226        BB != E; ++BB) {
227     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
228          I != E; ++I)
229       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
230         MachineOperand &Op = I->getOperand(op);
231         if (!Op.isJTI()) continue;
232
233         // Remember that this JT is live.
234         JTIsLive.set(Op.getIndex());
235       }
236   }
237
238   // Finally, remove dead jump tables.  This happens when the
239   // indirect jump was unreachable (and thus deleted).
240   for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
241     if (!JTIsLive.test(i)) {
242       JTI->RemoveJumpTable(i);
243       MadeChange = true;
244     }
245
246   delete RS;
247   return MadeChange;
248 }
249
250 //===----------------------------------------------------------------------===//
251 //  Tail Merging of Blocks
252 //===----------------------------------------------------------------------===//
253
254 /// HashMachineInstr - Compute a hash value for MI and its operands.
255 static unsigned HashMachineInstr(const MachineInstr *MI) {
256   unsigned Hash = MI->getOpcode();
257   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
258     const MachineOperand &Op = MI->getOperand(i);
259
260     // Merge in bits from the operand if easy.
261     unsigned OperandHash = 0;
262     switch (Op.getType()) {
263     case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
264     case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
265     case MachineOperand::MO_MachineBasicBlock:
266       OperandHash = Op.getMBB()->getNumber();
267       break;
268     case MachineOperand::MO_FrameIndex:
269     case MachineOperand::MO_ConstantPoolIndex:
270     case MachineOperand::MO_JumpTableIndex:
271       OperandHash = Op.getIndex();
272       break;
273     case MachineOperand::MO_GlobalAddress:
274     case MachineOperand::MO_ExternalSymbol:
275       // Global address / external symbol are too hard, don't bother, but do
276       // pull in the offset.
277       OperandHash = Op.getOffset();
278       break;
279     default: break;
280     }
281
282     Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
283   }
284   return Hash;
285 }
286
287 /// HashEndOfMBB - Hash the last instruction in the MBB.
288 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
289   MachineBasicBlock::const_iterator I = MBB->end();
290   if (I == MBB->begin())
291     return 0;   // Empty MBB.
292
293   --I;
294   // Skip debug info so it will not affect codegen.
295   while (I->isDebugValue()) {
296     if (I==MBB->begin())
297       return 0;      // MBB empty except for debug info.
298     --I;
299   }
300
301   return HashMachineInstr(I);
302 }
303
304 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
305 /// of instructions they actually have in common together at their end.  Return
306 /// iterators for the first shared instruction in each block.
307 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
308                                         MachineBasicBlock *MBB2,
309                                         MachineBasicBlock::iterator &I1,
310                                         MachineBasicBlock::iterator &I2) {
311   I1 = MBB1->end();
312   I2 = MBB2->end();
313
314   unsigned TailLen = 0;
315   while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
316     --I1; --I2;
317     // Skip debugging pseudos; necessary to avoid changing the code.
318     while (I1->isDebugValue()) {
319       if (I1==MBB1->begin()) {
320         while (I2->isDebugValue()) {
321           if (I2==MBB2->begin())
322             // I1==DBG at begin; I2==DBG at begin
323             return TailLen;
324           --I2;
325         }
326         ++I2;
327         // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
328         return TailLen;
329       }
330       --I1;
331     }
332     // I1==first (untested) non-DBG preceding known match
333     while (I2->isDebugValue()) {
334       if (I2==MBB2->begin()) {
335         ++I1;
336         // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
337         return TailLen;
338       }
339       --I2;
340     }
341     // I1, I2==first (untested) non-DBGs preceding known match
342     if (!I1->isIdenticalTo(I2) ||
343         // FIXME: This check is dubious. It's used to get around a problem where
344         // people incorrectly expect inline asm directives to remain in the same
345         // relative order. This is untenable because normal compiler
346         // optimizations (like this one) may reorder and/or merge these
347         // directives.
348         I1->isInlineAsm()) {
349       ++I1; ++I2;
350       break;
351     }
352     ++TailLen;
353   }
354   // Back past possible debugging pseudos at beginning of block.  This matters
355   // when one block differs from the other only by whether debugging pseudos
356   // are present at the beginning.  (This way, the various checks later for
357   // I1==MBB1->begin() work as expected.)
358   if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
359     --I2;
360     while (I2->isDebugValue()) {
361       if (I2 == MBB2->begin()) {
362         return TailLen;
363         }
364       --I2;
365     }
366     ++I2;
367   }
368   if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
369     --I1;
370     while (I1->isDebugValue()) {
371       if (I1 == MBB1->begin())
372         return TailLen;
373       --I1;
374     }
375     ++I1;
376   }
377   return TailLen;
378 }
379
380 void BranchFolder::MaintainLiveIns(MachineBasicBlock *CurMBB,
381                                    MachineBasicBlock *NewMBB) {
382   if (RS) {
383     RS->enterBasicBlock(CurMBB);
384     if (!CurMBB->empty())
385       RS->forward(prior(CurMBB->end()));
386     BitVector RegsLiveAtExit(TRI->getNumRegs());
387     RS->getRegsUsed(RegsLiveAtExit, false);
388     for (unsigned int i = 0, e = TRI->getNumRegs(); i != e; i++)
389       if (RegsLiveAtExit[i])
390         NewMBB->addLiveIn(i);
391   }
392 }
393
394 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
395 /// after it, replacing it with an unconditional branch to NewDest.
396 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
397                                            MachineBasicBlock *NewDest) {
398   MachineBasicBlock *CurMBB = OldInst->getParent();
399
400   TII->ReplaceTailWithBranchTo(OldInst, NewDest);
401
402   // For targets that use the register scavenger, we must maintain LiveIns.
403   MaintainLiveIns(CurMBB, NewDest);
404
405   ++NumTailMerge;
406 }
407
408 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
409 /// MBB so that the part before the iterator falls into the part starting at the
410 /// iterator.  This returns the new MBB.
411 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
412                                             MachineBasicBlock::iterator BBI1) {
413   if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
414     return 0;
415
416   MachineFunction &MF = *CurMBB.getParent();
417
418   // Create the fall-through block.
419   MachineFunction::iterator MBBI = &CurMBB;
420   MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
421   CurMBB.getParent()->insert(++MBBI, NewMBB);
422
423   // Move all the successors of this block to the specified block.
424   NewMBB->transferSuccessors(&CurMBB);
425
426   // Add an edge from CurMBB to NewMBB for the fall-through.
427   CurMBB.addSuccessor(NewMBB);
428
429   // Splice the code over.
430   NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
431
432   // For targets that use the register scavenger, we must maintain LiveIns.
433   MaintainLiveIns(&CurMBB, NewMBB);
434
435   return NewMBB;
436 }
437
438 /// EstimateRuntime - Make a rough estimate for how long it will take to run
439 /// the specified code.
440 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
441                                 MachineBasicBlock::iterator E) {
442   unsigned Time = 0;
443   for (; I != E; ++I) {
444     if (I->isDebugValue())
445       continue;
446     if (I->isCall())
447       Time += 10;
448     else if (I->mayLoad() || I->mayStore())
449       Time += 2;
450     else
451       ++Time;
452   }
453   return Time;
454 }
455
456 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
457 // branches temporarily for tail merging).  In the case where CurMBB ends
458 // with a conditional branch to the next block, optimize by reversing the
459 // test and conditionally branching to SuccMBB instead.
460 static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
461                     const TargetInstrInfo *TII) {
462   MachineFunction *MF = CurMBB->getParent();
463   MachineFunction::iterator I = llvm::next(MachineFunction::iterator(CurMBB));
464   MachineBasicBlock *TBB = 0, *FBB = 0;
465   SmallVector<MachineOperand, 4> Cond;
466   DebugLoc dl;  // FIXME: this is nowhere
467   if (I != MF->end() &&
468       !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
469     MachineBasicBlock *NextBB = I;
470     if (TBB == NextBB && !Cond.empty() && !FBB) {
471       if (!TII->ReverseBranchCondition(Cond)) {
472         TII->RemoveBranch(*CurMBB);
473         TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond, dl);
474         return;
475       }
476     }
477   }
478   TII->InsertBranch(*CurMBB, SuccBB, NULL,
479                     SmallVector<MachineOperand, 0>(), dl);
480 }
481
482 bool
483 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
484   if (getHash() < o.getHash())
485     return true;
486    else if (getHash() > o.getHash())
487     return false;
488   else if (getBlock()->getNumber() < o.getBlock()->getNumber())
489     return true;
490   else if (getBlock()->getNumber() > o.getBlock()->getNumber())
491     return false;
492   else {
493     // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
494     // an object with itself.
495 #ifndef _GLIBCXX_DEBUG
496     llvm_unreachable("Predecessor appears twice");
497 #else
498     return false;
499 #endif
500   }
501 }
502
503 /// CountTerminators - Count the number of terminators in the given
504 /// block and set I to the position of the first non-terminator, if there
505 /// is one, or MBB->end() otherwise.
506 static unsigned CountTerminators(MachineBasicBlock *MBB,
507                                  MachineBasicBlock::iterator &I) {
508   I = MBB->end();
509   unsigned NumTerms = 0;
510   for (;;) {
511     if (I == MBB->begin()) {
512       I = MBB->end();
513       break;
514     }
515     --I;
516     if (!I->isTerminator()) break;
517     ++NumTerms;
518   }
519   return NumTerms;
520 }
521
522 /// ProfitableToMerge - Check if two machine basic blocks have a common tail
523 /// and decide if it would be profitable to merge those tails.  Return the
524 /// length of the common tail and iterators to the first common instruction
525 /// in each block.
526 static bool ProfitableToMerge(MachineBasicBlock *MBB1,
527                               MachineBasicBlock *MBB2,
528                               unsigned minCommonTailLength,
529                               unsigned &CommonTailLen,
530                               MachineBasicBlock::iterator &I1,
531                               MachineBasicBlock::iterator &I2,
532                               MachineBasicBlock *SuccBB,
533                               MachineBasicBlock *PredBB) {
534   CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
535   if (CommonTailLen == 0)
536     return false;
537   DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
538                << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
539                << '\n');
540
541   // It's almost always profitable to merge any number of non-terminator
542   // instructions with the block that falls through into the common successor.
543   if (MBB1 == PredBB || MBB2 == PredBB) {
544     MachineBasicBlock::iterator I;
545     unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
546     if (CommonTailLen > NumTerms)
547       return true;
548   }
549
550   // If one of the blocks can be completely merged and happens to be in
551   // a position where the other could fall through into it, merge any number
552   // of instructions, because it can be done without a branch.
553   // TODO: If the blocks are not adjacent, move one of them so that they are?
554   if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
555     return true;
556   if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
557     return true;
558
559   // If both blocks have an unconditional branch temporarily stripped out,
560   // count that as an additional common instruction for the following
561   // heuristics.
562   unsigned EffectiveTailLen = CommonTailLen;
563   if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
564       !MBB1->back().isBarrier() &&
565       !MBB2->back().isBarrier())
566     ++EffectiveTailLen;
567
568   // Check if the common tail is long enough to be worthwhile.
569   if (EffectiveTailLen >= minCommonTailLength)
570     return true;
571
572   // If we are optimizing for code size, 2 instructions in common is enough if
573   // we don't have to split a block.  At worst we will be introducing 1 new
574   // branch instruction, which is likely to be smaller than the 2
575   // instructions that would be deleted in the merge.
576   MachineFunction *MF = MBB1->getParent();
577   if (EffectiveTailLen >= 2 &&
578       MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize) &&
579       (I1 == MBB1->begin() || I2 == MBB2->begin()))
580     return true;
581
582   return false;
583 }
584
585 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
586 /// hash CurHash (guaranteed to match the last element).  Build the vector
587 /// SameTails of all those that have the (same) largest number of instructions
588 /// in common of any pair of these blocks.  SameTails entries contain an
589 /// iterator into MergePotentials (from which the MachineBasicBlock can be
590 /// found) and a MachineBasicBlock::iterator into that MBB indicating the
591 /// instruction where the matching code sequence begins.
592 /// Order of elements in SameTails is the reverse of the order in which
593 /// those blocks appear in MergePotentials (where they are not necessarily
594 /// consecutive).
595 unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
596                                         unsigned minCommonTailLength,
597                                         MachineBasicBlock *SuccBB,
598                                         MachineBasicBlock *PredBB) {
599   unsigned maxCommonTailLength = 0U;
600   SameTails.clear();
601   MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
602   MPIterator HighestMPIter = prior(MergePotentials.end());
603   for (MPIterator CurMPIter = prior(MergePotentials.end()),
604                   B = MergePotentials.begin();
605        CurMPIter != B && CurMPIter->getHash() == CurHash;
606        --CurMPIter) {
607     for (MPIterator I = prior(CurMPIter); I->getHash() == CurHash ; --I) {
608       unsigned CommonTailLen;
609       if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
610                             minCommonTailLength,
611                             CommonTailLen, TrialBBI1, TrialBBI2,
612                             SuccBB, PredBB)) {
613         if (CommonTailLen > maxCommonTailLength) {
614           SameTails.clear();
615           maxCommonTailLength = CommonTailLen;
616           HighestMPIter = CurMPIter;
617           SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
618         }
619         if (HighestMPIter == CurMPIter &&
620             CommonTailLen == maxCommonTailLength)
621           SameTails.push_back(SameTailElt(I, TrialBBI2));
622       }
623       if (I == B)
624         break;
625     }
626   }
627   return maxCommonTailLength;
628 }
629
630 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
631 /// MergePotentials, restoring branches at ends of blocks as appropriate.
632 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
633                                         MachineBasicBlock *SuccBB,
634                                         MachineBasicBlock *PredBB) {
635   MPIterator CurMPIter, B;
636   for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
637        CurMPIter->getHash() == CurHash;
638        --CurMPIter) {
639     // Put the unconditional branch back, if we need one.
640     MachineBasicBlock *CurMBB = CurMPIter->getBlock();
641     if (SuccBB && CurMBB != PredBB)
642       FixTail(CurMBB, SuccBB, TII);
643     if (CurMPIter == B)
644       break;
645   }
646   if (CurMPIter->getHash() != CurHash)
647     CurMPIter++;
648   MergePotentials.erase(CurMPIter, MergePotentials.end());
649 }
650
651 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
652 /// only of the common tail.  Create a block that does by splitting one.
653 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
654                                              unsigned maxCommonTailLength,
655                                              unsigned &commonTailIndex) {
656   commonTailIndex = 0;
657   unsigned TimeEstimate = ~0U;
658   for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
659     // Use PredBB if possible; that doesn't require a new branch.
660     if (SameTails[i].getBlock() == PredBB) {
661       commonTailIndex = i;
662       break;
663     }
664     // Otherwise, make a (fairly bogus) choice based on estimate of
665     // how long it will take the various blocks to execute.
666     unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
667                                  SameTails[i].getTailStartPos());
668     if (t <= TimeEstimate) {
669       TimeEstimate = t;
670       commonTailIndex = i;
671     }
672   }
673
674   MachineBasicBlock::iterator BBI =
675     SameTails[commonTailIndex].getTailStartPos();
676   MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
677
678   // If the common tail includes any debug info we will take it pretty
679   // randomly from one of the inputs.  Might be better to remove it?
680   DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
681                << maxCommonTailLength);
682
683   MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
684   if (!newMBB) {
685     DEBUG(dbgs() << "... failed!");
686     return false;
687   }
688
689   SameTails[commonTailIndex].setBlock(newMBB);
690   SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
691
692   // If we split PredBB, newMBB is the new predecessor.
693   if (PredBB == MBB)
694     PredBB = newMBB;
695
696   return true;
697 }
698
699 // See if any of the blocks in MergePotentials (which all have a common single
700 // successor, or all have no successor) can be tail-merged.  If there is a
701 // successor, any blocks in MergePotentials that are not tail-merged and
702 // are not immediately before Succ must have an unconditional branch to
703 // Succ added (but the predecessor/successor lists need no adjustment).
704 // The lone predecessor of Succ that falls through into Succ,
705 // if any, is given in PredBB.
706
707 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
708                                       MachineBasicBlock *PredBB) {
709   bool MadeChange = false;
710
711   // Except for the special cases below, tail-merge if there are at least
712   // this many instructions in common.
713   unsigned minCommonTailLength = TailMergeSize;
714
715   DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
716         for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
717           dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
718                  << (i == e-1 ? "" : ", ");
719         dbgs() << "\n";
720         if (SuccBB) {
721           dbgs() << "  with successor BB#" << SuccBB->getNumber() << '\n';
722           if (PredBB)
723             dbgs() << "  which has fall-through from BB#"
724                    << PredBB->getNumber() << "\n";
725         }
726         dbgs() << "Looking for common tails of at least "
727                << minCommonTailLength << " instruction"
728                << (minCommonTailLength == 1 ? "" : "s") << '\n';
729        );
730
731   // Sort by hash value so that blocks with identical end sequences sort
732   // together.
733   std::stable_sort(MergePotentials.begin(), MergePotentials.end());
734
735   // Walk through equivalence sets looking for actual exact matches.
736   while (MergePotentials.size() > 1) {
737     unsigned CurHash = MergePotentials.back().getHash();
738
739     // Build SameTails, identifying the set of blocks with this hash code
740     // and with the maximum number of instructions in common.
741     unsigned maxCommonTailLength = ComputeSameTails(CurHash,
742                                                     minCommonTailLength,
743                                                     SuccBB, PredBB);
744
745     // If we didn't find any pair that has at least minCommonTailLength
746     // instructions in common, remove all blocks with this hash code and retry.
747     if (SameTails.empty()) {
748       RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
749       continue;
750     }
751
752     // If one of the blocks is the entire common tail (and not the entry
753     // block, which we can't jump to), we can treat all blocks with this same
754     // tail at once.  Use PredBB if that is one of the possibilities, as that
755     // will not introduce any extra branches.
756     MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
757                                  getParent()->begin();
758     unsigned commonTailIndex = SameTails.size();
759     // If there are two blocks, check to see if one can be made to fall through
760     // into the other.
761     if (SameTails.size() == 2 &&
762         SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
763         SameTails[1].tailIsWholeBlock())
764       commonTailIndex = 1;
765     else if (SameTails.size() == 2 &&
766              SameTails[1].getBlock()->isLayoutSuccessor(
767                                                      SameTails[0].getBlock()) &&
768              SameTails[0].tailIsWholeBlock())
769       commonTailIndex = 0;
770     else {
771       // Otherwise just pick one, favoring the fall-through predecessor if
772       // there is one.
773       for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
774         MachineBasicBlock *MBB = SameTails[i].getBlock();
775         if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
776           continue;
777         if (MBB == PredBB) {
778           commonTailIndex = i;
779           break;
780         }
781         if (SameTails[i].tailIsWholeBlock())
782           commonTailIndex = i;
783       }
784     }
785
786     if (commonTailIndex == SameTails.size() ||
787         (SameTails[commonTailIndex].getBlock() == PredBB &&
788          !SameTails[commonTailIndex].tailIsWholeBlock())) {
789       // None of the blocks consist entirely of the common tail.
790       // Split a block so that one does.
791       if (!CreateCommonTailOnlyBlock(PredBB,
792                                      maxCommonTailLength, commonTailIndex)) {
793         RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
794         continue;
795       }
796     }
797
798     MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
799     // MBB is common tail.  Adjust all other BB's to jump to this one.
800     // Traversal must be forwards so erases work.
801     DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
802                  << " for ");
803     for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
804       if (commonTailIndex == i)
805         continue;
806       DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
807                    << (i == e-1 ? "" : ", "));
808       // Hack the end off BB i, making it jump to BB commonTailIndex instead.
809       ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
810       // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
811       MergePotentials.erase(SameTails[i].getMPIter());
812     }
813     DEBUG(dbgs() << "\n");
814     // We leave commonTailIndex in the worklist in case there are other blocks
815     // that match it with a smaller number of instructions.
816     MadeChange = true;
817   }
818   return MadeChange;
819 }
820
821 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
822   bool MadeChange = false;
823   if (!EnableTailMerge) return MadeChange;
824
825   // First find blocks with no successors.
826   MergePotentials.clear();
827   for (MachineFunction::iterator I = MF.begin(), E = MF.end();
828        I != E && MergePotentials.size() < TailMergeThreshold; ++I) {
829     if (TriedMerging.count(I))
830       continue;
831     if (I->succ_empty())
832       MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I));
833   }
834
835   // If this is a large problem, avoid visiting the same basic blocks
836   // multiple times.
837   if (MergePotentials.size() == TailMergeThreshold)
838     for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
839       TriedMerging.insert(MergePotentials[i].getBlock());
840
841   // See if we can do any tail merging on those.
842   if (MergePotentials.size() >= 2)
843     MadeChange |= TryTailMergeBlocks(NULL, NULL);
844
845   // Look at blocks (IBB) with multiple predecessors (PBB).
846   // We change each predecessor to a canonical form, by
847   // (1) temporarily removing any unconditional branch from the predecessor
848   // to IBB, and
849   // (2) alter conditional branches so they branch to the other block
850   // not IBB; this may require adding back an unconditional branch to IBB
851   // later, where there wasn't one coming in.  E.g.
852   //   Bcc IBB
853   //   fallthrough to QBB
854   // here becomes
855   //   Bncc QBB
856   // with a conceptual B to IBB after that, which never actually exists.
857   // With those changes, we see whether the predecessors' tails match,
858   // and merge them if so.  We change things out of canonical form and
859   // back to the way they were later in the process.  (OptimizeBranches
860   // would undo some of this, but we can't use it, because we'd get into
861   // a compile-time infinite loop repeatedly doing and undoing the same
862   // transformations.)
863
864   for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
865        I != E; ++I) {
866     if (I->pred_size() < 2) continue;
867     SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
868     MachineBasicBlock *IBB = I;
869     MachineBasicBlock *PredBB = prior(I);
870     MergePotentials.clear();
871     for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
872            E2 = I->pred_end();
873          P != E2 && MergePotentials.size() < TailMergeThreshold; ++P) {
874       MachineBasicBlock *PBB = *P;
875       if (TriedMerging.count(PBB))
876         continue;
877
878       // Skip blocks that loop to themselves, can't tail merge these.
879       if (PBB == IBB)
880         continue;
881
882       // Visit each predecessor only once.
883       if (!UniquePreds.insert(PBB))
884         continue;
885
886       // Skip blocks which may jump to a landing pad. Can't tail merge these.
887       if (PBB->getLandingPadSuccessor())
888         continue;
889
890       MachineBasicBlock *TBB = 0, *FBB = 0;
891       SmallVector<MachineOperand, 4> Cond;
892       if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
893         // Failing case: IBB is the target of a cbr, and we cannot reverse the
894         // branch.
895         SmallVector<MachineOperand, 4> NewCond(Cond);
896         if (!Cond.empty() && TBB == IBB) {
897           if (TII->ReverseBranchCondition(NewCond))
898             continue;
899           // This is the QBB case described above
900           if (!FBB)
901             FBB = llvm::next(MachineFunction::iterator(PBB));
902         }
903
904         // Failing case: the only way IBB can be reached from PBB is via
905         // exception handling.  Happens for landing pads.  Would be nice to have
906         // a bit in the edge so we didn't have to do all this.
907         if (IBB->isLandingPad()) {
908           MachineFunction::iterator IP = PBB;  IP++;
909           MachineBasicBlock *PredNextBB = NULL;
910           if (IP != MF.end())
911             PredNextBB = IP;
912           if (TBB == NULL) {
913             if (IBB != PredNextBB)      // fallthrough
914               continue;
915           } else if (FBB) {
916             if (TBB != IBB && FBB != IBB)   // cbr then ubr
917               continue;
918           } else if (Cond.empty()) {
919             if (TBB != IBB)               // ubr
920               continue;
921           } else {
922             if (TBB != IBB && IBB != PredNextBB)  // cbr
923               continue;
924           }
925         }
926
927         // Remove the unconditional branch at the end, if any.
928         if (TBB && (Cond.empty() || FBB)) {
929           DebugLoc dl;  // FIXME: this is nowhere
930           TII->RemoveBranch(*PBB);
931           if (!Cond.empty())
932             // reinsert conditional branch only, for now
933             TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, 0, NewCond, dl);
934         }
935
936         MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB), *P));
937       }
938     }
939
940     // If this is a large problem, avoid visiting the same basic blocks multiple
941     // times.
942     if (MergePotentials.size() == TailMergeThreshold)
943       for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
944         TriedMerging.insert(MergePotentials[i].getBlock());
945
946     if (MergePotentials.size() >= 2)
947       MadeChange |= TryTailMergeBlocks(IBB, PredBB);
948
949     // Reinsert an unconditional branch if needed. The 1 below can occur as a
950     // result of removing blocks in TryTailMergeBlocks.
951     PredBB = prior(I);     // this may have been changed in TryTailMergeBlocks
952     if (MergePotentials.size() == 1 &&
953         MergePotentials.begin()->getBlock() != PredBB)
954       FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
955   }
956
957   return MadeChange;
958 }
959
960 //===----------------------------------------------------------------------===//
961 //  Branch Optimization
962 //===----------------------------------------------------------------------===//
963
964 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
965   bool MadeChange = false;
966
967   // Make sure blocks are numbered in order
968   MF.RenumberBlocks();
969
970   for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
971        I != E; ) {
972     MachineBasicBlock *MBB = I++;
973     MadeChange |= OptimizeBlock(MBB);
974
975     // If it is dead, remove it.
976     if (MBB->pred_empty()) {
977       RemoveDeadBlock(MBB);
978       MadeChange = true;
979       ++NumDeadBlocks;
980     }
981   }
982   return MadeChange;
983 }
984
985 // Blocks should be considered empty if they contain only debug info;
986 // else the debug info would affect codegen.
987 static bool IsEmptyBlock(MachineBasicBlock *MBB) {
988   if (MBB->empty())
989     return true;
990   for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
991        MBBI!=MBBE; ++MBBI) {
992     if (!MBBI->isDebugValue())
993       return false;
994   }
995   return true;
996 }
997
998 // Blocks with only debug info and branches should be considered the same
999 // as blocks with only branches.
1000 static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
1001   MachineBasicBlock::iterator MBBI, MBBE;
1002   for (MBBI = MBB->begin(), MBBE = MBB->end(); MBBI!=MBBE; ++MBBI) {
1003     if (!MBBI->isDebugValue())
1004       break;
1005   }
1006   return (MBBI->isBranch());
1007 }
1008
1009 /// IsBetterFallthrough - Return true if it would be clearly better to
1010 /// fall-through to MBB1 than to fall through into MBB2.  This has to return
1011 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1012 /// result in infinite loops.
1013 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
1014                                 MachineBasicBlock *MBB2) {
1015   // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
1016   // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
1017   // optimize branches that branch to either a return block or an assert block
1018   // into a fallthrough to the return.
1019   if (IsEmptyBlock(MBB1) || IsEmptyBlock(MBB2)) return false;
1020
1021   // If there is a clear successor ordering we make sure that one block
1022   // will fall through to the next
1023   if (MBB1->isSuccessor(MBB2)) return true;
1024   if (MBB2->isSuccessor(MBB1)) return false;
1025
1026   // Neither block consists entirely of debug info (per IsEmptyBlock check),
1027   // so we needn't test for falling off the beginning here.
1028   MachineBasicBlock::iterator MBB1I = --MBB1->end();
1029   while (MBB1I->isDebugValue())
1030     --MBB1I;
1031   MachineBasicBlock::iterator MBB2I = --MBB2->end();
1032   while (MBB2I->isDebugValue())
1033     --MBB2I;
1034   return MBB2I->isCall() && !MBB1I->isCall();
1035 }
1036
1037 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1038 /// instructions on the block. Always use the DebugLoc of the first
1039 /// branching instruction found unless its absent, in which case use the
1040 /// DebugLoc of the second if present.
1041 static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
1042   MachineBasicBlock::iterator I = MBB.end();
1043   if (I == MBB.begin())
1044     return DebugLoc();
1045   --I;
1046   while (I->isDebugValue() && I != MBB.begin())
1047     --I;
1048   if (I->isBranch())
1049     return I->getDebugLoc();
1050   return DebugLoc();
1051 }
1052
1053 /// OptimizeBlock - Analyze and optimize control flow related to the specified
1054 /// block.  This is never called on the entry block.
1055 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1056   bool MadeChange = false;
1057   MachineFunction &MF = *MBB->getParent();
1058 ReoptimizeBlock:
1059
1060   MachineFunction::iterator FallThrough = MBB;
1061   ++FallThrough;
1062
1063   // If this block is empty, make everyone use its fall-through, not the block
1064   // explicitly.  Landing pads should not do this since the landing-pad table
1065   // points to this block.  Blocks with their addresses taken shouldn't be
1066   // optimized away.
1067   if (IsEmptyBlock(MBB) && !MBB->isLandingPad() && !MBB->hasAddressTaken()) {
1068     // Dead block?  Leave for cleanup later.
1069     if (MBB->pred_empty()) return MadeChange;
1070
1071     if (FallThrough == MF.end()) {
1072       // TODO: Simplify preds to not branch here if possible!
1073     } else {
1074       // Rewrite all predecessors of the old block to go to the fallthrough
1075       // instead.
1076       while (!MBB->pred_empty()) {
1077         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1078         Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
1079       }
1080       // If MBB was the target of a jump table, update jump tables to go to the
1081       // fallthrough instead.
1082       if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1083         MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
1084       MadeChange = true;
1085     }
1086     return MadeChange;
1087   }
1088
1089   // Check to see if we can simplify the terminator of the block before this
1090   // one.
1091   MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
1092
1093   MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
1094   SmallVector<MachineOperand, 4> PriorCond;
1095   bool PriorUnAnalyzable =
1096     TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1097   if (!PriorUnAnalyzable) {
1098     // If the CFG for the prior block has extra edges, remove them.
1099     MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1100                                               !PriorCond.empty());
1101
1102     // If the previous branch is conditional and both conditions go to the same
1103     // destination, remove the branch, replacing it with an unconditional one or
1104     // a fall-through.
1105     if (PriorTBB && PriorTBB == PriorFBB) {
1106       DebugLoc dl = getBranchDebugLoc(PrevBB);
1107       TII->RemoveBranch(PrevBB);
1108       PriorCond.clear();
1109       if (PriorTBB != MBB)
1110         TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond, dl);
1111       MadeChange = true;
1112       ++NumBranchOpts;
1113       goto ReoptimizeBlock;
1114     }
1115
1116     // If the previous block unconditionally falls through to this block and
1117     // this block has no other predecessors, move the contents of this block
1118     // into the prior block. This doesn't usually happen when SimplifyCFG
1119     // has been used, but it can happen if tail merging splits a fall-through
1120     // predecessor of a block.
1121     // This has to check PrevBB->succ_size() because EH edges are ignored by
1122     // AnalyzeBranch.
1123     if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1124         PrevBB.succ_size() == 1 &&
1125         !MBB->hasAddressTaken() && !MBB->isLandingPad()) {
1126       DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1127                    << "From MBB: " << *MBB);
1128       // Remove redundant DBG_VALUEs first.
1129       if (PrevBB.begin() != PrevBB.end()) {
1130         MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1131         --PrevBBIter;
1132         MachineBasicBlock::iterator MBBIter = MBB->begin();
1133         // Check if DBG_VALUE at the end of PrevBB is identical to the
1134         // DBG_VALUE at the beginning of MBB.
1135         while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1136                && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1137           if (!MBBIter->isIdenticalTo(PrevBBIter))
1138             break;
1139           MachineInstr *DuplicateDbg = MBBIter;
1140           ++MBBIter; -- PrevBBIter;
1141           DuplicateDbg->eraseFromParent();
1142         }
1143       }
1144       PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1145       PrevBB.removeSuccessor(PrevBB.succ_begin());
1146       assert(PrevBB.succ_empty());
1147       PrevBB.transferSuccessors(MBB);
1148       MadeChange = true;
1149       return MadeChange;
1150     }
1151
1152     // If the previous branch *only* branches to *this* block (conditional or
1153     // not) remove the branch.
1154     if (PriorTBB == MBB && PriorFBB == 0) {
1155       TII->RemoveBranch(PrevBB);
1156       MadeChange = true;
1157       ++NumBranchOpts;
1158       goto ReoptimizeBlock;
1159     }
1160
1161     // If the prior block branches somewhere else on the condition and here if
1162     // the condition is false, remove the uncond second branch.
1163     if (PriorFBB == MBB) {
1164       DebugLoc dl = getBranchDebugLoc(PrevBB);
1165       TII->RemoveBranch(PrevBB);
1166       TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond, dl);
1167       MadeChange = true;
1168       ++NumBranchOpts;
1169       goto ReoptimizeBlock;
1170     }
1171
1172     // If the prior block branches here on true and somewhere else on false, and
1173     // if the branch condition is reversible, reverse the branch to create a
1174     // fall-through.
1175     if (PriorTBB == MBB) {
1176       SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1177       if (!TII->ReverseBranchCondition(NewPriorCond)) {
1178         DebugLoc dl = getBranchDebugLoc(PrevBB);
1179         TII->RemoveBranch(PrevBB);
1180         TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond, dl);
1181         MadeChange = true;
1182         ++NumBranchOpts;
1183         goto ReoptimizeBlock;
1184       }
1185     }
1186
1187     // If this block has no successors (e.g. it is a return block or ends with
1188     // a call to a no-return function like abort or __cxa_throw) and if the pred
1189     // falls through into this block, and if it would otherwise fall through
1190     // into the block after this, move this block to the end of the function.
1191     //
1192     // We consider it more likely that execution will stay in the function (e.g.
1193     // due to loops) than it is to exit it.  This asserts in loops etc, moving
1194     // the assert condition out of the loop body.
1195     if (MBB->succ_empty() && !PriorCond.empty() && PriorFBB == 0 &&
1196         MachineFunction::iterator(PriorTBB) == FallThrough &&
1197         !MBB->canFallThrough()) {
1198       bool DoTransform = true;
1199
1200       // We have to be careful that the succs of PredBB aren't both no-successor
1201       // blocks.  If neither have successors and if PredBB is the second from
1202       // last block in the function, we'd just keep swapping the two blocks for
1203       // last.  Only do the swap if one is clearly better to fall through than
1204       // the other.
1205       if (FallThrough == --MF.end() &&
1206           !IsBetterFallthrough(PriorTBB, MBB))
1207         DoTransform = false;
1208
1209       if (DoTransform) {
1210         // Reverse the branch so we will fall through on the previous true cond.
1211         SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1212         if (!TII->ReverseBranchCondition(NewPriorCond)) {
1213           DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1214                        << "To make fallthrough to: " << *PriorTBB << "\n");
1215
1216           DebugLoc dl = getBranchDebugLoc(PrevBB);
1217           TII->RemoveBranch(PrevBB);
1218           TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond, dl);
1219
1220           // Move this block to the end of the function.
1221           MBB->moveAfter(--MF.end());
1222           MadeChange = true;
1223           ++NumBranchOpts;
1224           return MadeChange;
1225         }
1226       }
1227     }
1228   }
1229
1230   // Analyze the branch in the current block.
1231   MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
1232   SmallVector<MachineOperand, 4> CurCond;
1233   bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1234   if (!CurUnAnalyzable) {
1235     // If the CFG for the prior block has extra edges, remove them.
1236     MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1237
1238     // If this is a two-way branch, and the FBB branches to this block, reverse
1239     // the condition so the single-basic-block loop is faster.  Instead of:
1240     //    Loop: xxx; jcc Out; jmp Loop
1241     // we want:
1242     //    Loop: xxx; jncc Loop; jmp Out
1243     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1244       SmallVector<MachineOperand, 4> NewCond(CurCond);
1245       if (!TII->ReverseBranchCondition(NewCond)) {
1246         DebugLoc dl = getBranchDebugLoc(*MBB);
1247         TII->RemoveBranch(*MBB);
1248         TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
1249         MadeChange = true;
1250         ++NumBranchOpts;
1251         goto ReoptimizeBlock;
1252       }
1253     }
1254
1255     // If this branch is the only thing in its block, see if we can forward
1256     // other blocks across it.
1257     if (CurTBB && CurCond.empty() && CurFBB == 0 &&
1258         IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1259         !MBB->hasAddressTaken()) {
1260       DebugLoc dl = getBranchDebugLoc(*MBB);
1261       // This block may contain just an unconditional branch.  Because there can
1262       // be 'non-branch terminators' in the block, try removing the branch and
1263       // then seeing if the block is empty.
1264       TII->RemoveBranch(*MBB);
1265       // If the only things remaining in the block are debug info, remove these
1266       // as well, so this will behave the same as an empty block in non-debug
1267       // mode.
1268       if (!MBB->empty()) {
1269         bool NonDebugInfoFound = false;
1270         for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
1271              I != E; ++I) {
1272           if (!I->isDebugValue()) {
1273             NonDebugInfoFound = true;
1274             break;
1275           }
1276         }
1277         if (!NonDebugInfoFound)
1278           // Make the block empty, losing the debug info (we could probably
1279           // improve this in some cases.)
1280           MBB->erase(MBB->begin(), MBB->end());
1281       }
1282       // If this block is just an unconditional branch to CurTBB, we can
1283       // usually completely eliminate the block.  The only case we cannot
1284       // completely eliminate the block is when the block before this one
1285       // falls through into MBB and we can't understand the prior block's branch
1286       // condition.
1287       if (MBB->empty()) {
1288         bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1289         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1290             !PrevBB.isSuccessor(MBB)) {
1291           // If the prior block falls through into us, turn it into an
1292           // explicit branch to us to make updates simpler.
1293           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1294               PriorTBB != MBB && PriorFBB != MBB) {
1295             if (PriorTBB == 0) {
1296               assert(PriorCond.empty() && PriorFBB == 0 &&
1297                      "Bad branch analysis");
1298               PriorTBB = MBB;
1299             } else {
1300               assert(PriorFBB == 0 && "Machine CFG out of date!");
1301               PriorFBB = MBB;
1302             }
1303             DebugLoc pdl = getBranchDebugLoc(PrevBB);
1304             TII->RemoveBranch(PrevBB);
1305             TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1306           }
1307
1308           // Iterate through all the predecessors, revectoring each in-turn.
1309           size_t PI = 0;
1310           bool DidChange = false;
1311           bool HasBranchToSelf = false;
1312           while(PI != MBB->pred_size()) {
1313             MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1314             if (PMBB == MBB) {
1315               // If this block has an uncond branch to itself, leave it.
1316               ++PI;
1317               HasBranchToSelf = true;
1318             } else {
1319               DidChange = true;
1320               PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1321               // If this change resulted in PMBB ending in a conditional
1322               // branch where both conditions go to the same destination,
1323               // change this to an unconditional branch (and fix the CFG).
1324               MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
1325               SmallVector<MachineOperand, 4> NewCurCond;
1326               bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1327                       NewCurFBB, NewCurCond, true);
1328               if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1329                 DebugLoc pdl = getBranchDebugLoc(*PMBB);
1330                 TII->RemoveBranch(*PMBB);
1331                 NewCurCond.clear();
1332                 TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond, pdl);
1333                 MadeChange = true;
1334                 ++NumBranchOpts;
1335                 PMBB->CorrectExtraCFGEdges(NewCurTBB, 0, false);
1336               }
1337             }
1338           }
1339
1340           // Change any jumptables to go to the new MBB.
1341           if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1342             MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1343           if (DidChange) {
1344             ++NumBranchOpts;
1345             MadeChange = true;
1346             if (!HasBranchToSelf) return MadeChange;
1347           }
1348         }
1349       }
1350
1351       // Add the branch back if the block is more than just an uncond branch.
1352       TII->InsertBranch(*MBB, CurTBB, 0, CurCond, dl);
1353     }
1354   }
1355
1356   // If the prior block doesn't fall through into this block, and if this
1357   // block doesn't fall through into some other block, see if we can find a
1358   // place to move this block where a fall-through will happen.
1359   if (!PrevBB.canFallThrough()) {
1360
1361     // Now we know that there was no fall-through into this block, check to
1362     // see if it has a fall-through into its successor.
1363     bool CurFallsThru = MBB->canFallThrough();
1364
1365     if (!MBB->isLandingPad()) {
1366       // Check all the predecessors of this block.  If one of them has no fall
1367       // throughs, move this block right after it.
1368       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1369            E = MBB->pred_end(); PI != E; ++PI) {
1370         // Analyze the branch at the end of the pred.
1371         MachineBasicBlock *PredBB = *PI;
1372         MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1373         MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
1374         SmallVector<MachineOperand, 4> PredCond;
1375         if (PredBB != MBB && !PredBB->canFallThrough() &&
1376             !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)
1377             && (!CurFallsThru || !CurTBB || !CurFBB)
1378             && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1379           // If the current block doesn't fall through, just move it.
1380           // If the current block can fall through and does not end with a
1381           // conditional branch, we need to append an unconditional jump to
1382           // the (current) next block.  To avoid a possible compile-time
1383           // infinite loop, move blocks only backward in this case.
1384           // Also, if there are already 2 branches here, we cannot add a third;
1385           // this means we have the case
1386           // Bcc next
1387           // B elsewhere
1388           // next:
1389           if (CurFallsThru) {
1390             MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1391             CurCond.clear();
1392             TII->InsertBranch(*MBB, NextBB, 0, CurCond, DebugLoc());
1393           }
1394           MBB->moveAfter(PredBB);
1395           MadeChange = true;
1396           goto ReoptimizeBlock;
1397         }
1398       }
1399     }
1400
1401     if (!CurFallsThru) {
1402       // Check all successors to see if we can move this block before it.
1403       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1404            E = MBB->succ_end(); SI != E; ++SI) {
1405         // Analyze the branch at the end of the block before the succ.
1406         MachineBasicBlock *SuccBB = *SI;
1407         MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1408
1409         // If this block doesn't already fall-through to that successor, and if
1410         // the succ doesn't already have a block that can fall through into it,
1411         // and if the successor isn't an EH destination, we can arrange for the
1412         // fallthrough to happen.
1413         if (SuccBB != MBB && &*SuccPrev != MBB &&
1414             !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1415             !SuccBB->isLandingPad()) {
1416           MBB->moveBefore(SuccBB);
1417           MadeChange = true;
1418           goto ReoptimizeBlock;
1419         }
1420       }
1421
1422       // Okay, there is no really great place to put this block.  If, however,
1423       // the block before this one would be a fall-through if this block were
1424       // removed, move this block to the end of the function.
1425       MachineBasicBlock *PrevTBB = 0, *PrevFBB = 0;
1426       SmallVector<MachineOperand, 4> PrevCond;
1427       if (FallThrough != MF.end() &&
1428           !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
1429           PrevBB.isSuccessor(FallThrough)) {
1430         MBB->moveAfter(--MF.end());
1431         MadeChange = true;
1432         return MadeChange;
1433       }
1434     }
1435   }
1436
1437   return MadeChange;
1438 }
1439
1440 //===----------------------------------------------------------------------===//
1441 //  Hoist Common Code
1442 //===----------------------------------------------------------------------===//
1443
1444 /// HoistCommonCode - Hoist common instruction sequences at the start of basic
1445 /// blocks to their common predecessor.
1446 bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1447   bool MadeChange = false;
1448   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
1449     MachineBasicBlock *MBB = I++;
1450     MadeChange |= HoistCommonCodeInSuccs(MBB);
1451   }
1452
1453   return MadeChange;
1454 }
1455
1456 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1457 /// its 'true' successor.
1458 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1459                                          MachineBasicBlock *TrueBB) {
1460   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1461          E = BB->succ_end(); SI != E; ++SI) {
1462     MachineBasicBlock *SuccBB = *SI;
1463     if (SuccBB != TrueBB)
1464       return SuccBB;
1465   }
1466   return NULL;
1467 }
1468
1469 /// findHoistingInsertPosAndDeps - Find the location to move common instructions
1470 /// in successors to. The location is ususally just before the terminator,
1471 /// however if the terminator is a conditional branch and its previous
1472 /// instruction is the flag setting instruction, the previous instruction is
1473 /// the preferred location. This function also gathers uses and defs of the
1474 /// instructions from the insertion point to the end of the block. The data is
1475 /// used by HoistCommonCodeInSuccs to ensure safety.
1476 static
1477 MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1478                                                   const TargetInstrInfo *TII,
1479                                                   const TargetRegisterInfo *TRI,
1480                                                   SmallSet<unsigned,4> &Uses,
1481                                                   SmallSet<unsigned,4> &Defs) {
1482   MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1483   if (!TII->isUnpredicatedTerminator(Loc))
1484     return MBB->end();
1485
1486   for (unsigned i = 0, e = Loc->getNumOperands(); i != e; ++i) {
1487     const MachineOperand &MO = Loc->getOperand(i);
1488     if (!MO.isReg())
1489       continue;
1490     unsigned Reg = MO.getReg();
1491     if (!Reg)
1492       continue;
1493     if (MO.isUse()) {
1494       Uses.insert(Reg);
1495       for (const uint16_t *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1496         Uses.insert(*AS);
1497     } else if (!MO.isDead())
1498       // Don't try to hoist code in the rare case the terminator defines a
1499       // register that is later used.
1500       return MBB->end();
1501   }
1502
1503   if (Uses.empty())
1504     return Loc;
1505   if (Loc == MBB->begin())
1506     return MBB->end();
1507
1508   // The terminator is probably a conditional branch, try not to separate the
1509   // branch from condition setting instruction.
1510   MachineBasicBlock::iterator PI = Loc;
1511   --PI;
1512   while (PI != MBB->begin() && Loc->isDebugValue())
1513     --PI;
1514
1515   bool IsDef = false;
1516   for (unsigned i = 0, e = PI->getNumOperands(); !IsDef && i != e; ++i) {
1517     const MachineOperand &MO = PI->getOperand(i);
1518     // If PI has a regmask operand, it is probably a call. Separate away.
1519     if (MO.isRegMask())
1520       return Loc;
1521     if (!MO.isReg() || MO.isUse())
1522       continue;
1523     unsigned Reg = MO.getReg();
1524     if (!Reg)
1525       continue;
1526     if (Uses.count(Reg))
1527       IsDef = true;
1528   }
1529   if (!IsDef)
1530     // The condition setting instruction is not just before the conditional
1531     // branch.
1532     return Loc;
1533
1534   // Be conservative, don't insert instruction above something that may have
1535   // side-effects. And since it's potentially bad to separate flag setting
1536   // instruction from the conditional branch, just abort the optimization
1537   // completely.
1538   // Also avoid moving code above predicated instruction since it's hard to
1539   // reason about register liveness with predicated instruction.
1540   bool DontMoveAcrossStore = true;
1541   if (!PI->isSafeToMove(TII, 0, DontMoveAcrossStore) ||
1542       TII->isPredicated(PI))
1543     return MBB->end();
1544
1545
1546   // Find out what registers are live. Note this routine is ignoring other live
1547   // registers which are only used by instructions in successor blocks.
1548   for (unsigned i = 0, e = PI->getNumOperands(); i != e; ++i) {
1549     const MachineOperand &MO = PI->getOperand(i);
1550     if (!MO.isReg())
1551       continue;
1552     unsigned Reg = MO.getReg();
1553     if (!Reg)
1554       continue;
1555     if (MO.isUse()) {
1556       Uses.insert(Reg);
1557       for (const uint16_t *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1558         Uses.insert(*AS);
1559     } else {
1560       if (Uses.count(Reg)) {
1561         Uses.erase(Reg);
1562         for (const uint16_t *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1563           Uses.erase(*SR); // Use getSubRegisters to be conservative
1564       }
1565       Defs.insert(Reg);
1566       for (const uint16_t *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1567         Defs.insert(*AS);
1568     }
1569   }
1570
1571   return PI;
1572 }
1573
1574 /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
1575 /// sequence at the start of the function, move the instructions before MBB
1576 /// terminator if it's legal.
1577 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1578   MachineBasicBlock *TBB = 0, *FBB = 0;
1579   SmallVector<MachineOperand, 4> Cond;
1580   if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
1581     return false;
1582
1583   if (!FBB) FBB = findFalseBlock(MBB, TBB);
1584   if (!FBB)
1585     // Malformed bcc? True and false blocks are the same?
1586     return false;
1587
1588   // Restrict the optimization to cases where MBB is the only predecessor,
1589   // it is an obvious win.
1590   if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1591     return false;
1592
1593   // Find a suitable position to hoist the common instructions to. Also figure
1594   // out which registers are used or defined by instructions from the insertion
1595   // point to the end of the block.
1596   SmallSet<unsigned, 4> Uses, Defs;
1597   MachineBasicBlock::iterator Loc =
1598     findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1599   if (Loc == MBB->end())
1600     return false;
1601
1602   bool HasDups = false;
1603   SmallVector<unsigned, 4> LocalDefs;
1604   SmallSet<unsigned, 4> LocalDefsSet;
1605   MachineBasicBlock::iterator TIB = TBB->begin();
1606   MachineBasicBlock::iterator FIB = FBB->begin();
1607   MachineBasicBlock::iterator TIE = TBB->end();
1608   MachineBasicBlock::iterator FIE = FBB->end();
1609   while (TIB != TIE && FIB != FIE) {
1610     // Skip dbg_value instructions. These do not count.
1611     if (TIB->isDebugValue()) {
1612       while (TIB != TIE && TIB->isDebugValue())
1613         ++TIB;
1614       if (TIB == TIE)
1615         break;
1616     }
1617     if (FIB->isDebugValue()) {
1618       while (FIB != FIE && FIB->isDebugValue())
1619         ++FIB;
1620       if (FIB == FIE)
1621         break;
1622     }
1623     if (!TIB->isIdenticalTo(FIB, MachineInstr::CheckKillDead))
1624       break;
1625
1626     if (TII->isPredicated(TIB))
1627       // Hard to reason about register liveness with predicated instruction.
1628       break;
1629
1630     bool IsSafe = true;
1631     for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1632       MachineOperand &MO = TIB->getOperand(i);
1633       // Don't attempt to hoist instructions with register masks.
1634       if (MO.isRegMask()) {
1635         IsSafe = false;
1636         break;
1637       }
1638       if (!MO.isReg())
1639         continue;
1640       unsigned Reg = MO.getReg();
1641       if (!Reg)
1642         continue;
1643       if (MO.isDef()) {
1644         if (Uses.count(Reg)) {
1645           // Avoid clobbering a register that's used by the instruction at
1646           // the point of insertion.
1647           IsSafe = false;
1648           break;
1649         }
1650
1651         if (Defs.count(Reg) && !MO.isDead()) {
1652           // Don't hoist the instruction if the def would be clobber by the
1653           // instruction at the point insertion. FIXME: This is overly
1654           // conservative. It should be possible to hoist the instructions
1655           // in BB2 in the following example:
1656           // BB1:
1657           // r1, eflag = op1 r2, r3
1658           // brcc eflag
1659           //
1660           // BB2:
1661           // r1 = op2, ...
1662           //    = op3, r1<kill>
1663           IsSafe = false;
1664           break;
1665         }
1666       } else if (!LocalDefsSet.count(Reg)) {
1667         if (Defs.count(Reg)) {
1668           // Use is defined by the instruction at the point of insertion.
1669           IsSafe = false;
1670           break;
1671         }
1672
1673         if (MO.isKill() && Uses.count(Reg))
1674           // Kills a register that's read by the instruction at the point of
1675           // insertion. Remove the kill marker.
1676           MO.setIsKill(false);
1677       }
1678     }
1679     if (!IsSafe)
1680       break;
1681
1682     bool DontMoveAcrossStore = true;
1683     if (!TIB->isSafeToMove(TII, 0, DontMoveAcrossStore))
1684       break;
1685
1686     // Remove kills from LocalDefsSet, these registers had short live ranges.
1687     for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1688       MachineOperand &MO = TIB->getOperand(i);
1689       if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1690         continue;
1691       unsigned Reg = MO.getReg();
1692       if (!Reg || !LocalDefsSet.count(Reg))
1693         continue;
1694       for (const uint16_t *OR = TRI->getOverlaps(Reg); *OR; ++OR)
1695         LocalDefsSet.erase(*OR);
1696     }
1697
1698     // Track local defs so we can update liveins.
1699     for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1700       MachineOperand &MO = TIB->getOperand(i);
1701       if (!MO.isReg() || !MO.isDef() || MO.isDead())
1702         continue;
1703       unsigned Reg = MO.getReg();
1704       if (!Reg)
1705         continue;
1706       LocalDefs.push_back(Reg);
1707       for (const uint16_t *OR = TRI->getOverlaps(Reg); *OR; ++OR)
1708         LocalDefsSet.insert(*OR);
1709     }
1710
1711     HasDups = true;
1712     ++TIB;
1713     ++FIB;
1714   }
1715
1716   if (!HasDups)
1717     return false;
1718
1719   MBB->splice(Loc, TBB, TBB->begin(), TIB);
1720   FBB->erase(FBB->begin(), FIB);
1721
1722   // Update livein's.
1723   for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
1724     unsigned Def = LocalDefs[i];
1725     if (LocalDefsSet.count(Def)) {
1726       TBB->addLiveIn(Def);
1727       FBB->addLiveIn(Def);
1728     }
1729   }
1730
1731   ++NumHoist;
1732   return true;
1733 }