blob: 9ca0091d20358226b4b1e0d3a883e45485f12705 [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
19#include "llvm/CodeGen/Passes.h"
Chris Lattner683747a2006-10-17 23:17:27 +000020#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000021#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000022#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000023#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Target/TargetMachine.h"
Chris Lattner12143052006-10-21 00:47:49 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/ADT/STLExtras.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000028using namespace llvm;
29
Chris Lattner12143052006-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 Lattner12143052006-10-21 00:47:49 +000033
Chris Lattner21ab22e2004-07-31 10:01:27 +000034namespace {
35 struct BranchFolder : public MachineFunctionPass {
36 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner7821a8a2006-10-14 00:21:48 +000037 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
38 const TargetInstrInfo *TII;
Chris Lattner683747a2006-10-17 23:17:27 +000039 MachineDebugInfo *MDI;
Chris Lattner7821a8a2006-10-14 00:21:48 +000040 bool MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +000041 private:
Chris Lattner12143052006-10-21 00:47:49 +000042 // Tail Merging.
43 bool TailMergeBlocks(MachineFunction &MF);
44 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
45 MachineBasicBlock *NewDest);
46
47 // Branch optzn.
48 bool OptimizeBranches(MachineFunction &MF);
Chris Lattner7d097842006-10-24 01:12:32 +000049 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000050 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner6b0e3f82006-10-29 21:05:41 +000051
52 bool CanFallThrough(MachineBasicBlock *CurBB);
53 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
54 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
55 const std::vector<MachineOperand> &Cond);
Chris Lattner21ab22e2004-07-31 10:01:27 +000056 };
57}
58
59FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
60
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000061/// RemoveDeadBlock - Remove the specified dead machine basic block from the
62/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +000063void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000064 assert(MBB->pred_empty() && "MBB must be dead!");
Chris Lattner683747a2006-10-17 23:17:27 +000065
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000066 MachineFunction *MF = MBB->getParent();
67 // drop all successors.
68 while (!MBB->succ_empty())
69 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +000070
71 // If there is DWARF info to active, check to see if there are any DWARF_LABEL
72 // records in the basic block. If so, unregister them from MachineDebugInfo.
73 if (MDI && !MBB->empty()) {
74 unsigned DWARF_LABELOpc = TII->getDWARF_LABELOpcode();
75 assert(DWARF_LABELOpc &&
76 "Target supports dwarf but didn't implement getDWARF_LABELOpcode!");
77
78 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
79 I != E; ++I) {
80 if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
81 // The label ID # is always operand #0, an immediate.
Jim Laskey66ebf092006-10-23 14:56:37 +000082 MDI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +000083 }
84 }
85 }
86
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000087 // Remove the block.
88 MF->getBasicBlockList().erase(MBB);
89}
90
Chris Lattner21ab22e2004-07-31 10:01:27 +000091bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner7821a8a2006-10-14 00:21:48 +000092 TII = MF.getTarget().getInstrInfo();
93 if (!TII) return false;
94
Chris Lattner683747a2006-10-17 23:17:27 +000095 MDI = getAnalysisToUpdate<MachineDebugInfo>();
Chris Lattner7821a8a2006-10-14 00:21:48 +000096
Chris Lattner21ab22e2004-07-31 10:01:27 +000097 bool EverMadeChange = false;
Chris Lattner12143052006-10-21 00:47:49 +000098 bool MadeChangeThisIteration = true;
99 while (MadeChangeThisIteration) {
100 MadeChangeThisIteration = false;
101 MadeChangeThisIteration |= TailMergeBlocks(MF);
102 MadeChangeThisIteration |= OptimizeBranches(MF);
103 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000104 }
105
Chris Lattner6acfe122006-10-28 18:34:47 +0000106 // See if any jump tables have become mergable or dead as the code generator
107 // did its thing.
108 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
109 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
110 if (!JTs.empty()) {
111 // Figure out how these jump tables should be merged.
112 std::vector<unsigned> JTMapping;
113 JTMapping.reserve(JTs.size());
114
115 // We always keep the 0th jump table.
116 JTMapping.push_back(0);
117
118 // Scan the jump tables, seeing if there are any duplicates. Note that this
119 // is N^2, which should be fixed someday.
120 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
121 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
122
123 // If a jump table was merge with another one, walk the function rewriting
124 // references to jump tables to reference the new JT ID's. Keep track of
125 // whether we see a jump table idx, if not, we can delete the JT.
126 std::vector<bool> JTIsLive;
127 JTIsLive.resize(JTs.size());
128 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
129 BB != E; ++BB) {
130 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
131 I != E; ++I)
132 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
133 MachineOperand &Op = I->getOperand(op);
134 if (!Op.isJumpTableIndex()) continue;
135 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
136 Op.setJumpTableIndex(NewIdx);
137
138 // Remember that this JT is live.
139 JTIsLive[NewIdx] = true;
140 }
141 }
142
143 // Finally, remove dead jump tables. This happens either because the
144 // indirect jump was unreachable (and thus deleted) or because the jump
145 // table was merged with some other one.
146 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
147 if (!JTIsLive[i]) {
148 JTI->RemoveJumpTable(i);
149 EverMadeChange = true;
150 }
151 }
152
Chris Lattner21ab22e2004-07-31 10:01:27 +0000153 return EverMadeChange;
154}
155
Chris Lattner12143052006-10-21 00:47:49 +0000156//===----------------------------------------------------------------------===//
157// Tail Merging of Blocks
158//===----------------------------------------------------------------------===//
159
160/// HashMachineInstr - Compute a hash value for MI and its operands.
161static unsigned HashMachineInstr(const MachineInstr *MI) {
162 unsigned Hash = MI->getOpcode();
163 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
164 const MachineOperand &Op = MI->getOperand(i);
165
166 // Merge in bits from the operand if easy.
167 unsigned OperandHash = 0;
168 switch (Op.getType()) {
169 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
170 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
171 case MachineOperand::MO_MachineBasicBlock:
172 OperandHash = Op.getMachineBasicBlock()->getNumber();
173 break;
174 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
175 case MachineOperand::MO_ConstantPoolIndex:
176 OperandHash = Op.getConstantPoolIndex();
177 break;
178 case MachineOperand::MO_JumpTableIndex:
179 OperandHash = Op.getJumpTableIndex();
180 break;
181 case MachineOperand::MO_GlobalAddress:
182 case MachineOperand::MO_ExternalSymbol:
183 // Global address / external symbol are too hard, don't bother, but do
184 // pull in the offset.
185 OperandHash = Op.getOffset();
186 break;
187 default: break;
188 }
189
190 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
191 }
192 return Hash;
193}
194
195/// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
196/// instructions, because cross-jumping only saves code when at least two
197/// instructions are removed (since a branch must be inserted).
198static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
199 MachineBasicBlock::const_iterator I = MBB->end();
200 if (I == MBB->begin())
201 return 0; // Empty MBB.
202
203 --I;
204 unsigned Hash = HashMachineInstr(I);
205
206 if (I == MBB->begin())
207 return Hash; // Single instr MBB.
208
209 --I;
210 // Hash in the second-to-last instruction.
211 Hash ^= HashMachineInstr(I) << 2;
212 return Hash;
213}
214
215/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
216/// of instructions they actually have in common together at their end. Return
217/// iterators for the first shared instruction in each block.
218static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
219 MachineBasicBlock *MBB2,
220 MachineBasicBlock::iterator &I1,
221 MachineBasicBlock::iterator &I2) {
222 I1 = MBB1->end();
223 I2 = MBB2->end();
224
225 unsigned TailLen = 0;
226 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
227 --I1; --I2;
228 if (!I1->isIdenticalTo(I2)) {
229 ++I1; ++I2;
230 break;
231 }
232 ++TailLen;
233 }
234 return TailLen;
235}
236
237/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000238/// after it, replacing it with an unconditional branch to NewDest. This
239/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000240void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
241 MachineBasicBlock *NewDest) {
242 MachineBasicBlock *OldBB = OldInst->getParent();
243
244 // Remove all the old successors of OldBB from the CFG.
245 while (!OldBB->succ_empty())
246 OldBB->removeSuccessor(OldBB->succ_begin());
247
248 // Remove all the dead instructions from the end of OldBB.
249 OldBB->erase(OldInst, OldBB->end());
250
Chris Lattner386e2902006-10-21 05:08:28 +0000251 // If OldBB isn't immediately before OldBB, insert a branch to it.
252 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
253 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner12143052006-10-21 00:47:49 +0000254 OldBB->addSuccessor(NewDest);
255 ++NumTailMerge;
256}
257
258bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
259 MadeChange = false;
260
Chris Lattner323ece62006-10-25 18:08:50 +0000261 return false;
262
Chris Lattner12143052006-10-21 00:47:49 +0000263 // Find blocks with no successors.
264 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
265 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
266 if (I->succ_empty())
267 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
268 }
269
270 // Sort by hash value so that blocks with identical end sequences sort
271 // together.
272 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
273
274 // Walk through equivalence sets looking for actual exact matches.
275 while (MergePotentials.size() > 1) {
276 unsigned CurHash = (MergePotentials.end()-1)->first;
277 unsigned PrevHash = (MergePotentials.end()-2)->first;
278 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
279
280 // If there is nothing that matches the hash of the current basic block,
281 // give up.
282 if (CurHash != PrevHash) {
283 MergePotentials.pop_back();
284 continue;
285 }
286
287 // Determine the actual length of the shared tail between these two basic
288 // blocks. Because the hash can have collisions, it's possible that this is
289 // less than 2.
290 MachineBasicBlock::iterator BBI1, BBI2;
291 unsigned CommonTailLen =
292 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
293 BBI1, BBI2);
294
295 // If the tails don't have at least two instructions in common, see if there
296 // is anything else in the equivalence class that does match.
297 if (CommonTailLen < 2) {
298 unsigned FoundMatch = ~0U;
299 for (int i = MergePotentials.size()-2;
300 i != -1 && MergePotentials[i].first == CurHash; --i) {
301 CommonTailLen = ComputeCommonTailLength(CurMBB,
302 MergePotentials[i].second,
303 BBI1, BBI2);
304 if (CommonTailLen >= 2) {
305 FoundMatch = i;
306 break;
307 }
308 }
309
310 // If we didn't find anything that has at least two instructions matching
311 // this one, bail out.
312 if (FoundMatch == ~0U) {
313 MergePotentials.pop_back();
314 continue;
315 }
316
317 // Otherwise, move the matching block to the right position.
318 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
319 }
320
321 // If either block is the entire common tail, make the longer one branch to
322 // the shorter one.
323 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
324 if (CurMBB->begin() == BBI1) {
325 // Hack the end off MBB2, making it jump to CurMBB instead.
326 ReplaceTailWithBranchTo(BBI2, CurMBB);
327 // This modifies MBB2, so remove it from the worklist.
328 MergePotentials.erase(MergePotentials.end()-2);
329 MadeChange = true;
330 continue;
331 } else if (MBB2->begin() == BBI2) {
332 // Hack the end off CurMBB, making it jump to MBBI@ instead.
333 ReplaceTailWithBranchTo(BBI1, MBB2);
334 // This modifies CurMBB, so remove it from the worklist.
335 MergePotentials.pop_back();
336 MadeChange = true;
337 continue;
338 }
339
340 MergePotentials.pop_back();
341 }
342
343 return MadeChange;
344}
345
346
347//===----------------------------------------------------------------------===//
348// Branch Optimization
349//===----------------------------------------------------------------------===//
350
351bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
352 MadeChange = false;
353
354 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
355 MachineBasicBlock *MBB = I++;
356 OptimizeBlock(MBB);
357
358 // If it is dead, remove it.
359 if (MBB->pred_empty()) {
360 RemoveDeadBlock(MBB);
361 MadeChange = true;
362 ++NumDeadBlocks;
363 }
364 }
365 return MadeChange;
366}
367
368
Chris Lattner386e2902006-10-21 05:08:28 +0000369/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
370/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
371/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
372/// be null.
373static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
374 MachineBasicBlock *DestA,
375 MachineBasicBlock *DestB,
376 bool isCond,
377 MachineFunction::iterator FallThru) {
378 bool MadeChange = false;
379 bool AddedFallThrough = false;
380
381 // If this block ends with a conditional branch that falls through to its
382 // successor, set DestB as the successor.
383 if (isCond) {
384 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
385 DestB = FallThru;
386 AddedFallThrough = true;
387 }
388 } else {
389 // If this is an unconditional branch with no explicit dest, it must just be
390 // a fallthrough into DestB.
391 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
392 DestA = FallThru;
393 AddedFallThrough = true;
394 }
395 }
396
397 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
398 while (SI != MBB.succ_end()) {
399 if (*SI == DestA) {
400 DestA = 0;
401 ++SI;
402 } else if (*SI == DestB) {
403 DestB = 0;
404 ++SI;
405 } else {
406 // Otherwise, this is a superfluous edge, remove it.
407 MBB.removeSuccessor(SI);
408 MadeChange = true;
409 }
410 }
411 if (!AddedFallThrough) {
412 assert(DestA == 0 && DestB == 0 &&
413 "MachineCFG is missing edges!");
414 } else if (isCond) {
415 assert(DestA == 0 && "MachineCFG is missing edges!");
416 }
417 return MadeChange;
418}
419
420
Chris Lattner21ab22e2004-07-31 10:01:27 +0000421/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
422/// 'Old', change the code and CFG so that it branches to 'New' instead.
423static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
424 MachineBasicBlock *Old,
425 MachineBasicBlock *New,
Chris Lattner7821a8a2006-10-14 00:21:48 +0000426 const TargetInstrInfo *TII) {
Chris Lattner21ab22e2004-07-31 10:01:27 +0000427 assert(Old != New && "Cannot replace self with self!");
428
429 MachineBasicBlock::iterator I = BB->end();
430 while (I != BB->begin()) {
431 --I;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000432 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000433
434 // Scan the operands of this machine instruction, replacing any uses of Old
435 // with New.
436 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
437 if (I->getOperand(i).isMachineBasicBlock() &&
438 I->getOperand(i).getMachineBasicBlock() == Old)
439 I->getOperand(i).setMachineBasicBlock(New);
440 }
441
Chris Lattnereb15eee2006-10-13 20:43:10 +0000442 // Update the successor information.
Chris Lattner21ab22e2004-07-31 10:01:27 +0000443 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
444 for (int i = Succs.size()-1; i >= 0; --i)
445 if (Succs[i] == Old) {
446 BB->removeSuccessor(Old);
447 BB->addSuccessor(New);
448 }
449}
450
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000451/// CanFallThrough - Return true if the specified block (with the specified
452/// branch condition) can implicitly transfer control to the block after it by
453/// falling off the end of it. This should return false if it can reach the
454/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
455///
456/// True is a conservative answer.
457///
458bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
459 bool BranchUnAnalyzable,
460 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
461 const std::vector<MachineOperand> &Cond) {
462 MachineFunction::iterator Fallthrough = CurBB;
463 ++Fallthrough;
464 // If FallthroughBlock is off the end of the function, it can't fall through.
465 if (Fallthrough == CurBB->getParent()->end())
466 return false;
467
468 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
469 if (!CurBB->isSuccessor(Fallthrough))
470 return false;
471
472 // If we couldn't analyze the branch, assume it could fall through.
473 if (BranchUnAnalyzable) return true;
474
Chris Lattner7d097842006-10-24 01:12:32 +0000475 // If there is no branch, control always falls through.
476 if (TBB == 0) return true;
477
478 // If there is some explicit branch to the fallthrough block, it can obviously
479 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000480 if (MachineFunction::iterator(TBB) == Fallthrough ||
481 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000482 return true;
483
484 // If it's an unconditional branch to some block not the fall through, it
485 // doesn't fall through.
486 if (Cond.empty()) return false;
487
488 // Otherwise, if it is conditional and has no explicit false block, it falls
489 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000490 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000491}
492
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000493/// CanFallThrough - Return true if the specified can implicitly transfer
494/// control to the block after it by falling off the end of it. This should
495/// return false if it can reach the block after it, but it uses an explicit
496/// branch to do so (e.g. a table jump).
497///
498/// True is a conservative answer.
499///
500bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
501 MachineBasicBlock *TBB = 0, *FBB = 0;
502 std::vector<MachineOperand> Cond;
503 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
504 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
505}
506
Chris Lattner7821a8a2006-10-14 00:21:48 +0000507/// OptimizeBlock - Analyze and optimize control flow related to the specified
508/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000509void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
510 MachineFunction::iterator FallThrough = MBB;
511 ++FallThrough;
512
Chris Lattnereb15eee2006-10-13 20:43:10 +0000513 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner21ab22e2004-07-31 10:01:27 +0000514 // explicitly.
515 if (MBB->empty()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000516 // Dead block? Leave for cleanup later.
517 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000518
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000519 if (FallThrough == MBB->getParent()->end()) {
520 // TODO: Simplify preds to not branch here if possible!
521 } else {
522 // Rewrite all predecessors of the old block to go to the fallthrough
523 // instead.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000524 while (!MBB->pred_empty()) {
525 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
526 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
527 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000528
529 // If MBB was the target of a jump table, update jump tables to go to the
530 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000531 MBB->getParent()->getJumpTableInfo()->
532 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000533 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000534 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000535 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000536 }
537
Chris Lattner7821a8a2006-10-14 00:21:48 +0000538 // Check to see if we can simplify the terminator of the block before this
539 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000540 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000541
Chris Lattner7821a8a2006-10-14 00:21:48 +0000542 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
543 std::vector<MachineOperand> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000544 bool PriorUnAnalyzable =
545 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000546 if (!PriorUnAnalyzable) {
547 // If the CFG for the prior block has extra edges, remove them.
548 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
549 !PriorCond.empty(), MBB);
550
Chris Lattner7821a8a2006-10-14 00:21:48 +0000551 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000552 // destination, remove the branch, replacing it with an unconditional one or
553 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000554 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000555 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000556 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000557 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000558 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000559 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000560 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000561 return OptimizeBlock(MBB);
562 }
563
564 // If the previous branch *only* branches to *this* block (conditional or
565 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000566 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000567 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000568 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000569 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000570 return OptimizeBlock(MBB);
571 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000572
573 // If the prior block branches somewhere else on the condition and here if
574 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000575 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000576 TII->RemoveBranch(PrevBB);
577 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
578 MadeChange = true;
579 ++NumBranchOpts;
580 return OptimizeBlock(MBB);
581 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000582
583 // If the prior block branches here on true and somewhere else on false, and
584 // if the branch condition is reversible, reverse the branch to create a
585 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000586 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000587 std::vector<MachineOperand> NewPriorCond(PriorCond);
588 if (!TII->ReverseBranchCondition(NewPriorCond)) {
589 TII->RemoveBranch(PrevBB);
590 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
591 MadeChange = true;
592 ++NumBranchOpts;
593 return OptimizeBlock(MBB);
594 }
595 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000596 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000597
Chris Lattner386e2902006-10-21 05:08:28 +0000598 // Analyze the branch in the current block.
599 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
600 std::vector<MachineOperand> CurCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000601 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
602 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +0000603 // If the CFG for the prior block has extra edges, remove them.
604 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattner7d097842006-10-24 01:12:32 +0000605 !CurCond.empty(),
606 ++MachineFunction::iterator(MBB));
Chris Lattnereb15eee2006-10-13 20:43:10 +0000607
Chris Lattner386e2902006-10-21 05:08:28 +0000608 // If this branch is the only thing in its block, see if we can forward
609 // other blocks across it.
610 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner7d097842006-10-24 01:12:32 +0000611 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000612 // This block may contain just an unconditional branch. Because there can
613 // be 'non-branch terminators' in the block, try removing the branch and
614 // then seeing if the block is empty.
615 TII->RemoveBranch(*MBB);
616
617 // If this block is just an unconditional branch to CurTBB, we can
618 // usually completely eliminate the block. The only case we cannot
619 // completely eliminate the block is when the block before this one
620 // falls through into MBB and we can't understand the prior block's branch
621 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +0000622 if (MBB->empty()) {
623 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
624 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
625 !PrevBB.isSuccessor(MBB)) {
626 // If the prior block falls through into us, turn it into an
627 // explicit branch to us to make updates simpler.
628 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
629 PriorTBB != MBB && PriorFBB != MBB) {
630 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +0000631 assert(PriorCond.empty() && PriorFBB == 0 &&
632 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +0000633 PriorTBB = MBB;
634 } else {
635 assert(PriorFBB == 0 && "Machine CFG out of date!");
636 PriorFBB = MBB;
637 }
638 TII->RemoveBranch(PrevBB);
639 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000640 }
Chris Lattner386e2902006-10-21 05:08:28 +0000641
Chris Lattnercf420cc2006-10-28 17:32:47 +0000642 // Iterate through all the predecessors, revectoring each in-turn.
643 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
644 bool DidChange = false;
645 bool HasBranchToSelf = false;
646 while (PI != MBB->pred_end()) {
647 if (*PI == MBB) {
648 // If this block has an uncond branch to itself, leave it.
649 ++PI;
650 HasBranchToSelf = true;
651 } else {
652 DidChange = true;
653 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
654 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000655 }
Chris Lattner386e2902006-10-21 05:08:28 +0000656
Chris Lattnercf420cc2006-10-28 17:32:47 +0000657 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +0000658 MBB->getParent()->getJumpTableInfo()->
659 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +0000660 if (DidChange) {
661 ++NumBranchOpts;
662 MadeChange = true;
663 if (!HasBranchToSelf) return;
664 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000665 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000666 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000667
Chris Lattner386e2902006-10-21 05:08:28 +0000668 // Add the branch back if the block is more than just an uncond branch.
669 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +0000670 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000671 }
672
673 // If the prior block doesn't fall through into this block, and if this
674 // block doesn't fall through into some other block, see if we can find a
675 // place to move this block where a fall-through will happen.
676 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
677 PriorTBB, PriorFBB, PriorCond)) {
678 // Now we know that there was no fall-through into this block, check to
679 // see if it has a fall-through into its successor.
680 if (!CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, CurCond)) {
681 // Check all the predecessors of this block. If one of them has no fall
682 // throughs, move this block right after it.
683 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
684 E = MBB->pred_end(); PI != E; ++PI) {
685 // Analyze the branch at the end of the pred.
686 MachineBasicBlock *PredBB = *PI;
687 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
688 MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
689 std::vector<MachineOperand> PredCond;
690 if (PredBB != MBB && !CanFallThrough(PredBB)) {
691 MBB->moveAfter(PredBB);
Chris Lattner7d097842006-10-24 01:12:32 +0000692 MadeChange = true;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000693 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +0000694 }
695 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000696
697 // Check all successors to see if we can move this block before it.
698 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
699 E = MBB->succ_end(); SI != E; ++SI) {
700 // Analyze the branch at the end of the block before the succ.
701 MachineBasicBlock *SuccBB = *SI;
702 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
703 MachineBasicBlock *SuccPrevTBB = 0, *SuccPrevFBB = 0;
704 std::vector<MachineOperand> SuccPrevCond;
705 if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
706 MBB->moveBefore(SuccBB);
707 MadeChange = true;
708 return OptimizeBlock(MBB);
709 }
710 }
711
712 // Okay, there is no really great place to put this block. If, however,
713 // the block before this one would be a fall-through if this block were
714 // removed, move this block to the end of the function.
715 if (FallThrough != MBB->getParent()->end() &&
716 PrevBB.isSuccessor(FallThrough)) {
717 MBB->moveAfter(--MBB->getParent()->end());
718 MadeChange = true;
719 return;
720 }
Chris Lattner7d097842006-10-24 01:12:32 +0000721 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000722 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000723}