blob: 97587d50122c64c88cf89942de87f42cff39bb59 [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 Lattnerd8ccff02006-11-01 00:38:31 +000033static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
Chris Lattner12143052006-10-21 00:47:49 +000034
Chris Lattner21ab22e2004-07-31 10:01:27 +000035namespace {
36 struct BranchFolder : public MachineFunctionPass {
37 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner7821a8a2006-10-14 00:21:48 +000038 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
39 const TargetInstrInfo *TII;
Chris Lattner683747a2006-10-17 23:17:27 +000040 MachineDebugInfo *MDI;
Chris Lattner7821a8a2006-10-14 00:21:48 +000041 bool MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +000042 private:
Chris Lattner12143052006-10-21 00:47:49 +000043 // Tail Merging.
44 bool TailMergeBlocks(MachineFunction &MF);
45 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
46 MachineBasicBlock *NewDest);
Chris Lattner1d08d832006-11-01 01:16:12 +000047 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
48 MachineBasicBlock::iterator BBI1);
49
Chris Lattner12143052006-10-21 00:47:49 +000050 // Branch optzn.
51 bool OptimizeBranches(MachineFunction &MF);
Chris Lattner7d097842006-10-24 01:12:32 +000052 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000053 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner6b0e3f82006-10-29 21:05:41 +000054
55 bool CanFallThrough(MachineBasicBlock *CurBB);
56 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
57 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
58 const std::vector<MachineOperand> &Cond);
Chris Lattner21ab22e2004-07-31 10:01:27 +000059 };
60}
61
62FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
63
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000064/// RemoveDeadBlock - Remove the specified dead machine basic block from the
65/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +000066void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000067 assert(MBB->pred_empty() && "MBB must be dead!");
Chris Lattner683747a2006-10-17 23:17:27 +000068
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000069 MachineFunction *MF = MBB->getParent();
70 // drop all successors.
71 while (!MBB->succ_empty())
72 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +000073
74 // If there is DWARF info to active, check to see if there are any DWARF_LABEL
75 // records in the basic block. If so, unregister them from MachineDebugInfo.
76 if (MDI && !MBB->empty()) {
77 unsigned DWARF_LABELOpc = TII->getDWARF_LABELOpcode();
78 assert(DWARF_LABELOpc &&
79 "Target supports dwarf but didn't implement getDWARF_LABELOpcode!");
80
81 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
82 I != E; ++I) {
83 if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
84 // The label ID # is always operand #0, an immediate.
Jim Laskey66ebf092006-10-23 14:56:37 +000085 MDI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +000086 }
87 }
88 }
89
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000090 // Remove the block.
91 MF->getBasicBlockList().erase(MBB);
92}
93
Chris Lattner21ab22e2004-07-31 10:01:27 +000094bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner7821a8a2006-10-14 00:21:48 +000095 TII = MF.getTarget().getInstrInfo();
96 if (!TII) return false;
97
Chris Lattner683747a2006-10-17 23:17:27 +000098 MDI = getAnalysisToUpdate<MachineDebugInfo>();
Chris Lattner7821a8a2006-10-14 00:21:48 +000099
Chris Lattner21ab22e2004-07-31 10:01:27 +0000100 bool EverMadeChange = false;
Chris Lattner12143052006-10-21 00:47:49 +0000101 bool MadeChangeThisIteration = true;
102 while (MadeChangeThisIteration) {
103 MadeChangeThisIteration = false;
104 MadeChangeThisIteration |= TailMergeBlocks(MF);
105 MadeChangeThisIteration |= OptimizeBranches(MF);
106 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000107 }
108
Chris Lattner6acfe122006-10-28 18:34:47 +0000109 // See if any jump tables have become mergable or dead as the code generator
110 // did its thing.
111 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
112 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
113 if (!JTs.empty()) {
114 // Figure out how these jump tables should be merged.
115 std::vector<unsigned> JTMapping;
116 JTMapping.reserve(JTs.size());
117
118 // We always keep the 0th jump table.
119 JTMapping.push_back(0);
120
121 // Scan the jump tables, seeing if there are any duplicates. Note that this
122 // is N^2, which should be fixed someday.
123 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
124 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
125
126 // If a jump table was merge with another one, walk the function rewriting
127 // references to jump tables to reference the new JT ID's. Keep track of
128 // whether we see a jump table idx, if not, we can delete the JT.
129 std::vector<bool> JTIsLive;
130 JTIsLive.resize(JTs.size());
131 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
132 BB != E; ++BB) {
133 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
134 I != E; ++I)
135 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
136 MachineOperand &Op = I->getOperand(op);
137 if (!Op.isJumpTableIndex()) continue;
138 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
139 Op.setJumpTableIndex(NewIdx);
140
141 // Remember that this JT is live.
142 JTIsLive[NewIdx] = true;
143 }
144 }
145
146 // Finally, remove dead jump tables. This happens either because the
147 // indirect jump was unreachable (and thus deleted) or because the jump
148 // table was merged with some other one.
149 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
150 if (!JTIsLive[i]) {
151 JTI->RemoveJumpTable(i);
152 EverMadeChange = true;
153 }
154 }
155
Chris Lattner21ab22e2004-07-31 10:01:27 +0000156 return EverMadeChange;
157}
158
Chris Lattner12143052006-10-21 00:47:49 +0000159//===----------------------------------------------------------------------===//
160// Tail Merging of Blocks
161//===----------------------------------------------------------------------===//
162
163/// HashMachineInstr - Compute a hash value for MI and its operands.
164static unsigned HashMachineInstr(const MachineInstr *MI) {
165 unsigned Hash = MI->getOpcode();
166 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
167 const MachineOperand &Op = MI->getOperand(i);
168
169 // Merge in bits from the operand if easy.
170 unsigned OperandHash = 0;
171 switch (Op.getType()) {
172 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
173 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
174 case MachineOperand::MO_MachineBasicBlock:
175 OperandHash = Op.getMachineBasicBlock()->getNumber();
176 break;
177 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
178 case MachineOperand::MO_ConstantPoolIndex:
179 OperandHash = Op.getConstantPoolIndex();
180 break;
181 case MachineOperand::MO_JumpTableIndex:
182 OperandHash = Op.getJumpTableIndex();
183 break;
184 case MachineOperand::MO_GlobalAddress:
185 case MachineOperand::MO_ExternalSymbol:
186 // Global address / external symbol are too hard, don't bother, but do
187 // pull in the offset.
188 OperandHash = Op.getOffset();
189 break;
190 default: break;
191 }
192
193 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
194 }
195 return Hash;
196}
197
198/// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
199/// instructions, because cross-jumping only saves code when at least two
200/// instructions are removed (since a branch must be inserted).
201static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
202 MachineBasicBlock::const_iterator I = MBB->end();
203 if (I == MBB->begin())
204 return 0; // Empty MBB.
205
206 --I;
207 unsigned Hash = HashMachineInstr(I);
208
209 if (I == MBB->begin())
210 return Hash; // Single instr MBB.
211
212 --I;
213 // Hash in the second-to-last instruction.
214 Hash ^= HashMachineInstr(I) << 2;
215 return Hash;
216}
217
218/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
219/// of instructions they actually have in common together at their end. Return
220/// iterators for the first shared instruction in each block.
221static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
222 MachineBasicBlock *MBB2,
223 MachineBasicBlock::iterator &I1,
224 MachineBasicBlock::iterator &I2) {
225 I1 = MBB1->end();
226 I2 = MBB2->end();
227
228 unsigned TailLen = 0;
229 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
230 --I1; --I2;
231 if (!I1->isIdenticalTo(I2)) {
232 ++I1; ++I2;
233 break;
234 }
235 ++TailLen;
236 }
237 return TailLen;
238}
239
240/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000241/// after it, replacing it with an unconditional branch to NewDest. This
242/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000243void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
244 MachineBasicBlock *NewDest) {
245 MachineBasicBlock *OldBB = OldInst->getParent();
246
247 // Remove all the old successors of OldBB from the CFG.
248 while (!OldBB->succ_empty())
249 OldBB->removeSuccessor(OldBB->succ_begin());
250
251 // Remove all the dead instructions from the end of OldBB.
252 OldBB->erase(OldInst, OldBB->end());
253
Chris Lattner386e2902006-10-21 05:08:28 +0000254 // If OldBB isn't immediately before OldBB, insert a branch to it.
255 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
256 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner12143052006-10-21 00:47:49 +0000257 OldBB->addSuccessor(NewDest);
258 ++NumTailMerge;
259}
260
Chris Lattner1d08d832006-11-01 01:16:12 +0000261/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
262/// MBB so that the part before the iterator falls into the part starting at the
263/// iterator. This returns the new MBB.
264MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
265 MachineBasicBlock::iterator BBI1) {
266 // Create the fall-through block.
267 MachineFunction::iterator MBBI = &CurMBB;
268 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
269 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
270
271 // Move all the successors of this block to the specified block.
272 while (!CurMBB.succ_empty()) {
273 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
274 NewMBB->addSuccessor(S);
275 CurMBB.removeSuccessor(S);
276 }
277
278 // Add an edge from CurMBB to NewMBB for the fall-through.
279 CurMBB.addSuccessor(NewMBB);
280
281 // Splice the code over.
282 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
283 return NewMBB;
284}
285
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000286/// EstimateRuntime - Make a rough estimate for how long it will take to run
287/// the specified code.
288static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
289 MachineBasicBlock::iterator E,
290 const TargetInstrInfo *TII) {
291 unsigned Time = 0;
292 for (; I != E; ++I) {
293 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
294 if (TID.Flags & M_CALL_FLAG)
295 Time += 10;
296 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
297 Time += 2;
298 else
299 ++Time;
300 }
301 return Time;
302}
303
304/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
305/// MBB2I and then insert an unconditional branch in the other block. Determine
306/// which is the best to split
307static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
308 MachineBasicBlock::iterator MBB1I,
309 MachineBasicBlock *MBB2,
310 MachineBasicBlock::iterator MBB2I,
311 const TargetInstrInfo *TII) {
312 // TODO: if we had some notion of which block was hotter, we could split
313 // the hot block, so it is the fall-through. Since we don't have profile info
314 // make a decision based on which will hurt most to split.
315 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
316 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
317
318 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
319 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
320 // have a lower overall impact on the program execution.
321 return MBB1Time < MBB2Time;
322}
323
Chris Lattner12143052006-10-21 00:47:49 +0000324bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
325 MadeChange = false;
326
Chris Lattnerd8ccff02006-11-01 00:38:31 +0000327 if (!EnableTailMerge) return false;
Chris Lattner323ece62006-10-25 18:08:50 +0000328
Chris Lattner12143052006-10-21 00:47:49 +0000329 // Find blocks with no successors.
330 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
331 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
332 if (I->succ_empty())
333 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
334 }
335
336 // Sort by hash value so that blocks with identical end sequences sort
337 // together.
338 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
339
340 // Walk through equivalence sets looking for actual exact matches.
341 while (MergePotentials.size() > 1) {
342 unsigned CurHash = (MergePotentials.end()-1)->first;
343 unsigned PrevHash = (MergePotentials.end()-2)->first;
344 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
345
346 // If there is nothing that matches the hash of the current basic block,
347 // give up.
348 if (CurHash != PrevHash) {
349 MergePotentials.pop_back();
350 continue;
351 }
352
353 // Determine the actual length of the shared tail between these two basic
354 // blocks. Because the hash can have collisions, it's possible that this is
355 // less than 2.
356 MachineBasicBlock::iterator BBI1, BBI2;
357 unsigned CommonTailLen =
358 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
359 BBI1, BBI2);
360
361 // If the tails don't have at least two instructions in common, see if there
362 // is anything else in the equivalence class that does match.
363 if (CommonTailLen < 2) {
364 unsigned FoundMatch = ~0U;
365 for (int i = MergePotentials.size()-2;
366 i != -1 && MergePotentials[i].first == CurHash; --i) {
367 CommonTailLen = ComputeCommonTailLength(CurMBB,
368 MergePotentials[i].second,
369 BBI1, BBI2);
370 if (CommonTailLen >= 2) {
371 FoundMatch = i;
372 break;
373 }
374 }
375
376 // If we didn't find anything that has at least two instructions matching
377 // this one, bail out.
378 if (FoundMatch == ~0U) {
379 MergePotentials.pop_back();
380 continue;
381 }
382
383 // Otherwise, move the matching block to the right position.
384 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
385 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000386
Chris Lattner12143052006-10-21 00:47:49 +0000387 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
Chris Lattner1d08d832006-11-01 01:16:12 +0000388
389 // If neither block is the entire common tail, split the tail of one block
390 // to make it redundant with the other tail.
391 if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
392 if (0) { // Enable this to disable partial tail merges.
393 MergePotentials.pop_back();
394 continue;
395 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000396
397 // Decide whether we want to split CurMBB or MBB2.
398 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
399 CurMBB = SplitMBBAt(*CurMBB, BBI1);
400 BBI1 = CurMBB->begin();
401 MergePotentials.back().second = CurMBB;
402 } else {
403 MBB2 = SplitMBBAt(*MBB2, BBI2);
404 BBI2 = MBB2->begin();
405 (MergePotentials.end()-2)->second = MBB2;
406 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000407 }
408
409 if (MBB2->begin() == BBI2) {
Chris Lattner12143052006-10-21 00:47:49 +0000410 // Hack the end off CurMBB, making it jump to MBBI@ instead.
411 ReplaceTailWithBranchTo(BBI1, MBB2);
412 // This modifies CurMBB, so remove it from the worklist.
413 MergePotentials.pop_back();
Chris Lattner1d08d832006-11-01 01:16:12 +0000414 } else {
415 assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
416 // Hack the end off MBB2, making it jump to CurMBB instead.
417 ReplaceTailWithBranchTo(BBI2, CurMBB);
418 // This modifies MBB2, so remove it from the worklist.
419 MergePotentials.erase(MergePotentials.end()-2);
Chris Lattner12143052006-10-21 00:47:49 +0000420 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000421 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000422 }
423
424 return MadeChange;
425}
426
427
428//===----------------------------------------------------------------------===//
429// Branch Optimization
430//===----------------------------------------------------------------------===//
431
432bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
433 MadeChange = false;
434
435 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
436 MachineBasicBlock *MBB = I++;
437 OptimizeBlock(MBB);
438
439 // If it is dead, remove it.
440 if (MBB->pred_empty()) {
441 RemoveDeadBlock(MBB);
442 MadeChange = true;
443 ++NumDeadBlocks;
444 }
445 }
446 return MadeChange;
447}
448
449
Chris Lattner386e2902006-10-21 05:08:28 +0000450/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
451/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
452/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
453/// be null.
454static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
455 MachineBasicBlock *DestA,
456 MachineBasicBlock *DestB,
457 bool isCond,
458 MachineFunction::iterator FallThru) {
459 bool MadeChange = false;
460 bool AddedFallThrough = false;
461
462 // If this block ends with a conditional branch that falls through to its
463 // successor, set DestB as the successor.
464 if (isCond) {
465 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
466 DestB = FallThru;
467 AddedFallThrough = true;
468 }
469 } else {
470 // If this is an unconditional branch with no explicit dest, it must just be
471 // a fallthrough into DestB.
472 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
473 DestA = FallThru;
474 AddedFallThrough = true;
475 }
476 }
477
478 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
479 while (SI != MBB.succ_end()) {
480 if (*SI == DestA) {
481 DestA = 0;
482 ++SI;
483 } else if (*SI == DestB) {
484 DestB = 0;
485 ++SI;
486 } else {
487 // Otherwise, this is a superfluous edge, remove it.
488 MBB.removeSuccessor(SI);
489 MadeChange = true;
490 }
491 }
492 if (!AddedFallThrough) {
493 assert(DestA == 0 && DestB == 0 &&
494 "MachineCFG is missing edges!");
495 } else if (isCond) {
496 assert(DestA == 0 && "MachineCFG is missing edges!");
497 }
498 return MadeChange;
499}
500
501
Chris Lattner21ab22e2004-07-31 10:01:27 +0000502/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
503/// 'Old', change the code and CFG so that it branches to 'New' instead.
504static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
505 MachineBasicBlock *Old,
506 MachineBasicBlock *New,
Chris Lattner7821a8a2006-10-14 00:21:48 +0000507 const TargetInstrInfo *TII) {
Chris Lattner21ab22e2004-07-31 10:01:27 +0000508 assert(Old != New && "Cannot replace self with self!");
509
510 MachineBasicBlock::iterator I = BB->end();
511 while (I != BB->begin()) {
512 --I;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000513 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000514
515 // Scan the operands of this machine instruction, replacing any uses of Old
516 // with New.
517 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
518 if (I->getOperand(i).isMachineBasicBlock() &&
519 I->getOperand(i).getMachineBasicBlock() == Old)
520 I->getOperand(i).setMachineBasicBlock(New);
521 }
522
Chris Lattnereb15eee2006-10-13 20:43:10 +0000523 // Update the successor information.
Chris Lattner21ab22e2004-07-31 10:01:27 +0000524 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
525 for (int i = Succs.size()-1; i >= 0; --i)
526 if (Succs[i] == Old) {
527 BB->removeSuccessor(Old);
528 BB->addSuccessor(New);
529 }
530}
531
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000532/// CanFallThrough - Return true if the specified block (with the specified
533/// branch condition) can implicitly transfer control to the block after it by
534/// falling off the end of it. This should return false if it can reach the
535/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
536///
537/// True is a conservative answer.
538///
539bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
540 bool BranchUnAnalyzable,
541 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
542 const std::vector<MachineOperand> &Cond) {
543 MachineFunction::iterator Fallthrough = CurBB;
544 ++Fallthrough;
545 // If FallthroughBlock is off the end of the function, it can't fall through.
546 if (Fallthrough == CurBB->getParent()->end())
547 return false;
548
549 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
550 if (!CurBB->isSuccessor(Fallthrough))
551 return false;
552
553 // If we couldn't analyze the branch, assume it could fall through.
554 if (BranchUnAnalyzable) return true;
555
Chris Lattner7d097842006-10-24 01:12:32 +0000556 // If there is no branch, control always falls through.
557 if (TBB == 0) return true;
558
559 // If there is some explicit branch to the fallthrough block, it can obviously
560 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000561 if (MachineFunction::iterator(TBB) == Fallthrough ||
562 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000563 return true;
564
565 // If it's an unconditional branch to some block not the fall through, it
566 // doesn't fall through.
567 if (Cond.empty()) return false;
568
569 // Otherwise, if it is conditional and has no explicit false block, it falls
570 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000571 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000572}
573
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000574/// CanFallThrough - Return true if the specified can implicitly transfer
575/// control to the block after it by falling off the end of it. This should
576/// return false if it can reach the block after it, but it uses an explicit
577/// branch to do so (e.g. a table jump).
578///
579/// True is a conservative answer.
580///
581bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
582 MachineBasicBlock *TBB = 0, *FBB = 0;
583 std::vector<MachineOperand> Cond;
584 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
585 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
586}
587
Chris Lattner7821a8a2006-10-14 00:21:48 +0000588/// OptimizeBlock - Analyze and optimize control flow related to the specified
589/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000590void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
591 MachineFunction::iterator FallThrough = MBB;
592 ++FallThrough;
593
Chris Lattnereb15eee2006-10-13 20:43:10 +0000594 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner21ab22e2004-07-31 10:01:27 +0000595 // explicitly.
596 if (MBB->empty()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000597 // Dead block? Leave for cleanup later.
598 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000599
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000600 if (FallThrough == MBB->getParent()->end()) {
601 // TODO: Simplify preds to not branch here if possible!
602 } else {
603 // Rewrite all predecessors of the old block to go to the fallthrough
604 // instead.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000605 while (!MBB->pred_empty()) {
606 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
607 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
608 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000609
610 // If MBB was the target of a jump table, update jump tables to go to the
611 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000612 MBB->getParent()->getJumpTableInfo()->
613 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000614 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000615 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000616 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000617 }
618
Chris Lattner7821a8a2006-10-14 00:21:48 +0000619 // Check to see if we can simplify the terminator of the block before this
620 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000621 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000622
Chris Lattner7821a8a2006-10-14 00:21:48 +0000623 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
624 std::vector<MachineOperand> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000625 bool PriorUnAnalyzable =
626 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000627 if (!PriorUnAnalyzable) {
628 // If the CFG for the prior block has extra edges, remove them.
629 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
630 !PriorCond.empty(), MBB);
631
Chris Lattner7821a8a2006-10-14 00:21:48 +0000632 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000633 // destination, remove the branch, replacing it with an unconditional one or
634 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000635 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000636 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000637 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000638 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000639 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000640 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000641 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000642 return OptimizeBlock(MBB);
643 }
644
645 // If the previous branch *only* branches to *this* block (conditional or
646 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000647 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000648 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000649 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000650 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000651 return OptimizeBlock(MBB);
652 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000653
654 // If the prior block branches somewhere else on the condition and here if
655 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000656 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000657 TII->RemoveBranch(PrevBB);
658 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
659 MadeChange = true;
660 ++NumBranchOpts;
661 return OptimizeBlock(MBB);
662 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000663
664 // If the prior block branches here on true and somewhere else on false, and
665 // if the branch condition is reversible, reverse the branch to create a
666 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000667 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000668 std::vector<MachineOperand> NewPriorCond(PriorCond);
669 if (!TII->ReverseBranchCondition(NewPriorCond)) {
670 TII->RemoveBranch(PrevBB);
671 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
672 MadeChange = true;
673 ++NumBranchOpts;
674 return OptimizeBlock(MBB);
675 }
676 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000677 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000678
Chris Lattner386e2902006-10-21 05:08:28 +0000679 // Analyze the branch in the current block.
680 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
681 std::vector<MachineOperand> CurCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000682 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
683 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +0000684 // If the CFG for the prior block has extra edges, remove them.
685 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattner7d097842006-10-24 01:12:32 +0000686 !CurCond.empty(),
687 ++MachineFunction::iterator(MBB));
Chris Lattnereb15eee2006-10-13 20:43:10 +0000688
Chris Lattner386e2902006-10-21 05:08:28 +0000689 // If this branch is the only thing in its block, see if we can forward
690 // other blocks across it.
691 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner7d097842006-10-24 01:12:32 +0000692 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000693 // This block may contain just an unconditional branch. Because there can
694 // be 'non-branch terminators' in the block, try removing the branch and
695 // then seeing if the block is empty.
696 TII->RemoveBranch(*MBB);
697
698 // If this block is just an unconditional branch to CurTBB, we can
699 // usually completely eliminate the block. The only case we cannot
700 // completely eliminate the block is when the block before this one
701 // falls through into MBB and we can't understand the prior block's branch
702 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +0000703 if (MBB->empty()) {
704 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
705 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
706 !PrevBB.isSuccessor(MBB)) {
707 // If the prior block falls through into us, turn it into an
708 // explicit branch to us to make updates simpler.
709 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
710 PriorTBB != MBB && PriorFBB != MBB) {
711 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +0000712 assert(PriorCond.empty() && PriorFBB == 0 &&
713 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +0000714 PriorTBB = MBB;
715 } else {
716 assert(PriorFBB == 0 && "Machine CFG out of date!");
717 PriorFBB = MBB;
718 }
719 TII->RemoveBranch(PrevBB);
720 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000721 }
Chris Lattner386e2902006-10-21 05:08:28 +0000722
Chris Lattnercf420cc2006-10-28 17:32:47 +0000723 // Iterate through all the predecessors, revectoring each in-turn.
724 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
725 bool DidChange = false;
726 bool HasBranchToSelf = false;
727 while (PI != MBB->pred_end()) {
728 if (*PI == MBB) {
729 // If this block has an uncond branch to itself, leave it.
730 ++PI;
731 HasBranchToSelf = true;
732 } else {
733 DidChange = true;
734 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
735 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000736 }
Chris Lattner386e2902006-10-21 05:08:28 +0000737
Chris Lattnercf420cc2006-10-28 17:32:47 +0000738 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +0000739 MBB->getParent()->getJumpTableInfo()->
740 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +0000741 if (DidChange) {
742 ++NumBranchOpts;
743 MadeChange = true;
744 if (!HasBranchToSelf) return;
745 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000746 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000747 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000748
Chris Lattner386e2902006-10-21 05:08:28 +0000749 // Add the branch back if the block is more than just an uncond branch.
750 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +0000751 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000752 }
753
754 // If the prior block doesn't fall through into this block, and if this
755 // block doesn't fall through into some other block, see if we can find a
756 // place to move this block where a fall-through will happen.
757 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
758 PriorTBB, PriorFBB, PriorCond)) {
759 // Now we know that there was no fall-through into this block, check to
760 // see if it has a fall-through into its successor.
761 if (!CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, CurCond)) {
762 // Check all the predecessors of this block. If one of them has no fall
763 // throughs, move this block right after it.
764 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
765 E = MBB->pred_end(); PI != E; ++PI) {
766 // Analyze the branch at the end of the pred.
767 MachineBasicBlock *PredBB = *PI;
768 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000769 std::vector<MachineOperand> PredCond;
770 if (PredBB != MBB && !CanFallThrough(PredBB)) {
771 MBB->moveAfter(PredBB);
Chris Lattner7d097842006-10-24 01:12:32 +0000772 MadeChange = true;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000773 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +0000774 }
775 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000776
777 // Check all successors to see if we can move this block before it.
778 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
779 E = MBB->succ_end(); SI != E; ++SI) {
780 // Analyze the branch at the end of the block before the succ.
781 MachineBasicBlock *SuccBB = *SI;
782 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000783 std::vector<MachineOperand> SuccPrevCond;
784 if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
785 MBB->moveBefore(SuccBB);
786 MadeChange = true;
787 return OptimizeBlock(MBB);
788 }
789 }
790
791 // Okay, there is no really great place to put this block. If, however,
792 // the block before this one would be a fall-through if this block were
793 // removed, move this block to the end of the function.
794 if (FallThrough != MBB->getParent()->end() &&
795 PrevBB.isSuccessor(FallThrough)) {
796 MBB->moveAfter(--MBB->getParent()->end());
797 MadeChange = true;
798 return;
799 }
Chris Lattner7d097842006-10-24 01:12:32 +0000800 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000801 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000802}