blob: 3e203850f90c49d5616a41ce19f3046afde5676b [file] [log] [blame]
Bob Wilson15acadd2009-11-26 00:32:21 +00001//===-- TailDuplication.cpp - Duplicate blocks into predecessors' tails ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass duplicates basic blocks ending in unconditional branches into
11// the tails of their predecessors.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "tailduplication"
16#include "llvm/Function.h"
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/CodeGen/MachineModuleInfo.h"
19#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +000020#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng111e7622009-12-03 08:43:53 +000021#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/CodeGen/MachineSSAUpdater.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000023#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
Evan Cheng75eb5352009-12-07 10:15:19 +000026#include "llvm/Support/ErrorHandling.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000027#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesenc66d3602011-08-09 23:49:21 +000028#include "llvm/ADT/DenseSet.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000029#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/SetVector.h"
31#include "llvm/ADT/Statistic.h"
32using namespace llvm;
33
Evan Cheng75eb5352009-12-07 10:15:19 +000034STATISTIC(NumTails , "Number of tails duplicated");
Bob Wilson15acadd2009-11-26 00:32:21 +000035STATISTIC(NumTailDups , "Number of tail duplicated blocks");
36STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
37STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
Rafael Espindola0cdca082011-06-08 14:13:31 +000038STATISTIC(NumAddedPHIs , "Number of phis added");
Bob Wilson15acadd2009-11-26 00:32:21 +000039
40// Heuristic for tail duplication.
41static cl::opt<unsigned>
42TailDuplicateSize("tail-dup-size",
43 cl::desc("Maximum instructions to consider tail duplicating"),
44 cl::init(2), cl::Hidden);
45
Evan Cheng75eb5352009-12-07 10:15:19 +000046static cl::opt<bool>
47TailDupVerify("tail-dup-verify",
48 cl::desc("Verify sanity of PHI instructions during taildup"),
49 cl::init(false), cl::Hidden);
50
51static cl::opt<unsigned>
52TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
53
Evan Cheng11572ba2009-12-04 19:09:10 +000054typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
Evan Cheng111e7622009-12-03 08:43:53 +000055
Bob Wilson15acadd2009-11-26 00:32:21 +000056namespace {
Bob Wilson2d521e52009-11-26 21:38:41 +000057 /// TailDuplicatePass - Perform tail duplication.
58 class TailDuplicatePass : public MachineFunctionPass {
Bob Wilson15acadd2009-11-26 00:32:21 +000059 const TargetInstrInfo *TII;
60 MachineModuleInfo *MMI;
Evan Cheng111e7622009-12-03 08:43:53 +000061 MachineRegisterInfo *MRI;
Andrew Trickd2a7bed2012-02-08 21:22:30 +000062 bool PreRegAlloc;
Evan Cheng111e7622009-12-03 08:43:53 +000063
64 // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
65 SmallVector<unsigned, 16> SSAUpdateVRs;
66
67 // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
68 // source virtual registers.
69 DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
Bob Wilson15acadd2009-11-26 00:32:21 +000070
71 public:
72 static char ID;
Andrew Trickd2a7bed2012-02-08 21:22:30 +000073 explicit TailDuplicatePass() :
74 MachineFunctionPass(ID), PreRegAlloc(false) {}
Bob Wilson15acadd2009-11-26 00:32:21 +000075
76 virtual bool runOnMachineFunction(MachineFunction &MF);
Bob Wilson15acadd2009-11-26 00:32:21 +000077
78 private:
Evan Cheng11572ba2009-12-04 19:09:10 +000079 void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
80 MachineBasicBlock *BB);
Evan Cheng79fc6f42009-12-04 09:42:45 +000081 void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
82 MachineBasicBlock *PredBB,
Evan Cheng75eb5352009-12-07 10:15:19 +000083 DenseMap<unsigned, unsigned> &LocalVRMap,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +000084 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies,
Rafael Espindola689d7d52011-06-09 23:22:56 +000085 const DenseSet<unsigned> &UsedByPhi,
86 bool Remove);
Evan Cheng79fc6f42009-12-04 09:42:45 +000087 void DuplicateInstruction(MachineInstr *MI,
88 MachineBasicBlock *TailBB,
89 MachineBasicBlock *PredBB,
90 MachineFunction &MF,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +000091 DenseMap<unsigned, unsigned> &LocalVRMap,
92 const DenseSet<unsigned> &UsedByPhi);
Evan Cheng75eb5352009-12-07 10:15:19 +000093 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
94 SmallVector<MachineBasicBlock*, 8> &TDBBs,
95 SmallSetVector<MachineBasicBlock*, 8> &Succs);
Bob Wilson15acadd2009-11-26 00:32:21 +000096 bool TailDuplicateBlocks(MachineFunction &MF);
Rafael Espindola54c25622011-06-09 19:54:42 +000097 bool shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindola9dbbd872011-06-23 03:41:29 +000098 bool IsSimple, MachineBasicBlock &TailBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +000099 bool isSimpleBB(MachineBasicBlock *TailBB);
Rafael Espindola40179bf2011-06-24 15:50:56 +0000100 bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000101 bool duplicateSimpleBB(MachineBasicBlock *TailBB,
Rafael Espindola275c1f92011-06-20 04:16:35 +0000102 SmallVector<MachineBasicBlock*, 8> &TDBBs,
103 const DenseSet<unsigned> &RegsUsedByPhi,
104 SmallVector<MachineInstr*, 16> &Copies);
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000105 bool TailDuplicate(MachineBasicBlock *TailBB,
106 bool IsSimple,
107 MachineFunction &MF,
Evan Cheng3466f132009-12-15 01:44:10 +0000108 SmallVector<MachineBasicBlock*, 8> &TDBBs,
109 SmallVector<MachineInstr*, 16> &Copies);
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000110 bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
111 bool IsSimple,
112 MachineFunction &MF);
113
Bob Wilson15acadd2009-11-26 00:32:21 +0000114 void RemoveDeadBlock(MachineBasicBlock *MBB);
115 };
116
Bob Wilson2d521e52009-11-26 21:38:41 +0000117 char TailDuplicatePass::ID = 0;
Bob Wilson15acadd2009-11-26 00:32:21 +0000118}
119
Andrew Trick1dd8c852012-02-08 21:23:13 +0000120char &llvm::TailDuplicateID = TailDuplicatePass::ID;
121
122INITIALIZE_PASS(TailDuplicatePass, "tailduplication", "Tail Duplication",
123 false, false)
Bob Wilson15acadd2009-11-26 00:32:21 +0000124
Bob Wilson2d521e52009-11-26 21:38:41 +0000125bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000126 TII = MF.getTarget().getInstrInfo();
Evan Cheng111e7622009-12-03 08:43:53 +0000127 MRI = &MF.getRegInfo();
Bob Wilson15acadd2009-11-26 00:32:21 +0000128 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Andrew Trickd2a7bed2012-02-08 21:22:30 +0000129 PreRegAlloc = MRI->isSSA();
Bob Wilson15acadd2009-11-26 00:32:21 +0000130
131 bool MadeChange = false;
Jakob Stoklund Olesen057d5392010-01-15 19:59:57 +0000132 while (TailDuplicateBlocks(MF))
133 MadeChange = true;
Bob Wilson15acadd2009-11-26 00:32:21 +0000134
135 return MadeChange;
136}
137
Evan Cheng75eb5352009-12-07 10:15:19 +0000138static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
139 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
140 MachineBasicBlock *MBB = I;
141 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
142 MBB->pred_end());
143 MachineBasicBlock::iterator MI = MBB->begin();
144 while (MI != MBB->end()) {
Chris Lattner518bb532010-02-09 19:54:29 +0000145 if (!MI->isPHI())
Evan Cheng75eb5352009-12-07 10:15:19 +0000146 break;
147 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
148 PE = Preds.end(); PI != PE; ++PI) {
149 MachineBasicBlock *PredBB = *PI;
150 bool Found = false;
151 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
152 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
153 if (PHIBB == PredBB) {
154 Found = true;
155 break;
156 }
157 }
158 if (!Found) {
David Greene00dec1b2010-01-05 01:25:15 +0000159 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
160 dbgs() << " missing input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000161 << PredBB->getNumber() << '\n';
162 llvm_unreachable(0);
163 }
164 }
165
166 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
167 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
168 if (CheckExtra && !Preds.count(PHIBB)) {
David Greene00dec1b2010-01-05 01:25:15 +0000169 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
Evan Cheng75eb5352009-12-07 10:15:19 +0000170 << ": " << *MI;
David Greene00dec1b2010-01-05 01:25:15 +0000171 dbgs() << " extra input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000172 << PHIBB->getNumber() << '\n';
Rafael Espindolad3f4eea2011-06-09 23:55:56 +0000173 llvm_unreachable(0);
Evan Cheng75eb5352009-12-07 10:15:19 +0000174 }
175 if (PHIBB->getNumber() < 0) {
David Greene00dec1b2010-01-05 01:25:15 +0000176 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
177 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
Evan Cheng75eb5352009-12-07 10:15:19 +0000178 llvm_unreachable(0);
179 }
180 }
181 ++MI;
182 }
183 }
184}
185
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000186/// TailDuplicateAndUpdate - Tail duplicate the block and cleanup.
187bool
188TailDuplicatePass::TailDuplicateAndUpdate(MachineBasicBlock *MBB,
189 bool IsSimple,
190 MachineFunction &MF) {
191 // Save the successors list.
192 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
193 MBB->succ_end());
194
195 SmallVector<MachineBasicBlock*, 8> TDBBs;
196 SmallVector<MachineInstr*, 16> Copies;
197 if (!TailDuplicate(MBB, IsSimple, MF, TDBBs, Copies))
198 return false;
199
200 ++NumTails;
201
202 SmallVector<MachineInstr*, 8> NewPHIs;
203 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
204
205 // TailBB's immediate successors are now successors of those predecessors
206 // which duplicated TailBB. Add the predecessors as sources to the PHI
207 // instructions.
208 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
209 if (PreRegAlloc)
210 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
211
212 // If it is dead, remove it.
213 if (isDead) {
214 NumInstrDups -= MBB->size();
215 RemoveDeadBlock(MBB);
216 ++NumDeadBlocks;
217 }
218
219 // Update SSA form.
220 if (!SSAUpdateVRs.empty()) {
221 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
222 unsigned VReg = SSAUpdateVRs[i];
223 SSAUpdate.Initialize(VReg);
224
225 // If the original definition is still around, add it as an available
226 // value.
227 MachineInstr *DefMI = MRI->getVRegDef(VReg);
228 MachineBasicBlock *DefBB = 0;
229 if (DefMI) {
230 DefBB = DefMI->getParent();
231 SSAUpdate.AddAvailableValue(DefBB, VReg);
232 }
233
234 // Add the new vregs as available values.
235 DenseMap<unsigned, AvailableValsTy>::iterator LI =
236 SSAUpdateVals.find(VReg);
237 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
238 MachineBasicBlock *SrcBB = LI->second[j].first;
239 unsigned SrcReg = LI->second[j].second;
240 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
241 }
242
243 // Rewrite uses that are outside of the original def's block.
244 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
245 while (UI != MRI->use_end()) {
246 MachineOperand &UseMO = UI.getOperand();
247 MachineInstr *UseMI = &*UI;
248 ++UI;
249 if (UseMI->isDebugValue()) {
250 // SSAUpdate can replace the use with an undef. That creates
251 // a debug instruction that is a kill.
252 // FIXME: Should it SSAUpdate job to delete debug instructions
253 // instead of replacing the use with undef?
254 UseMI->eraseFromParent();
255 continue;
256 }
257 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
258 continue;
259 SSAUpdate.RewriteUse(UseMO);
260 }
261 }
262
263 SSAUpdateVRs.clear();
264 SSAUpdateVals.clear();
265 }
266
267 // Eliminate some of the copies inserted by tail duplication to maintain
268 // SSA form.
269 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
270 MachineInstr *Copy = Copies[i];
271 if (!Copy->isCopy())
272 continue;
273 unsigned Dst = Copy->getOperand(0).getReg();
274 unsigned Src = Copy->getOperand(1).getReg();
Jakob Stoklund Olesen0fda5452012-05-20 18:42:51 +0000275 if (MRI->hasOneNonDBGUse(Src) &&
276 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000277 // Copy is the only use. Do trivial copy propagation here.
278 MRI->replaceRegWith(Dst, Src);
279 Copy->eraseFromParent();
280 }
281 }
282
283 if (NewPHIs.size())
284 NumAddedPHIs += NewPHIs.size();
285
286 return true;
287}
288
Bob Wilson15acadd2009-11-26 00:32:21 +0000289/// TailDuplicateBlocks - Look for small blocks that are unconditionally
290/// branched to and do not fall through. Tail-duplicate their instructions
291/// into their predecessors to eliminate (dynamic) branches.
Bob Wilson2d521e52009-11-26 21:38:41 +0000292bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000293 bool MadeChange = false;
294
Evan Cheng75eb5352009-12-07 10:15:19 +0000295 if (PreRegAlloc && TailDupVerify) {
David Greene00dec1b2010-01-05 01:25:15 +0000296 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Evan Cheng75eb5352009-12-07 10:15:19 +0000297 VerifyPHIs(MF, true);
298 }
299
Bob Wilson15acadd2009-11-26 00:32:21 +0000300 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
301 MachineBasicBlock *MBB = I++;
302
Evan Cheng75eb5352009-12-07 10:15:19 +0000303 if (NumTails == TailDupLimit)
304 break;
305
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000306 bool IsSimple = isSimpleBB(MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000307
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000308 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
Rafael Espindolac0af3522011-07-04 00:13:36 +0000309 continue;
Evan Cheng75eb5352009-12-07 10:15:19 +0000310
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000311 MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
Bob Wilson15acadd2009-11-26 00:32:21 +0000312 }
Rafael Espindolac0af3522011-07-04 00:13:36 +0000313
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000314 if (PreRegAlloc && TailDupVerify)
315 VerifyPHIs(MF, false);
Evan Cheng111e7622009-12-03 08:43:53 +0000316
Bob Wilson15acadd2009-11-26 00:32:21 +0000317 return MadeChange;
318}
319
Evan Cheng111e7622009-12-03 08:43:53 +0000320static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
321 const MachineRegisterInfo *MRI) {
322 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
323 UE = MRI->use_end(); UI != UE; ++UI) {
324 MachineInstr *UseMI = &*UI;
Rafael Espindoladb3983b2011-06-17 13:59:43 +0000325 if (UseMI->isDebugValue())
326 continue;
Evan Cheng111e7622009-12-03 08:43:53 +0000327 if (UseMI->getParent() != BB)
328 return true;
329 }
330 return false;
331}
332
333static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
334 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
335 if (MI->getOperand(i+1).getMBB() == SrcBB)
336 return i;
337 return 0;
338}
339
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000340
341// Remember which registers are used by phis in this block. This is
342// used to determine which registers are liveout while modifying the
343// block (which is why we need to copy the information).
344static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
Rafael Espindola33b46582011-06-10 21:01:53 +0000345 DenseSet<unsigned> *UsedByPhi) {
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000346 for(MachineBasicBlock::const_iterator I = BB.begin(), E = BB.end();
347 I != E; ++I) {
348 const MachineInstr &MI = *I;
349 if (!MI.isPHI())
350 break;
351 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
352 unsigned SrcReg = MI.getOperand(i).getReg();
353 UsedByPhi->insert(SrcReg);
354 }
355 }
356}
357
Evan Cheng111e7622009-12-03 08:43:53 +0000358/// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
359/// SSA update.
Evan Cheng11572ba2009-12-04 19:09:10 +0000360void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
361 MachineBasicBlock *BB) {
362 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
Evan Cheng111e7622009-12-03 08:43:53 +0000363 if (LI != SSAUpdateVals.end())
Evan Cheng11572ba2009-12-04 19:09:10 +0000364 LI->second.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000365 else {
366 AvailableValsTy Vals;
Evan Cheng11572ba2009-12-04 19:09:10 +0000367 Vals.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000368 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
369 SSAUpdateVRs.push_back(OrigReg);
370 }
371}
372
Evan Cheng75eb5352009-12-07 10:15:19 +0000373/// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
374/// Remember the source register that's contributed by PredBB and update SSA
375/// update map.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000376void TailDuplicatePass::ProcessPHI(MachineInstr *MI,
377 MachineBasicBlock *TailBB,
378 MachineBasicBlock *PredBB,
Evan Cheng75eb5352009-12-07 10:15:19 +0000379 DenseMap<unsigned, unsigned> &LocalVRMap,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000380 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies,
Rafael Espindola33b46582011-06-10 21:01:53 +0000381 const DenseSet<unsigned> &RegsUsedByPhi,
Rafael Espindola689d7d52011-06-09 23:22:56 +0000382 bool Remove) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000383 unsigned DefReg = MI->getOperand(0).getReg();
384 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
385 assert(SrcOpIdx && "Unable to find matching PHI source?");
386 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Evan Cheng75eb5352009-12-07 10:15:19 +0000387 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000388 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
Evan Cheng75eb5352009-12-07 10:15:19 +0000389
390 // Insert a copy from source to the end of the block. The def register is the
391 // available value liveout of the block.
392 unsigned NewDef = MRI->createVirtualRegister(RC);
393 Copies.push_back(std::make_pair(NewDef, SrcReg));
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000394 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
Evan Cheng75eb5352009-12-07 10:15:19 +0000395 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000396
Rafael Espindola689d7d52011-06-09 23:22:56 +0000397 if (!Remove)
398 return;
399
Evan Cheng79fc6f42009-12-04 09:42:45 +0000400 // Remove PredBB from the PHI node.
401 MI->RemoveOperand(SrcOpIdx+1);
402 MI->RemoveOperand(SrcOpIdx);
403 if (MI->getNumOperands() == 1)
404 MI->eraseFromParent();
405}
406
407/// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
408/// the source operands due to earlier PHI translation.
409void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
410 MachineBasicBlock *TailBB,
411 MachineBasicBlock *PredBB,
412 MachineFunction &MF,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000413 DenseMap<unsigned, unsigned> &LocalVRMap,
414 const DenseSet<unsigned> &UsedByPhi) {
Jakob Stoklund Olesen30ac0462010-01-06 23:47:07 +0000415 MachineInstr *NewMI = TII->duplicate(MI, MF);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000416 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
417 MachineOperand &MO = NewMI->getOperand(i);
418 if (!MO.isReg())
419 continue;
420 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000421 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng79fc6f42009-12-04 09:42:45 +0000422 continue;
423 if (MO.isDef()) {
424 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
425 unsigned NewReg = MRI->createVirtualRegister(RC);
426 MO.setReg(NewReg);
427 LocalVRMap.insert(std::make_pair(Reg, NewReg));
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000428 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
Evan Cheng11572ba2009-12-04 19:09:10 +0000429 AddSSAUpdateEntry(Reg, NewReg, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000430 } else {
431 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
Jakob Stoklund Olesen0fda5452012-05-20 18:42:51 +0000432 if (VI != LocalVRMap.end()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000433 MO.setReg(VI->second);
Jakob Stoklund Olesen0fda5452012-05-20 18:42:51 +0000434 MRI->constrainRegClass(VI->second, MRI->getRegClass(Reg));
435 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000436 }
437 }
Evan Chengdf7e8bd2012-02-20 07:51:58 +0000438 PredBB->insert(PredBB->instr_end(), NewMI);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000439}
440
441/// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
442/// blocks, the successors have gained new predecessors. Update the PHI
443/// instructions in them accordingly.
Evan Cheng75eb5352009-12-07 10:15:19 +0000444void
445TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
446 SmallVector<MachineBasicBlock*, 8> &TDBBs,
Evan Cheng79fc6f42009-12-04 09:42:45 +0000447 SmallSetVector<MachineBasicBlock*,8> &Succs) {
448 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
449 SE = Succs.end(); SI != SE; ++SI) {
450 MachineBasicBlock *SuccBB = *SI;
451 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
452 II != EE; ++II) {
Chris Lattner518bb532010-02-09 19:54:29 +0000453 if (!II->isPHI())
Evan Cheng79fc6f42009-12-04 09:42:45 +0000454 break;
Evan Cheng75eb5352009-12-07 10:15:19 +0000455 unsigned Idx = 0;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000456 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
Evan Cheng75eb5352009-12-07 10:15:19 +0000457 MachineOperand &MO = II->getOperand(i+1);
458 if (MO.getMBB() == FromBB) {
459 Idx = i;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000460 break;
Evan Cheng75eb5352009-12-07 10:15:19 +0000461 }
462 }
463
464 assert(Idx != 0);
465 MachineOperand &MO0 = II->getOperand(Idx);
466 unsigned Reg = MO0.getReg();
467 if (isDead) {
468 // Folded into the previous BB.
469 // There could be duplicate phi source entries. FIXME: Should sdisel
470 // or earlier pass fixed this?
471 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
472 MachineOperand &MO = II->getOperand(i+1);
473 if (MO.getMBB() == FromBB) {
474 II->RemoveOperand(i+1);
475 II->RemoveOperand(i);
476 }
477 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000478 } else
479 Idx = 0;
480
481 // If Idx is set, the operands at Idx and Idx+1 must be removed.
482 // We reuse the location to avoid expensive RemoveOperand calls.
483
Evan Cheng75eb5352009-12-07 10:15:19 +0000484 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
485 if (LI != SSAUpdateVals.end()) {
486 // This register is defined in the tail block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000487 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
Evan Cheng11572ba2009-12-04 19:09:10 +0000488 MachineBasicBlock *SrcBB = LI->second[j].first;
Rafael Espindolad3f4eea2011-06-09 23:55:56 +0000489 // If we didn't duplicate a bb into a particular predecessor, we
490 // might still have added an entry to SSAUpdateVals to correcly
491 // recompute SSA. If that case, avoid adding a dummy extra argument
492 // this PHI.
493 if (!SrcBB->isSuccessor(SuccBB))
494 continue;
495
Evan Cheng11572ba2009-12-04 19:09:10 +0000496 unsigned SrcReg = LI->second[j].second;
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000497 if (Idx != 0) {
498 II->getOperand(Idx).setReg(SrcReg);
499 II->getOperand(Idx+1).setMBB(SrcBB);
500 Idx = 0;
501 } else {
502 II->addOperand(MachineOperand::CreateReg(SrcReg, false));
503 II->addOperand(MachineOperand::CreateMBB(SrcBB));
504 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000505 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000506 } else {
507 // Live in tail block, must also be live in predecessors.
508 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
509 MachineBasicBlock *SrcBB = TDBBs[j];
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000510 if (Idx != 0) {
511 II->getOperand(Idx).setReg(Reg);
512 II->getOperand(Idx+1).setMBB(SrcBB);
513 Idx = 0;
514 } else {
515 II->addOperand(MachineOperand::CreateReg(Reg, false));
516 II->addOperand(MachineOperand::CreateMBB(SrcBB));
517 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000518 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000519 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000520 if (Idx != 0) {
521 II->RemoveOperand(Idx+1);
522 II->RemoveOperand(Idx);
523 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000524 }
525 }
526}
527
Rafael Espindola54c25622011-06-09 19:54:42 +0000528/// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
Evan Cheng75eb5352009-12-07 10:15:19 +0000529bool
Rafael Espindola54c25622011-06-09 19:54:42 +0000530TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000531 bool IsSimple,
Rafael Espindola54c25622011-06-09 19:54:42 +0000532 MachineBasicBlock &TailBB) {
533 // Only duplicate blocks that end with unconditional branches.
534 if (TailBB.canFallThrough())
535 return false;
536
Rafael Espindolaec324e52011-06-17 05:54:50 +0000537 // Don't try to tail-duplicate single-block loops.
538 if (TailBB.isSuccessor(&TailBB))
539 return false;
540
Rafael Espindola54c25622011-06-09 19:54:42 +0000541 // Set the limit on the cost to duplicate. When optimizing for size,
Bob Wilson15acadd2009-11-26 00:32:21 +0000542 // duplicate only one, because one branch instruction can be eliminated to
543 // compensate for the duplication.
544 unsigned MaxDuplicateCount;
Jakob Stoklund Olesen83520622011-01-30 20:38:12 +0000545 if (TailDuplicateSize.getNumOccurrences() == 0 &&
546 MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
Bob Wilson38582252009-11-30 18:56:45 +0000547 MaxDuplicateCount = 1;
Bob Wilson15acadd2009-11-26 00:32:21 +0000548 else
549 MaxDuplicateCount = TailDuplicateSize;
550
Rafael Espindolaec324e52011-06-17 05:54:50 +0000551 // If the target has hardware branch prediction that can handle indirect
552 // branches, duplicating them can often make them predictable when there
553 // are common paths through the code. The limit needs to be high enough
554 // to allow undoing the effects of tail merging and other optimizations
555 // that rearrange the predecessors of the indirect branch.
Bob Wilsoncb44b282010-01-16 00:42:25 +0000556
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000557 bool HasIndirectbr = false;
558 if (!TailBB.empty())
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000559 HasIndirectbr = TailBB.back().isIndirectBranch();
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000560
561 if (HasIndirectbr && PreRegAlloc)
562 MaxDuplicateCount = 20;
Bob Wilsonbfdcf3b2010-01-15 06:29:17 +0000563
Bob Wilson15acadd2009-11-26 00:32:21 +0000564 // Check the instructions in the block to determine whether tail-duplication
565 // is invalid or unlikely to be profitable.
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000566 unsigned InstrCount = 0;
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000567 for (MachineBasicBlock::iterator I = TailBB.begin(); I != TailBB.end(); ++I) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000568 // Non-duplicable things shouldn't be tail-duplicated.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000569 if (I->isNotDuplicable())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000570 return false;
571
Evan Cheng79fc6f42009-12-04 09:42:45 +0000572 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
573 // A return may expand into a lot more instructions (e.g. reload of callee
574 // saved registers) after PEI.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000575 if (PreRegAlloc && I->isReturn())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000576 return false;
577
578 // Avoid duplicating calls before register allocation. Calls presents a
579 // barrier to register allocation so duplicating them may end up increasing
580 // spills.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000581 if (PreRegAlloc && I->isCall())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000582 return false;
583
Devang Patelcbe1e312010-03-16 21:02:07 +0000584 if (!I->isPHI() && !I->isDebugValue())
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000585 InstrCount += 1;
Rafael Espindolaec324e52011-06-17 05:54:50 +0000586
587 if (InstrCount > MaxDuplicateCount)
588 return false;
Bob Wilson15acadd2009-11-26 00:32:21 +0000589 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000590
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000591 if (HasIndirectbr && PreRegAlloc)
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000592 return true;
593
594 if (IsSimple)
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000595 return true;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000596
597 if (!PreRegAlloc)
598 return true;
599
Rafael Espindola40179bf2011-06-24 15:50:56 +0000600 return canCompletelyDuplicateBB(TailBB);
Rafael Espindola54c25622011-06-09 19:54:42 +0000601}
602
Rafael Espindola275c1f92011-06-20 04:16:35 +0000603/// isSimpleBB - True if this BB has only one unconditional jump.
604bool
605TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
606 if (TailBB->succ_size() != 1)
607 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000608 if (TailBB->pred_empty())
609 return false;
Rafael Espindolad6379a92011-06-22 22:31:57 +0000610 MachineBasicBlock::iterator I = TailBB->begin();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000611 MachineBasicBlock::iterator E = TailBB->end();
Rafael Espindolad6379a92011-06-22 22:31:57 +0000612 while (I != E && I->isDebugValue())
Rafael Espindola275c1f92011-06-20 04:16:35 +0000613 ++I;
614 if (I == E)
615 return true;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000616 return I->isUnconditionalBranch();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000617}
618
619static bool
620bothUsedInPHI(const MachineBasicBlock &A,
621 SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
622 for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
623 SE = A.succ_end(); SI != SE; ++SI) {
624 MachineBasicBlock *BB = *SI;
625 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
626 return true;
627 }
628
629 return false;
630}
631
632bool
Rafael Espindola40179bf2011-06-24 15:50:56 +0000633TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
Rafael Espindola275c1f92011-06-20 04:16:35 +0000634 SmallPtrSet<MachineBasicBlock*, 8> Succs(BB.succ_begin(), BB.succ_end());
635
636 for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
637 PE = BB.pred_end(); PI != PE; ++PI) {
638 MachineBasicBlock *PredBB = *PI;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000639
Rafael Espindola40179bf2011-06-24 15:50:56 +0000640 if (PredBB->succ_size() > 1)
641 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000642
Rafael Espindola275c1f92011-06-20 04:16:35 +0000643 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
644 SmallVector<MachineOperand, 4> PredCond;
645 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
646 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000647
Rafael Espindola40179bf2011-06-24 15:50:56 +0000648 if (!PredCond.empty())
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000649 return false;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000650 }
651 return true;
652}
653
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000654bool
Rafael Espindola275c1f92011-06-20 04:16:35 +0000655TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
656 SmallVector<MachineBasicBlock*, 8> &TDBBs,
657 const DenseSet<unsigned> &UsedByPhi,
658 SmallVector<MachineInstr*, 16> &Copies) {
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000659 SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
660 TailBB->succ_end());
Rafael Espindola275c1f92011-06-20 04:16:35 +0000661 SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
662 TailBB->pred_end());
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000663 bool Changed = false;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000664 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
665 PE = Preds.end(); PI != PE; ++PI) {
666 MachineBasicBlock *PredBB = *PI;
667
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000668 if (PredBB->getLandingPadSuccessor())
669 continue;
670
671 if (bothUsedInPHI(*PredBB, Succs))
672 continue;
673
Rafael Espindola275c1f92011-06-20 04:16:35 +0000674 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
675 SmallVector<MachineOperand, 4> PredCond;
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000676 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
677 continue;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000678
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000679 Changed = true;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000680 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
681 << "From simple Succ: " << *TailBB);
682
683 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Francois Pichet289a2792011-06-20 05:19:37 +0000684 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(PredBB));
Rafael Espindola275c1f92011-06-20 04:16:35 +0000685
Rafael Espindola275c1f92011-06-20 04:16:35 +0000686 // Make PredFBB explicit.
687 if (PredCond.empty())
688 PredFBB = PredTBB;
689
690 // Make fall through explicit.
691 if (!PredTBB)
692 PredTBB = NextBB;
693 if (!PredFBB)
694 PredFBB = NextBB;
695
696 // Redirect
697 if (PredFBB == TailBB)
698 PredFBB = NewTarget;
699 if (PredTBB == TailBB)
700 PredTBB = NewTarget;
701
702 // Make the branch unconditional if possible
Rafael Espindola689c2472011-06-20 14:11:42 +0000703 if (PredTBB == PredFBB) {
704 PredCond.clear();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000705 PredFBB = NULL;
Rafael Espindola689c2472011-06-20 14:11:42 +0000706 }
Rafael Espindola275c1f92011-06-20 04:16:35 +0000707
708 // Avoid adding fall through branches.
709 if (PredFBB == NextBB)
710 PredFBB = NULL;
711 if (PredTBB == NextBB && PredFBB == NULL)
712 PredTBB = NULL;
713
714 TII->RemoveBranch(*PredBB);
715
716 if (PredTBB)
717 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
718
719 PredBB->removeSuccessor(TailBB);
Rafael Espindola689c2472011-06-20 14:11:42 +0000720 unsigned NumSuccessors = PredBB->succ_size();
721 assert(NumSuccessors <= 1);
722 if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
723 PredBB->addSuccessor(NewTarget);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000724
725 TDBBs.push_back(PredBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000726 }
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000727 return Changed;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000728}
729
Rafael Espindola54c25622011-06-09 19:54:42 +0000730/// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
731/// of its predecessors.
732bool
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000733TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
734 bool IsSimple,
735 MachineFunction &MF,
Rafael Espindola54c25622011-06-09 19:54:42 +0000736 SmallVector<MachineBasicBlock*, 8> &TDBBs,
737 SmallVector<MachineInstr*, 16> &Copies) {
David Greene00dec1b2010-01-05 01:25:15 +0000738 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
Evan Cheng75eb5352009-12-07 10:15:19 +0000739
Rafael Espindola275c1f92011-06-20 04:16:35 +0000740 DenseSet<unsigned> UsedByPhi;
741 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
742
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000743 if (IsSimple)
744 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000745
Bob Wilson15acadd2009-11-26 00:32:21 +0000746 // Iterate through all the unique predecessors and tail-duplicate this
747 // block into them, if possible. Copying the list ahead of time also
748 // avoids trouble with the predecessor list reallocating.
749 bool Changed = false;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000750 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
751 TailBB->pred_end());
Bob Wilson15acadd2009-11-26 00:32:21 +0000752 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
753 PE = Preds.end(); PI != PE; ++PI) {
754 MachineBasicBlock *PredBB = *PI;
755
756 assert(TailBB != PredBB &&
757 "Single-block loop should have been rejected earlier!");
Rafael Espindola9a9a3a52011-06-10 20:08:23 +0000758 // EH edges are ignored by AnalyzeBranch.
759 if (PredBB->succ_size() > 1)
760 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000761
762 MachineBasicBlock *PredTBB, *PredFBB;
763 SmallVector<MachineOperand, 4> PredCond;
764 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
765 continue;
766 if (!PredCond.empty())
767 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000768 // Don't duplicate into a fall-through predecessor (at least for now).
769 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
770 continue;
771
David Greene00dec1b2010-01-05 01:25:15 +0000772 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000773 << "From Succ: " << *TailBB);
774
Evan Cheng75eb5352009-12-07 10:15:19 +0000775 TDBBs.push_back(PredBB);
776
Bob Wilson15acadd2009-11-26 00:32:21 +0000777 // Remove PredBB's unconditional branch.
778 TII->RemoveBranch(*PredBB);
Evan Cheng111e7622009-12-03 08:43:53 +0000779
Bob Wilson15acadd2009-11-26 00:32:21 +0000780 // Clone the contents of TailBB into PredBB.
Evan Cheng111e7622009-12-03 08:43:53 +0000781 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000782 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Chengdf7e8bd2012-02-20 07:51:58 +0000783 // Use instr_iterator here to properly handle bundles, e.g.
784 // ARM Thumb2 IT block.
785 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
786 while (I != TailBB->instr_end()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000787 MachineInstr *MI = &*I;
788 ++I;
Chris Lattner518bb532010-02-09 19:54:29 +0000789 if (MI->isPHI()) {
Evan Cheng111e7622009-12-03 08:43:53 +0000790 // Replace the uses of the def of the PHI with the register coming
791 // from PredBB.
Rafael Espindola689d7d52011-06-09 23:22:56 +0000792 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000793 } else {
794 // Replace def of virtual registers with new registers, and update
795 // uses with PHI source register or the new registers.
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000796 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng111e7622009-12-03 08:43:53 +0000797 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000798 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000799 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000800 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000801 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
802 TII->get(TargetOpcode::COPY),
803 CopyInfos[i].first).addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000804 }
Rafael Espindolaec324e52011-06-17 05:54:50 +0000805
806 // Simplify
807 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
808
Bob Wilson15acadd2009-11-26 00:32:21 +0000809 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
810
811 // Update the CFG.
812 PredBB->removeSuccessor(PredBB->succ_begin());
813 assert(PredBB->succ_empty() &&
814 "TailDuplicate called on block with multiple successors!");
815 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
Evan Cheng79fc6f42009-12-04 09:42:45 +0000816 E = TailBB->succ_end(); I != E; ++I)
817 PredBB->addSuccessor(*I);
Bob Wilson15acadd2009-11-26 00:32:21 +0000818
819 Changed = true;
820 ++NumTailDups;
821 }
822
823 // If TailBB was duplicated into all its predecessors except for the prior
824 // block, which falls through unconditionally, move the contents of this
825 // block into the prior block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000826 MachineBasicBlock *PrevBB = prior(MachineFunction::iterator(TailBB));
Bob Wilson15acadd2009-11-26 00:32:21 +0000827 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
828 SmallVector<MachineOperand, 4> PriorCond;
Bob Wilson15acadd2009-11-26 00:32:21 +0000829 // This has to check PrevBB->succ_size() because EH edges are ignored by
830 // AnalyzeBranch.
Andrew Trickd2a7bed2012-02-08 21:22:30 +0000831 if (PrevBB->succ_size() == 1 &&
Rafael Espindolaa899b222011-06-09 21:43:25 +0000832 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
833 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
Bob Wilson15acadd2009-11-26 00:32:21 +0000834 !TailBB->hasAddressTaken()) {
David Greene00dec1b2010-01-05 01:25:15 +0000835 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000836 << "From MBB: " << *TailBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000837 if (PreRegAlloc) {
838 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000839 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000840 MachineBasicBlock::iterator I = TailBB->begin();
841 // Process PHI instructions first.
Chris Lattner518bb532010-02-09 19:54:29 +0000842 while (I != TailBB->end() && I->isPHI()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000843 // Replace the uses of the def of the PHI with the register coming
844 // from PredBB.
845 MachineInstr *MI = &*I++;
Rafael Espindola689d7d52011-06-09 23:22:56 +0000846 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000847 if (MI->getParent())
848 MI->eraseFromParent();
849 }
850
851 // Now copy the non-PHI instructions.
852 while (I != TailBB->end()) {
853 // Replace def of virtual registers with new registers, and update
854 // uses with PHI source register or the new registers.
855 MachineInstr *MI = &*I++;
Evan Chengdf7e8bd2012-02-20 07:51:58 +0000856 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000857 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000858 MI->eraseFromParent();
859 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000860 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000861 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000862 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
863 TII->get(TargetOpcode::COPY),
864 CopyInfos[i].first)
865 .addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000866 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000867 } else {
868 // No PHIs to worry about, just splice the instructions over.
869 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
870 }
871 PrevBB->removeSuccessor(PrevBB->succ_begin());
872 assert(PrevBB->succ_empty());
873 PrevBB->transferSuccessors(TailBB);
Evan Cheng75eb5352009-12-07 10:15:19 +0000874 TDBBs.push_back(PrevBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000875 Changed = true;
876 }
877
Rafael Espindola689d7d52011-06-09 23:22:56 +0000878 // If this is after register allocation, there are no phis to fix.
879 if (!PreRegAlloc)
880 return Changed;
881
882 // If we made no changes so far, we are safe.
883 if (!Changed)
884 return Changed;
885
886
887 // Handle the nasty case in that we duplicated a block that is part of a loop
888 // into some but not all of its predecessors. For example:
Rafael Espindola4d7b4572011-06-09 23:51:45 +0000889 // 1 -> 2 <-> 3 |
890 // \ |
891 // \---> rest |
Rafael Espindola689d7d52011-06-09 23:22:56 +0000892 // if we duplicate 2 into 1 but not into 3, we end up with
Rafael Espindola4d7b4572011-06-09 23:51:45 +0000893 // 12 -> 3 <-> 2 -> rest |
894 // \ / |
895 // \----->-----/ |
Rafael Espindola689d7d52011-06-09 23:22:56 +0000896 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
897 // with a phi in 3 (which now dominates 2).
898 // What we do here is introduce a copy in 3 of the register defined by the
899 // phi, just like when we are duplicating 2 into 3, but we don't copy any
900 // real instructions or remove the 3 -> 2 edge from the phi in 2.
901 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
902 PE = Preds.end(); PI != PE; ++PI) {
903 MachineBasicBlock *PredBB = *PI;
904 if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
905 continue;
906
907 // EH edges
908 if (PredBB->succ_size() != 1)
909 continue;
910
911 DenseMap<unsigned, unsigned> LocalVRMap;
912 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
913 MachineBasicBlock::iterator I = TailBB->begin();
914 // Process PHI instructions first.
915 while (I != TailBB->end() && I->isPHI()) {
916 // Replace the uses of the def of the PHI with the register coming
917 // from PredBB.
918 MachineInstr *MI = &*I++;
919 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
920 }
921 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
922 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
923 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
924 TII->get(TargetOpcode::COPY),
925 CopyInfos[i].first).addReg(CopyInfos[i].second));
926 }
927 }
928
Bob Wilson15acadd2009-11-26 00:32:21 +0000929 return Changed;
930}
931
932/// RemoveDeadBlock - Remove the specified dead machine basic block from the
933/// function, updating the CFG.
Bob Wilson2d521e52009-11-26 21:38:41 +0000934void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000935 assert(MBB->pred_empty() && "MBB must be dead!");
David Greene00dec1b2010-01-05 01:25:15 +0000936 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000937
938 // Remove all successors.
939 while (!MBB->succ_empty())
940 MBB->removeSuccessor(MBB->succ_end()-1);
941
Bob Wilson15acadd2009-11-26 00:32:21 +0000942 // Remove the block.
943 MBB->eraseFromParent();
944}