blob: d8ec3406921bb7fde087f157e39c5f6a26e37d5a [file] [log] [blame]
Chris Lattner21ab22e2004-07-31 10:01:27 +00001//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner21ab22e2004-07-31 10:01:27 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner21ab22e2004-07-31 10:01:27 +00008//===----------------------------------------------------------------------===//
9//
10// This pass forwards branches to unconditional branches to make them branch
11// directly to the target block. This pass often results in dead MBB's, which
12// it then removes.
13//
14// Note that this pass must be run after register allocation, it cannot handle
15// SSA form.
16//
17//===----------------------------------------------------------------------===//
18
Chris Lattnerf10a56a2006-11-18 21:56:39 +000019#define DEBUG_TYPE "branchfolding"
Chris Lattner21ab22e2004-07-31 10:01:27 +000020#include "llvm/CodeGen/Passes.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000021#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000023#include "llvm/CodeGen/MachineJumpTableInfo.h"
Dale Johannesen69cb9b72007-03-20 21:35:06 +000024#include "llvm/CodeGen/RegisterScavenging.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000025#include "llvm/Target/TargetInstrInfo.h"
26#include "llvm/Target/TargetMachine.h"
Dale Johannesen69cb9b72007-03-20 21:35:06 +000027#include "llvm/Target/MRegisterInfo.h"
Chris Lattner12143052006-10-21 00:47:49 +000028#include "llvm/Support/CommandLine.h"
Chris Lattnerf10a56a2006-11-18 21:56:39 +000029#include "llvm/Support/Debug.h"
Chris Lattner12143052006-10-21 00:47:49 +000030#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/ADT/STLExtras.h"
Jeff Cohend41b30d2006-11-05 19:31:28 +000032#include <algorithm>
Chris Lattner21ab22e2004-07-31 10:01:27 +000033using namespace llvm;
34
Chris Lattnercd3245a2006-12-19 22:41:21 +000035STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
36STATISTIC(NumBranchOpts, "Number of branches optimized");
37STATISTIC(NumTailMerge , "Number of block tails merged");
Chris Lattnerd8ccff02006-11-01 00:38:31 +000038static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
Chris Lattner12143052006-10-21 00:47:49 +000039
Chris Lattner21ab22e2004-07-31 10:01:27 +000040namespace {
41 struct BranchFolder : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000042 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +000043 BranchFolder() : MachineFunctionPass((intptr_t)&ID) {}
44
Chris Lattner21ab22e2004-07-31 10:01:27 +000045 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner7821a8a2006-10-14 00:21:48 +000046 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
47 const TargetInstrInfo *TII;
Jim Laskey44c3b9f2007-01-26 21:22:28 +000048 MachineModuleInfo *MMI;
Chris Lattner7821a8a2006-10-14 00:21:48 +000049 bool MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +000050 private:
Chris Lattner12143052006-10-21 00:47:49 +000051 // Tail Merging.
52 bool TailMergeBlocks(MachineFunction &MF);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +000053 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
54 MachineBasicBlock* PredBB);
Chris Lattner12143052006-10-21 00:47:49 +000055 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
56 MachineBasicBlock *NewDest);
Chris Lattner1d08d832006-11-01 01:16:12 +000057 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
58 MachineBasicBlock::iterator BBI1);
Dale Johannesen69cb9b72007-03-20 21:35:06 +000059
Dale Johannesen7d33b4c2007-05-07 20:57:21 +000060 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
Dale Johannesen69cb9b72007-03-20 21:35:06 +000061 const MRegisterInfo *RegInfo;
62 RegScavenger *RS;
Chris Lattner12143052006-10-21 00:47:49 +000063 // Branch optzn.
64 bool OptimizeBranches(MachineFunction &MF);
Chris Lattner7d097842006-10-24 01:12:32 +000065 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000066 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner6b0e3f82006-10-29 21:05:41 +000067
68 bool CanFallThrough(MachineBasicBlock *CurBB);
69 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
70 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
71 const std::vector<MachineOperand> &Cond);
Chris Lattner21ab22e2004-07-31 10:01:27 +000072 };
Devang Patel19974732007-05-03 01:11:54 +000073 char BranchFolder::ID = 0;
Chris Lattner21ab22e2004-07-31 10:01:27 +000074}
75
Dale Johannesen14ba0cc2007-05-15 21:19:17 +000076static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
77 MachineBasicBlock *DestA,
78 MachineBasicBlock *DestB,
79 bool isCond,
80 MachineFunction::iterator FallThru);
81
Chris Lattner21ab22e2004-07-31 10:01:27 +000082FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
83
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000084/// RemoveDeadBlock - Remove the specified dead machine basic block from the
85/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +000086void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey033c9712007-02-22 16:39:03 +000087 assert(MBB->pred_empty() && "MBB must be dead!");
Jim Laskey02b3f5e2007-02-21 22:42:20 +000088 DOUT << "\nRemoving MBB: " << *MBB;
Chris Lattner683747a2006-10-17 23:17:27 +000089
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000090 MachineFunction *MF = MBB->getParent();
91 // drop all successors.
92 while (!MBB->succ_empty())
93 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +000094
Jim Laskey1ee29252007-01-26 14:34:52 +000095 // If there is DWARF info to active, check to see if there are any LABEL
Jim Laskey44c3b9f2007-01-26 21:22:28 +000096 // records in the basic block. If so, unregister them from MachineModuleInfo.
97 if (MMI && !MBB->empty()) {
Chris Lattner683747a2006-10-17 23:17:27 +000098 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
99 I != E; ++I) {
Jim Laskey1ee29252007-01-26 14:34:52 +0000100 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
Chris Lattner683747a2006-10-17 23:17:27 +0000101 // The label ID # is always operand #0, an immediate.
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000102 MMI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +0000103 }
104 }
105 }
106
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000107 // Remove the block.
108 MF->getBasicBlockList().erase(MBB);
109}
110
Chris Lattner21ab22e2004-07-31 10:01:27 +0000111bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000112 TII = MF.getTarget().getInstrInfo();
113 if (!TII) return false;
114
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000115 // Fix CFG. The later algorithms expect it to be right.
116 bool EverMadeChange = false;
117 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
118 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
119 std::vector<MachineOperand> Cond;
120 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
121 EverMadeChange |= CorrectExtraCFGEdges(*MBB, TBB, FBB,
122 !Cond.empty(), next(I));
123 }
124
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000125 RegInfo = MF.getTarget().getRegisterInfo();
126 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
127
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000128 MMI = getAnalysisToUpdate<MachineModuleInfo>();
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000129
Chris Lattner12143052006-10-21 00:47:49 +0000130 bool MadeChangeThisIteration = true;
131 while (MadeChangeThisIteration) {
132 MadeChangeThisIteration = false;
133 MadeChangeThisIteration |= TailMergeBlocks(MF);
134 MadeChangeThisIteration |= OptimizeBranches(MF);
135 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000136 }
137
Chris Lattner6acfe122006-10-28 18:34:47 +0000138 // See if any jump tables have become mergable or dead as the code generator
139 // did its thing.
140 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
141 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
142 if (!JTs.empty()) {
143 // Figure out how these jump tables should be merged.
144 std::vector<unsigned> JTMapping;
145 JTMapping.reserve(JTs.size());
146
147 // We always keep the 0th jump table.
148 JTMapping.push_back(0);
149
150 // Scan the jump tables, seeing if there are any duplicates. Note that this
151 // is N^2, which should be fixed someday.
152 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
153 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
154
155 // If a jump table was merge with another one, walk the function rewriting
156 // references to jump tables to reference the new JT ID's. Keep track of
157 // whether we see a jump table idx, if not, we can delete the JT.
158 std::vector<bool> JTIsLive;
159 JTIsLive.resize(JTs.size());
160 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
161 BB != E; ++BB) {
162 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
163 I != E; ++I)
164 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
165 MachineOperand &Op = I->getOperand(op);
166 if (!Op.isJumpTableIndex()) continue;
167 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
168 Op.setJumpTableIndex(NewIdx);
169
170 // Remember that this JT is live.
171 JTIsLive[NewIdx] = true;
172 }
173 }
174
175 // Finally, remove dead jump tables. This happens either because the
176 // indirect jump was unreachable (and thus deleted) or because the jump
177 // table was merged with some other one.
178 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
179 if (!JTIsLive[i]) {
180 JTI->RemoveJumpTable(i);
181 EverMadeChange = true;
182 }
183 }
184
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000185 delete RS;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000186 return EverMadeChange;
187}
188
Chris Lattner12143052006-10-21 00:47:49 +0000189//===----------------------------------------------------------------------===//
190// Tail Merging of Blocks
191//===----------------------------------------------------------------------===//
192
193/// HashMachineInstr - Compute a hash value for MI and its operands.
194static unsigned HashMachineInstr(const MachineInstr *MI) {
195 unsigned Hash = MI->getOpcode();
196 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
197 const MachineOperand &Op = MI->getOperand(i);
198
199 // Merge in bits from the operand if easy.
200 unsigned OperandHash = 0;
201 switch (Op.getType()) {
202 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
203 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
204 case MachineOperand::MO_MachineBasicBlock:
205 OperandHash = Op.getMachineBasicBlock()->getNumber();
206 break;
207 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
208 case MachineOperand::MO_ConstantPoolIndex:
209 OperandHash = Op.getConstantPoolIndex();
210 break;
211 case MachineOperand::MO_JumpTableIndex:
212 OperandHash = Op.getJumpTableIndex();
213 break;
214 case MachineOperand::MO_GlobalAddress:
215 case MachineOperand::MO_ExternalSymbol:
216 // Global address / external symbol are too hard, don't bother, but do
217 // pull in the offset.
218 OperandHash = Op.getOffset();
219 break;
220 default: break;
221 }
222
223 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
224 }
225 return Hash;
226}
227
228/// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
229/// instructions, because cross-jumping only saves code when at least two
230/// instructions are removed (since a branch must be inserted).
231static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
232 MachineBasicBlock::const_iterator I = MBB->end();
233 if (I == MBB->begin())
234 return 0; // Empty MBB.
235
236 --I;
237 unsigned Hash = HashMachineInstr(I);
238
239 if (I == MBB->begin())
240 return Hash; // Single instr MBB.
241
242 --I;
243 // Hash in the second-to-last instruction.
244 Hash ^= HashMachineInstr(I) << 2;
245 return Hash;
246}
247
248/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
249/// of instructions they actually have in common together at their end. Return
250/// iterators for the first shared instruction in each block.
251static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
252 MachineBasicBlock *MBB2,
253 MachineBasicBlock::iterator &I1,
254 MachineBasicBlock::iterator &I2) {
255 I1 = MBB1->end();
256 I2 = MBB2->end();
257
258 unsigned TailLen = 0;
259 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
260 --I1; --I2;
261 if (!I1->isIdenticalTo(I2)) {
262 ++I1; ++I2;
263 break;
264 }
265 ++TailLen;
266 }
267 return TailLen;
268}
269
270/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000271/// after it, replacing it with an unconditional branch to NewDest. This
272/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000273void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
274 MachineBasicBlock *NewDest) {
275 MachineBasicBlock *OldBB = OldInst->getParent();
276
277 // Remove all the old successors of OldBB from the CFG.
278 while (!OldBB->succ_empty())
279 OldBB->removeSuccessor(OldBB->succ_begin());
280
281 // Remove all the dead instructions from the end of OldBB.
282 OldBB->erase(OldInst, OldBB->end());
283
Chris Lattner386e2902006-10-21 05:08:28 +0000284 // If OldBB isn't immediately before OldBB, insert a branch to it.
285 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
286 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner12143052006-10-21 00:47:49 +0000287 OldBB->addSuccessor(NewDest);
288 ++NumTailMerge;
289}
290
Chris Lattner1d08d832006-11-01 01:16:12 +0000291/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
292/// MBB so that the part before the iterator falls into the part starting at the
293/// iterator. This returns the new MBB.
294MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
295 MachineBasicBlock::iterator BBI1) {
296 // Create the fall-through block.
297 MachineFunction::iterator MBBI = &CurMBB;
298 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
299 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
300
301 // Move all the successors of this block to the specified block.
302 while (!CurMBB.succ_empty()) {
303 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
304 NewMBB->addSuccessor(S);
305 CurMBB.removeSuccessor(S);
306 }
307
308 // Add an edge from CurMBB to NewMBB for the fall-through.
309 CurMBB.addSuccessor(NewMBB);
310
311 // Splice the code over.
312 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000313
314 // For targets that use the register scavenger, we must maintain LiveIns.
315 if (RS) {
316 RS->enterBasicBlock(&CurMBB);
317 if (!CurMBB.empty())
318 RS->forward(prior(CurMBB.end()));
319 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
320 RS->getRegsUsed(RegsLiveAtExit, false);
321 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
322 if (RegsLiveAtExit[i])
323 NewMBB->addLiveIn(i);
324 }
325
Chris Lattner1d08d832006-11-01 01:16:12 +0000326 return NewMBB;
327}
328
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000329/// EstimateRuntime - Make a rough estimate for how long it will take to run
330/// the specified code.
331static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
332 MachineBasicBlock::iterator E,
333 const TargetInstrInfo *TII) {
334 unsigned Time = 0;
335 for (; I != E; ++I) {
336 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
337 if (TID.Flags & M_CALL_FLAG)
338 Time += 10;
339 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
340 Time += 2;
341 else
342 ++Time;
343 }
344 return Time;
345}
346
347/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
348/// MBB2I and then insert an unconditional branch in the other block. Determine
349/// which is the best to split
350static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
351 MachineBasicBlock::iterator MBB1I,
352 MachineBasicBlock *MBB2,
353 MachineBasicBlock::iterator MBB2I,
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000354 const TargetInstrInfo *TII,
355 MachineBasicBlock *PredBB) {
Dale Johannesen54f4a672007-05-10 23:59:23 +0000356 // If one block is the entry block, split the other one; we can't generate
357 // a branch to the entry block, as its label is not emitted.
358 MachineBasicBlock *Entry = MBB1->getParent()->begin();
359 if (MBB1 == Entry)
360 return false;
361 if (MBB2 == Entry)
362 return true;
363
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000364 // If one block falls through into the common successor, choose that
365 // one to split; it is one instruction less to do that.
366 if (PredBB) {
367 if (MBB1 == PredBB)
368 return true;
369 else if (MBB2 == PredBB)
370 return false;
371 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000372 // TODO: if we had some notion of which block was hotter, we could split
373 // the hot block, so it is the fall-through. Since we don't have profile info
374 // make a decision based on which will hurt most to split.
375 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
376 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
377
378 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
379 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
380 // have a lower overall impact on the program execution.
381 return MBB1Time < MBB2Time;
382}
383
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000384// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
385// branches temporarily for tail merging). In the case where CurMBB ends
386// with a conditional branch to the next block, optimize by reversing the
387// test and conditionally branching to SuccMBB instead.
388
389static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
390 const TargetInstrInfo *TII) {
391 MachineFunction *MF = CurMBB->getParent();
392 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
393 MachineBasicBlock *TBB = 0, *FBB = 0;
394 std::vector<MachineOperand> Cond;
395 if (I != MF->end() &&
396 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
397 MachineBasicBlock *NextBB = I;
398 if (TBB == NextBB && Cond.size() && !FBB) {
399 if (!TII->ReverseBranchCondition(Cond)) {
400 TII->RemoveBranch(*CurMBB);
401 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
402 return;
403 }
404 }
405 }
406 TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
407}
408
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000409// See if any of the blocks in MergePotentials (which all have a common single
410// successor, or all have no successor) can be tail-merged. If there is a
411// successor, any blocks in MergePotentials that are not tail-merged and
412// are not immediately before Succ must have an unconditional branch to
413// Succ added (but the predecessor/successor lists need no adjustment).
414// The lone predecessor of Succ that falls through into Succ,
415// if any, is given in PredBB.
416
417bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
418 MachineBasicBlock* PredBB) {
Chris Lattner12143052006-10-21 00:47:49 +0000419 MadeChange = false;
420
Chris Lattner12143052006-10-21 00:47:49 +0000421 // Sort by hash value so that blocks with identical end sequences sort
422 // together.
423 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
424
425 // Walk through equivalence sets looking for actual exact matches.
426 while (MergePotentials.size() > 1) {
427 unsigned CurHash = (MergePotentials.end()-1)->first;
428 unsigned PrevHash = (MergePotentials.end()-2)->first;
429 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
430
431 // If there is nothing that matches the hash of the current basic block,
432 // give up.
433 if (CurHash != PrevHash) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000434 if (SuccBB && CurMBB != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000435 FixTail(CurMBB, SuccBB, TII);
Chris Lattner12143052006-10-21 00:47:49 +0000436 MergePotentials.pop_back();
437 continue;
438 }
439
440 // Determine the actual length of the shared tail between these two basic
441 // blocks. Because the hash can have collisions, it's possible that this is
442 // less than 2.
443 MachineBasicBlock::iterator BBI1, BBI2;
444 unsigned CommonTailLen =
445 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
446 BBI1, BBI2);
447
448 // If the tails don't have at least two instructions in common, see if there
449 // is anything else in the equivalence class that does match.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000450 // Since instructions may get combined later (e.g. single stores into
451 // store multiple) this measure is not particularly accurate.
Chris Lattner12143052006-10-21 00:47:49 +0000452 if (CommonTailLen < 2) {
453 unsigned FoundMatch = ~0U;
454 for (int i = MergePotentials.size()-2;
455 i != -1 && MergePotentials[i].first == CurHash; --i) {
456 CommonTailLen = ComputeCommonTailLength(CurMBB,
457 MergePotentials[i].second,
458 BBI1, BBI2);
459 if (CommonTailLen >= 2) {
460 FoundMatch = i;
461 break;
462 }
463 }
464
465 // If we didn't find anything that has at least two instructions matching
466 // this one, bail out.
467 if (FoundMatch == ~0U) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000468 // Put the unconditional branch back, if we need one.
469 if (SuccBB && CurMBB != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000470 FixTail(CurMBB, SuccBB, TII);
Chris Lattner12143052006-10-21 00:47:49 +0000471 MergePotentials.pop_back();
472 continue;
473 }
474
475 // Otherwise, move the matching block to the right position.
476 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
477 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000478
Chris Lattner12143052006-10-21 00:47:49 +0000479 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
Chris Lattner1d08d832006-11-01 01:16:12 +0000480
481 // If neither block is the entire common tail, split the tail of one block
Dale Johannesen54f4a672007-05-10 23:59:23 +0000482 // to make it redundant with the other tail. Also, we cannot jump to the
483 // entry block, so if one block is the entry block, split the other one.
484 MachineBasicBlock *Entry = CurMBB->getParent()->begin();
485 if (CurMBB->begin() == BBI1 && CurMBB != Entry)
486 ; // CurMBB is common tail
487 else if (MBB2->begin() == BBI2 && MBB2 != Entry)
488 ; // MBB2 is common tail
489 else {
Chris Lattner1d08d832006-11-01 01:16:12 +0000490 if (0) { // Enable this to disable partial tail merges.
491 MergePotentials.pop_back();
492 continue;
493 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000494
495 // Decide whether we want to split CurMBB or MBB2.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000496 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII, PredBB)) {
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000497 CurMBB = SplitMBBAt(*CurMBB, BBI1);
498 BBI1 = CurMBB->begin();
499 MergePotentials.back().second = CurMBB;
500 } else {
501 MBB2 = SplitMBBAt(*MBB2, BBI2);
502 BBI2 = MBB2->begin();
503 (MergePotentials.end()-2)->second = MBB2;
504 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000505 }
506
Dale Johannesen54f4a672007-05-10 23:59:23 +0000507 if (MBB2->begin() == BBI2 && MBB2 != Entry) {
Chris Lattner12143052006-10-21 00:47:49 +0000508 // Hack the end off CurMBB, making it jump to MBBI@ instead.
509 ReplaceTailWithBranchTo(BBI1, MBB2);
510 // This modifies CurMBB, so remove it from the worklist.
511 MergePotentials.pop_back();
Chris Lattner1d08d832006-11-01 01:16:12 +0000512 } else {
Dale Johannesen54f4a672007-05-10 23:59:23 +0000513 assert(CurMBB->begin() == BBI1 && CurMBB != Entry &&
514 "Didn't split block correctly?");
Chris Lattner1d08d832006-11-01 01:16:12 +0000515 // Hack the end off MBB2, making it jump to CurMBB instead.
516 ReplaceTailWithBranchTo(BBI2, CurMBB);
517 // This modifies MBB2, so remove it from the worklist.
518 MergePotentials.erase(MergePotentials.end()-2);
Chris Lattner12143052006-10-21 00:47:49 +0000519 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000520 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000521 }
Chris Lattner12143052006-10-21 00:47:49 +0000522 return MadeChange;
523}
524
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000525bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000526
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000527 if (!EnableTailMerge) return false;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000528
529 MadeChange = false;
530
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000531 // First find blocks with no successors.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000532 MergePotentials.clear();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000533 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
534 if (I->succ_empty())
535 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
536 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000537 // See if we can do any tail merging on those.
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000538 MadeChange |= TryMergeBlocks(NULL, NULL);
539
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000540 // Look at blocks (IBB) with multiple predecessors (PBB).
541 // We change each predecessor to a canonical form, by
542 // (1) temporarily removing any unconditional branch from the predecessor
543 // to IBB, and
544 // (2) alter conditional branches so they branch to the other block
545 // not IBB; this may require adding back an unconditional branch to IBB
546 // later, where there wasn't one coming in. E.g.
547 // Bcc IBB
548 // fallthrough to QBB
549 // here becomes
550 // Bncc QBB
551 // with a conceptual B to IBB after that, which never actually exists.
552 // With those changes, we see whether the predecessors' tails match,
553 // and merge them if so. We change things out of canonical form and
554 // back to the way they were later in the process. (OptimizeBranches
555 // would undo some of this, but we can't use it, because we'd get into
556 // a compile-time infinite loop repeatedly doing and undoing the same
557 // transformations.)
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000558
559 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
560 if (!I->succ_empty() && I->pred_size() >= 2) {
561 MachineBasicBlock *IBB = I;
562 MachineBasicBlock *PredBB = prior(I);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000563 MergePotentials.clear();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000564 for (MachineBasicBlock::pred_iterator P = I->pred_begin(), E2 = I->pred_end();
565 P != E2; ++P) {
566 MachineBasicBlock* PBB = *P;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000567 // Skip blocks that loop to themselves, can't tail merge these.
568 if (PBB==IBB)
569 continue;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000570 MachineBasicBlock *TBB = 0, *FBB = 0;
571 std::vector<MachineOperand> Cond;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000572 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
573 // Failing case: IBB is the target of a cbr, and
574 // we cannot reverse the branch.
575 std::vector<MachineOperand> NewCond(Cond);
576 if (Cond.size() && TBB==IBB) {
577 if (TII->ReverseBranchCondition(NewCond))
578 continue;
579 // This is the QBB case described above
580 if (!FBB)
581 FBB = next(MachineFunction::iterator(PBB));
582 }
583 // Remove the unconditional branch at the end, if any.
584 if (TBB && (Cond.size()==0 || FBB)) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000585 TII->RemoveBranch(*PBB);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000586 if (Cond.size())
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000587 // reinsert conditional branch only, for now
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000588 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000589 }
590 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB), *P));
591 }
592 }
593 if (MergePotentials.size() >= 2)
594 MadeChange |= TryMergeBlocks(I, PredBB);
595 // Reinsert an unconditional branch if needed.
596 // The 1 below can be either an original single predecessor, or a result
597 // of removing blocks in TryMergeBlocks.
Dale Johannesen1cf08c12007-05-18 01:28:58 +0000598 PredBB = prior(I); // this may have been changed in TryMergeBlocks
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000599 if (MergePotentials.size()==1 &&
600 (MergePotentials.begin())->second != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000601 FixTail((MergePotentials.begin())->second, I, TII);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000602 }
603 }
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000604 return MadeChange;
605}
Chris Lattner12143052006-10-21 00:47:49 +0000606
607//===----------------------------------------------------------------------===//
608// Branch Optimization
609//===----------------------------------------------------------------------===//
610
611bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
612 MadeChange = false;
613
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000614 // Make sure blocks are numbered in order
615 MF.RenumberBlocks();
616
Chris Lattner12143052006-10-21 00:47:49 +0000617 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
618 MachineBasicBlock *MBB = I++;
619 OptimizeBlock(MBB);
620
621 // If it is dead, remove it.
Jim Laskey033c9712007-02-22 16:39:03 +0000622 if (MBB->pred_empty()) {
Chris Lattner12143052006-10-21 00:47:49 +0000623 RemoveDeadBlock(MBB);
624 MadeChange = true;
625 ++NumDeadBlocks;
626 }
627 }
628 return MadeChange;
629}
630
631
Chris Lattner386e2902006-10-21 05:08:28 +0000632/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
633/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
634/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
635/// be null.
636static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
637 MachineBasicBlock *DestA,
638 MachineBasicBlock *DestB,
639 bool isCond,
640 MachineFunction::iterator FallThru) {
641 bool MadeChange = false;
642 bool AddedFallThrough = false;
643
644 // If this block ends with a conditional branch that falls through to its
645 // successor, set DestB as the successor.
646 if (isCond) {
647 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
648 DestB = FallThru;
649 AddedFallThrough = true;
650 }
651 } else {
652 // If this is an unconditional branch with no explicit dest, it must just be
653 // a fallthrough into DestB.
654 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
655 DestA = FallThru;
656 AddedFallThrough = true;
657 }
658 }
659
660 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
661 while (SI != MBB.succ_end()) {
662 if (*SI == DestA) {
663 DestA = 0;
664 ++SI;
665 } else if (*SI == DestB) {
666 DestB = 0;
667 ++SI;
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000668 } else if ((*SI)->isLandingPad()) {
669 ++SI;
Chris Lattner386e2902006-10-21 05:08:28 +0000670 } else {
671 // Otherwise, this is a superfluous edge, remove it.
672 MBB.removeSuccessor(SI);
673 MadeChange = true;
674 }
675 }
676 if (!AddedFallThrough) {
677 assert(DestA == 0 && DestB == 0 &&
678 "MachineCFG is missing edges!");
679 } else if (isCond) {
680 assert(DestA == 0 && "MachineCFG is missing edges!");
681 }
682 return MadeChange;
683}
684
685
Chris Lattner21ab22e2004-07-31 10:01:27 +0000686/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
687/// 'Old', change the code and CFG so that it branches to 'New' instead.
688static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
689 MachineBasicBlock *Old,
690 MachineBasicBlock *New,
Chris Lattner7821a8a2006-10-14 00:21:48 +0000691 const TargetInstrInfo *TII) {
Chris Lattner21ab22e2004-07-31 10:01:27 +0000692 assert(Old != New && "Cannot replace self with self!");
693
694 MachineBasicBlock::iterator I = BB->end();
695 while (I != BB->begin()) {
696 --I;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000697 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000698
699 // Scan the operands of this machine instruction, replacing any uses of Old
700 // with New.
701 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
702 if (I->getOperand(i).isMachineBasicBlock() &&
703 I->getOperand(i).getMachineBasicBlock() == Old)
704 I->getOperand(i).setMachineBasicBlock(New);
705 }
706
Chris Lattnereb15eee2006-10-13 20:43:10 +0000707 // Update the successor information.
Chris Lattner21ab22e2004-07-31 10:01:27 +0000708 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
709 for (int i = Succs.size()-1; i >= 0; --i)
710 if (Succs[i] == Old) {
711 BB->removeSuccessor(Old);
712 BB->addSuccessor(New);
713 }
714}
715
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000716/// CanFallThrough - Return true if the specified block (with the specified
717/// branch condition) can implicitly transfer control to the block after it by
718/// falling off the end of it. This should return false if it can reach the
719/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
720///
721/// True is a conservative answer.
722///
723bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
724 bool BranchUnAnalyzable,
725 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
726 const std::vector<MachineOperand> &Cond) {
727 MachineFunction::iterator Fallthrough = CurBB;
728 ++Fallthrough;
729 // If FallthroughBlock is off the end of the function, it can't fall through.
730 if (Fallthrough == CurBB->getParent()->end())
731 return false;
732
733 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
734 if (!CurBB->isSuccessor(Fallthrough))
735 return false;
736
737 // If we couldn't analyze the branch, assume it could fall through.
738 if (BranchUnAnalyzable) return true;
739
Chris Lattner7d097842006-10-24 01:12:32 +0000740 // If there is no branch, control always falls through.
741 if (TBB == 0) return true;
742
743 // If there is some explicit branch to the fallthrough block, it can obviously
744 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000745 if (MachineFunction::iterator(TBB) == Fallthrough ||
746 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000747 return true;
748
749 // If it's an unconditional branch to some block not the fall through, it
750 // doesn't fall through.
751 if (Cond.empty()) return false;
752
753 // Otherwise, if it is conditional and has no explicit false block, it falls
754 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000755 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000756}
757
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000758/// CanFallThrough - Return true if the specified can implicitly transfer
759/// control to the block after it by falling off the end of it. This should
760/// return false if it can reach the block after it, but it uses an explicit
761/// branch to do so (e.g. a table jump).
762///
763/// True is a conservative answer.
764///
765bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
766 MachineBasicBlock *TBB = 0, *FBB = 0;
767 std::vector<MachineOperand> Cond;
768 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
769 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
770}
771
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000772/// IsBetterFallthrough - Return true if it would be clearly better to
773/// fall-through to MBB1 than to fall through into MBB2. This has to return
774/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
775/// result in infinite loops.
776static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
777 MachineBasicBlock *MBB2,
778 const TargetInstrInfo &TII) {
Chris Lattner154e1042006-11-18 21:30:35 +0000779 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
780 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000781 // optimize branches that branch to either a return block or an assert block
782 // into a fallthrough to the return.
783 if (MBB1->empty() || MBB2->empty()) return false;
784
785 MachineInstr *MBB1I = --MBB1->end();
786 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner154e1042006-11-18 21:30:35 +0000787 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000788}
789
Chris Lattner7821a8a2006-10-14 00:21:48 +0000790/// OptimizeBlock - Analyze and optimize control flow related to the specified
791/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000792void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
793 MachineFunction::iterator FallThrough = MBB;
794 ++FallThrough;
795
Chris Lattnereb15eee2006-10-13 20:43:10 +0000796 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner21ab22e2004-07-31 10:01:27 +0000797 // explicitly.
798 if (MBB->empty()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000799 // Dead block? Leave for cleanup later.
Jim Laskey033c9712007-02-22 16:39:03 +0000800 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000801
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000802 if (FallThrough == MBB->getParent()->end()) {
803 // TODO: Simplify preds to not branch here if possible!
804 } else {
805 // Rewrite all predecessors of the old block to go to the fallthrough
806 // instead.
Jim Laskey033c9712007-02-22 16:39:03 +0000807 while (!MBB->pred_empty()) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000808 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
809 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
810 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000811
812 // If MBB was the target of a jump table, update jump tables to go to the
813 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000814 MBB->getParent()->getJumpTableInfo()->
815 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000816 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000817 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000818 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000819 }
820
Chris Lattner7821a8a2006-10-14 00:21:48 +0000821 // Check to see if we can simplify the terminator of the block before this
822 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000823 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000824
Chris Lattner7821a8a2006-10-14 00:21:48 +0000825 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
826 std::vector<MachineOperand> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000827 bool PriorUnAnalyzable =
828 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000829 if (!PriorUnAnalyzable) {
830 // If the CFG for the prior block has extra edges, remove them.
831 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
832 !PriorCond.empty(), MBB);
833
Chris Lattner7821a8a2006-10-14 00:21:48 +0000834 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000835 // destination, remove the branch, replacing it with an unconditional one or
836 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000837 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000838 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000839 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000840 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000841 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000842 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000843 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000844 return OptimizeBlock(MBB);
845 }
846
847 // If the previous branch *only* branches to *this* block (conditional or
848 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000849 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000850 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000851 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000852 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000853 return OptimizeBlock(MBB);
854 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000855
856 // If the prior block branches somewhere else on the condition and here if
857 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000858 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000859 TII->RemoveBranch(PrevBB);
860 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
861 MadeChange = true;
862 ++NumBranchOpts;
863 return OptimizeBlock(MBB);
864 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000865
866 // If the prior block branches here on true and somewhere else on false, and
867 // if the branch condition is reversible, reverse the branch to create a
868 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000869 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000870 std::vector<MachineOperand> NewPriorCond(PriorCond);
871 if (!TII->ReverseBranchCondition(NewPriorCond)) {
872 TII->RemoveBranch(PrevBB);
873 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
874 MadeChange = true;
875 ++NumBranchOpts;
876 return OptimizeBlock(MBB);
877 }
878 }
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000879
Chris Lattner154e1042006-11-18 21:30:35 +0000880 // If this block doesn't fall through (e.g. it ends with an uncond branch or
881 // has no successors) and if the pred falls through into this block, and if
882 // it would otherwise fall through into the block after this, move this
883 // block to the end of the function.
884 //
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000885 // We consider it more likely that execution will stay in the function (e.g.
886 // due to loops) than it is to exit it. This asserts in loops etc, moving
887 // the assert condition out of the loop body.
Chris Lattner154e1042006-11-18 21:30:35 +0000888 if (!PriorCond.empty() && PriorFBB == 0 &&
889 MachineFunction::iterator(PriorTBB) == FallThrough &&
890 !CanFallThrough(MBB)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000891 bool DoTransform = true;
892
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000893 // We have to be careful that the succs of PredBB aren't both no-successor
894 // blocks. If neither have successors and if PredBB is the second from
895 // last block in the function, we'd just keep swapping the two blocks for
896 // last. Only do the swap if one is clearly better to fall through than
897 // the other.
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000898 if (FallThrough == --MBB->getParent()->end() &&
899 !IsBetterFallthrough(PriorTBB, MBB, *TII))
900 DoTransform = false;
901
902 // We don't want to do this transformation if we have control flow like:
903 // br cond BB2
904 // BB1:
905 // ..
906 // jmp BBX
907 // BB2:
908 // ..
909 // ret
910 //
911 // In this case, we could actually be moving the return block *into* a
912 // loop!
Chris Lattner4b105912006-11-18 22:25:39 +0000913 if (DoTransform && !MBB->succ_empty() &&
914 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000915 DoTransform = false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000916
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000917
918 if (DoTransform) {
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000919 // Reverse the branch so we will fall through on the previous true cond.
920 std::vector<MachineOperand> NewPriorCond(PriorCond);
921 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000922 DOUT << "\nMoving MBB: " << *MBB;
923 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
924
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000925 TII->RemoveBranch(PrevBB);
926 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
927
928 // Move this block to the end of the function.
929 MBB->moveAfter(--MBB->getParent()->end());
930 MadeChange = true;
931 ++NumBranchOpts;
932 return;
933 }
934 }
935 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000936 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000937
Chris Lattner386e2902006-10-21 05:08:28 +0000938 // Analyze the branch in the current block.
939 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
940 std::vector<MachineOperand> CurCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000941 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
942 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +0000943 // If the CFG for the prior block has extra edges, remove them.
944 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattner7d097842006-10-24 01:12:32 +0000945 !CurCond.empty(),
946 ++MachineFunction::iterator(MBB));
Chris Lattnereb15eee2006-10-13 20:43:10 +0000947
Chris Lattner5d056952006-11-08 01:03:21 +0000948 // If this is a two-way branch, and the FBB branches to this block, reverse
949 // the condition so the single-basic-block loop is faster. Instead of:
950 // Loop: xxx; jcc Out; jmp Loop
951 // we want:
952 // Loop: xxx; jncc Loop; jmp Out
953 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
954 std::vector<MachineOperand> NewCond(CurCond);
955 if (!TII->ReverseBranchCondition(NewCond)) {
956 TII->RemoveBranch(*MBB);
957 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
958 MadeChange = true;
959 ++NumBranchOpts;
960 return OptimizeBlock(MBB);
961 }
962 }
963
964
Chris Lattner386e2902006-10-21 05:08:28 +0000965 // If this branch is the only thing in its block, see if we can forward
966 // other blocks across it.
967 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner7d097842006-10-24 01:12:32 +0000968 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000969 // This block may contain just an unconditional branch. Because there can
970 // be 'non-branch terminators' in the block, try removing the branch and
971 // then seeing if the block is empty.
972 TII->RemoveBranch(*MBB);
973
974 // If this block is just an unconditional branch to CurTBB, we can
975 // usually completely eliminate the block. The only case we cannot
976 // completely eliminate the block is when the block before this one
977 // falls through into MBB and we can't understand the prior block's branch
978 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +0000979 if (MBB->empty()) {
980 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
981 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
982 !PrevBB.isSuccessor(MBB)) {
983 // If the prior block falls through into us, turn it into an
984 // explicit branch to us to make updates simpler.
985 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
986 PriorTBB != MBB && PriorFBB != MBB) {
987 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +0000988 assert(PriorCond.empty() && PriorFBB == 0 &&
989 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +0000990 PriorTBB = MBB;
991 } else {
992 assert(PriorFBB == 0 && "Machine CFG out of date!");
993 PriorFBB = MBB;
994 }
995 TII->RemoveBranch(PrevBB);
996 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000997 }
Chris Lattner386e2902006-10-21 05:08:28 +0000998
Chris Lattnercf420cc2006-10-28 17:32:47 +0000999 // Iterate through all the predecessors, revectoring each in-turn.
1000 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
1001 bool DidChange = false;
1002 bool HasBranchToSelf = false;
1003 while (PI != MBB->pred_end()) {
1004 if (*PI == MBB) {
1005 // If this block has an uncond branch to itself, leave it.
1006 ++PI;
1007 HasBranchToSelf = true;
1008 } else {
1009 DidChange = true;
1010 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
1011 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001012 }
Chris Lattner386e2902006-10-21 05:08:28 +00001013
Chris Lattnercf420cc2006-10-28 17:32:47 +00001014 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +00001015 MBB->getParent()->getJumpTableInfo()->
1016 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +00001017 if (DidChange) {
1018 ++NumBranchOpts;
1019 MadeChange = true;
1020 if (!HasBranchToSelf) return;
1021 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001022 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001023 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001024
Chris Lattner386e2902006-10-21 05:08:28 +00001025 // Add the branch back if the block is more than just an uncond branch.
1026 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +00001027 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001028 }
1029
1030 // If the prior block doesn't fall through into this block, and if this
1031 // block doesn't fall through into some other block, see if we can find a
1032 // place to move this block where a fall-through will happen.
1033 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1034 PriorTBB, PriorFBB, PriorCond)) {
1035 // Now we know that there was no fall-through into this block, check to
1036 // see if it has a fall-through into its successor.
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001037 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
Chris Lattner77edc4b2007-04-30 23:35:00 +00001038 CurCond);
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001039
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001040 if (!MBB->isLandingPad()) {
1041 // Check all the predecessors of this block. If one of them has no fall
1042 // throughs, move this block right after it.
1043 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1044 E = MBB->pred_end(); PI != E; ++PI) {
1045 // Analyze the branch at the end of the pred.
1046 MachineBasicBlock *PredBB = *PI;
1047 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1048 if (PredBB != MBB && !CanFallThrough(PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001049 && (!CurFallsThru || !CurTBB || !CurFBB)
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001050 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1051 // If the current block doesn't fall through, just move it.
1052 // If the current block can fall through and does not end with a
1053 // conditional branch, we need to append an unconditional jump to
1054 // the (current) next block. To avoid a possible compile-time
1055 // infinite loop, move blocks only backward in this case.
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001056 // Also, if there are already 2 branches here, we cannot add a third;
1057 // this means we have the case
1058 // Bcc next
1059 // B elsewhere
1060 // next:
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001061 if (CurFallsThru) {
1062 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1063 CurCond.clear();
1064 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1065 }
1066 MBB->moveAfter(PredBB);
1067 MadeChange = true;
1068 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +00001069 }
1070 }
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001071 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001072
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001073 if (!CurFallsThru) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001074 // Check all successors to see if we can move this block before it.
1075 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1076 E = MBB->succ_end(); SI != E; ++SI) {
1077 // Analyze the branch at the end of the block before the succ.
1078 MachineBasicBlock *SuccBB = *SI;
1079 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001080 std::vector<MachineOperand> SuccPrevCond;
Chris Lattner77edc4b2007-04-30 23:35:00 +00001081
1082 // If this block doesn't already fall-through to that successor, and if
1083 // the succ doesn't already have a block that can fall through into it,
1084 // and if the successor isn't an EH destination, we can arrange for the
1085 // fallthrough to happen.
1086 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1087 !SuccBB->isLandingPad()) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001088 MBB->moveBefore(SuccBB);
1089 MadeChange = true;
1090 return OptimizeBlock(MBB);
1091 }
1092 }
1093
1094 // Okay, there is no really great place to put this block. If, however,
1095 // the block before this one would be a fall-through if this block were
1096 // removed, move this block to the end of the function.
1097 if (FallThrough != MBB->getParent()->end() &&
1098 PrevBB.isSuccessor(FallThrough)) {
1099 MBB->moveAfter(--MBB->getParent()->end());
1100 MadeChange = true;
1101 return;
1102 }
Chris Lattner7d097842006-10-24 01:12:32 +00001103 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001104 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001105}