blob: ddd3bca03b9799fe7658b8e23dcd71d3b20c066d [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"
Jeff Cohend41b30d2006-11-05 19:31:28 +000028#include <algorithm>
Chris Lattner21ab22e2004-07-31 10:01:27 +000029using namespace llvm;
30
Chris Lattner12143052006-10-21 00:47:49 +000031static Statistic<> NumDeadBlocks("branchfold", "Number of dead blocks removed");
32static Statistic<> NumBranchOpts("branchfold", "Number of branches optimized");
33static Statistic<> NumTailMerge ("branchfold", "Number of block tails merged");
Chris Lattnerd8ccff02006-11-01 00:38:31 +000034static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
Chris Lattner12143052006-10-21 00:47:49 +000035
Chris Lattner21ab22e2004-07-31 10:01:27 +000036namespace {
37 struct BranchFolder : public MachineFunctionPass {
38 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner7821a8a2006-10-14 00:21:48 +000039 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
40 const TargetInstrInfo *TII;
Chris Lattner683747a2006-10-17 23:17:27 +000041 MachineDebugInfo *MDI;
Chris Lattner7821a8a2006-10-14 00:21:48 +000042 bool MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +000043 private:
Chris Lattner12143052006-10-21 00:47:49 +000044 // Tail Merging.
45 bool TailMergeBlocks(MachineFunction &MF);
46 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
47 MachineBasicBlock *NewDest);
Chris Lattner1d08d832006-11-01 01:16:12 +000048 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
49 MachineBasicBlock::iterator BBI1);
50
Chris Lattner12143052006-10-21 00:47:49 +000051 // Branch optzn.
52 bool OptimizeBranches(MachineFunction &MF);
Chris Lattner7d097842006-10-24 01:12:32 +000053 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000054 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner6b0e3f82006-10-29 21:05:41 +000055
56 bool CanFallThrough(MachineBasicBlock *CurBB);
57 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
58 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
59 const std::vector<MachineOperand> &Cond);
Chris Lattner21ab22e2004-07-31 10:01:27 +000060 };
61}
62
63FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
64
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000065/// RemoveDeadBlock - Remove the specified dead machine basic block from the
66/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +000067void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000068 assert(MBB->pred_empty() && "MBB must be dead!");
Chris Lattner683747a2006-10-17 23:17:27 +000069
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000070 MachineFunction *MF = MBB->getParent();
71 // drop all successors.
72 while (!MBB->succ_empty())
73 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +000074
75 // If there is DWARF info to active, check to see if there are any DWARF_LABEL
76 // records in the basic block. If so, unregister them from MachineDebugInfo.
77 if (MDI && !MBB->empty()) {
78 unsigned DWARF_LABELOpc = TII->getDWARF_LABELOpcode();
79 assert(DWARF_LABELOpc &&
80 "Target supports dwarf but didn't implement getDWARF_LABELOpcode!");
81
82 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
83 I != E; ++I) {
84 if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
85 // The label ID # is always operand #0, an immediate.
Jim Laskey66ebf092006-10-23 14:56:37 +000086 MDI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +000087 }
88 }
89 }
90
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000091 // Remove the block.
92 MF->getBasicBlockList().erase(MBB);
93}
94
Chris Lattner21ab22e2004-07-31 10:01:27 +000095bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner7821a8a2006-10-14 00:21:48 +000096 TII = MF.getTarget().getInstrInfo();
97 if (!TII) return false;
98
Chris Lattner683747a2006-10-17 23:17:27 +000099 MDI = getAnalysisToUpdate<MachineDebugInfo>();
Chris Lattner7821a8a2006-10-14 00:21:48 +0000100
Chris Lattner21ab22e2004-07-31 10:01:27 +0000101 bool EverMadeChange = false;
Chris Lattner12143052006-10-21 00:47:49 +0000102 bool MadeChangeThisIteration = true;
103 while (MadeChangeThisIteration) {
104 MadeChangeThisIteration = false;
105 MadeChangeThisIteration |= TailMergeBlocks(MF);
106 MadeChangeThisIteration |= OptimizeBranches(MF);
107 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000108 }
109
Chris Lattner6acfe122006-10-28 18:34:47 +0000110 // See if any jump tables have become mergable or dead as the code generator
111 // did its thing.
112 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
113 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
114 if (!JTs.empty()) {
115 // Figure out how these jump tables should be merged.
116 std::vector<unsigned> JTMapping;
117 JTMapping.reserve(JTs.size());
118
119 // We always keep the 0th jump table.
120 JTMapping.push_back(0);
121
122 // Scan the jump tables, seeing if there are any duplicates. Note that this
123 // is N^2, which should be fixed someday.
124 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
125 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
126
127 // If a jump table was merge with another one, walk the function rewriting
128 // references to jump tables to reference the new JT ID's. Keep track of
129 // whether we see a jump table idx, if not, we can delete the JT.
130 std::vector<bool> JTIsLive;
131 JTIsLive.resize(JTs.size());
132 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
133 BB != E; ++BB) {
134 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
135 I != E; ++I)
136 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
137 MachineOperand &Op = I->getOperand(op);
138 if (!Op.isJumpTableIndex()) continue;
139 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
140 Op.setJumpTableIndex(NewIdx);
141
142 // Remember that this JT is live.
143 JTIsLive[NewIdx] = true;
144 }
145 }
146
147 // Finally, remove dead jump tables. This happens either because the
148 // indirect jump was unreachable (and thus deleted) or because the jump
149 // table was merged with some other one.
150 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
151 if (!JTIsLive[i]) {
152 JTI->RemoveJumpTable(i);
153 EverMadeChange = true;
154 }
155 }
156
Chris Lattner21ab22e2004-07-31 10:01:27 +0000157 return EverMadeChange;
158}
159
Chris Lattner12143052006-10-21 00:47:49 +0000160//===----------------------------------------------------------------------===//
161// Tail Merging of Blocks
162//===----------------------------------------------------------------------===//
163
164/// HashMachineInstr - Compute a hash value for MI and its operands.
165static unsigned HashMachineInstr(const MachineInstr *MI) {
166 unsigned Hash = MI->getOpcode();
167 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
168 const MachineOperand &Op = MI->getOperand(i);
169
170 // Merge in bits from the operand if easy.
171 unsigned OperandHash = 0;
172 switch (Op.getType()) {
173 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
174 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
175 case MachineOperand::MO_MachineBasicBlock:
176 OperandHash = Op.getMachineBasicBlock()->getNumber();
177 break;
178 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
179 case MachineOperand::MO_ConstantPoolIndex:
180 OperandHash = Op.getConstantPoolIndex();
181 break;
182 case MachineOperand::MO_JumpTableIndex:
183 OperandHash = Op.getJumpTableIndex();
184 break;
185 case MachineOperand::MO_GlobalAddress:
186 case MachineOperand::MO_ExternalSymbol:
187 // Global address / external symbol are too hard, don't bother, but do
188 // pull in the offset.
189 OperandHash = Op.getOffset();
190 break;
191 default: break;
192 }
193
194 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
195 }
196 return Hash;
197}
198
199/// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
200/// instructions, because cross-jumping only saves code when at least two
201/// instructions are removed (since a branch must be inserted).
202static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
203 MachineBasicBlock::const_iterator I = MBB->end();
204 if (I == MBB->begin())
205 return 0; // Empty MBB.
206
207 --I;
208 unsigned Hash = HashMachineInstr(I);
209
210 if (I == MBB->begin())
211 return Hash; // Single instr MBB.
212
213 --I;
214 // Hash in the second-to-last instruction.
215 Hash ^= HashMachineInstr(I) << 2;
216 return Hash;
217}
218
219/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
220/// of instructions they actually have in common together at their end. Return
221/// iterators for the first shared instruction in each block.
222static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
223 MachineBasicBlock *MBB2,
224 MachineBasicBlock::iterator &I1,
225 MachineBasicBlock::iterator &I2) {
226 I1 = MBB1->end();
227 I2 = MBB2->end();
228
229 unsigned TailLen = 0;
230 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
231 --I1; --I2;
232 if (!I1->isIdenticalTo(I2)) {
233 ++I1; ++I2;
234 break;
235 }
236 ++TailLen;
237 }
238 return TailLen;
239}
240
241/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000242/// after it, replacing it with an unconditional branch to NewDest. This
243/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000244void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
245 MachineBasicBlock *NewDest) {
246 MachineBasicBlock *OldBB = OldInst->getParent();
247
248 // Remove all the old successors of OldBB from the CFG.
249 while (!OldBB->succ_empty())
250 OldBB->removeSuccessor(OldBB->succ_begin());
251
252 // Remove all the dead instructions from the end of OldBB.
253 OldBB->erase(OldInst, OldBB->end());
254
Chris Lattner386e2902006-10-21 05:08:28 +0000255 // If OldBB isn't immediately before OldBB, insert a branch to it.
256 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
257 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner12143052006-10-21 00:47:49 +0000258 OldBB->addSuccessor(NewDest);
259 ++NumTailMerge;
260}
261
Chris Lattner1d08d832006-11-01 01:16:12 +0000262/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
263/// MBB so that the part before the iterator falls into the part starting at the
264/// iterator. This returns the new MBB.
265MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
266 MachineBasicBlock::iterator BBI1) {
267 // Create the fall-through block.
268 MachineFunction::iterator MBBI = &CurMBB;
269 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
270 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
271
272 // Move all the successors of this block to the specified block.
273 while (!CurMBB.succ_empty()) {
274 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
275 NewMBB->addSuccessor(S);
276 CurMBB.removeSuccessor(S);
277 }
278
279 // Add an edge from CurMBB to NewMBB for the fall-through.
280 CurMBB.addSuccessor(NewMBB);
281
282 // Splice the code over.
283 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
284 return NewMBB;
285}
286
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000287/// EstimateRuntime - Make a rough estimate for how long it will take to run
288/// the specified code.
289static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
290 MachineBasicBlock::iterator E,
291 const TargetInstrInfo *TII) {
292 unsigned Time = 0;
293 for (; I != E; ++I) {
294 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
295 if (TID.Flags & M_CALL_FLAG)
296 Time += 10;
297 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
298 Time += 2;
299 else
300 ++Time;
301 }
302 return Time;
303}
304
305/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
306/// MBB2I and then insert an unconditional branch in the other block. Determine
307/// which is the best to split
308static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
309 MachineBasicBlock::iterator MBB1I,
310 MachineBasicBlock *MBB2,
311 MachineBasicBlock::iterator MBB2I,
312 const TargetInstrInfo *TII) {
313 // TODO: if we had some notion of which block was hotter, we could split
314 // the hot block, so it is the fall-through. Since we don't have profile info
315 // make a decision based on which will hurt most to split.
316 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
317 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
318
319 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
320 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
321 // have a lower overall impact on the program execution.
322 return MBB1Time < MBB2Time;
323}
324
Chris Lattner12143052006-10-21 00:47:49 +0000325bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
326 MadeChange = false;
327
Chris Lattnerd8ccff02006-11-01 00:38:31 +0000328 if (!EnableTailMerge) return false;
Chris Lattner323ece62006-10-25 18:08:50 +0000329
Chris Lattner12143052006-10-21 00:47:49 +0000330 // Find blocks with no successors.
331 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
332 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
333 if (I->succ_empty())
334 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
335 }
336
337 // Sort by hash value so that blocks with identical end sequences sort
338 // together.
339 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
340
341 // Walk through equivalence sets looking for actual exact matches.
342 while (MergePotentials.size() > 1) {
343 unsigned CurHash = (MergePotentials.end()-1)->first;
344 unsigned PrevHash = (MergePotentials.end()-2)->first;
345 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
346
347 // If there is nothing that matches the hash of the current basic block,
348 // give up.
349 if (CurHash != PrevHash) {
350 MergePotentials.pop_back();
351 continue;
352 }
353
354 // Determine the actual length of the shared tail between these two basic
355 // blocks. Because the hash can have collisions, it's possible that this is
356 // less than 2.
357 MachineBasicBlock::iterator BBI1, BBI2;
358 unsigned CommonTailLen =
359 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
360 BBI1, BBI2);
361
362 // If the tails don't have at least two instructions in common, see if there
363 // is anything else in the equivalence class that does match.
364 if (CommonTailLen < 2) {
365 unsigned FoundMatch = ~0U;
366 for (int i = MergePotentials.size()-2;
367 i != -1 && MergePotentials[i].first == CurHash; --i) {
368 CommonTailLen = ComputeCommonTailLength(CurMBB,
369 MergePotentials[i].second,
370 BBI1, BBI2);
371 if (CommonTailLen >= 2) {
372 FoundMatch = i;
373 break;
374 }
375 }
376
377 // If we didn't find anything that has at least two instructions matching
378 // this one, bail out.
379 if (FoundMatch == ~0U) {
380 MergePotentials.pop_back();
381 continue;
382 }
383
384 // Otherwise, move the matching block to the right position.
385 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
386 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000387
Chris Lattner12143052006-10-21 00:47:49 +0000388 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
Chris Lattner1d08d832006-11-01 01:16:12 +0000389
390 // If neither block is the entire common tail, split the tail of one block
391 // to make it redundant with the other tail.
392 if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
393 if (0) { // Enable this to disable partial tail merges.
394 MergePotentials.pop_back();
395 continue;
396 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000397
398 // Decide whether we want to split CurMBB or MBB2.
399 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
400 CurMBB = SplitMBBAt(*CurMBB, BBI1);
401 BBI1 = CurMBB->begin();
402 MergePotentials.back().second = CurMBB;
403 } else {
404 MBB2 = SplitMBBAt(*MBB2, BBI2);
405 BBI2 = MBB2->begin();
406 (MergePotentials.end()-2)->second = MBB2;
407 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000408 }
409
410 if (MBB2->begin() == BBI2) {
Chris Lattner12143052006-10-21 00:47:49 +0000411 // Hack the end off CurMBB, making it jump to MBBI@ instead.
412 ReplaceTailWithBranchTo(BBI1, MBB2);
413 // This modifies CurMBB, so remove it from the worklist.
414 MergePotentials.pop_back();
Chris Lattner1d08d832006-11-01 01:16:12 +0000415 } else {
416 assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
417 // Hack the end off MBB2, making it jump to CurMBB instead.
418 ReplaceTailWithBranchTo(BBI2, CurMBB);
419 // This modifies MBB2, so remove it from the worklist.
420 MergePotentials.erase(MergePotentials.end()-2);
Chris Lattner12143052006-10-21 00:47:49 +0000421 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000422 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000423 }
424
425 return MadeChange;
426}
427
428
429//===----------------------------------------------------------------------===//
430// Branch Optimization
431//===----------------------------------------------------------------------===//
432
433bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
434 MadeChange = false;
435
436 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
437 MachineBasicBlock *MBB = I++;
438 OptimizeBlock(MBB);
439
440 // If it is dead, remove it.
441 if (MBB->pred_empty()) {
442 RemoveDeadBlock(MBB);
443 MadeChange = true;
444 ++NumDeadBlocks;
445 }
446 }
447 return MadeChange;
448}
449
450
Chris Lattner386e2902006-10-21 05:08:28 +0000451/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
452/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
453/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
454/// be null.
455static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
456 MachineBasicBlock *DestA,
457 MachineBasicBlock *DestB,
458 bool isCond,
459 MachineFunction::iterator FallThru) {
460 bool MadeChange = false;
461 bool AddedFallThrough = false;
462
463 // If this block ends with a conditional branch that falls through to its
464 // successor, set DestB as the successor.
465 if (isCond) {
466 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
467 DestB = FallThru;
468 AddedFallThrough = true;
469 }
470 } else {
471 // If this is an unconditional branch with no explicit dest, it must just be
472 // a fallthrough into DestB.
473 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
474 DestA = FallThru;
475 AddedFallThrough = true;
476 }
477 }
478
479 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
480 while (SI != MBB.succ_end()) {
481 if (*SI == DestA) {
482 DestA = 0;
483 ++SI;
484 } else if (*SI == DestB) {
485 DestB = 0;
486 ++SI;
487 } else {
488 // Otherwise, this is a superfluous edge, remove it.
489 MBB.removeSuccessor(SI);
490 MadeChange = true;
491 }
492 }
493 if (!AddedFallThrough) {
494 assert(DestA == 0 && DestB == 0 &&
495 "MachineCFG is missing edges!");
496 } else if (isCond) {
497 assert(DestA == 0 && "MachineCFG is missing edges!");
498 }
499 return MadeChange;
500}
501
502
Chris Lattner21ab22e2004-07-31 10:01:27 +0000503/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
504/// 'Old', change the code and CFG so that it branches to 'New' instead.
505static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
506 MachineBasicBlock *Old,
507 MachineBasicBlock *New,
Chris Lattner7821a8a2006-10-14 00:21:48 +0000508 const TargetInstrInfo *TII) {
Chris Lattner21ab22e2004-07-31 10:01:27 +0000509 assert(Old != New && "Cannot replace self with self!");
510
511 MachineBasicBlock::iterator I = BB->end();
512 while (I != BB->begin()) {
513 --I;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000514 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000515
516 // Scan the operands of this machine instruction, replacing any uses of Old
517 // with New.
518 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
519 if (I->getOperand(i).isMachineBasicBlock() &&
520 I->getOperand(i).getMachineBasicBlock() == Old)
521 I->getOperand(i).setMachineBasicBlock(New);
522 }
523
Chris Lattnereb15eee2006-10-13 20:43:10 +0000524 // Update the successor information.
Chris Lattner21ab22e2004-07-31 10:01:27 +0000525 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
526 for (int i = Succs.size()-1; i >= 0; --i)
527 if (Succs[i] == Old) {
528 BB->removeSuccessor(Old);
529 BB->addSuccessor(New);
530 }
531}
532
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000533/// CanFallThrough - Return true if the specified block (with the specified
534/// branch condition) can implicitly transfer control to the block after it by
535/// falling off the end of it. This should return false if it can reach the
536/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
537///
538/// True is a conservative answer.
539///
540bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
541 bool BranchUnAnalyzable,
542 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
543 const std::vector<MachineOperand> &Cond) {
544 MachineFunction::iterator Fallthrough = CurBB;
545 ++Fallthrough;
546 // If FallthroughBlock is off the end of the function, it can't fall through.
547 if (Fallthrough == CurBB->getParent()->end())
548 return false;
549
550 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
551 if (!CurBB->isSuccessor(Fallthrough))
552 return false;
553
554 // If we couldn't analyze the branch, assume it could fall through.
555 if (BranchUnAnalyzable) return true;
556
Chris Lattner7d097842006-10-24 01:12:32 +0000557 // If there is no branch, control always falls through.
558 if (TBB == 0) return true;
559
560 // If there is some explicit branch to the fallthrough block, it can obviously
561 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000562 if (MachineFunction::iterator(TBB) == Fallthrough ||
563 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000564 return true;
565
566 // If it's an unconditional branch to some block not the fall through, it
567 // doesn't fall through.
568 if (Cond.empty()) return false;
569
570 // Otherwise, if it is conditional and has no explicit false block, it falls
571 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000572 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000573}
574
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000575/// CanFallThrough - Return true if the specified can implicitly transfer
576/// control to the block after it by falling off the end of it. This should
577/// return false if it can reach the block after it, but it uses an explicit
578/// branch to do so (e.g. a table jump).
579///
580/// True is a conservative answer.
581///
582bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
583 MachineBasicBlock *TBB = 0, *FBB = 0;
584 std::vector<MachineOperand> Cond;
585 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
586 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
587}
588
Chris Lattner7821a8a2006-10-14 00:21:48 +0000589/// OptimizeBlock - Analyze and optimize control flow related to the specified
590/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000591void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
592 MachineFunction::iterator FallThrough = MBB;
593 ++FallThrough;
594
Chris Lattnereb15eee2006-10-13 20:43:10 +0000595 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner21ab22e2004-07-31 10:01:27 +0000596 // explicitly.
597 if (MBB->empty()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000598 // Dead block? Leave for cleanup later.
599 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000600
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000601 if (FallThrough == MBB->getParent()->end()) {
602 // TODO: Simplify preds to not branch here if possible!
603 } else {
604 // Rewrite all predecessors of the old block to go to the fallthrough
605 // instead.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000606 while (!MBB->pred_empty()) {
607 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
608 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
609 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000610
611 // If MBB was the target of a jump table, update jump tables to go to the
612 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000613 MBB->getParent()->getJumpTableInfo()->
614 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000615 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000616 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000617 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000618 }
619
Chris Lattner7821a8a2006-10-14 00:21:48 +0000620 // Check to see if we can simplify the terminator of the block before this
621 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000622 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000623
Chris Lattner7821a8a2006-10-14 00:21:48 +0000624 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
625 std::vector<MachineOperand> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000626 bool PriorUnAnalyzable =
627 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000628 if (!PriorUnAnalyzable) {
629 // If the CFG for the prior block has extra edges, remove them.
630 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
631 !PriorCond.empty(), MBB);
632
Chris Lattner7821a8a2006-10-14 00:21:48 +0000633 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000634 // destination, remove the branch, replacing it with an unconditional one or
635 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000636 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000637 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000638 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000639 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000640 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000641 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000642 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000643 return OptimizeBlock(MBB);
644 }
645
646 // If the previous branch *only* branches to *this* block (conditional or
647 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000648 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000649 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000650 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000651 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000652 return OptimizeBlock(MBB);
653 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000654
655 // If the prior block branches somewhere else on the condition and here if
656 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000657 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000658 TII->RemoveBranch(PrevBB);
659 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
660 MadeChange = true;
661 ++NumBranchOpts;
662 return OptimizeBlock(MBB);
663 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000664
665 // If the prior block branches here on true and somewhere else on false, and
666 // if the branch condition is reversible, reverse the branch to create a
667 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000668 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000669 std::vector<MachineOperand> NewPriorCond(PriorCond);
670 if (!TII->ReverseBranchCondition(NewPriorCond)) {
671 TII->RemoveBranch(PrevBB);
672 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
673 MadeChange = true;
674 ++NumBranchOpts;
675 return OptimizeBlock(MBB);
676 }
677 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000678 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000679
Chris Lattner386e2902006-10-21 05:08:28 +0000680 // Analyze the branch in the current block.
681 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
682 std::vector<MachineOperand> CurCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000683 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
684 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +0000685 // If the CFG for the prior block has extra edges, remove them.
686 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattner7d097842006-10-24 01:12:32 +0000687 !CurCond.empty(),
688 ++MachineFunction::iterator(MBB));
Chris Lattnereb15eee2006-10-13 20:43:10 +0000689
Chris Lattner5d056952006-11-08 01:03:21 +0000690 // If this is a two-way branch, and the FBB branches to this block, reverse
691 // the condition so the single-basic-block loop is faster. Instead of:
692 // Loop: xxx; jcc Out; jmp Loop
693 // we want:
694 // Loop: xxx; jncc Loop; jmp Out
695 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
696 std::vector<MachineOperand> NewCond(CurCond);
697 if (!TII->ReverseBranchCondition(NewCond)) {
698 TII->RemoveBranch(*MBB);
699 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
700 MadeChange = true;
701 ++NumBranchOpts;
702 return OptimizeBlock(MBB);
703 }
704 }
705
706
Chris Lattner386e2902006-10-21 05:08:28 +0000707 // If this branch is the only thing in its block, see if we can forward
708 // other blocks across it.
709 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner7d097842006-10-24 01:12:32 +0000710 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000711 // This block may contain just an unconditional branch. Because there can
712 // be 'non-branch terminators' in the block, try removing the branch and
713 // then seeing if the block is empty.
714 TII->RemoveBranch(*MBB);
715
716 // If this block is just an unconditional branch to CurTBB, we can
717 // usually completely eliminate the block. The only case we cannot
718 // completely eliminate the block is when the block before this one
719 // falls through into MBB and we can't understand the prior block's branch
720 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +0000721 if (MBB->empty()) {
722 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
723 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
724 !PrevBB.isSuccessor(MBB)) {
725 // If the prior block falls through into us, turn it into an
726 // explicit branch to us to make updates simpler.
727 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
728 PriorTBB != MBB && PriorFBB != MBB) {
729 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +0000730 assert(PriorCond.empty() && PriorFBB == 0 &&
731 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +0000732 PriorTBB = MBB;
733 } else {
734 assert(PriorFBB == 0 && "Machine CFG out of date!");
735 PriorFBB = MBB;
736 }
737 TII->RemoveBranch(PrevBB);
738 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000739 }
Chris Lattner386e2902006-10-21 05:08:28 +0000740
Chris Lattnercf420cc2006-10-28 17:32:47 +0000741 // Iterate through all the predecessors, revectoring each in-turn.
742 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
743 bool DidChange = false;
744 bool HasBranchToSelf = false;
745 while (PI != MBB->pred_end()) {
746 if (*PI == MBB) {
747 // If this block has an uncond branch to itself, leave it.
748 ++PI;
749 HasBranchToSelf = true;
750 } else {
751 DidChange = true;
752 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
753 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000754 }
Chris Lattner386e2902006-10-21 05:08:28 +0000755
Chris Lattnercf420cc2006-10-28 17:32:47 +0000756 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +0000757 MBB->getParent()->getJumpTableInfo()->
758 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +0000759 if (DidChange) {
760 ++NumBranchOpts;
761 MadeChange = true;
762 if (!HasBranchToSelf) return;
763 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000764 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000765 }
Chris Lattnereb15eee2006-10-13 20:43:10 +0000766
Chris Lattner386e2902006-10-21 05:08:28 +0000767 // Add the branch back if the block is more than just an uncond branch.
768 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +0000769 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000770 }
771
772 // If the prior block doesn't fall through into this block, and if this
773 // block doesn't fall through into some other block, see if we can find a
774 // place to move this block where a fall-through will happen.
775 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
776 PriorTBB, PriorFBB, PriorCond)) {
777 // Now we know that there was no fall-through into this block, check to
778 // see if it has a fall-through into its successor.
779 if (!CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, CurCond)) {
780 // Check all the predecessors of this block. If one of them has no fall
781 // throughs, move this block right after it.
782 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
783 E = MBB->pred_end(); PI != E; ++PI) {
784 // Analyze the branch at the end of the pred.
785 MachineBasicBlock *PredBB = *PI;
786 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000787 std::vector<MachineOperand> PredCond;
788 if (PredBB != MBB && !CanFallThrough(PredBB)) {
789 MBB->moveAfter(PredBB);
Chris Lattner7d097842006-10-24 01:12:32 +0000790 MadeChange = true;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000791 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +0000792 }
793 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000794
795 // Check all successors to see if we can move this block before it.
796 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
797 E = MBB->succ_end(); SI != E; ++SI) {
798 // Analyze the branch at the end of the block before the succ.
799 MachineBasicBlock *SuccBB = *SI;
800 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000801 std::vector<MachineOperand> SuccPrevCond;
802 if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
803 MBB->moveBefore(SuccBB);
804 MadeChange = true;
805 return OptimizeBlock(MBB);
806 }
807 }
808
809 // Okay, there is no really great place to put this block. If, however,
810 // the block before this one would be a fall-through if this block were
811 // removed, move this block to the end of the function.
812 if (FallThrough != MBB->getParent()->end() &&
813 PrevBB.isSuccessor(FallThrough)) {
814 MBB->moveAfter(--MBB->getParent()->end());
815 MadeChange = true;
816 return;
817 }
Chris Lattner7d097842006-10-24 01:12:32 +0000818 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000819 }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000820}