blob: dc527b9fd54973b3d68fc5abd0d42d71ce4bd0fb [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 Lattner60c9d4d2006-10-21 00:47:49 +000033
Chris Lattner25e48dd2004-07-31 10:01:27 +000034namespace {
35 struct BranchFolder : public MachineFunctionPass {
36 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner3218e0e2006-10-14 00:21:48 +000037 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
38 const TargetInstrInfo *TII;
Chris Lattner73da3202006-10-17 23:17:27 +000039 MachineDebugInfo *MDI;
Chris Lattner3218e0e2006-10-14 00:21:48 +000040 bool MadeChange;
Chris Lattner25e48dd2004-07-31 10:01:27 +000041 private:
Chris Lattner60c9d4d2006-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 Lattnerceb51d82006-10-24 01:12:32 +000049 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner73da3202006-10-17 23:17:27 +000050 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner25e48dd2004-07-31 10:01:27 +000051 };
52}
53
54FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
55
Chris Lattner56c9d252006-10-17 17:13:52 +000056/// RemoveDeadBlock - Remove the specified dead machine basic block from the
57/// function, updating the CFG.
Chris Lattner73da3202006-10-17 23:17:27 +000058void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Chris Lattner56c9d252006-10-17 17:13:52 +000059 assert(MBB->pred_empty() && "MBB must be dead!");
Chris Lattner73da3202006-10-17 23:17:27 +000060
Chris Lattner56c9d252006-10-17 17:13:52 +000061 MachineFunction *MF = MBB->getParent();
62 // drop all successors.
63 while (!MBB->succ_empty())
64 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner73da3202006-10-17 23:17:27 +000065
66 // If there is DWARF info to active, check to see if there are any DWARF_LABEL
67 // records in the basic block. If so, unregister them from MachineDebugInfo.
68 if (MDI && !MBB->empty()) {
69 unsigned DWARF_LABELOpc = TII->getDWARF_LABELOpcode();
70 assert(DWARF_LABELOpc &&
71 "Target supports dwarf but didn't implement getDWARF_LABELOpcode!");
72
73 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
74 I != E; ++I) {
75 if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
76 // The label ID # is always operand #0, an immediate.
Jim Laskey5e1a3402006-10-23 14:56:37 +000077 MDI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner73da3202006-10-17 23:17:27 +000078 }
79 }
80 }
81
Chris Lattner56c9d252006-10-17 17:13:52 +000082 // Remove the block.
83 MF->getBasicBlockList().erase(MBB);
84}
85
Chris Lattner25e48dd2004-07-31 10:01:27 +000086bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner3218e0e2006-10-14 00:21:48 +000087 TII = MF.getTarget().getInstrInfo();
88 if (!TII) return false;
89
Chris Lattner73da3202006-10-17 23:17:27 +000090 MDI = getAnalysisToUpdate<MachineDebugInfo>();
Chris Lattner3218e0e2006-10-14 00:21:48 +000091
Chris Lattner25e48dd2004-07-31 10:01:27 +000092 bool EverMadeChange = false;
Chris Lattner60c9d4d2006-10-21 00:47:49 +000093 bool MadeChangeThisIteration = true;
94 while (MadeChangeThisIteration) {
95 MadeChangeThisIteration = false;
96 MadeChangeThisIteration |= TailMergeBlocks(MF);
97 MadeChangeThisIteration |= OptimizeBranches(MF);
98 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner25e48dd2004-07-31 10:01:27 +000099 }
100
Chris Lattnerc07657f2006-10-28 18:34:47 +0000101 // See if any jump tables have become mergable or dead as the code generator
102 // did its thing.
103 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
104 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
105 if (!JTs.empty()) {
106 // Figure out how these jump tables should be merged.
107 std::vector<unsigned> JTMapping;
108 JTMapping.reserve(JTs.size());
109
110 // We always keep the 0th jump table.
111 JTMapping.push_back(0);
112
113 // Scan the jump tables, seeing if there are any duplicates. Note that this
114 // is N^2, which should be fixed someday.
115 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
116 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
117
118 // If a jump table was merge with another one, walk the function rewriting
119 // references to jump tables to reference the new JT ID's. Keep track of
120 // whether we see a jump table idx, if not, we can delete the JT.
121 std::vector<bool> JTIsLive;
122 JTIsLive.resize(JTs.size());
123 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
124 BB != E; ++BB) {
125 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
126 I != E; ++I)
127 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
128 MachineOperand &Op = I->getOperand(op);
129 if (!Op.isJumpTableIndex()) continue;
130 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
131 Op.setJumpTableIndex(NewIdx);
132
133 // Remember that this JT is live.
134 JTIsLive[NewIdx] = true;
135 }
136 }
137
138 // Finally, remove dead jump tables. This happens either because the
139 // indirect jump was unreachable (and thus deleted) or because the jump
140 // table was merged with some other one.
141 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
142 if (!JTIsLive[i]) {
143 JTI->RemoveJumpTable(i);
144 EverMadeChange = true;
145 }
146 }
147
Chris Lattner25e48dd2004-07-31 10:01:27 +0000148 return EverMadeChange;
149}
150
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000151//===----------------------------------------------------------------------===//
152// Tail Merging of Blocks
153//===----------------------------------------------------------------------===//
154
155/// HashMachineInstr - Compute a hash value for MI and its operands.
156static unsigned HashMachineInstr(const MachineInstr *MI) {
157 unsigned Hash = MI->getOpcode();
158 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
159 const MachineOperand &Op = MI->getOperand(i);
160
161 // Merge in bits from the operand if easy.
162 unsigned OperandHash = 0;
163 switch (Op.getType()) {
164 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
165 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
166 case MachineOperand::MO_MachineBasicBlock:
167 OperandHash = Op.getMachineBasicBlock()->getNumber();
168 break;
169 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
170 case MachineOperand::MO_ConstantPoolIndex:
171 OperandHash = Op.getConstantPoolIndex();
172 break;
173 case MachineOperand::MO_JumpTableIndex:
174 OperandHash = Op.getJumpTableIndex();
175 break;
176 case MachineOperand::MO_GlobalAddress:
177 case MachineOperand::MO_ExternalSymbol:
178 // Global address / external symbol are too hard, don't bother, but do
179 // pull in the offset.
180 OperandHash = Op.getOffset();
181 break;
182 default: break;
183 }
184
185 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
186 }
187 return Hash;
188}
189
190/// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
191/// instructions, because cross-jumping only saves code when at least two
192/// instructions are removed (since a branch must be inserted).
193static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
194 MachineBasicBlock::const_iterator I = MBB->end();
195 if (I == MBB->begin())
196 return 0; // Empty MBB.
197
198 --I;
199 unsigned Hash = HashMachineInstr(I);
200
201 if (I == MBB->begin())
202 return Hash; // Single instr MBB.
203
204 --I;
205 // Hash in the second-to-last instruction.
206 Hash ^= HashMachineInstr(I) << 2;
207 return Hash;
208}
209
210/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
211/// of instructions they actually have in common together at their end. Return
212/// iterators for the first shared instruction in each block.
213static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
214 MachineBasicBlock *MBB2,
215 MachineBasicBlock::iterator &I1,
216 MachineBasicBlock::iterator &I2) {
217 I1 = MBB1->end();
218 I2 = MBB2->end();
219
220 unsigned TailLen = 0;
221 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
222 --I1; --I2;
223 if (!I1->isIdenticalTo(I2)) {
224 ++I1; ++I2;
225 break;
226 }
227 ++TailLen;
228 }
229 return TailLen;
230}
231
232/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner4fe01c42006-10-21 05:08:28 +0000233/// after it, replacing it with an unconditional branch to NewDest. This
234/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000235void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
236 MachineBasicBlock *NewDest) {
237 MachineBasicBlock *OldBB = OldInst->getParent();
238
239 // Remove all the old successors of OldBB from the CFG.
240 while (!OldBB->succ_empty())
241 OldBB->removeSuccessor(OldBB->succ_begin());
242
243 // Remove all the dead instructions from the end of OldBB.
244 OldBB->erase(OldInst, OldBB->end());
245
Chris Lattner4fe01c42006-10-21 05:08:28 +0000246 // If OldBB isn't immediately before OldBB, insert a branch to it.
247 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
248 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000249 OldBB->addSuccessor(NewDest);
250 ++NumTailMerge;
251}
252
253bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
254 MadeChange = false;
255
Chris Lattner9feb3082006-10-25 18:08:50 +0000256 return false;
257
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000258 // Find blocks with no successors.
259 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
260 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
261 if (I->succ_empty())
262 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
263 }
264
265 // Sort by hash value so that blocks with identical end sequences sort
266 // together.
267 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
268
269 // Walk through equivalence sets looking for actual exact matches.
270 while (MergePotentials.size() > 1) {
271 unsigned CurHash = (MergePotentials.end()-1)->first;
272 unsigned PrevHash = (MergePotentials.end()-2)->first;
273 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
274
275 // If there is nothing that matches the hash of the current basic block,
276 // give up.
277 if (CurHash != PrevHash) {
278 MergePotentials.pop_back();
279 continue;
280 }
281
282 // Determine the actual length of the shared tail between these two basic
283 // blocks. Because the hash can have collisions, it's possible that this is
284 // less than 2.
285 MachineBasicBlock::iterator BBI1, BBI2;
286 unsigned CommonTailLen =
287 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
288 BBI1, BBI2);
289
290 // If the tails don't have at least two instructions in common, see if there
291 // is anything else in the equivalence class that does match.
292 if (CommonTailLen < 2) {
293 unsigned FoundMatch = ~0U;
294 for (int i = MergePotentials.size()-2;
295 i != -1 && MergePotentials[i].first == CurHash; --i) {
296 CommonTailLen = ComputeCommonTailLength(CurMBB,
297 MergePotentials[i].second,
298 BBI1, BBI2);
299 if (CommonTailLen >= 2) {
300 FoundMatch = i;
301 break;
302 }
303 }
304
305 // If we didn't find anything that has at least two instructions matching
306 // this one, bail out.
307 if (FoundMatch == ~0U) {
308 MergePotentials.pop_back();
309 continue;
310 }
311
312 // Otherwise, move the matching block to the right position.
313 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
314 }
315
316 // If either block is the entire common tail, make the longer one branch to
317 // the shorter one.
318 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
319 if (CurMBB->begin() == BBI1) {
320 // Hack the end off MBB2, making it jump to CurMBB instead.
321 ReplaceTailWithBranchTo(BBI2, CurMBB);
322 // This modifies MBB2, so remove it from the worklist.
323 MergePotentials.erase(MergePotentials.end()-2);
324 MadeChange = true;
325 continue;
326 } else if (MBB2->begin() == BBI2) {
327 // Hack the end off CurMBB, making it jump to MBBI@ instead.
328 ReplaceTailWithBranchTo(BBI1, MBB2);
329 // This modifies CurMBB, so remove it from the worklist.
330 MergePotentials.pop_back();
331 MadeChange = true;
332 continue;
333 }
334
335 MergePotentials.pop_back();
336 }
337
338 return MadeChange;
339}
340
341
342//===----------------------------------------------------------------------===//
343// Branch Optimization
344//===----------------------------------------------------------------------===//
345
346bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
347 MadeChange = false;
348
349 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
350 MachineBasicBlock *MBB = I++;
351 OptimizeBlock(MBB);
352
353 // If it is dead, remove it.
354 if (MBB->pred_empty()) {
355 RemoveDeadBlock(MBB);
356 MadeChange = true;
357 ++NumDeadBlocks;
358 }
359 }
360 return MadeChange;
361}
362
363
Chris Lattner4fe01c42006-10-21 05:08:28 +0000364/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
365/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
366/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
367/// be null.
368static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
369 MachineBasicBlock *DestA,
370 MachineBasicBlock *DestB,
371 bool isCond,
372 MachineFunction::iterator FallThru) {
373 bool MadeChange = false;
374 bool AddedFallThrough = false;
375
376 // If this block ends with a conditional branch that falls through to its
377 // successor, set DestB as the successor.
378 if (isCond) {
379 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
380 DestB = FallThru;
381 AddedFallThrough = true;
382 }
383 } else {
384 // If this is an unconditional branch with no explicit dest, it must just be
385 // a fallthrough into DestB.
386 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
387 DestA = FallThru;
388 AddedFallThrough = true;
389 }
390 }
391
392 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
393 while (SI != MBB.succ_end()) {
394 if (*SI == DestA) {
395 DestA = 0;
396 ++SI;
397 } else if (*SI == DestB) {
398 DestB = 0;
399 ++SI;
400 } else {
401 // Otherwise, this is a superfluous edge, remove it.
402 MBB.removeSuccessor(SI);
403 MadeChange = true;
404 }
405 }
406 if (!AddedFallThrough) {
407 assert(DestA == 0 && DestB == 0 &&
408 "MachineCFG is missing edges!");
409 } else if (isCond) {
410 assert(DestA == 0 && "MachineCFG is missing edges!");
411 }
412 return MadeChange;
413}
414
415
Chris Lattner25e48dd2004-07-31 10:01:27 +0000416/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
417/// 'Old', change the code and CFG so that it branches to 'New' instead.
418static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
419 MachineBasicBlock *Old,
420 MachineBasicBlock *New,
Chris Lattner3218e0e2006-10-14 00:21:48 +0000421 const TargetInstrInfo *TII) {
Chris Lattner25e48dd2004-07-31 10:01:27 +0000422 assert(Old != New && "Cannot replace self with self!");
423
424 MachineBasicBlock::iterator I = BB->end();
425 while (I != BB->begin()) {
426 --I;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000427 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000428
429 // Scan the operands of this machine instruction, replacing any uses of Old
430 // with New.
431 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
432 if (I->getOperand(i).isMachineBasicBlock() &&
433 I->getOperand(i).getMachineBasicBlock() == Old)
434 I->getOperand(i).setMachineBasicBlock(New);
435 }
436
Chris Lattner3e8e57c2006-10-13 20:43:10 +0000437 // Update the successor information.
Chris Lattner25e48dd2004-07-31 10:01:27 +0000438 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
439 for (int i = Succs.size()-1; i >= 0; --i)
440 if (Succs[i] == Old) {
441 BB->removeSuccessor(Old);
442 BB->addSuccessor(New);
443 }
444}
445
Chris Lattnerceb51d82006-10-24 01:12:32 +0000446/// CanFallThrough - Return true of the specified branch condition can transfer
447/// control to FallthroughBlock, the block immediately after the branch.
448static bool CanFallThrough(MachineBasicBlock *TBB,
449 MachineBasicBlock *FBB,
450 const std::vector<MachineOperand> &Cond,
451 MachineFunction::iterator FallthroughBlock) {
452 // If there is no branch, control always falls through.
453 if (TBB == 0) return true;
454
455 // If there is some explicit branch to the fallthrough block, it can obviously
456 // reach, even though the branch should get folded to fall through implicitly.
457 if (MachineFunction::iterator(TBB) == FallthroughBlock ||
458 MachineFunction::iterator(FBB) == FallthroughBlock)
459 return true;
460
461 // If it's an unconditional branch to some block not the fall through, it
462 // doesn't fall through.
463 if (Cond.empty()) return false;
464
465 // Otherwise, if it is conditional and has no explicit false block, it falls
466 // through.
Chris Lattner0d4479b72006-10-25 22:21:37 +0000467 return FBB == 0;
Chris Lattnerceb51d82006-10-24 01:12:32 +0000468}
469
Chris Lattner3218e0e2006-10-14 00:21:48 +0000470/// OptimizeBlock - Analyze and optimize control flow related to the specified
471/// block. This is never called on the entry block.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000472void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
473 MachineFunction::iterator FallThrough = MBB;
474 ++FallThrough;
475
Chris Lattner3e8e57c2006-10-13 20:43:10 +0000476 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner25e48dd2004-07-31 10:01:27 +0000477 // explicitly.
478 if (MBB->empty()) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000479 // Dead block? Leave for cleanup later.
480 if (MBB->pred_empty()) return;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000481
Chris Lattner56c9d252006-10-17 17:13:52 +0000482 if (FallThrough == MBB->getParent()->end()) {
483 // TODO: Simplify preds to not branch here if possible!
484 } else {
485 // Rewrite all predecessors of the old block to go to the fallthrough
486 // instead.
Chris Lattner3218e0e2006-10-14 00:21:48 +0000487 while (!MBB->pred_empty()) {
488 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
489 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
490 }
Chris Lattner56c9d252006-10-17 17:13:52 +0000491
492 // If MBB was the target of a jump table, update jump tables to go to the
493 // fallthrough instead.
Chris Lattnerc07657f2006-10-28 18:34:47 +0000494 MBB->getParent()->getJumpTableInfo()->
495 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner3218e0e2006-10-14 00:21:48 +0000496 MadeChange = true;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000497 }
Chris Lattner3218e0e2006-10-14 00:21:48 +0000498 return;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000499 }
500
Chris Lattner3218e0e2006-10-14 00:21:48 +0000501 // Check to see if we can simplify the terminator of the block before this
502 // one.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000503 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerbca3e292006-10-17 18:16:40 +0000504
Chris Lattner3218e0e2006-10-14 00:21:48 +0000505 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
506 std::vector<MachineOperand> PriorCond;
Chris Lattner4fe01c42006-10-21 05:08:28 +0000507 bool PriorUnAnalyzable = false;
508 PriorUnAnalyzable = TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
509 if (!PriorUnAnalyzable) {
510 // If the CFG for the prior block has extra edges, remove them.
511 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
512 !PriorCond.empty(), MBB);
513
Chris Lattner3218e0e2006-10-14 00:21:48 +0000514 // If the previous branch is conditional and both conditions go to the same
Chris Lattner3ca52182006-10-21 05:43:30 +0000515 // destination, remove the branch, replacing it with an unconditional one or
516 // a fall-through.
Chris Lattner3218e0e2006-10-14 00:21:48 +0000517 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000518 TII->RemoveBranch(PrevBB);
Chris Lattner3218e0e2006-10-14 00:21:48 +0000519 PriorCond.clear();
Chris Lattnerceb51d82006-10-24 01:12:32 +0000520 if (PriorTBB != MBB)
Chris Lattner4fe01c42006-10-21 05:08:28 +0000521 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner3218e0e2006-10-14 00:21:48 +0000522 MadeChange = true;
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000523 ++NumBranchOpts;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000524 return OptimizeBlock(MBB);
525 }
526
527 // If the previous branch *only* branches to *this* block (conditional or
528 // not) remove the branch.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000529 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000530 TII->RemoveBranch(PrevBB);
Chris Lattner3218e0e2006-10-14 00:21:48 +0000531 MadeChange = true;
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000532 ++NumBranchOpts;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000533 return OptimizeBlock(MBB);
534 }
Chris Lattner3ca52182006-10-21 05:43:30 +0000535
536 // If the prior block branches somewhere else on the condition and here if
537 // the condition is false, remove the uncond second branch.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000538 if (PriorFBB == MBB) {
Chris Lattner3ca52182006-10-21 05:43:30 +0000539 TII->RemoveBranch(PrevBB);
540 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
541 MadeChange = true;
542 ++NumBranchOpts;
543 return OptimizeBlock(MBB);
544 }
Chris Lattner28f17f42006-10-21 05:54:00 +0000545
546 // If the prior block branches here on true and somewhere else on false, and
547 // if the branch condition is reversible, reverse the branch to create a
548 // fall-through.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000549 if (PriorTBB == MBB) {
Chris Lattner28f17f42006-10-21 05:54:00 +0000550 std::vector<MachineOperand> NewPriorCond(PriorCond);
551 if (!TII->ReverseBranchCondition(NewPriorCond)) {
552 TII->RemoveBranch(PrevBB);
553 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
554 MadeChange = true;
555 ++NumBranchOpts;
556 return OptimizeBlock(MBB);
557 }
558 }
Chris Lattner3218e0e2006-10-14 00:21:48 +0000559 }
Chris Lattner3218e0e2006-10-14 00:21:48 +0000560
Chris Lattner4fe01c42006-10-21 05:08:28 +0000561 // Analyze the branch in the current block.
562 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
563 std::vector<MachineOperand> CurCond;
564 if (!TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond)) {
565 // If the CFG for the prior block has extra edges, remove them.
566 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattnerceb51d82006-10-24 01:12:32 +0000567 !CurCond.empty(),
568 ++MachineFunction::iterator(MBB));
Chris Lattner3e8e57c2006-10-13 20:43:10 +0000569
Chris Lattner4fe01c42006-10-21 05:08:28 +0000570 // If this branch is the only thing in its block, see if we can forward
571 // other blocks across it.
572 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattnerceb51d82006-10-24 01:12:32 +0000573 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000574 // This block may contain just an unconditional branch. Because there can
575 // be 'non-branch terminators' in the block, try removing the branch and
576 // then seeing if the block is empty.
577 TII->RemoveBranch(*MBB);
578
579 // If this block is just an unconditional branch to CurTBB, we can
580 // usually completely eliminate the block. The only case we cannot
581 // completely eliminate the block is when the block before this one
582 // falls through into MBB and we can't understand the prior block's branch
583 // condition.
Chris Lattneraf838382006-10-28 17:32:47 +0000584 if (MBB->empty()) {
585 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
586 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
587 !PrevBB.isSuccessor(MBB)) {
588 // If the prior block falls through into us, turn it into an
589 // explicit branch to us to make updates simpler.
590 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
591 PriorTBB != MBB && PriorFBB != MBB) {
592 if (PriorTBB == 0) {
Chris Lattnerc07657f2006-10-28 18:34:47 +0000593 assert(PriorCond.empty() && PriorFBB == 0 &&
594 "Bad branch analysis");
Chris Lattneraf838382006-10-28 17:32:47 +0000595 PriorTBB = MBB;
596 } else {
597 assert(PriorFBB == 0 && "Machine CFG out of date!");
598 PriorFBB = MBB;
599 }
600 TII->RemoveBranch(PrevBB);
601 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner4fe01c42006-10-21 05:08:28 +0000602 }
Chris Lattner4fe01c42006-10-21 05:08:28 +0000603
Chris Lattneraf838382006-10-28 17:32:47 +0000604 // Iterate through all the predecessors, revectoring each in-turn.
605 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
606 bool DidChange = false;
607 bool HasBranchToSelf = false;
608 while (PI != MBB->pred_end()) {
609 if (*PI == MBB) {
610 // If this block has an uncond branch to itself, leave it.
611 ++PI;
612 HasBranchToSelf = true;
613 } else {
614 DidChange = true;
615 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
616 }
Chris Lattner9f5a1292006-10-21 06:11:43 +0000617 }
Chris Lattner4fe01c42006-10-21 05:08:28 +0000618
Chris Lattneraf838382006-10-28 17:32:47 +0000619 // Change any jumptables to go to the new MBB.
Chris Lattnerc07657f2006-10-28 18:34:47 +0000620 MBB->getParent()->getJumpTableInfo()->
621 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattneraf838382006-10-28 17:32:47 +0000622 if (DidChange) {
623 ++NumBranchOpts;
624 MadeChange = true;
625 if (!HasBranchToSelf) return;
626 }
Chris Lattner9f5a1292006-10-21 06:11:43 +0000627 }
Chris Lattner3e8e57c2006-10-13 20:43:10 +0000628 }
Chris Lattner3e8e57c2006-10-13 20:43:10 +0000629
Chris Lattner4fe01c42006-10-21 05:08:28 +0000630 // Add the branch back if the block is more than just an uncond branch.
631 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner25e48dd2004-07-31 10:01:27 +0000632 }
Chris Lattnerceb51d82006-10-24 01:12:32 +0000633
634 // If the prior block doesn't fall through into this block, and if this
635 // block doesn't fall through into some other block, see if we can find a
636 // place to move this block where a fall-through will happen.
637 if (!PriorUnAnalyzable && !CanFallThrough(PriorTBB, PriorFBB,
638 PriorCond, MBB)) {
639 // Now we know that there was no fall-through into this block, check to
640 // see if it has fall-throughs.
641 if (!CanFallThrough(CurTBB, CurFBB, CurCond, FallThrough)) {
642
643 // Check all the predecessors of this block. If one of them has no fall
644 // throughs, move this block right after it.
645 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
646 E = MBB->pred_end(); PI != E; ++PI) {
647 // Analyze the branch at the end of the pred.
648 MachineBasicBlock *PredBB = *PI;
649 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
650 MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
651 std::vector<MachineOperand> PredCond;
652 if (PredBB != MBB &&
653 !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond) &&
654 !CanFallThrough(PredTBB, PredFBB, PredCond, PredFallthrough)) {
655 MBB->moveAfter(PredBB);
656 MadeChange = true;
657 return OptimizeBlock(MBB);
658 }
659 }
660
661 // Check all successors to see if we can move this block before it.
662 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
663 E = MBB->succ_end(); SI != E; ++SI) {
664 // Analyze the branch at the end of the block before the succ.
665 MachineBasicBlock *SuccBB = *SI;
666 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
667 MachineBasicBlock *SuccPrevTBB = 0, *SuccPrevFBB = 0;
668 std::vector<MachineOperand> SuccPrevCond;
669 if (SuccBB != MBB &&
670 !TII->AnalyzeBranch(*SuccPrev, SuccPrevTBB, SuccPrevFBB,
671 SuccPrevCond) &&
672 !CanFallThrough(SuccPrevTBB, SuccPrevFBB, SuccPrevCond, SuccBB)) {
673 MBB->moveBefore(SuccBB);
674 MadeChange = true;
675 return OptimizeBlock(MBB);
676 }
677 }
678
679 // Okay, there is no really great place to put this block. If, however,
680 // the block before this one would be a fall-through if this block were
681 // removed, move this block to the end of the function.
682 if (FallThrough != MBB->getParent()->end() &&
683 CanFallThrough(PriorTBB, PriorFBB, PriorCond, FallThrough)) {
684 MBB->moveAfter(--MBB->getParent()->end());
685 MadeChange = true;
686 return;
687 }
688 }
689 }
Chris Lattner25e48dd2004-07-31 10:01:27 +0000690 }
Chris Lattner25e48dd2004-07-31 10:01:27 +0000691}