blob: 2abeb2d31b2d0cac6aca985b4edfe7663dafd04a [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);
53 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
54 MachineBasicBlock *NewDest);
Chris Lattner1d08d832006-11-01 01:16:12 +000055 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
56 MachineBasicBlock::iterator BBI1);
Dale Johannesen69cb9b72007-03-20 21:35:06 +000057
58 const MRegisterInfo *RegInfo;
59 RegScavenger *RS;
Chris Lattner12143052006-10-21 00:47:49 +000060 // Branch optzn.
61 bool OptimizeBranches(MachineFunction &MF);
Chris Lattner7d097842006-10-24 01:12:32 +000062 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000063 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner6b0e3f82006-10-29 21:05:41 +000064
65 bool CanFallThrough(MachineBasicBlock *CurBB);
66 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
67 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
68 const std::vector<MachineOperand> &Cond);
Chris Lattner21ab22e2004-07-31 10:01:27 +000069 };
Devang Patel19974732007-05-03 01:11:54 +000070 char BranchFolder::ID = 0;
Chris Lattner21ab22e2004-07-31 10:01:27 +000071}
72
73FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
74
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000075/// RemoveDeadBlock - Remove the specified dead machine basic block from the
76/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +000077void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey033c9712007-02-22 16:39:03 +000078 assert(MBB->pred_empty() && "MBB must be dead!");
Jim Laskey02b3f5e2007-02-21 22:42:20 +000079 DOUT << "\nRemoving MBB: " << *MBB;
Chris Lattner683747a2006-10-17 23:17:27 +000080
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000081 MachineFunction *MF = MBB->getParent();
82 // drop all successors.
83 while (!MBB->succ_empty())
84 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +000085
Jim Laskey1ee29252007-01-26 14:34:52 +000086 // If there is DWARF info to active, check to see if there are any LABEL
Jim Laskey44c3b9f2007-01-26 21:22:28 +000087 // records in the basic block. If so, unregister them from MachineModuleInfo.
88 if (MMI && !MBB->empty()) {
Chris Lattner683747a2006-10-17 23:17:27 +000089 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
90 I != E; ++I) {
Jim Laskey1ee29252007-01-26 14:34:52 +000091 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
Chris Lattner683747a2006-10-17 23:17:27 +000092 // The label ID # is always operand #0, an immediate.
Jim Laskey44c3b9f2007-01-26 21:22:28 +000093 MMI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +000094 }
95 }
96 }
97
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000098 // Remove the block.
99 MF->getBasicBlockList().erase(MBB);
100}
101
Chris Lattner21ab22e2004-07-31 10:01:27 +0000102bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000103 TII = MF.getTarget().getInstrInfo();
104 if (!TII) return false;
105
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000106 RegInfo = MF.getTarget().getRegisterInfo();
107 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
108
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000109 MMI = getAnalysisToUpdate<MachineModuleInfo>();
Chris Lattner7821a8a2006-10-14 00:21:48 +0000110
Chris Lattner21ab22e2004-07-31 10:01:27 +0000111 bool EverMadeChange = false;
Chris Lattner12143052006-10-21 00:47:49 +0000112 bool MadeChangeThisIteration = true;
113 while (MadeChangeThisIteration) {
114 MadeChangeThisIteration = false;
115 MadeChangeThisIteration |= TailMergeBlocks(MF);
116 MadeChangeThisIteration |= OptimizeBranches(MF);
117 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000118 }
119
Chris Lattner6acfe122006-10-28 18:34:47 +0000120 // See if any jump tables have become mergable or dead as the code generator
121 // did its thing.
122 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
123 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
124 if (!JTs.empty()) {
125 // Figure out how these jump tables should be merged.
126 std::vector<unsigned> JTMapping;
127 JTMapping.reserve(JTs.size());
128
129 // We always keep the 0th jump table.
130 JTMapping.push_back(0);
131
132 // Scan the jump tables, seeing if there are any duplicates. Note that this
133 // is N^2, which should be fixed someday.
134 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
135 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
136
137 // If a jump table was merge with another one, walk the function rewriting
138 // references to jump tables to reference the new JT ID's. Keep track of
139 // whether we see a jump table idx, if not, we can delete the JT.
140 std::vector<bool> JTIsLive;
141 JTIsLive.resize(JTs.size());
142 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
143 BB != E; ++BB) {
144 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
145 I != E; ++I)
146 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
147 MachineOperand &Op = I->getOperand(op);
148 if (!Op.isJumpTableIndex()) continue;
149 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
150 Op.setJumpTableIndex(NewIdx);
151
152 // Remember that this JT is live.
153 JTIsLive[NewIdx] = true;
154 }
155 }
156
157 // Finally, remove dead jump tables. This happens either because the
158 // indirect jump was unreachable (and thus deleted) or because the jump
159 // table was merged with some other one.
160 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
161 if (!JTIsLive[i]) {
162 JTI->RemoveJumpTable(i);
163 EverMadeChange = true;
164 }
165 }
166
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000167 delete RS;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000168 return EverMadeChange;
169}
170
Chris Lattner12143052006-10-21 00:47:49 +0000171//===----------------------------------------------------------------------===//
172// Tail Merging of Blocks
173//===----------------------------------------------------------------------===//
174
175/// HashMachineInstr - Compute a hash value for MI and its operands.
176static unsigned HashMachineInstr(const MachineInstr *MI) {
177 unsigned Hash = MI->getOpcode();
178 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
179 const MachineOperand &Op = MI->getOperand(i);
180
181 // Merge in bits from the operand if easy.
182 unsigned OperandHash = 0;
183 switch (Op.getType()) {
184 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
185 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
186 case MachineOperand::MO_MachineBasicBlock:
187 OperandHash = Op.getMachineBasicBlock()->getNumber();
188 break;
189 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
190 case MachineOperand::MO_ConstantPoolIndex:
191 OperandHash = Op.getConstantPoolIndex();
192 break;
193 case MachineOperand::MO_JumpTableIndex:
194 OperandHash = Op.getJumpTableIndex();
195 break;
196 case MachineOperand::MO_GlobalAddress:
197 case MachineOperand::MO_ExternalSymbol:
198 // Global address / external symbol are too hard, don't bother, but do
199 // pull in the offset.
200 OperandHash = Op.getOffset();
201 break;
202 default: break;
203 }
204
205 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
206 }
207 return Hash;
208}
209
210/// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
211/// instructions, because cross-jumping only saves code when at least two
212/// instructions are removed (since a branch must be inserted).
213static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
214 MachineBasicBlock::const_iterator I = MBB->end();
215 if (I == MBB->begin())
216 return 0; // Empty MBB.
217
218 --I;
219 unsigned Hash = HashMachineInstr(I);
220
221 if (I == MBB->begin())
222 return Hash; // Single instr MBB.
223
224 --I;
225 // Hash in the second-to-last instruction.
226 Hash ^= HashMachineInstr(I) << 2;
227 return Hash;
228}
229
230/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
231/// of instructions they actually have in common together at their end. Return
232/// iterators for the first shared instruction in each block.
233static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
234 MachineBasicBlock *MBB2,
235 MachineBasicBlock::iterator &I1,
236 MachineBasicBlock::iterator &I2) {
237 I1 = MBB1->end();
238 I2 = MBB2->end();
239
240 unsigned TailLen = 0;
241 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
242 --I1; --I2;
243 if (!I1->isIdenticalTo(I2)) {
244 ++I1; ++I2;
245 break;
246 }
247 ++TailLen;
248 }
249 return TailLen;
250}
251
252/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000253/// after it, replacing it with an unconditional branch to NewDest. This
254/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000255void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
256 MachineBasicBlock *NewDest) {
257 MachineBasicBlock *OldBB = OldInst->getParent();
258
259 // Remove all the old successors of OldBB from the CFG.
260 while (!OldBB->succ_empty())
261 OldBB->removeSuccessor(OldBB->succ_begin());
262
263 // Remove all the dead instructions from the end of OldBB.
264 OldBB->erase(OldInst, OldBB->end());
265
Chris Lattner386e2902006-10-21 05:08:28 +0000266 // If OldBB isn't immediately before OldBB, insert a branch to it.
267 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
268 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner12143052006-10-21 00:47:49 +0000269 OldBB->addSuccessor(NewDest);
270 ++NumTailMerge;
271}
272
Chris Lattner1d08d832006-11-01 01:16:12 +0000273/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
274/// MBB so that the part before the iterator falls into the part starting at the
275/// iterator. This returns the new MBB.
276MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
277 MachineBasicBlock::iterator BBI1) {
278 // Create the fall-through block.
279 MachineFunction::iterator MBBI = &CurMBB;
280 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
281 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
282
283 // Move all the successors of this block to the specified block.
284 while (!CurMBB.succ_empty()) {
285 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
286 NewMBB->addSuccessor(S);
287 CurMBB.removeSuccessor(S);
288 }
289
290 // Add an edge from CurMBB to NewMBB for the fall-through.
291 CurMBB.addSuccessor(NewMBB);
292
293 // Splice the code over.
294 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000295
296 // For targets that use the register scavenger, we must maintain LiveIns.
297 if (RS) {
298 RS->enterBasicBlock(&CurMBB);
299 if (!CurMBB.empty())
300 RS->forward(prior(CurMBB.end()));
301 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
302 RS->getRegsUsed(RegsLiveAtExit, false);
303 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
304 if (RegsLiveAtExit[i])
305 NewMBB->addLiveIn(i);
306 }
307
Chris Lattner1d08d832006-11-01 01:16:12 +0000308 return NewMBB;
309}
310
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000311/// EstimateRuntime - Make a rough estimate for how long it will take to run
312/// the specified code.
313static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
314 MachineBasicBlock::iterator E,
315 const TargetInstrInfo *TII) {
316 unsigned Time = 0;
317 for (; I != E; ++I) {
318 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
319 if (TID.Flags & M_CALL_FLAG)
320 Time += 10;
321 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
322 Time += 2;
323 else
324 ++Time;
325 }
326 return Time;
327}
328
329/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
330/// MBB2I and then insert an unconditional branch in the other block. Determine
331/// which is the best to split
332static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
333 MachineBasicBlock::iterator MBB1I,
334 MachineBasicBlock *MBB2,
335 MachineBasicBlock::iterator MBB2I,
336 const TargetInstrInfo *TII) {
337 // TODO: if we had some notion of which block was hotter, we could split
338 // the hot block, so it is the fall-through. Since we don't have profile info
339 // make a decision based on which will hurt most to split.
340 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
341 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
342
343 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
344 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
345 // have a lower overall impact on the program execution.
346 return MBB1Time < MBB2Time;
347}
348
Chris Lattner12143052006-10-21 00:47:49 +0000349bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
350 MadeChange = false;
351
Chris Lattnerd8ccff02006-11-01 00:38:31 +0000352 if (!EnableTailMerge) return false;
Chris Lattner323ece62006-10-25 18:08:50 +0000353
Chris Lattner12143052006-10-21 00:47:49 +0000354 // Find blocks with no successors.
355 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
356 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
357 if (I->succ_empty())
358 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
359 }
360
361 // Sort by hash value so that blocks with identical end sequences sort
362 // together.
363 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
364
365 // Walk through equivalence sets looking for actual exact matches.
366 while (MergePotentials.size() > 1) {
367 unsigned CurHash = (MergePotentials.end()-1)->first;
368 unsigned PrevHash = (MergePotentials.end()-2)->first;
369 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
370
371 // If there is nothing that matches the hash of the current basic block,
372 // give up.
373 if (CurHash != PrevHash) {
374 MergePotentials.pop_back();
375 continue;
376 }
377
378 // Determine the actual length of the shared tail between these two basic
379 // blocks. Because the hash can have collisions, it's possible that this is
380 // less than 2.
381 MachineBasicBlock::iterator BBI1, BBI2;
382 unsigned CommonTailLen =
383 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
384 BBI1, BBI2);
385
386 // If the tails don't have at least two instructions in common, see if there
387 // is anything else in the equivalence class that does match.
388 if (CommonTailLen < 2) {
389 unsigned FoundMatch = ~0U;
390 for (int i = MergePotentials.size()-2;
391 i != -1 && MergePotentials[i].first == CurHash; --i) {
392 CommonTailLen = ComputeCommonTailLength(CurMBB,
393 MergePotentials[i].second,
394 BBI1, BBI2);
395 if (CommonTailLen >= 2) {
396 FoundMatch = i;
397 break;
398 }
399 }
400
401 // If we didn't find anything that has at least two instructions matching
402 // this one, bail out.
403 if (FoundMatch == ~0U) {
404 MergePotentials.pop_back();
405 continue;
406 }
407
408 // Otherwise, move the matching block to the right position.
409 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
410 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000411
Chris Lattner12143052006-10-21 00:47:49 +0000412 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
Chris Lattner1d08d832006-11-01 01:16:12 +0000413
414 // If neither block is the entire common tail, split the tail of one block
415 // to make it redundant with the other tail.
416 if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
417 if (0) { // Enable this to disable partial tail merges.
418 MergePotentials.pop_back();
419 continue;
420 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000421
422 // Decide whether we want to split CurMBB or MBB2.
423 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
424 CurMBB = SplitMBBAt(*CurMBB, BBI1);
425 BBI1 = CurMBB->begin();
426 MergePotentials.back().second = CurMBB;
427 } else {
428 MBB2 = SplitMBBAt(*MBB2, BBI2);
429 BBI2 = MBB2->begin();
430 (MergePotentials.end()-2)->second = MBB2;
431 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000432 }
433
434 if (MBB2->begin() == BBI2) {
Chris Lattner12143052006-10-21 00:47:49 +0000435 // Hack the end off CurMBB, making it jump to MBBI@ instead.
436 ReplaceTailWithBranchTo(BBI1, MBB2);
437 // This modifies CurMBB, so remove it from the worklist.
438 MergePotentials.pop_back();
Chris Lattner1d08d832006-11-01 01:16:12 +0000439 } else {
440 assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
441 // Hack the end off MBB2, making it jump to CurMBB instead.
442 ReplaceTailWithBranchTo(BBI2, CurMBB);
443 // This modifies MBB2, so remove it from the worklist.
444 MergePotentials.erase(MergePotentials.end()-2);
Chris Lattner12143052006-10-21 00:47:49 +0000445 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000446 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000447 }
448
449 return MadeChange;
450}
451
452
453//===----------------------------------------------------------------------===//
454// Branch Optimization
455//===----------------------------------------------------------------------===//
456
457bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
458 MadeChange = false;
459
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000460 // Make sure blocks are numbered in order
461 MF.RenumberBlocks();
462
Chris Lattner12143052006-10-21 00:47:49 +0000463 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
464 MachineBasicBlock *MBB = I++;
465 OptimizeBlock(MBB);
466
467 // If it is dead, remove it.
Jim Laskey033c9712007-02-22 16:39:03 +0000468 if (MBB->pred_empty()) {
Chris Lattner12143052006-10-21 00:47:49 +0000469 RemoveDeadBlock(MBB);
470 MadeChange = true;
471 ++NumDeadBlocks;
472 }
473 }
474 return MadeChange;
475}
476
477
Chris Lattner386e2902006-10-21 05:08:28 +0000478/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
479/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
480/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
481/// be null.
482static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
483 MachineBasicBlock *DestA,
484 MachineBasicBlock *DestB,
485 bool isCond,
486 MachineFunction::iterator FallThru) {
487 bool MadeChange = false;
488 bool AddedFallThrough = false;
489
490 // If this block ends with a conditional branch that falls through to its
491 // successor, set DestB as the successor.
492 if (isCond) {
493 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
494 DestB = FallThru;
495 AddedFallThrough = true;
496 }
497 } else {
498 // If this is an unconditional branch with no explicit dest, it must just be
499 // a fallthrough into DestB.
500 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
501 DestA = FallThru;
502 AddedFallThrough = true;
503 }
504 }
505
506 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
507 while (SI != MBB.succ_end()) {
508 if (*SI == DestA) {
509 DestA = 0;
510 ++SI;
511 } else if (*SI == DestB) {
512 DestB = 0;
513 ++SI;
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000514 } else if ((*SI)->isLandingPad()) {
515 ++SI;
Chris Lattner386e2902006-10-21 05:08:28 +0000516 } else {
517 // Otherwise, this is a superfluous edge, remove it.
518 MBB.removeSuccessor(SI);
519 MadeChange = true;
520 }
521 }
522 if (!AddedFallThrough) {
523 assert(DestA == 0 && DestB == 0 &&
524 "MachineCFG is missing edges!");
525 } else if (isCond) {
526 assert(DestA == 0 && "MachineCFG is missing edges!");
527 }
528 return MadeChange;
529}
530
531
Chris Lattner21ab22e2004-07-31 10:01:27 +0000532/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
533/// 'Old', change the code and CFG so that it branches to 'New' instead.
534static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
535 MachineBasicBlock *Old,
536 MachineBasicBlock *New,
Chris Lattner7821a8a2006-10-14 00:21:48 +0000537 const TargetInstrInfo *TII) {
Chris Lattner21ab22e2004-07-31 10:01:27 +0000538 assert(Old != New && "Cannot replace self with self!");
539
540 MachineBasicBlock::iterator I = BB->end();
541 while (I != BB->begin()) {
542 --I;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000543 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000544
545 // Scan the operands of this machine instruction, replacing any uses of Old
546 // with New.
547 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
548 if (I->getOperand(i).isMachineBasicBlock() &&
549 I->getOperand(i).getMachineBasicBlock() == Old)
550 I->getOperand(i).setMachineBasicBlock(New);
551 }
552
Chris Lattnereb15eee2006-10-13 20:43:10 +0000553 // Update the successor information.
Chris Lattner21ab22e2004-07-31 10:01:27 +0000554 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
555 for (int i = Succs.size()-1; i >= 0; --i)
556 if (Succs[i] == Old) {
557 BB->removeSuccessor(Old);
558 BB->addSuccessor(New);
559 }
560}
561
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000562/// CanFallThrough - Return true if the specified block (with the specified
563/// branch condition) can implicitly transfer control to the block after it by
564/// falling off the end of it. This should return false if it can reach the
565/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
566///
567/// True is a conservative answer.
568///
569bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
570 bool BranchUnAnalyzable,
571 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
572 const std::vector<MachineOperand> &Cond) {
573 MachineFunction::iterator Fallthrough = CurBB;
574 ++Fallthrough;
575 // If FallthroughBlock is off the end of the function, it can't fall through.
576 if (Fallthrough == CurBB->getParent()->end())
577 return false;
578
579 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
580 if (!CurBB->isSuccessor(Fallthrough))
581 return false;
582
583 // If we couldn't analyze the branch, assume it could fall through.
584 if (BranchUnAnalyzable) return true;
585
Chris Lattner7d097842006-10-24 01:12:32 +0000586 // If there is no branch, control always falls through.
587 if (TBB == 0) return true;
588
589 // If there is some explicit branch to the fallthrough block, it can obviously
590 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000591 if (MachineFunction::iterator(TBB) == Fallthrough ||
592 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000593 return true;
594
595 // If it's an unconditional branch to some block not the fall through, it
596 // doesn't fall through.
597 if (Cond.empty()) return false;
598
599 // Otherwise, if it is conditional and has no explicit false block, it falls
600 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000601 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000602}
603
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000604/// CanFallThrough - Return true if the specified can implicitly transfer
605/// control to the block after it by falling off the end of it. This should
606/// return false if it can reach the block after it, but it uses an explicit
607/// branch to do so (e.g. a table jump).
608///
609/// True is a conservative answer.
610///
611bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
612 MachineBasicBlock *TBB = 0, *FBB = 0;
613 std::vector<MachineOperand> Cond;
614 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
615 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
616}
617
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000618/// IsBetterFallthrough - Return true if it would be clearly better to
619/// fall-through to MBB1 than to fall through into MBB2. This has to return
620/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
621/// result in infinite loops.
622static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
623 MachineBasicBlock *MBB2,
624 const TargetInstrInfo &TII) {
Chris Lattner154e1042006-11-18 21:30:35 +0000625 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
626 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000627 // optimize branches that branch to either a return block or an assert block
628 // into a fallthrough to the return.
629 if (MBB1->empty() || MBB2->empty()) return false;
630
631 MachineInstr *MBB1I = --MBB1->end();
632 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner154e1042006-11-18 21:30:35 +0000633 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000634}
635
Chris Lattner7821a8a2006-10-14 00:21:48 +0000636/// OptimizeBlock - Analyze and optimize control flow related to the specified
637/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000638void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
639 MachineFunction::iterator FallThrough = MBB;
640 ++FallThrough;
641
Chris Lattnereb15eee2006-10-13 20:43:10 +0000642 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner21ab22e2004-07-31 10:01:27 +0000643 // explicitly.
644 if (MBB->empty()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000645 // Dead block? Leave for cleanup later.
Jim Laskey033c9712007-02-22 16:39:03 +0000646 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000647
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000648 if (FallThrough == MBB->getParent()->end()) {
649 // TODO: Simplify preds to not branch here if possible!
650 } else {
651 // Rewrite all predecessors of the old block to go to the fallthrough
652 // instead.
Jim Laskey033c9712007-02-22 16:39:03 +0000653 while (!MBB->pred_empty()) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000654 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
655 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
656 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000657
658 // If MBB was the target of a jump table, update jump tables to go to the
659 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000660 MBB->getParent()->getJumpTableInfo()->
661 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000662 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000663 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000664 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000665 }
666
Chris Lattner7821a8a2006-10-14 00:21:48 +0000667 // Check to see if we can simplify the terminator of the block before this
668 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000669 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000670
Chris Lattner7821a8a2006-10-14 00:21:48 +0000671 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
672 std::vector<MachineOperand> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000673 bool PriorUnAnalyzable =
674 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000675 if (!PriorUnAnalyzable) {
676 // If the CFG for the prior block has extra edges, remove them.
677 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
678 !PriorCond.empty(), MBB);
679
Chris Lattner7821a8a2006-10-14 00:21:48 +0000680 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000681 // destination, remove the branch, replacing it with an unconditional one or
682 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000683 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000684 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000685 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000686 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000687 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000688 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000689 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000690 return OptimizeBlock(MBB);
691 }
692
693 // If the previous branch *only* branches to *this* block (conditional or
694 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000695 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000696 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000697 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000698 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000699 return OptimizeBlock(MBB);
700 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000701
702 // If the prior block branches somewhere else on the condition and here if
703 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000704 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000705 TII->RemoveBranch(PrevBB);
706 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
707 MadeChange = true;
708 ++NumBranchOpts;
709 return OptimizeBlock(MBB);
710 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000711
712 // If the prior block branches here on true and somewhere else on false, and
713 // if the branch condition is reversible, reverse the branch to create a
714 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000715 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000716 std::vector<MachineOperand> NewPriorCond(PriorCond);
717 if (!TII->ReverseBranchCondition(NewPriorCond)) {
718 TII->RemoveBranch(PrevBB);
719 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
720 MadeChange = true;
721 ++NumBranchOpts;
722 return OptimizeBlock(MBB);
723 }
724 }
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000725
Chris Lattner154e1042006-11-18 21:30:35 +0000726 // If this block doesn't fall through (e.g. it ends with an uncond branch or
727 // has no successors) and if the pred falls through into this block, and if
728 // it would otherwise fall through into the block after this, move this
729 // block to the end of the function.
730 //
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000731 // We consider it more likely that execution will stay in the function (e.g.
732 // due to loops) than it is to exit it. This asserts in loops etc, moving
733 // the assert condition out of the loop body.
Chris Lattner154e1042006-11-18 21:30:35 +0000734 if (!PriorCond.empty() && PriorFBB == 0 &&
735 MachineFunction::iterator(PriorTBB) == FallThrough &&
736 !CanFallThrough(MBB)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000737 bool DoTransform = true;
738
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000739 // We have to be careful that the succs of PredBB aren't both no-successor
740 // blocks. If neither have successors and if PredBB is the second from
741 // last block in the function, we'd just keep swapping the two blocks for
742 // last. Only do the swap if one is clearly better to fall through than
743 // the other.
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000744 if (FallThrough == --MBB->getParent()->end() &&
745 !IsBetterFallthrough(PriorTBB, MBB, *TII))
746 DoTransform = false;
747
748 // We don't want to do this transformation if we have control flow like:
749 // br cond BB2
750 // BB1:
751 // ..
752 // jmp BBX
753 // BB2:
754 // ..
755 // ret
756 //
757 // In this case, we could actually be moving the return block *into* a
758 // loop!
Chris Lattner4b105912006-11-18 22:25:39 +0000759 if (DoTransform && !MBB->succ_empty() &&
760 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000761 DoTransform = false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000762
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000763
764 if (DoTransform) {
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000765 // Reverse the branch so we will fall through on the previous true cond.
766 std::vector<MachineOperand> NewPriorCond(PriorCond);
767 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000768 DOUT << "\nMoving MBB: " << *MBB;
769 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
770
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000771 TII->RemoveBranch(PrevBB);
772 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
773
774 // Move this block to the end of the function.
775 MBB->moveAfter(--MBB->getParent()->end());
776 MadeChange = true;
777 ++NumBranchOpts;
778 return;
779 }
780 }
781 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000782 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000783
Chris Lattner386e2902006-10-21 05:08:28 +0000784 // Analyze the branch in the current block.
785 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
786 std::vector<MachineOperand> CurCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000787 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
788 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +0000789 // If the CFG for the prior block has extra edges, remove them.
790 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattner7d097842006-10-24 01:12:32 +0000791 !CurCond.empty(),
792 ++MachineFunction::iterator(MBB));
Chris Lattnereb15eee2006-10-13 20:43:10 +0000793
Chris Lattner5d056952006-11-08 01:03:21 +0000794 // If this is a two-way branch, and the FBB branches to this block, reverse
795 // the condition so the single-basic-block loop is faster. Instead of:
796 // Loop: xxx; jcc Out; jmp Loop
797 // we want:
798 // Loop: xxx; jncc Loop; jmp Out
799 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
800 std::vector<MachineOperand> NewCond(CurCond);
801 if (!TII->ReverseBranchCondition(NewCond)) {
802 TII->RemoveBranch(*MBB);
803 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
804 MadeChange = true;
805 ++NumBranchOpts;
806 return OptimizeBlock(MBB);
807 }
808 }
809
810
Chris Lattner386e2902006-10-21 05:08:28 +0000811 // If this branch is the only thing in its block, see if we can forward
812 // other blocks across it.
813 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner7d097842006-10-24 01:12:32 +0000814 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000815 // This block may contain just an unconditional branch. Because there can
816 // be 'non-branch terminators' in the block, try removing the branch and
817 // then seeing if the block is empty.
818 TII->RemoveBranch(*MBB);
819
820 // If this block is just an unconditional branch to CurTBB, we can
821 // usually completely eliminate the block. The only case we cannot
822 // completely eliminate the block is when the block before this one
823 // falls through into MBB and we can't understand the prior block's branch
824 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +0000825 if (MBB->empty()) {
826 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
827 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
828 !PrevBB.isSuccessor(MBB)) {
829 // If the prior block falls through into us, turn it into an
830 // explicit branch to us to make updates simpler.
831 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
832 PriorTBB != MBB && PriorFBB != MBB) {
833 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +0000834 assert(PriorCond.empty() && PriorFBB == 0 &&
835 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +0000836 PriorTBB = MBB;
837 } else {
838 assert(PriorFBB == 0 && "Machine CFG out of date!");
839 PriorFBB = MBB;
840 }
841 TII->RemoveBranch(PrevBB);
842 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000843 }
Chris Lattner386e2902006-10-21 05:08:28 +0000844
Chris Lattnercf420cc2006-10-28 17:32:47 +0000845 // Iterate through all the predecessors, revectoring each in-turn.
846 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
847 bool DidChange = false;
848 bool HasBranchToSelf = false;
849 while (PI != MBB->pred_end()) {
850 if (*PI == MBB) {
851 // If this block has an uncond branch to itself, leave it.
852 ++PI;
853 HasBranchToSelf = true;
854 } else {
855 DidChange = true;
856 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
857 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000858 }
Chris Lattner386e2902006-10-21 05:08:28 +0000859
Chris Lattnercf420cc2006-10-28 17:32:47 +0000860 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +0000861 MBB->getParent()->getJumpTableInfo()->
862 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +0000863 if (DidChange) {
864 ++NumBranchOpts;
865 MadeChange = true;
866 if (!HasBranchToSelf) return;
867 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000868 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000869 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000870
Chris Lattner386e2902006-10-21 05:08:28 +0000871 // Add the branch back if the block is more than just an uncond branch.
872 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +0000873 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000874 }
875
876 // If the prior block doesn't fall through into this block, and if this
877 // block doesn't fall through into some other block, see if we can find a
878 // place to move this block where a fall-through will happen.
879 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
880 PriorTBB, PriorFBB, PriorCond)) {
881 // Now we know that there was no fall-through into this block, check to
882 // see if it has a fall-through into its successor.
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000883 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
Chris Lattner77edc4b2007-04-30 23:35:00 +0000884 CurCond);
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000885
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000886 if (!MBB->isLandingPad()) {
887 // Check all the predecessors of this block. If one of them has no fall
888 // throughs, move this block right after it.
889 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
890 E = MBB->pred_end(); PI != E; ++PI) {
891 // Analyze the branch at the end of the pred.
892 MachineBasicBlock *PredBB = *PI;
893 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
894 if (PredBB != MBB && !CanFallThrough(PredBB)
895 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
896 // If the current block doesn't fall through, just move it.
897 // If the current block can fall through and does not end with a
898 // conditional branch, we need to append an unconditional jump to
899 // the (current) next block. To avoid a possible compile-time
900 // infinite loop, move blocks only backward in this case.
901 if (CurFallsThru) {
902 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
903 CurCond.clear();
904 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
905 }
906 MBB->moveAfter(PredBB);
907 MadeChange = true;
908 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +0000909 }
910 }
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000911 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000912
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000913 if (!CurFallsThru) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000914 // Check all successors to see if we can move this block before it.
915 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
916 E = MBB->succ_end(); SI != E; ++SI) {
917 // Analyze the branch at the end of the block before the succ.
918 MachineBasicBlock *SuccBB = *SI;
919 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000920 std::vector<MachineOperand> SuccPrevCond;
Chris Lattner77edc4b2007-04-30 23:35:00 +0000921
922 // If this block doesn't already fall-through to that successor, and if
923 // the succ doesn't already have a block that can fall through into it,
924 // and if the successor isn't an EH destination, we can arrange for the
925 // fallthrough to happen.
926 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
927 !SuccBB->isLandingPad()) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000928 MBB->moveBefore(SuccBB);
929 MadeChange = true;
930 return OptimizeBlock(MBB);
931 }
932 }
933
934 // Okay, there is no really great place to put this block. If, however,
935 // the block before this one would be a fall-through if this block were
936 // removed, move this block to the end of the function.
937 if (FallThrough != MBB->getParent()->end() &&
938 PrevBB.isSuccessor(FallThrough)) {
939 MBB->moveAfter(--MBB->getParent()->end());
940 MadeChange = true;
941 return;
942 }
Chris Lattner7d097842006-10-24 01:12:32 +0000943 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000944 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000945}