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