blob: 11381466548fc501023a5be991197fa1589bd0b9 [file] [log] [blame]
Chris Lattner25e48dd2004-07-31 10:01:27 +00001//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner25e48dd2004-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 Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner25e48dd2004-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
19#include "llvm/CodeGen/Passes.h"
Chris Lattner73da3202006-10-17 23:17:27 +000020#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner25e48dd2004-07-31 10:01:27 +000021#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattner56c9d252006-10-17 17:13:52 +000022#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner25e48dd2004-07-31 10:01:27 +000023#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Target/TargetMachine.h"
Chris Lattner60c9d4d2006-10-21 00:47:49 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/ADT/Statistic.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000027#include "llvm/ADT/STLExtras.h"
Chris Lattner25e48dd2004-07-31 10:01:27 +000028using namespace llvm;
29
Chris Lattner60c9d4d2006-10-21 00:47:49 +000030static Statistic<> NumDeadBlocks("branchfold", "Number of dead blocks removed");
31static Statistic<> NumBranchOpts("branchfold", "Number of branches optimized");
32static Statistic<> NumTailMerge ("branchfold", "Number of block tails merged");
Chris Lattner3ac71b32006-11-01 00:38:31 +000033static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
Chris Lattner60c9d4d2006-10-21 00:47:49 +000034
Chris Lattner25e48dd2004-07-31 10:01:27 +000035namespace {
36 struct BranchFolder : public MachineFunctionPass {
37 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner3218e0e2006-10-14 00:21:48 +000038 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
39 const TargetInstrInfo *TII;
Chris Lattner73da3202006-10-17 23:17:27 +000040 MachineDebugInfo *MDI;
Chris Lattner3218e0e2006-10-14 00:21:48 +000041 bool MadeChange;
Chris Lattner25e48dd2004-07-31 10:01:27 +000042 private:
Chris Lattner60c9d4d2006-10-21 00:47:49 +000043 // Tail Merging.
44 bool TailMergeBlocks(MachineFunction &MF);
45 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
46 MachineBasicBlock *NewDest);
47
48 // Branch optzn.
49 bool OptimizeBranches(MachineFunction &MF);
Chris Lattnerceb51d82006-10-24 01:12:32 +000050 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner73da3202006-10-17 23:17:27 +000051 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner504eeda2006-10-29 21:05:41 +000052
53 bool CanFallThrough(MachineBasicBlock *CurBB);
54 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
55 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
56 const std::vector<MachineOperand> &Cond);
Chris Lattner25e48dd2004-07-31 10:01:27 +000057 };
58}
59
60FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
61
Chris Lattner56c9d252006-10-17 17:13:52 +000062/// RemoveDeadBlock - Remove the specified dead machine basic block from the
63/// function, updating the CFG.
Chris Lattner73da3202006-10-17 23:17:27 +000064void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Chris Lattner56c9d252006-10-17 17:13:52 +000065 assert(MBB->pred_empty() && "MBB must be dead!");
Chris Lattner73da3202006-10-17 23:17:27 +000066
Chris Lattner56c9d252006-10-17 17:13:52 +000067 MachineFunction *MF = MBB->getParent();
68 // drop all successors.
69 while (!MBB->succ_empty())
70 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner73da3202006-10-17 23:17:27 +000071
72 // If there is DWARF info to active, check to see if there are any DWARF_LABEL
73 // records in the basic block. If so, unregister them from MachineDebugInfo.
74 if (MDI && !MBB->empty()) {
75 unsigned DWARF_LABELOpc = TII->getDWARF_LABELOpcode();
76 assert(DWARF_LABELOpc &&
77 "Target supports dwarf but didn't implement getDWARF_LABELOpcode!");
78
79 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
80 I != E; ++I) {
81 if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
82 // The label ID # is always operand #0, an immediate.
Jim Laskey5e1a3402006-10-23 14:56:37 +000083 MDI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner73da3202006-10-17 23:17:27 +000084 }
85 }
86 }
87
Chris Lattner56c9d252006-10-17 17:13:52 +000088 // Remove the block.
89 MF->getBasicBlockList().erase(MBB);
90}
91
Chris Lattner25e48dd2004-07-31 10:01:27 +000092bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner3218e0e2006-10-14 00:21:48 +000093 TII = MF.getTarget().getInstrInfo();
94 if (!TII) return false;
95
Chris Lattner73da3202006-10-17 23:17:27 +000096 MDI = getAnalysisToUpdate<MachineDebugInfo>();
Chris Lattner3218e0e2006-10-14 00:21:48 +000097
Chris Lattner25e48dd2004-07-31 10:01:27 +000098 bool EverMadeChange = false;
Chris Lattner60c9d4d2006-10-21 00:47:49 +000099 bool MadeChangeThisIteration = true;
100 while (MadeChangeThisIteration) {
101 MadeChangeThisIteration = false;
102 MadeChangeThisIteration |= TailMergeBlocks(MF);
103 MadeChangeThisIteration |= OptimizeBranches(MF);
104 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000105 }
106
Chris Lattnerc07657f2006-10-28 18:34:47 +0000107 // See if any jump tables have become mergable or dead as the code generator
108 // did its thing.
109 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
110 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
111 if (!JTs.empty()) {
112 // Figure out how these jump tables should be merged.
113 std::vector<unsigned> JTMapping;
114 JTMapping.reserve(JTs.size());
115
116 // We always keep the 0th jump table.
117 JTMapping.push_back(0);
118
119 // Scan the jump tables, seeing if there are any duplicates. Note that this
120 // is N^2, which should be fixed someday.
121 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
122 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
123
124 // If a jump table was merge with another one, walk the function rewriting
125 // references to jump tables to reference the new JT ID's. Keep track of
126 // whether we see a jump table idx, if not, we can delete the JT.
127 std::vector<bool> JTIsLive;
128 JTIsLive.resize(JTs.size());
129 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
130 BB != E; ++BB) {
131 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
132 I != E; ++I)
133 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
134 MachineOperand &Op = I->getOperand(op);
135 if (!Op.isJumpTableIndex()) continue;
136 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
137 Op.setJumpTableIndex(NewIdx);
138
139 // Remember that this JT is live.
140 JTIsLive[NewIdx] = true;
141 }
142 }
143
144 // Finally, remove dead jump tables. This happens either because the
145 // indirect jump was unreachable (and thus deleted) or because the jump
146 // table was merged with some other one.
147 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
148 if (!JTIsLive[i]) {
149 JTI->RemoveJumpTable(i);
150 EverMadeChange = true;
151 }
152 }
153
Chris Lattner25e48dd2004-07-31 10:01:27 +0000154 return EverMadeChange;
155}
156
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000157//===----------------------------------------------------------------------===//
158// Tail Merging of Blocks
159//===----------------------------------------------------------------------===//
160
161/// HashMachineInstr - Compute a hash value for MI and its operands.
162static unsigned HashMachineInstr(const MachineInstr *MI) {
163 unsigned Hash = MI->getOpcode();
164 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
165 const MachineOperand &Op = MI->getOperand(i);
166
167 // Merge in bits from the operand if easy.
168 unsigned OperandHash = 0;
169 switch (Op.getType()) {
170 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
171 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
172 case MachineOperand::MO_MachineBasicBlock:
173 OperandHash = Op.getMachineBasicBlock()->getNumber();
174 break;
175 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
176 case MachineOperand::MO_ConstantPoolIndex:
177 OperandHash = Op.getConstantPoolIndex();
178 break;
179 case MachineOperand::MO_JumpTableIndex:
180 OperandHash = Op.getJumpTableIndex();
181 break;
182 case MachineOperand::MO_GlobalAddress:
183 case MachineOperand::MO_ExternalSymbol:
184 // Global address / external symbol are too hard, don't bother, but do
185 // pull in the offset.
186 OperandHash = Op.getOffset();
187 break;
188 default: break;
189 }
190
191 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
192 }
193 return Hash;
194}
195
196/// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
197/// instructions, because cross-jumping only saves code when at least two
198/// instructions are removed (since a branch must be inserted).
199static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
200 MachineBasicBlock::const_iterator I = MBB->end();
201 if (I == MBB->begin())
202 return 0; // Empty MBB.
203
204 --I;
205 unsigned Hash = HashMachineInstr(I);
206
207 if (I == MBB->begin())
208 return Hash; // Single instr MBB.
209
210 --I;
211 // Hash in the second-to-last instruction.
212 Hash ^= HashMachineInstr(I) << 2;
213 return Hash;
214}
215
216/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
217/// of instructions they actually have in common together at their end. Return
218/// iterators for the first shared instruction in each block.
219static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
220 MachineBasicBlock *MBB2,
221 MachineBasicBlock::iterator &I1,
222 MachineBasicBlock::iterator &I2) {
223 I1 = MBB1->end();
224 I2 = MBB2->end();
225
226 unsigned TailLen = 0;
227 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
228 --I1; --I2;
229 if (!I1->isIdenticalTo(I2)) {
230 ++I1; ++I2;
231 break;
232 }
233 ++TailLen;
234 }
235 return TailLen;
236}
237
238/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner4fe01c42006-10-21 05:08:28 +0000239/// after it, replacing it with an unconditional branch to NewDest. This
240/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000241void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
242 MachineBasicBlock *NewDest) {
243 MachineBasicBlock *OldBB = OldInst->getParent();
244
245 // Remove all the old successors of OldBB from the CFG.
246 while (!OldBB->succ_empty())
247 OldBB->removeSuccessor(OldBB->succ_begin());
248
249 // Remove all the dead instructions from the end of OldBB.
250 OldBB->erase(OldInst, OldBB->end());
251
Chris Lattner4fe01c42006-10-21 05:08:28 +0000252 // If OldBB isn't immediately before OldBB, insert a branch to it.
253 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
254 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000255 OldBB->addSuccessor(NewDest);
256 ++NumTailMerge;
257}
258
259bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
260 MadeChange = false;
261
Chris Lattner3ac71b32006-11-01 00:38:31 +0000262 if (!EnableTailMerge) return false;
Chris Lattner9feb3082006-10-25 18:08:50 +0000263
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000264 // Find blocks with no successors.
265 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
266 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
267 if (I->succ_empty())
268 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
269 }
270
271 // Sort by hash value so that blocks with identical end sequences sort
272 // together.
273 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
274
275 // Walk through equivalence sets looking for actual exact matches.
276 while (MergePotentials.size() > 1) {
277 unsigned CurHash = (MergePotentials.end()-1)->first;
278 unsigned PrevHash = (MergePotentials.end()-2)->first;
279 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
280
281 // If there is nothing that matches the hash of the current basic block,
282 // give up.
283 if (CurHash != PrevHash) {
284 MergePotentials.pop_back();
285 continue;
286 }
287
288 // Determine the actual length of the shared tail between these two basic
289 // blocks. Because the hash can have collisions, it's possible that this is
290 // less than 2.
291 MachineBasicBlock::iterator BBI1, BBI2;
292 unsigned CommonTailLen =
293 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
294 BBI1, BBI2);
295
296 // If the tails don't have at least two instructions in common, see if there
297 // is anything else in the equivalence class that does match.
298 if (CommonTailLen < 2) {
299 unsigned FoundMatch = ~0U;
300 for (int i = MergePotentials.size()-2;
301 i != -1 && MergePotentials[i].first == CurHash; --i) {
302 CommonTailLen = ComputeCommonTailLength(CurMBB,
303 MergePotentials[i].second,
304 BBI1, BBI2);
305 if (CommonTailLen >= 2) {
306 FoundMatch = i;
307 break;
308 }
309 }
310
311 // If we didn't find anything that has at least two instructions matching
312 // this one, bail out.
313 if (FoundMatch == ~0U) {
314 MergePotentials.pop_back();
315 continue;
316 }
317
318 // Otherwise, move the matching block to the right position.
319 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
320 }
321
322 // If either block is the entire common tail, make the longer one branch to
323 // the shorter one.
324 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
325 if (CurMBB->begin() == BBI1) {
326 // Hack the end off MBB2, making it jump to CurMBB instead.
327 ReplaceTailWithBranchTo(BBI2, CurMBB);
328 // This modifies MBB2, so remove it from the worklist.
329 MergePotentials.erase(MergePotentials.end()-2);
330 MadeChange = true;
331 continue;
332 } else if (MBB2->begin() == BBI2) {
333 // Hack the end off CurMBB, making it jump to MBBI@ instead.
334 ReplaceTailWithBranchTo(BBI1, MBB2);
335 // This modifies CurMBB, so remove it from the worklist.
336 MergePotentials.pop_back();
337 MadeChange = true;
338 continue;
339 }
340
341 MergePotentials.pop_back();
342 }
343
344 return MadeChange;
345}
346
347
348//===----------------------------------------------------------------------===//
349// Branch Optimization
350//===----------------------------------------------------------------------===//
351
352bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
353 MadeChange = false;
354
355 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
356 MachineBasicBlock *MBB = I++;
357 OptimizeBlock(MBB);
358
359 // If it is dead, remove it.
360 if (MBB->pred_empty()) {
361 RemoveDeadBlock(MBB);
362 MadeChange = true;
363 ++NumDeadBlocks;
364 }
365 }
366 return MadeChange;
367}
368
369
Chris Lattner4fe01c42006-10-21 05:08:28 +0000370/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
371/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
372/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
373/// be null.
374static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
375 MachineBasicBlock *DestA,
376 MachineBasicBlock *DestB,
377 bool isCond,
378 MachineFunction::iterator FallThru) {
379 bool MadeChange = false;
380 bool AddedFallThrough = false;
381
382 // If this block ends with a conditional branch that falls through to its
383 // successor, set DestB as the successor.
384 if (isCond) {
385 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
386 DestB = FallThru;
387 AddedFallThrough = true;
388 }
389 } else {
390 // If this is an unconditional branch with no explicit dest, it must just be
391 // a fallthrough into DestB.
392 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
393 DestA = FallThru;
394 AddedFallThrough = true;
395 }
396 }
397
398 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
399 while (SI != MBB.succ_end()) {
400 if (*SI == DestA) {
401 DestA = 0;
402 ++SI;
403 } else if (*SI == DestB) {
404 DestB = 0;
405 ++SI;
406 } else {
407 // Otherwise, this is a superfluous edge, remove it.
408 MBB.removeSuccessor(SI);
409 MadeChange = true;
410 }
411 }
412 if (!AddedFallThrough) {
413 assert(DestA == 0 && DestB == 0 &&
414 "MachineCFG is missing edges!");
415 } else if (isCond) {
416 assert(DestA == 0 && "MachineCFG is missing edges!");
417 }
418 return MadeChange;
419}
420
421
Chris Lattner25e48dd2004-07-31 10:01:27 +0000422/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
423/// 'Old', change the code and CFG so that it branches to 'New' instead.
424static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
425 MachineBasicBlock *Old,
426 MachineBasicBlock *New,
Chris Lattner3218e0e2006-10-14 00:21:48 +0000427 const TargetInstrInfo *TII) {
Chris Lattner25e48dd2004-07-31 10:01:27 +0000428 assert(Old != New && "Cannot replace self with self!");
429
430 MachineBasicBlock::iterator I = BB->end();
431 while (I != BB->begin()) {
432 --I;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000433 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000434
435 // Scan the operands of this machine instruction, replacing any uses of Old
436 // with New.
437 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
438 if (I->getOperand(i).isMachineBasicBlock() &&
439 I->getOperand(i).getMachineBasicBlock() == Old)
440 I->getOperand(i).setMachineBasicBlock(New);
441 }
442
Chris Lattner3e8e57c2006-10-13 20:43:10 +0000443 // Update the successor information.
Chris Lattner25e48dd2004-07-31 10:01:27 +0000444 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
445 for (int i = Succs.size()-1; i >= 0; --i)
446 if (Succs[i] == Old) {
447 BB->removeSuccessor(Old);
448 BB->addSuccessor(New);
449 }
450}
451
Chris Lattner504eeda2006-10-29 21:05:41 +0000452/// CanFallThrough - Return true if the specified block (with the specified
453/// branch condition) can implicitly transfer control to the block after it by
454/// falling off the end of it. This should return false if it can reach the
455/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
456///
457/// True is a conservative answer.
458///
459bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
460 bool BranchUnAnalyzable,
461 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
462 const std::vector<MachineOperand> &Cond) {
463 MachineFunction::iterator Fallthrough = CurBB;
464 ++Fallthrough;
465 // If FallthroughBlock is off the end of the function, it can't fall through.
466 if (Fallthrough == CurBB->getParent()->end())
467 return false;
468
469 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
470 if (!CurBB->isSuccessor(Fallthrough))
471 return false;
472
473 // If we couldn't analyze the branch, assume it could fall through.
474 if (BranchUnAnalyzable) return true;
475
Chris Lattnerceb51d82006-10-24 01:12:32 +0000476 // If there is no branch, control always falls through.
477 if (TBB == 0) return true;
478
479 // If there is some explicit branch to the fallthrough block, it can obviously
480 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner504eeda2006-10-29 21:05:41 +0000481 if (MachineFunction::iterator(TBB) == Fallthrough ||
482 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattnerceb51d82006-10-24 01:12:32 +0000483 return true;
484
485 // If it's an unconditional branch to some block not the fall through, it
486 // doesn't fall through.
487 if (Cond.empty()) return false;
488
489 // Otherwise, if it is conditional and has no explicit false block, it falls
490 // through.
Chris Lattner0d4479b72006-10-25 22:21:37 +0000491 return FBB == 0;
Chris Lattnerceb51d82006-10-24 01:12:32 +0000492}
493
Chris Lattner504eeda2006-10-29 21:05:41 +0000494/// CanFallThrough - Return true if the specified can implicitly transfer
495/// control to the block after it by falling off the end of it. This should
496/// return false if it can reach the block after it, but it uses an explicit
497/// branch to do so (e.g. a table jump).
498///
499/// True is a conservative answer.
500///
501bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
502 MachineBasicBlock *TBB = 0, *FBB = 0;
503 std::vector<MachineOperand> Cond;
504 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
505 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
506}
507
Chris Lattner3218e0e2006-10-14 00:21:48 +0000508/// OptimizeBlock - Analyze and optimize control flow related to the specified
509/// block. This is never called on the entry block.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000510void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
511 MachineFunction::iterator FallThrough = MBB;
512 ++FallThrough;
513
Chris Lattner3e8e57c2006-10-13 20:43:10 +0000514 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner25e48dd2004-07-31 10:01:27 +0000515 // explicitly.
516 if (MBB->empty()) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000517 // Dead block? Leave for cleanup later.
518 if (MBB->pred_empty()) return;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000519
Chris Lattner56c9d252006-10-17 17:13:52 +0000520 if (FallThrough == MBB->getParent()->end()) {
521 // TODO: Simplify preds to not branch here if possible!
522 } else {
523 // Rewrite all predecessors of the old block to go to the fallthrough
524 // instead.
Chris Lattner3218e0e2006-10-14 00:21:48 +0000525 while (!MBB->pred_empty()) {
526 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
527 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
528 }
Chris Lattner56c9d252006-10-17 17:13:52 +0000529
530 // If MBB was the target of a jump table, update jump tables to go to the
531 // fallthrough instead.
Chris Lattnerc07657f2006-10-28 18:34:47 +0000532 MBB->getParent()->getJumpTableInfo()->
533 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner3218e0e2006-10-14 00:21:48 +0000534 MadeChange = true;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000535 }
Chris Lattner3218e0e2006-10-14 00:21:48 +0000536 return;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000537 }
538
Chris Lattner3218e0e2006-10-14 00:21:48 +0000539 // Check to see if we can simplify the terminator of the block before this
540 // one.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000541 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerbca3e292006-10-17 18:16:40 +0000542
Chris Lattner3218e0e2006-10-14 00:21:48 +0000543 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
544 std::vector<MachineOperand> PriorCond;
Chris Lattner504eeda2006-10-29 21:05:41 +0000545 bool PriorUnAnalyzable =
546 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner4fe01c42006-10-21 05:08:28 +0000547 if (!PriorUnAnalyzable) {
548 // If the CFG for the prior block has extra edges, remove them.
549 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
550 !PriorCond.empty(), MBB);
551
Chris Lattner3218e0e2006-10-14 00:21:48 +0000552 // If the previous branch is conditional and both conditions go to the same
Chris Lattner3ca52182006-10-21 05:43:30 +0000553 // destination, remove the branch, replacing it with an unconditional one or
554 // a fall-through.
Chris Lattner3218e0e2006-10-14 00:21:48 +0000555 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000556 TII->RemoveBranch(PrevBB);
Chris Lattner3218e0e2006-10-14 00:21:48 +0000557 PriorCond.clear();
Chris Lattnerceb51d82006-10-24 01:12:32 +0000558 if (PriorTBB != MBB)
Chris Lattner4fe01c42006-10-21 05:08:28 +0000559 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner3218e0e2006-10-14 00:21:48 +0000560 MadeChange = true;
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000561 ++NumBranchOpts;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000562 return OptimizeBlock(MBB);
563 }
564
565 // If the previous branch *only* branches to *this* block (conditional or
566 // not) remove the branch.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000567 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000568 TII->RemoveBranch(PrevBB);
Chris Lattner3218e0e2006-10-14 00:21:48 +0000569 MadeChange = true;
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000570 ++NumBranchOpts;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000571 return OptimizeBlock(MBB);
572 }
Chris Lattner3ca52182006-10-21 05:43:30 +0000573
574 // If the prior block branches somewhere else on the condition and here if
575 // the condition is false, remove the uncond second branch.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000576 if (PriorFBB == MBB) {
Chris Lattner3ca52182006-10-21 05:43:30 +0000577 TII->RemoveBranch(PrevBB);
578 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
579 MadeChange = true;
580 ++NumBranchOpts;
581 return OptimizeBlock(MBB);
582 }
Chris Lattner28f17f42006-10-21 05:54:00 +0000583
584 // If the prior block branches here on true and somewhere else on false, and
585 // if the branch condition is reversible, reverse the branch to create a
586 // fall-through.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000587 if (PriorTBB == MBB) {
Chris Lattner28f17f42006-10-21 05:54:00 +0000588 std::vector<MachineOperand> NewPriorCond(PriorCond);
589 if (!TII->ReverseBranchCondition(NewPriorCond)) {
590 TII->RemoveBranch(PrevBB);
591 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
592 MadeChange = true;
593 ++NumBranchOpts;
594 return OptimizeBlock(MBB);
595 }
596 }
Chris Lattner3218e0e2006-10-14 00:21:48 +0000597 }
Chris Lattner3218e0e2006-10-14 00:21:48 +0000598
Chris Lattner4fe01c42006-10-21 05:08:28 +0000599 // Analyze the branch in the current block.
600 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
601 std::vector<MachineOperand> CurCond;
Chris Lattner504eeda2006-10-29 21:05:41 +0000602 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
603 if (!CurUnAnalyzable) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000604 // If the CFG for the prior block has extra edges, remove them.
605 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattnerceb51d82006-10-24 01:12:32 +0000606 !CurCond.empty(),
607 ++MachineFunction::iterator(MBB));
Chris Lattner3e8e57c2006-10-13 20:43:10 +0000608
Chris Lattner4fe01c42006-10-21 05:08:28 +0000609 // If this branch is the only thing in its block, see if we can forward
610 // other blocks across it.
611 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattnerceb51d82006-10-24 01:12:32 +0000612 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000613 // This block may contain just an unconditional branch. Because there can
614 // be 'non-branch terminators' in the block, try removing the branch and
615 // then seeing if the block is empty.
616 TII->RemoveBranch(*MBB);
617
618 // If this block is just an unconditional branch to CurTBB, we can
619 // usually completely eliminate the block. The only case we cannot
620 // completely eliminate the block is when the block before this one
621 // falls through into MBB and we can't understand the prior block's branch
622 // condition.
Chris Lattneraf838382006-10-28 17:32:47 +0000623 if (MBB->empty()) {
624 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
625 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
626 !PrevBB.isSuccessor(MBB)) {
627 // If the prior block falls through into us, turn it into an
628 // explicit branch to us to make updates simpler.
629 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
630 PriorTBB != MBB && PriorFBB != MBB) {
631 if (PriorTBB == 0) {
Chris Lattnerc07657f2006-10-28 18:34:47 +0000632 assert(PriorCond.empty() && PriorFBB == 0 &&
633 "Bad branch analysis");
Chris Lattneraf838382006-10-28 17:32:47 +0000634 PriorTBB = MBB;
635 } else {
636 assert(PriorFBB == 0 && "Machine CFG out of date!");
637 PriorFBB = MBB;
638 }
639 TII->RemoveBranch(PrevBB);
640 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner4fe01c42006-10-21 05:08:28 +0000641 }
Chris Lattner4fe01c42006-10-21 05:08:28 +0000642
Chris Lattneraf838382006-10-28 17:32:47 +0000643 // Iterate through all the predecessors, revectoring each in-turn.
644 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
645 bool DidChange = false;
646 bool HasBranchToSelf = false;
647 while (PI != MBB->pred_end()) {
648 if (*PI == MBB) {
649 // If this block has an uncond branch to itself, leave it.
650 ++PI;
651 HasBranchToSelf = true;
652 } else {
653 DidChange = true;
654 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
655 }
Chris Lattner9f5a1292006-10-21 06:11:43 +0000656 }
Chris Lattner4fe01c42006-10-21 05:08:28 +0000657
Chris Lattneraf838382006-10-28 17:32:47 +0000658 // Change any jumptables to go to the new MBB.
Chris Lattnerc07657f2006-10-28 18:34:47 +0000659 MBB->getParent()->getJumpTableInfo()->
660 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattneraf838382006-10-28 17:32:47 +0000661 if (DidChange) {
662 ++NumBranchOpts;
663 MadeChange = true;
664 if (!HasBranchToSelf) return;
665 }
Chris Lattner9f5a1292006-10-21 06:11:43 +0000666 }
Chris Lattner3e8e57c2006-10-13 20:43:10 +0000667 }
Chris Lattner3e8e57c2006-10-13 20:43:10 +0000668
Chris Lattner4fe01c42006-10-21 05:08:28 +0000669 // Add the branch back if the block is more than just an uncond branch.
670 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner25e48dd2004-07-31 10:01:27 +0000671 }
Chris Lattner504eeda2006-10-29 21:05:41 +0000672 }
673
674 // If the prior block doesn't fall through into this block, and if this
675 // block doesn't fall through into some other block, see if we can find a
676 // place to move this block where a fall-through will happen.
677 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
678 PriorTBB, PriorFBB, PriorCond)) {
679 // Now we know that there was no fall-through into this block, check to
680 // see if it has a fall-through into its successor.
681 if (!CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, CurCond)) {
682 // Check all the predecessors of this block. If one of them has no fall
683 // throughs, move this block right after it.
684 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
685 E = MBB->pred_end(); PI != E; ++PI) {
686 // Analyze the branch at the end of the pred.
687 MachineBasicBlock *PredBB = *PI;
688 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
689 MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
690 std::vector<MachineOperand> PredCond;
691 if (PredBB != MBB && !CanFallThrough(PredBB)) {
692 MBB->moveAfter(PredBB);
Chris Lattnerceb51d82006-10-24 01:12:32 +0000693 MadeChange = true;
Chris Lattner504eeda2006-10-29 21:05:41 +0000694 return OptimizeBlock(MBB);
Chris Lattnerceb51d82006-10-24 01:12:32 +0000695 }
696 }
Chris Lattner504eeda2006-10-29 21:05:41 +0000697
698 // Check all successors to see if we can move this block before it.
699 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
700 E = MBB->succ_end(); SI != E; ++SI) {
701 // Analyze the branch at the end of the block before the succ.
702 MachineBasicBlock *SuccBB = *SI;
703 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
704 MachineBasicBlock *SuccPrevTBB = 0, *SuccPrevFBB = 0;
705 std::vector<MachineOperand> SuccPrevCond;
706 if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
707 MBB->moveBefore(SuccBB);
708 MadeChange = true;
709 return OptimizeBlock(MBB);
710 }
711 }
712
713 // Okay, there is no really great place to put this block. If, however,
714 // the block before this one would be a fall-through if this block were
715 // removed, move this block to the end of the function.
716 if (FallThrough != MBB->getParent()->end() &&
717 PrevBB.isSuccessor(FallThrough)) {
718 MBB->moveAfter(--MBB->getParent()->end());
719 MadeChange = true;
720 return;
721 }
Chris Lattnerceb51d82006-10-24 01:12:32 +0000722 }
Chris Lattner25e48dd2004-07-31 10:01:27 +0000723 }
Chris Lattner25e48dd2004-07-31 10:01:27 +0000724}