blob: 33f96df302f8c800fcaf0c391c15dcc286244c00 [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 {
42 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner7821a8a2006-10-14 00:21:48 +000043 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
44 const TargetInstrInfo *TII;
Jim Laskey44c3b9f2007-01-26 21:22:28 +000045 MachineModuleInfo *MMI;
Chris Lattner7821a8a2006-10-14 00:21:48 +000046 bool MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +000047 private:
Chris Lattner12143052006-10-21 00:47:49 +000048 // Tail Merging.
49 bool TailMergeBlocks(MachineFunction &MF);
50 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
51 MachineBasicBlock *NewDest);
Chris Lattner1d08d832006-11-01 01:16:12 +000052 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
53 MachineBasicBlock::iterator BBI1);
Dale Johannesen69cb9b72007-03-20 21:35:06 +000054
55 const MRegisterInfo *RegInfo;
56 RegScavenger *RS;
Chris Lattner12143052006-10-21 00:47:49 +000057 // Branch optzn.
58 bool OptimizeBranches(MachineFunction &MF);
Chris Lattner7d097842006-10-24 01:12:32 +000059 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000060 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner6b0e3f82006-10-29 21:05:41 +000061
62 bool CanFallThrough(MachineBasicBlock *CurBB);
63 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
64 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
65 const std::vector<MachineOperand> &Cond);
Chris Lattner21ab22e2004-07-31 10:01:27 +000066 };
67}
68
69FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
70
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000071/// RemoveDeadBlock - Remove the specified dead machine basic block from the
72/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +000073void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey033c9712007-02-22 16:39:03 +000074 assert(MBB->pred_empty() && "MBB must be dead!");
Jim Laskey02b3f5e2007-02-21 22:42:20 +000075 DOUT << "\nRemoving MBB: " << *MBB;
Chris Lattner683747a2006-10-17 23:17:27 +000076
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000077 MachineFunction *MF = MBB->getParent();
78 // drop all successors.
79 while (!MBB->succ_empty())
80 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +000081
Jim Laskey1ee29252007-01-26 14:34:52 +000082 // If there is DWARF info to active, check to see if there are any LABEL
Jim Laskey44c3b9f2007-01-26 21:22:28 +000083 // records in the basic block. If so, unregister them from MachineModuleInfo.
84 if (MMI && !MBB->empty()) {
Chris Lattner683747a2006-10-17 23:17:27 +000085 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
86 I != E; ++I) {
Jim Laskey1ee29252007-01-26 14:34:52 +000087 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
Chris Lattner683747a2006-10-17 23:17:27 +000088 // The label ID # is always operand #0, an immediate.
Jim Laskey44c3b9f2007-01-26 21:22:28 +000089 MMI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +000090 }
91 }
92 }
93
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000094 // Remove the block.
95 MF->getBasicBlockList().erase(MBB);
96}
97
Chris Lattner21ab22e2004-07-31 10:01:27 +000098bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner7821a8a2006-10-14 00:21:48 +000099 TII = MF.getTarget().getInstrInfo();
100 if (!TII) return false;
101
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000102 RegInfo = MF.getTarget().getRegisterInfo();
103 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
104
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000105 MMI = getAnalysisToUpdate<MachineModuleInfo>();
Chris Lattner7821a8a2006-10-14 00:21:48 +0000106
Chris Lattner21ab22e2004-07-31 10:01:27 +0000107 bool EverMadeChange = false;
Chris Lattner12143052006-10-21 00:47:49 +0000108 bool MadeChangeThisIteration = true;
109 while (MadeChangeThisIteration) {
110 MadeChangeThisIteration = false;
111 MadeChangeThisIteration |= TailMergeBlocks(MF);
112 MadeChangeThisIteration |= OptimizeBranches(MF);
113 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000114 }
115
Chris Lattner6acfe122006-10-28 18:34:47 +0000116 // See if any jump tables have become mergable or dead as the code generator
117 // did its thing.
118 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
119 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
120 if (!JTs.empty()) {
121 // Figure out how these jump tables should be merged.
122 std::vector<unsigned> JTMapping;
123 JTMapping.reserve(JTs.size());
124
125 // We always keep the 0th jump table.
126 JTMapping.push_back(0);
127
128 // Scan the jump tables, seeing if there are any duplicates. Note that this
129 // is N^2, which should be fixed someday.
130 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
131 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
132
133 // If a jump table was merge with another one, walk the function rewriting
134 // references to jump tables to reference the new JT ID's. Keep track of
135 // whether we see a jump table idx, if not, we can delete the JT.
136 std::vector<bool> JTIsLive;
137 JTIsLive.resize(JTs.size());
138 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
139 BB != E; ++BB) {
140 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
141 I != E; ++I)
142 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
143 MachineOperand &Op = I->getOperand(op);
144 if (!Op.isJumpTableIndex()) continue;
145 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
146 Op.setJumpTableIndex(NewIdx);
147
148 // Remember that this JT is live.
149 JTIsLive[NewIdx] = true;
150 }
151 }
152
153 // Finally, remove dead jump tables. This happens either because the
154 // indirect jump was unreachable (and thus deleted) or because the jump
155 // table was merged with some other one.
156 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
157 if (!JTIsLive[i]) {
158 JTI->RemoveJumpTable(i);
159 EverMadeChange = true;
160 }
161 }
162
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000163 delete RS;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000164 return EverMadeChange;
165}
166
Chris Lattner12143052006-10-21 00:47:49 +0000167//===----------------------------------------------------------------------===//
168// Tail Merging of Blocks
169//===----------------------------------------------------------------------===//
170
171/// HashMachineInstr - Compute a hash value for MI and its operands.
172static unsigned HashMachineInstr(const MachineInstr *MI) {
173 unsigned Hash = MI->getOpcode();
174 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
175 const MachineOperand &Op = MI->getOperand(i);
176
177 // Merge in bits from the operand if easy.
178 unsigned OperandHash = 0;
179 switch (Op.getType()) {
180 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
181 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
182 case MachineOperand::MO_MachineBasicBlock:
183 OperandHash = Op.getMachineBasicBlock()->getNumber();
184 break;
185 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
186 case MachineOperand::MO_ConstantPoolIndex:
187 OperandHash = Op.getConstantPoolIndex();
188 break;
189 case MachineOperand::MO_JumpTableIndex:
190 OperandHash = Op.getJumpTableIndex();
191 break;
192 case MachineOperand::MO_GlobalAddress:
193 case MachineOperand::MO_ExternalSymbol:
194 // Global address / external symbol are too hard, don't bother, but do
195 // pull in the offset.
196 OperandHash = Op.getOffset();
197 break;
198 default: break;
199 }
200
201 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
202 }
203 return Hash;
204}
205
206/// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
207/// instructions, because cross-jumping only saves code when at least two
208/// instructions are removed (since a branch must be inserted).
209static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
210 MachineBasicBlock::const_iterator I = MBB->end();
211 if (I == MBB->begin())
212 return 0; // Empty MBB.
213
214 --I;
215 unsigned Hash = HashMachineInstr(I);
216
217 if (I == MBB->begin())
218 return Hash; // Single instr MBB.
219
220 --I;
221 // Hash in the second-to-last instruction.
222 Hash ^= HashMachineInstr(I) << 2;
223 return Hash;
224}
225
226/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
227/// of instructions they actually have in common together at their end. Return
228/// iterators for the first shared instruction in each block.
229static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
230 MachineBasicBlock *MBB2,
231 MachineBasicBlock::iterator &I1,
232 MachineBasicBlock::iterator &I2) {
233 I1 = MBB1->end();
234 I2 = MBB2->end();
235
236 unsigned TailLen = 0;
237 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
238 --I1; --I2;
239 if (!I1->isIdenticalTo(I2)) {
240 ++I1; ++I2;
241 break;
242 }
243 ++TailLen;
244 }
245 return TailLen;
246}
247
248/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000249/// after it, replacing it with an unconditional branch to NewDest. This
250/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000251void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
252 MachineBasicBlock *NewDest) {
253 MachineBasicBlock *OldBB = OldInst->getParent();
254
255 // Remove all the old successors of OldBB from the CFG.
256 while (!OldBB->succ_empty())
257 OldBB->removeSuccessor(OldBB->succ_begin());
258
259 // Remove all the dead instructions from the end of OldBB.
260 OldBB->erase(OldInst, OldBB->end());
261
Chris Lattner386e2902006-10-21 05:08:28 +0000262 // If OldBB isn't immediately before OldBB, insert a branch to it.
263 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
264 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner12143052006-10-21 00:47:49 +0000265 OldBB->addSuccessor(NewDest);
266 ++NumTailMerge;
267}
268
Chris Lattner1d08d832006-11-01 01:16:12 +0000269/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
270/// MBB so that the part before the iterator falls into the part starting at the
271/// iterator. This returns the new MBB.
272MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
273 MachineBasicBlock::iterator BBI1) {
274 // Create the fall-through block.
275 MachineFunction::iterator MBBI = &CurMBB;
276 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
277 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
278
279 // Move all the successors of this block to the specified block.
280 while (!CurMBB.succ_empty()) {
281 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
282 NewMBB->addSuccessor(S);
283 CurMBB.removeSuccessor(S);
284 }
285
286 // Add an edge from CurMBB to NewMBB for the fall-through.
287 CurMBB.addSuccessor(NewMBB);
288
289 // Splice the code over.
290 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000291
292 // For targets that use the register scavenger, we must maintain LiveIns.
293 if (RS) {
294 RS->enterBasicBlock(&CurMBB);
295 if (!CurMBB.empty())
296 RS->forward(prior(CurMBB.end()));
297 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
298 RS->getRegsUsed(RegsLiveAtExit, false);
299 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
300 if (RegsLiveAtExit[i])
301 NewMBB->addLiveIn(i);
302 }
303
Chris Lattner1d08d832006-11-01 01:16:12 +0000304 return NewMBB;
305}
306
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000307/// EstimateRuntime - Make a rough estimate for how long it will take to run
308/// the specified code.
309static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
310 MachineBasicBlock::iterator E,
311 const TargetInstrInfo *TII) {
312 unsigned Time = 0;
313 for (; I != E; ++I) {
314 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
315 if (TID.Flags & M_CALL_FLAG)
316 Time += 10;
317 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
318 Time += 2;
319 else
320 ++Time;
321 }
322 return Time;
323}
324
325/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
326/// MBB2I and then insert an unconditional branch in the other block. Determine
327/// which is the best to split
328static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
329 MachineBasicBlock::iterator MBB1I,
330 MachineBasicBlock *MBB2,
331 MachineBasicBlock::iterator MBB2I,
332 const TargetInstrInfo *TII) {
333 // TODO: if we had some notion of which block was hotter, we could split
334 // the hot block, so it is the fall-through. Since we don't have profile info
335 // make a decision based on which will hurt most to split.
336 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
337 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
338
339 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
340 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
341 // have a lower overall impact on the program execution.
342 return MBB1Time < MBB2Time;
343}
344
Chris Lattner12143052006-10-21 00:47:49 +0000345bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
346 MadeChange = false;
347
Chris Lattnerd8ccff02006-11-01 00:38:31 +0000348 if (!EnableTailMerge) return false;
Chris Lattner323ece62006-10-25 18:08:50 +0000349
Chris Lattner12143052006-10-21 00:47:49 +0000350 // Find blocks with no successors.
351 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
352 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
353 if (I->succ_empty())
354 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
355 }
356
357 // Sort by hash value so that blocks with identical end sequences sort
358 // together.
359 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
360
361 // Walk through equivalence sets looking for actual exact matches.
362 while (MergePotentials.size() > 1) {
363 unsigned CurHash = (MergePotentials.end()-1)->first;
364 unsigned PrevHash = (MergePotentials.end()-2)->first;
365 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
366
367 // If there is nothing that matches the hash of the current basic block,
368 // give up.
369 if (CurHash != PrevHash) {
370 MergePotentials.pop_back();
371 continue;
372 }
373
374 // Determine the actual length of the shared tail between these two basic
375 // blocks. Because the hash can have collisions, it's possible that this is
376 // less than 2.
377 MachineBasicBlock::iterator BBI1, BBI2;
378 unsigned CommonTailLen =
379 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
380 BBI1, BBI2);
381
382 // If the tails don't have at least two instructions in common, see if there
383 // is anything else in the equivalence class that does match.
384 if (CommonTailLen < 2) {
385 unsigned FoundMatch = ~0U;
386 for (int i = MergePotentials.size()-2;
387 i != -1 && MergePotentials[i].first == CurHash; --i) {
388 CommonTailLen = ComputeCommonTailLength(CurMBB,
389 MergePotentials[i].second,
390 BBI1, BBI2);
391 if (CommonTailLen >= 2) {
392 FoundMatch = i;
393 break;
394 }
395 }
396
397 // If we didn't find anything that has at least two instructions matching
398 // this one, bail out.
399 if (FoundMatch == ~0U) {
400 MergePotentials.pop_back();
401 continue;
402 }
403
404 // Otherwise, move the matching block to the right position.
405 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
406 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000407
Chris Lattner12143052006-10-21 00:47:49 +0000408 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
Chris Lattner1d08d832006-11-01 01:16:12 +0000409
410 // If neither block is the entire common tail, split the tail of one block
411 // to make it redundant with the other tail.
412 if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
413 if (0) { // Enable this to disable partial tail merges.
414 MergePotentials.pop_back();
415 continue;
416 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000417
418 // Decide whether we want to split CurMBB or MBB2.
419 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
420 CurMBB = SplitMBBAt(*CurMBB, BBI1);
421 BBI1 = CurMBB->begin();
422 MergePotentials.back().second = CurMBB;
423 } else {
424 MBB2 = SplitMBBAt(*MBB2, BBI2);
425 BBI2 = MBB2->begin();
426 (MergePotentials.end()-2)->second = MBB2;
427 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000428 }
429
430 if (MBB2->begin() == BBI2) {
Chris Lattner12143052006-10-21 00:47:49 +0000431 // Hack the end off CurMBB, making it jump to MBBI@ instead.
432 ReplaceTailWithBranchTo(BBI1, MBB2);
433 // This modifies CurMBB, so remove it from the worklist.
434 MergePotentials.pop_back();
Chris Lattner1d08d832006-11-01 01:16:12 +0000435 } else {
436 assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
437 // Hack the end off MBB2, making it jump to CurMBB instead.
438 ReplaceTailWithBranchTo(BBI2, CurMBB);
439 // This modifies MBB2, so remove it from the worklist.
440 MergePotentials.erase(MergePotentials.end()-2);
Chris Lattner12143052006-10-21 00:47:49 +0000441 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000442 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000443 }
444
445 return MadeChange;
446}
447
448
449//===----------------------------------------------------------------------===//
450// Branch Optimization
451//===----------------------------------------------------------------------===//
452
453bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
454 MadeChange = false;
455
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000456 // Make sure blocks are numbered in order
457 MF.RenumberBlocks();
458
Chris Lattner12143052006-10-21 00:47:49 +0000459 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
460 MachineBasicBlock *MBB = I++;
461 OptimizeBlock(MBB);
462
463 // If it is dead, remove it.
Jim Laskey033c9712007-02-22 16:39:03 +0000464 if (MBB->pred_empty()) {
Chris Lattner12143052006-10-21 00:47:49 +0000465 RemoveDeadBlock(MBB);
466 MadeChange = true;
467 ++NumDeadBlocks;
468 }
469 }
470 return MadeChange;
471}
472
473
Chris Lattner386e2902006-10-21 05:08:28 +0000474/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
475/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
476/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
477/// be null.
478static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
479 MachineBasicBlock *DestA,
480 MachineBasicBlock *DestB,
481 bool isCond,
482 MachineFunction::iterator FallThru) {
483 bool MadeChange = false;
484 bool AddedFallThrough = false;
485
486 // If this block ends with a conditional branch that falls through to its
487 // successor, set DestB as the successor.
488 if (isCond) {
489 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
490 DestB = FallThru;
491 AddedFallThrough = true;
492 }
493 } else {
494 // If this is an unconditional branch with no explicit dest, it must just be
495 // a fallthrough into DestB.
496 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
497 DestA = FallThru;
498 AddedFallThrough = true;
499 }
500 }
501
502 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
503 while (SI != MBB.succ_end()) {
504 if (*SI == DestA) {
505 DestA = 0;
506 ++SI;
507 } else if (*SI == DestB) {
508 DestB = 0;
509 ++SI;
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000510 } else if ((*SI)->isLandingPad()) {
511 ++SI;
Chris Lattner386e2902006-10-21 05:08:28 +0000512 } else {
513 // Otherwise, this is a superfluous edge, remove it.
514 MBB.removeSuccessor(SI);
515 MadeChange = true;
516 }
517 }
518 if (!AddedFallThrough) {
519 assert(DestA == 0 && DestB == 0 &&
520 "MachineCFG is missing edges!");
521 } else if (isCond) {
522 assert(DestA == 0 && "MachineCFG is missing edges!");
523 }
524 return MadeChange;
525}
526
527
Chris Lattner21ab22e2004-07-31 10:01:27 +0000528/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
529/// 'Old', change the code and CFG so that it branches to 'New' instead.
530static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
531 MachineBasicBlock *Old,
532 MachineBasicBlock *New,
Chris Lattner7821a8a2006-10-14 00:21:48 +0000533 const TargetInstrInfo *TII) {
Chris Lattner21ab22e2004-07-31 10:01:27 +0000534 assert(Old != New && "Cannot replace self with self!");
535
536 MachineBasicBlock::iterator I = BB->end();
537 while (I != BB->begin()) {
538 --I;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000539 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000540
541 // Scan the operands of this machine instruction, replacing any uses of Old
542 // with New.
543 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
544 if (I->getOperand(i).isMachineBasicBlock() &&
545 I->getOperand(i).getMachineBasicBlock() == Old)
546 I->getOperand(i).setMachineBasicBlock(New);
547 }
548
Chris Lattnereb15eee2006-10-13 20:43:10 +0000549 // Update the successor information.
Chris Lattner21ab22e2004-07-31 10:01:27 +0000550 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
551 for (int i = Succs.size()-1; i >= 0; --i)
552 if (Succs[i] == Old) {
553 BB->removeSuccessor(Old);
554 BB->addSuccessor(New);
555 }
556}
557
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000558/// CanFallThrough - Return true if the specified block (with the specified
559/// branch condition) can implicitly transfer control to the block after it by
560/// falling off the end of it. This should return false if it can reach the
561/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
562///
563/// True is a conservative answer.
564///
565bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
566 bool BranchUnAnalyzable,
567 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
568 const std::vector<MachineOperand> &Cond) {
569 MachineFunction::iterator Fallthrough = CurBB;
570 ++Fallthrough;
571 // If FallthroughBlock is off the end of the function, it can't fall through.
572 if (Fallthrough == CurBB->getParent()->end())
573 return false;
574
575 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
576 if (!CurBB->isSuccessor(Fallthrough))
577 return false;
578
579 // If we couldn't analyze the branch, assume it could fall through.
580 if (BranchUnAnalyzable) return true;
581
Chris Lattner7d097842006-10-24 01:12:32 +0000582 // If there is no branch, control always falls through.
583 if (TBB == 0) return true;
584
585 // If there is some explicit branch to the fallthrough block, it can obviously
586 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000587 if (MachineFunction::iterator(TBB) == Fallthrough ||
588 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000589 return true;
590
591 // If it's an unconditional branch to some block not the fall through, it
592 // doesn't fall through.
593 if (Cond.empty()) return false;
594
595 // Otherwise, if it is conditional and has no explicit false block, it falls
596 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000597 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000598}
599
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000600/// CanFallThrough - Return true if the specified can implicitly transfer
601/// control to the block after it by falling off the end of it. This should
602/// return false if it can reach the block after it, but it uses an explicit
603/// branch to do so (e.g. a table jump).
604///
605/// True is a conservative answer.
606///
607bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
608 MachineBasicBlock *TBB = 0, *FBB = 0;
609 std::vector<MachineOperand> Cond;
610 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
611 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
612}
613
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000614/// IsBetterFallthrough - Return true if it would be clearly better to
615/// fall-through to MBB1 than to fall through into MBB2. This has to return
616/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
617/// result in infinite loops.
618static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
619 MachineBasicBlock *MBB2,
620 const TargetInstrInfo &TII) {
Chris Lattner154e1042006-11-18 21:30:35 +0000621 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
622 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000623 // optimize branches that branch to either a return block or an assert block
624 // into a fallthrough to the return.
625 if (MBB1->empty() || MBB2->empty()) return false;
626
627 MachineInstr *MBB1I = --MBB1->end();
628 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner154e1042006-11-18 21:30:35 +0000629 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000630}
631
Chris Lattner7821a8a2006-10-14 00:21:48 +0000632/// OptimizeBlock - Analyze and optimize control flow related to the specified
633/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000634void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
635 MachineFunction::iterator FallThrough = MBB;
636 ++FallThrough;
637
Chris Lattnereb15eee2006-10-13 20:43:10 +0000638 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner21ab22e2004-07-31 10:01:27 +0000639 // explicitly.
640 if (MBB->empty()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000641 // Dead block? Leave for cleanup later.
Jim Laskey033c9712007-02-22 16:39:03 +0000642 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000643
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000644 if (FallThrough == MBB->getParent()->end()) {
645 // TODO: Simplify preds to not branch here if possible!
646 } else {
647 // Rewrite all predecessors of the old block to go to the fallthrough
648 // instead.
Jim Laskey033c9712007-02-22 16:39:03 +0000649 while (!MBB->pred_empty()) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000650 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
651 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
652 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000653
654 // If MBB was the target of a jump table, update jump tables to go to the
655 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000656 MBB->getParent()->getJumpTableInfo()->
657 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000658 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000659 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000660 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000661 }
662
Chris Lattner7821a8a2006-10-14 00:21:48 +0000663 // Check to see if we can simplify the terminator of the block before this
664 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000665 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000666
Chris Lattner7821a8a2006-10-14 00:21:48 +0000667 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
668 std::vector<MachineOperand> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000669 bool PriorUnAnalyzable =
670 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000671 if (!PriorUnAnalyzable) {
672 // If the CFG for the prior block has extra edges, remove them.
673 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
674 !PriorCond.empty(), MBB);
675
Chris Lattner7821a8a2006-10-14 00:21:48 +0000676 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000677 // destination, remove the branch, replacing it with an unconditional one or
678 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000679 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000680 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000681 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000682 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000683 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000684 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000685 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000686 return OptimizeBlock(MBB);
687 }
688
689 // If the previous branch *only* branches to *this* block (conditional or
690 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000691 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000692 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000693 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000694 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000695 return OptimizeBlock(MBB);
696 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000697
698 // If the prior block branches somewhere else on the condition and here if
699 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000700 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000701 TII->RemoveBranch(PrevBB);
702 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
703 MadeChange = true;
704 ++NumBranchOpts;
705 return OptimizeBlock(MBB);
706 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000707
708 // If the prior block branches here on true and somewhere else on false, and
709 // if the branch condition is reversible, reverse the branch to create a
710 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000711 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000712 std::vector<MachineOperand> NewPriorCond(PriorCond);
713 if (!TII->ReverseBranchCondition(NewPriorCond)) {
714 TII->RemoveBranch(PrevBB);
715 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
716 MadeChange = true;
717 ++NumBranchOpts;
718 return OptimizeBlock(MBB);
719 }
720 }
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000721
Chris Lattner154e1042006-11-18 21:30:35 +0000722 // If this block doesn't fall through (e.g. it ends with an uncond branch or
723 // has no successors) and if the pred falls through into this block, and if
724 // it would otherwise fall through into the block after this, move this
725 // block to the end of the function.
726 //
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000727 // We consider it more likely that execution will stay in the function (e.g.
728 // due to loops) than it is to exit it. This asserts in loops etc, moving
729 // the assert condition out of the loop body.
Chris Lattner154e1042006-11-18 21:30:35 +0000730 if (!PriorCond.empty() && PriorFBB == 0 &&
731 MachineFunction::iterator(PriorTBB) == FallThrough &&
732 !CanFallThrough(MBB)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000733 bool DoTransform = true;
734
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000735 // We have to be careful that the succs of PredBB aren't both no-successor
736 // blocks. If neither have successors and if PredBB is the second from
737 // last block in the function, we'd just keep swapping the two blocks for
738 // last. Only do the swap if one is clearly better to fall through than
739 // the other.
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000740 if (FallThrough == --MBB->getParent()->end() &&
741 !IsBetterFallthrough(PriorTBB, MBB, *TII))
742 DoTransform = false;
743
744 // We don't want to do this transformation if we have control flow like:
745 // br cond BB2
746 // BB1:
747 // ..
748 // jmp BBX
749 // BB2:
750 // ..
751 // ret
752 //
753 // In this case, we could actually be moving the return block *into* a
754 // loop!
Chris Lattner4b105912006-11-18 22:25:39 +0000755 if (DoTransform && !MBB->succ_empty() &&
756 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000757 DoTransform = false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000758
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000759
760 if (DoTransform) {
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000761 // Reverse the branch so we will fall through on the previous true cond.
762 std::vector<MachineOperand> NewPriorCond(PriorCond);
763 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000764 DOUT << "\nMoving MBB: " << *MBB;
765 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
766
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000767 TII->RemoveBranch(PrevBB);
768 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
769
770 // Move this block to the end of the function.
771 MBB->moveAfter(--MBB->getParent()->end());
772 MadeChange = true;
773 ++NumBranchOpts;
774 return;
775 }
776 }
777 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000778 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000779
Chris Lattner386e2902006-10-21 05:08:28 +0000780 // Analyze the branch in the current block.
781 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
782 std::vector<MachineOperand> CurCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000783 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
784 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +0000785 // If the CFG for the prior block has extra edges, remove them.
786 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattner7d097842006-10-24 01:12:32 +0000787 !CurCond.empty(),
788 ++MachineFunction::iterator(MBB));
Chris Lattnereb15eee2006-10-13 20:43:10 +0000789
Chris Lattner5d056952006-11-08 01:03:21 +0000790 // If this is a two-way branch, and the FBB branches to this block, reverse
791 // the condition so the single-basic-block loop is faster. Instead of:
792 // Loop: xxx; jcc Out; jmp Loop
793 // we want:
794 // Loop: xxx; jncc Loop; jmp Out
795 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
796 std::vector<MachineOperand> NewCond(CurCond);
797 if (!TII->ReverseBranchCondition(NewCond)) {
798 TII->RemoveBranch(*MBB);
799 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
800 MadeChange = true;
801 ++NumBranchOpts;
802 return OptimizeBlock(MBB);
803 }
804 }
805
806
Chris Lattner386e2902006-10-21 05:08:28 +0000807 // If this branch is the only thing in its block, see if we can forward
808 // other blocks across it.
809 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner7d097842006-10-24 01:12:32 +0000810 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000811 // This block may contain just an unconditional branch. Because there can
812 // be 'non-branch terminators' in the block, try removing the branch and
813 // then seeing if the block is empty.
814 TII->RemoveBranch(*MBB);
815
816 // If this block is just an unconditional branch to CurTBB, we can
817 // usually completely eliminate the block. The only case we cannot
818 // completely eliminate the block is when the block before this one
819 // falls through into MBB and we can't understand the prior block's branch
820 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +0000821 if (MBB->empty()) {
822 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
823 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
824 !PrevBB.isSuccessor(MBB)) {
825 // If the prior block falls through into us, turn it into an
826 // explicit branch to us to make updates simpler.
827 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
828 PriorTBB != MBB && PriorFBB != MBB) {
829 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +0000830 assert(PriorCond.empty() && PriorFBB == 0 &&
831 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +0000832 PriorTBB = MBB;
833 } else {
834 assert(PriorFBB == 0 && "Machine CFG out of date!");
835 PriorFBB = MBB;
836 }
837 TII->RemoveBranch(PrevBB);
838 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000839 }
Chris Lattner386e2902006-10-21 05:08:28 +0000840
Chris Lattnercf420cc2006-10-28 17:32:47 +0000841 // Iterate through all the predecessors, revectoring each in-turn.
842 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
843 bool DidChange = false;
844 bool HasBranchToSelf = false;
845 while (PI != MBB->pred_end()) {
846 if (*PI == MBB) {
847 // If this block has an uncond branch to itself, leave it.
848 ++PI;
849 HasBranchToSelf = true;
850 } else {
851 DidChange = true;
852 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
853 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000854 }
Chris Lattner386e2902006-10-21 05:08:28 +0000855
Chris Lattnercf420cc2006-10-28 17:32:47 +0000856 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +0000857 MBB->getParent()->getJumpTableInfo()->
858 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +0000859 if (DidChange) {
860 ++NumBranchOpts;
861 MadeChange = true;
862 if (!HasBranchToSelf) return;
863 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000864 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000865 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000866
Chris Lattner386e2902006-10-21 05:08:28 +0000867 // Add the branch back if the block is more than just an uncond branch.
868 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +0000869 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000870 }
871
872 // If the prior block doesn't fall through into this block, and if this
873 // block doesn't fall through into some other block, see if we can find a
874 // place to move this block where a fall-through will happen.
875 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
876 PriorTBB, PriorFBB, PriorCond)) {
877 // Now we know that there was no fall-through into this block, check to
878 // see if it has a fall-through into its successor.
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000879 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
Chris Lattner77edc4b2007-04-30 23:35:00 +0000880 CurCond);
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000881
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000882 if (!MBB->isLandingPad()) {
883 // Check all the predecessors of this block. If one of them has no fall
884 // throughs, move this block right after it.
885 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
886 E = MBB->pred_end(); PI != E; ++PI) {
887 // Analyze the branch at the end of the pred.
888 MachineBasicBlock *PredBB = *PI;
889 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
890 if (PredBB != MBB && !CanFallThrough(PredBB)
891 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
892 // If the current block doesn't fall through, just move it.
893 // If the current block can fall through and does not end with a
894 // conditional branch, we need to append an unconditional jump to
895 // the (current) next block. To avoid a possible compile-time
896 // infinite loop, move blocks only backward in this case.
897 if (CurFallsThru) {
898 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
899 CurCond.clear();
900 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
901 }
902 MBB->moveAfter(PredBB);
903 MadeChange = true;
904 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +0000905 }
906 }
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000907 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000908
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000909 if (!CurFallsThru) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000910 // Check all successors to see if we can move this block before it.
911 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
912 E = MBB->succ_end(); SI != E; ++SI) {
913 // Analyze the branch at the end of the block before the succ.
914 MachineBasicBlock *SuccBB = *SI;
915 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000916 std::vector<MachineOperand> SuccPrevCond;
Chris Lattner77edc4b2007-04-30 23:35:00 +0000917
918 // If this block doesn't already fall-through to that successor, and if
919 // the succ doesn't already have a block that can fall through into it,
920 // and if the successor isn't an EH destination, we can arrange for the
921 // fallthrough to happen.
922 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
923 !SuccBB->isLandingPad()) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000924 MBB->moveBefore(SuccBB);
925 MadeChange = true;
926 return OptimizeBlock(MBB);
927 }
928 }
929
930 // Okay, there is no really great place to put this block. If, however,
931 // the block before this one would be a fall-through if this block were
932 // removed, move this block to the end of the function.
933 if (FallThrough != MBB->getParent()->end() &&
934 PrevBB.isSuccessor(FallThrough)) {
935 MBB->moveAfter(--MBB->getParent()->end());
936 MadeChange = true;
937 return;
938 }
Chris Lattner7d097842006-10-24 01:12:32 +0000939 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000940 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000941}